Postgresql插入或更新操作upsert


冪等性的一個要求是多次操作的結果一致。對於update操作,多次直接的結果都是最后update的值,是滿足需求的。但對於insert,如果已經插入,第二次會報錯,duplicate error, 主鍵重復或者unique key duplicate。所以需要做一下處理。

最簡單的就是,try-catch,當報錯的時候,調用update去更新,或者策略更簡單點,直接返回就行,不需要更新,以第一條為准。

PostgreSQL從9.5之后就提供了原子的upsert語法: 不存在則插入,發生沖突可以update。

Inert語法

官方文檔: https://www.postgresql.org/docs/devel/sql-insert.html

[ WITH [ RECURSIVE ] with_query [, ...] ]
INSERT INTO table_name [ AS alias ] [ ( column_name [, ...] ) ]
   [ OVERRIDING { SYSTEM | USER} VALUE ]
   { DEFAULT VALUES | VALUES ( { expression | DEFAULT } [, ...] ) [, ...] | query }
   [ ON CONFLICT [ conflict_target ] conflict_action ]
   [ RETURNING * | output_expression [ [ AS ] output_name ] [, ...] ]

where conflict_target can be one of:

   ( { index_column_name | ( index_expression ) } [ COLLATE collation ] [ opclass ] [, ...] ) [ WHERE index_predicate ]
   ON CONSTRAINT constraint_name

and conflict_action is one of:

   DO NOTHING
   DO UPDATE SET { column_name = { expression | DEFAULT } |
                   ( column_name [, ...] ) = [ ROW ] ( { expression | DEFAULT } [, ...] ) |
                   ( column_name [, ...] ) = ( sub-SELECT )
                 } [, ...]
             [ WHERE condition ]

index_column_name

The name of a table_name column. Used to infer arbiter indexes. Follows CREATE INDEX format. SELECT privilege on index_column_name is required.

index_expression

Similar to index_column_name, but used to infer expressions on table_name columns appearing within index definitions (not simple columns). Follows CREATE INDEX format. SELECT privilege on any column appearing within index_expression is required.

使用示例

創建表

CREATE TABLE "test"."upsert_test" (
 "id" int4 NOT NULL,
 "name" varchar(255) COLLATE "pg_catalog"."default"
)
;

當主鍵id沖突時,更新其他字段

INSERT INTO test.upsert_test(id, "name")
   VALUES(1, 'm'),(2, 'n'),(4, 'c')
   ON conflict(id) DO UPDATE
   SET "name" = excluded.name;
  • did 沖突的主鍵
  • EXCLUDED 代指要插入的記錄

當主鍵或者unique key發生沖突時,什么都不做

INSERT INTO test.upsert_test(id, "name")
VALUES(1, 'm'),(2, 'n'),(4, 'c')
ON conflict(id)  DO NOTHING;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM