Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Postgres ignore + replace #298

Merged
merged 5 commits into from
May 9, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/main/kotlin/org/jetbrains/exposed/sql/vendors/PostgreSQL.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,33 @@ internal object PostgreSQLFunctionProvider : FunctionProvider() {
if (limit != null) transaction.throwUnsupportedException("PostgreSQL doesn't support LIMIT in UPDATE clause.")
return super.update(targets, columnsAndValues, limit, where, transaction)
}

override fun replace(table: Table, data: List<Pair<Column<*>, Any?>>, transaction: Transaction): String {

val builder = QueryBuilder(true)
val sql = if (data.isEmpty()) ""
else data.joinToString(prefix = "VALUES (", postfix = ")") { (col, value) ->
builder.registerArgument(col, value)
}

val columns = data.map { it.first }

val def = super.insert(false, table, columns, sql, transaction)

val uniqueCols = columns.filter { it.indexInPK != null }.sortedBy { it.indexInPK }
if (uniqueCols.isEmpty())
transaction.throwUnsupportedException("Postgres replace table must supply at least one primary key")
val conflictKey = uniqueCols.joinToString { transaction.identity(it) }
return def + "ON CONFLICT ($conflictKey) DO UPDATE SET " + columns.joinToString { "${transaction.identity(it)}=EXCLUDED.${transaction.identity(it)}" }
}

override fun insert(ignore: Boolean, table: Table, columns: List<Column<*>>, expr: String, transaction: Transaction): String {
val def = super.insert(false, table, columns, expr, transaction)
return if (ignore) "$def $onConflictIgnore" else def
}

private const val onConflictIgnore = "ON CONFLICT DO NOTHING"

}

internal class PostgreSQLDialect : VendorDialect(dialectName, PostgreSQLDataTypeProvider, PostgreSQLFunctionProvider) {
Expand Down