public class Upsert extends PostgresSqlPart

Generates an upsert statement for PostgreSQL.


Sample Generated SQL:

INSERT INTO "tableName" ("col1", "col2", "col3")
VALUES (val1, val2, val3),
       (val1, val2, val3),
       (val1, val2, val3)
ON CONFLICT ("id") DO UPDATE SET "col1" = EXCLUDED."col1", "col2" = EXCLUDED."col2", "col3" = EXCLUDED."col3"
  • Constructor Details

    • Upsert

      public Upsert(String table, String... keyFieldNames)
      Creates an upsert into table that uses the given key fields for ON CONFLICT; at least one is required.
    • Upsert

      public Upsert(String table, List<String> keyFieldNames)
      Creates an upsert into table that uses the given key fields for ON CONFLICT; at least one is required.
  • Method Details

    • setPretty

      public Upsert setPretty(boolean pretty)
      Indicates if line breaks and indentations should be added to output upsert statement (default false).

      Example output (pretty = true):


      INSERT INTO "tableName" ("col1", "col2", "col3")
      VALUES (val1, val2, val3),
             (val1, val2, val3),
             (val1, val2, val3)
      ON CONFLICT ("id") DO UPDATE SET "col1" = EXCLUDED."col1", "col2" = EXCLUDED."col2", "col3" = EXCLUDED."col3"

      Example output (pretty = false):
      INSERT INTO "tableName" ("col1", "col2", "col3") VALUES (val1, val2, val3), (val1, val2, val3), (val1, val2, val3) ON CONFLICT ("id") DO UPDATE SET "col1" = EXCLUDED."col1", "col2" = EXCLUDED."col2", "col3" = EXCLUDED."col3"
      Overrides:
      setPretty in class SqlPart
    • getTable

      public String getTable()
    • nextRow

      public Upsert nextRow()
      Starts a new row for subsequent add(String, Object) calls; the first row already exists after construction.
    • add

      public Upsert add(String columnName, Object value)
      Adds a column value (an SQL literal, written as-is) to the current row; only the first row's column names are used.
    • getRows

      public List<InsertRow> getRows()
    • getLastRow

      public InsertRow getLastRow()
    • collectSqlFragment

      public void collectSqlFragment(CodeWriter writer)
      Description copied from class: SqlPart
      Writes this part's SQL to the writer; used by SqlPart.getSqlFragment() and by enclosing parts.
      Specified by:
      collectSqlFragment in class SqlPart
    • getKeyFieldNames

      public List<String> getKeyFieldNames()
      Returns the key fields listed in the ON CONFLICT clause.
    • setConflictAction

      public Upsert setConflictAction(ConflictAction action)
      Indicates the action to perform on conflict (default ConflictAction.UPDATE); null selects the default.
    • getConflictAction

      public ConflictAction getConflictAction()
      Indicates the action to perform on conflict (default ConflictAction.UPDATE).