From 85a2499da3dcda11ca086aa3be180b17f0ddd2c3 Mon Sep 17 00:00:00 2001 From: James Moger Date: Mon, 4 Apr 2016 13:50:18 -0400 Subject: Fix #23: Postgres 9.5 UPSERT syntax was incorrect --- src/main/java/com/iciql/SQLDialectPostgreSQL.java | 29 +++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/main/java/com/iciql/SQLDialectPostgreSQL.java b/src/main/java/com/iciql/SQLDialectPostgreSQL.java index 382c435..54e47b0 100644 --- a/src/main/java/com/iciql/SQLDialectPostgreSQL.java +++ b/src/main/java/com/iciql/SQLDialectPostgreSQL.java @@ -106,7 +106,14 @@ public class SQLDialectPostgreSQL extends SQLDialectDefault { public void prepareMerge(SQLStatement stat, String schemaName, String tableName, TableDefinition def, Object obj) { - if (databaseVersion < 9.5f) { + FieldDefinition primaryKey = null; + for (FieldDefinition field : def.fields) { + if (field.isPrimaryKey) { + primaryKey = field; + } + } + + if (primaryKey == null || databaseVersion < 9.5f) { // simulated UPSERT for <= 9.4 release super.prepareMerge(stat, schemaName, tableName, def, obj); return; @@ -129,7 +136,25 @@ public class SQLDialectPostgreSQL extends SQLDialectDefault { Object parameter = serialize(value, field.typeAdapter); stat.addParameter(parameter); } - buff.append(") ON CONFLICT DO UPDATE SET"); + + buff.append(") ON CONFLICT ("); + buff.resetCount(); + for (FieldDefinition field : def.fields) { + if (field.isPrimaryKey) { + buff.appendExceptFirst(", "); + buff.append(field.columnName); + } + } + buff.append(") DO UPDATE SET "); + buff.resetCount(); + for (FieldDefinition field : def.fields) { + buff.appendExceptFirst(", "); + buff.append(field.columnName); + buff.append("=?"); + Object value = def.getValue(obj, field); + Object parameter = serialize(value, field.typeAdapter); + stat.addParameter(parameter); + } stat.setSQL(buff.toString()); } -- cgit v1.2.3