简体   繁体   中英

ON CONFLICT using pg_prepare() errors 'name' does not exist

I have a simple DB class with this method

function __construct($host, $user, $pass, $db) {
    $this->link = pg_connect("host=$host port=5432 dbname=$db user=$user password=$pass") or $this->error();
}

public function run($sql, $args = null) {
    if(!$args)
        $this->query = pg_query($sql);
    else {
        $v = md5(uniqid(mt_rand(), true));
        $this->query = pg_prepare($v, $sql);
        $this->query = pg_execute($v, $args);
    }
    return $this;
}

Using this I can the following query without prepared statements, and it works perfectly fine.

$db->run("
    INSERT INTO userExercise (userid, exerciseid, date, sets)
    VALUES ($user->id, $exerciseid, '$date', '$sets')

    ON CONFLICT (userid, date, exerciseid)
    DO UPDATE SET sets = '$sets'

    RETURNING LASTVAL()"
);

However when I do a prepared, I get the error "ERROR: prepared statement "41982c47c3c84749552cd9808ad03422" does not exist"

    $db->run("
        INSERT INTO userExercise (userid, exerciseid, date, sets)
        VALUES ($1, $2, $3 $4)

        ON CONFLICT (userid, date, exerciseid)
        DO UPDATE SET sets = $4

        RETURNING LASTVAL()",
        [$user->id, $exerciseid, $date, $sets]
    );

The 41982c47c3c84749552cd9808ad03422 resulting from md5 to give a unique name. The issue appears to be from the ON CONFLICT . How I may fix this?

you are not checking the result from pg_prepare, and probably there is a syntax error. Like VALUES ($1, $2, $3 $4) should have 1 more comma.

Also, RETURNING LASTVAL() should probably be something like RETURNING ID , or whatever your serial column is called. Otherwise you will get bogus results for the conflict case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM