/
InsertStatement.kt
222 lines (196 loc) · 9.41 KB
/
InsertStatement.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
package org.jetbrains.exposed.sql.statements
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.statements.api.PreparedStatementApi
import org.jetbrains.exposed.sql.vendors.*
import org.jetbrains.exposed.sql.vendors.inProperCase
import java.sql.ResultSet
import java.sql.SQLException
import kotlin.properties.Delegates
/**
* Represents the SQL statement that inserts a new row into a table.
*
* @param table Table to insert the new row into.
* @param isIgnore Whether to ignore errors or not.
* **Note** [isIgnore] is not supported by all vendors. Please check the documentation.
*/
open class InsertStatement<Key : Any>(
val table: Table,
val isIgnore: Boolean = false
) : UpdateBuilder<Int>(StatementType.INSERT, listOf(table)) {
/**
* The number of rows affected by the insert operation.
*
* When returned by a `BatchInsertStatement` or `BatchUpsertStatement`, the returned value is calculated using the
* sum of the individual values generated by each statement.
*
* **Note**: Some vendors support returning the affected-row value of 2 if an existing row is updated by an upsert
* operation; please check the documentation.
*/
var insertedCount: Int by Delegates.notNull()
/** The [ResultRow]s generated by processing the database result set retrieved after executing the statement. */
var resultedValues: List<ResultRow>? = null
private set
infix operator fun <T> get(column: Column<T>): T {
val row = resultedValues?.firstOrNull() ?: error("No key generated")
return row[column]
}
infix operator fun <T> get(column: CompositeColumn<T>): T {
val row = resultedValues?.firstOrNull() ?: error("No key generated")
return row[column]
}
/**
* Returns the value of a given [column] from the first stored [ResultRow], or `null` if either no results were
* retrieved from the database or if the column cannot be found in the row.
*/
fun <T> getOrNull(column: Column<T>): T? = resultedValues?.firstOrNull()?.getOrNull(column)
@Suppress("NestedBlockDepth", "ComplexMethod")
private fun processResults(rs: ResultSet?, inserted: Int): List<ResultRow> {
val autoGeneratedKeys = arrayListOf<MutableMap<Column<*>, Any?>>()
if (inserted > 0) {
val returnedColumns = (if (currentDialect.supportsOnlyIdentifiersInGeneratedKeys) autoIncColumns else table.columns).mapNotNull { col ->
@Suppress("SwallowedException")
try {
rs?.findColumn(col.name)?.let { col to it }
} catch (e: SQLException) {
null
}
}
val firstAutoIncColumn = autoIncColumns.firstOrNull { it.autoIncColumnType != null } ?: autoIncColumns.firstOrNull()
if (firstAutoIncColumn != null || returnedColumns.isNotEmpty()) {
while (rs?.next() == true) {
val returnedValues = returnedColumns.associateTo(mutableMapOf()) { it.first to rs.getObject(it.second) }
if (returnedValues.isEmpty() && firstAutoIncColumn != null) returnedValues[firstAutoIncColumn] = rs.getObject(1)
autoGeneratedKeys.add(returnedValues)
}
if (inserted > 1 && firstAutoIncColumn != null && autoGeneratedKeys.isNotEmpty() && !currentDialect.supportsMultipleGeneratedKeys) {
// H2/SQLite only returns one last generated key...
(autoGeneratedKeys[0][firstAutoIncColumn] as? Number)?.toLong()?.let {
var id = it
while (autoGeneratedKeys.size < inserted) {
id -= 1
autoGeneratedKeys.add(0, mutableMapOf(firstAutoIncColumn to id))
}
}
}
assert(
isIgnore || autoGeneratedKeys.isEmpty() || autoGeneratedKeys.size == inserted ||
currentDialect.supportsTernaryAffectedRowValues
) {
"Number of autoincs (${autoGeneratedKeys.size}) doesn't match number of batch entries ($inserted)"
}
}
}
arguments!!.forEachIndexed { itemIndx, pairs ->
val map = autoGeneratedKeys.getOrNull(itemIndx) ?: hashMapOf<Column<*>, Any?>().apply {
autoGeneratedKeys.add(itemIndx, this)
}
pairs.forEach { (col, value) ->
if (value != DefaultValueMarker) {
if (isColumnValuePreferredFromResultSet(col, value)) {
map.getOrPut(col) { value }
} else {
map[col] = value
}
}
}
}
@Suppress("UNCHECKED_CAST")
return autoGeneratedKeys.map { ResultRow.createAndFillValues(it as Map<Expression<*>, Any?>) }
}
protected open fun isColumnValuePreferredFromResultSet(column: Column<*>, value: Any?): Boolean {
return column.columnType.isAutoInc || value is NextVal<*>
}
@Suppress("NestedBlockDepth")
protected open fun valuesAndDefaults(values: Map<Column<*>, Any?> = this.values): Map<Column<*>, Any?> {
val result = values.toMutableMap()
targets.forEach { table ->
table.columns.forEach { column ->
if ((column.dbDefaultValue != null || column.defaultValueFun != null) && column !in values.keys) {
val value = when {
column.defaultValueFun != null -> column.defaultValueFun!!()
else -> DefaultValueMarker
}
result[column] = value
}
}
}
return result
}
override fun prepareSQL(transaction: Transaction, prepared: Boolean): String {
val values = arguments!!.first()
val sql = values.toSqlString(prepared)
return transaction.db.dialect.functionProvider
.insert(isIgnore, table, values.map { it.first }, sql, transaction)
}
protected fun List<Pair<Column<*>, Any?>>.toSqlString(prepared: Boolean): String {
val builder = QueryBuilder(prepared)
return if (isEmpty()) {
""
} else {
with(builder) {
this@toSqlString.appendTo(prefix = "VALUES (", postfix = ")") { (column, value) ->
registerArgument(column, value)
}
toString()
}
}
}
protected open fun PreparedStatementApi.execInsertFunction(): Pair<Int, ResultSet?> {
val inserted = if (arguments().count() > 1 || isAlwaysBatch) executeBatch().sum() else executeUpdate()
val rs = if (autoIncColumns.isNotEmpty()) {
resultSet
} else {
null
}
return inserted to rs
}
override fun PreparedStatementApi.executeInternal(transaction: Transaction): Int {
val (inserted, rs) = execInsertFunction()
return inserted.apply {
insertedCount = this
resultedValues = processResults(rs, this)
}
}
protected val autoIncColumns: List<Column<*>>
get() {
val nextValExpressionColumns = values.filterValues { it is NextVal<*> }.keys
return targets.flatMap { it.columns }.filter { column ->
when {
column.autoIncColumnType?.nextValExpression != null -> currentDialect.supportsSequenceAsGeneratedKeys
column.columnType.isAutoInc -> true
column in nextValExpressionColumns -> currentDialect.supportsSequenceAsGeneratedKeys
column.columnType is EntityIDColumnType<*> -> !currentDialect.supportsOnlyIdentifiersInGeneratedKeys
else -> false
}
}
}
override fun prepared(transaction: Transaction, sql: String): PreparedStatementApi = when {
// https://github.com/pgjdbc/pgjdbc/issues/1168
// Column names always escaped/quoted in RETURNING clause
autoIncColumns.isNotEmpty() && currentDialect is PostgreSQLDialect ->
transaction.connection.prepareStatement(sql, true)
autoIncColumns.isNotEmpty() ->
// http://viralpatel.net/blogs/oracle-java-jdbc-get-primary-key-insert-sql/
transaction.connection.prepareStatement(sql, autoIncColumns.map { it.name.inProperCase() }.toTypedArray())
else -> transaction.connection.prepareStatement(sql, false)
}
protected open var arguments: List<List<Pair<Column<*>, Any?>>>? = null
get() = field ?: run {
val nullableColumns = table.columns.filter { it.columnType.nullable && !it.isDatabaseGenerated }
val valuesAndDefaults = valuesAndDefaults() as MutableMap
valuesAndDefaults.putAll((nullableColumns - valuesAndDefaults.keys).associateWith { null })
val result = valuesAndDefaults.toList().sortedBy { it.first }
listOf(result).apply { field = this }
}
override fun arguments(): List<Iterable<Pair<IColumnType<*>, Any?>>> {
return arguments?.map { args ->
val builder = QueryBuilder(true)
args.filter { (_, value) ->
value != DefaultValueMarker
}.forEach { (column, value) ->
builder.registerArgument(column, value)
}
builder.args
} ?: emptyList()
}
}