Re: Upsert error "column reference is ambiguous" - Mailing list pgsql-general

From Christophe Pettus
Subject Re: Upsert error "column reference is ambiguous"
Date
Msg-id D794C225-9F5D-4DF4-BE3F-39AD8C3430B1@thebuild.com
Whole thread Raw
In response to Re: Upsert error "column reference is ambiguous"  (Tim Starling <tstarling@wikimedia.org>)
Responses Re: Upsert error "column reference is ambiguous"
List pgsql-general

> On Apr 28, 2025, at 15:36, Tim Starling <tstarling@wikimedia.org> wrote:
> function upsert( $table, $names, $values, $key, $set ) {
>    if ( $this->type === 'mysql' ) {
>        $conflict = 'ON DUPLICATE KEY UPDATE';
>    } else {
>        $conflict = "ON CONFLICT ($key) DO UPDATE SET";
>    }
>    return $this->query( "INSERT INTO $table ($names) " .
>        "VALUES ($values) $conflict $set" );

I'll mention that you can do this without ON CONFLICT in PostgreSQL in a way that, while not nearly as clean as ON
CONFLICT,isn't a huge hack, either: 

"DO $$ BEGIN INSERT INTO $table($names) VALUES($values); EXCEPTION WHEN integrity_constraint_violation THEN UPDATE
$tableSET $set WHERE $key=$values[0]; END; $$ LANGUAGE plpgsql;" 

It does require knowing which of the VALUES is the key value being inserted (pseudocode syntax above), but if that is
stylizedto always be the first value, that does not seem insurmountable. 





pgsql-general by date:

Previous
From: Tim Starling
Date:
Subject: Re: Upsert error "column reference is ambiguous"
Next
From: Christophe Pettus
Date:
Subject: Re: Upsert error "column reference is ambiguous"