/
EntityGrouping.kt
430 lines (398 loc) · 19.8 KB
/
EntityGrouping.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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
/*
* Copyright 2018-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ktorm.entity
import org.ktorm.dsl.*
import org.ktorm.schema.BaseTable
import org.ktorm.schema.ColumnDeclaring
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.LinkedHashMap
import kotlin.experimental.ExperimentalTypeInference
/**
* Wraps an [EntitySequence] with a [keySelector] function, which can be applied to each record to get its key,
* or used as the `group by` clause of the generated SQL.
*
* An [EntityGrouping] structure serves as an intermediate step in group-and-fold operations: they group elements
* by their keys and then fold each group with some aggregation operation.
*
* Entity groups are created by attaching `keySelector: (T) -> ColumnDeclaring<K>` function to an entity sequence.
* To get an instance of [EntityGrouping], use the extension function [EntitySequence.groupingBy].
*
* For the list of group-and-fold operations available, see the extension functions below.
*
* @property sequence the source entity sequence of this grouping.
* @property keySelector a function used to extract the key of a record in the source table.
*/
public class EntityGrouping<E : Any, T : BaseTable<E>, K : Any>(
public val sequence: EntitySequence<E, T>,
public val keySelector: (T) -> ColumnDeclaring<K>
) {
/**
* Create a [kotlin.collections.Grouping] instance that wraps this original entity grouping returning all the
* elements in the source sequence when being iterated.
*/
public fun asKotlinGrouping(): Grouping<E, K?> = object : Grouping<E, K?> {
private val allEntities = ArrayList<E>()
private val allEntitiesWithKeys = IdentityHashMap<E, K?>()
init {
val keyColumn = keySelector(sequence.sourceTable)
val expr = sequence.expression.copy(
columns = sequence.expression.columns + keyColumn.aliased("_group_key")
)
for (row in Query(sequence.database, expr)) {
val entity = sequence.sourceTable.createEntity(row)
val groupKey = keyColumn.sqlType.getResult(row, expr.columns.size)
allEntities += entity
allEntitiesWithKeys[entity] = groupKey
}
}
override fun sourceIterator(): Iterator<E> {
return allEntities.iterator()
}
override fun keyOf(element: E): K? {
return allEntitiesWithKeys[element]
}
}
}
/**
* Group elements from the source sequence by key and perform the given aggregation for elements in each group,
* then store the results in a new [Map].
*
* The key for each group is provided by the [EntityGrouping.keySelector] function, and the generated SQL is like:
* `select key, aggregation from source group by key`.
*
* Ktorm also supports aggregating two or more columns, we just need to wrap our aggregate expressions by [tupleOf]
* in the closure, then the function’s return type becomes `Map<K?, TupleN<C1?, C2?, .. Cn?>>`.
*
* @param aggregationSelector a function that accepts the source table and returns the aggregate expression.
* @return a [Map] associating the key of each group with the result of aggregation of the group elements.
*/
@OptIn(ExperimentalTypeInference::class)
@OverloadResolutionByLambdaReturnType
public inline fun <E : Any, T : BaseTable<E>, K, C> EntityGrouping<E, T, K>.aggregateColumns(
aggregationSelector: (T) -> ColumnDeclaring<C>
): Map<K?, C?> where K : Any, C : Any {
return aggregateColumnsTo(LinkedHashMap(), aggregationSelector)
}
/**
* Group elements from the source sequence by key and perform the given aggregation for elements in each group,
* then store the results in the [destination] map.
*
* The key for each group is provided by the [EntityGrouping.keySelector] function, and the generated SQL is like:
* `select key, aggregation from source group by key`.
*
* Ktorm also supports aggregating two or more columns, we just need to wrap our aggregate expressions by [tupleOf]
* in the closure, then the function’s return type becomes `Map<K?, TupleN<C1?, C2?, .. Cn?>>`.
*
* @param destination a [MutableMap] used to store the results.
* @param aggregationSelector a function that accepts the source table and returns the aggregate expression.
* @return the [destination] map associating the key of each group with the result of aggregation of the group elements.
*/
@OptIn(ExperimentalTypeInference::class)
@OverloadResolutionByLambdaReturnType
public inline fun <E : Any, T : BaseTable<E>, K, C, M> EntityGrouping<E, T, K>.aggregateColumnsTo(
destination: M,
aggregationSelector: (T) -> ColumnDeclaring<C>
): M where K : Any, C : Any, M : MutableMap<in K?, in C?> {
val keyColumn = keySelector(sequence.sourceTable)
val aggregation = aggregationSelector(sequence.sourceTable)
val expr = sequence.expression.copy(
columns = listOf(keyColumn, aggregation).map { it.aliased(null) },
groupBy = listOf(keyColumn.asExpression())
)
for (row in Query(sequence.database, expr)) {
val key = keyColumn.sqlType.getResult(row, 1)
val value = aggregation.sqlType.getResult(row, 2)
destination[key] = value
}
return destination
}
/**
* Group elements from the source sequence by key and count elements in each group.
*
* The key for each group is provided by the [EntityGrouping.keySelector] function, and the generated SQL is like:
* `select key, count(*) from source group by key`.
*
* @return a [Map] associating the key of each group with the count of elements in the group.
*/
public fun <E : Any, T : BaseTable<E>, K> EntityGrouping<E, T, K>.eachCount(): Map<K?, Int> where K : Any {
return eachCountTo(LinkedHashMap())
}
/**
* Group elements from the source sequence by key and count elements in each group,
* then store the results in the [destination] map.
*
* The key for each group is provided by the [EntityGrouping.keySelector] function, and the generated SQL is like:
* `select key, count(*) from source group by key`.
*
* @param destination a [MutableMap] used to store the results.
* @return the [destination] map associating the key of each group with the count of elements in the group.
*/
@Suppress("UNCHECKED_CAST")
public fun <E : Any, T : BaseTable<E>, K, M> EntityGrouping<E, T, K>.eachCountTo(
destination: M
): M where K : Any, M : MutableMap<in K?, Int> {
return aggregateColumnsTo(destination as MutableMap<in K?, Int?>) { count() } as M
}
/**
* Group elements from the source sequence by key and sum the columns or expressions provided by the [columnSelector]
* function for elements in each group.
*
* The key for each group is provided by the [EntityGrouping.keySelector] function, and the generated SQL is like:
* `select key, sum(column) from source group by key`.
*
* @param columnSelector a function that accepts the source table and returns the column or expression for summing.
* @return a [Map] associating the key of each group with the summing result in the group.
*/
public inline fun <E : Any, T : BaseTable<E>, K, C> EntityGrouping<E, T, K>.eachSumBy(
columnSelector: (T) -> ColumnDeclaring<C>
): Map<K?, C?> where K : Any, C : Number {
return eachSumByTo(LinkedHashMap(), columnSelector)
}
/**
* Group elements from the source sequence by key and sum the columns or expressions provided by the [columnSelector]
* function for elements in each group, then store the results in the [destination] map.
*
* The key for each group is provided by the [EntityGrouping.keySelector] function, and the generated SQL is like:
* `select key, sum(column) from source group by key`.
*
* @param destination a [MutableMap] used to store the results.
* @param columnSelector a function that accepts the source table and returns the column or expression for summing.
* @return the [destination] map associating the key of each group with the summing result in the group.
*/
public inline fun <E : Any, T : BaseTable<E>, K, C, M> EntityGrouping<E, T, K>.eachSumByTo(
destination: M,
columnSelector: (T) -> ColumnDeclaring<C>
): M where K : Any, C : Number, M : MutableMap<in K?, in C?> {
return aggregateColumnsTo(destination) { sum(columnSelector(it)) }
}
/**
* Group elements from the source sequence by key and get the max value of the columns or expressions provided by the
* [columnSelector] function for elements in each group.
*
* The key for each group is provided by the [EntityGrouping.keySelector] function, and the generated SQL is like:
* `select key, max(column) from source group by key`.
*
* @param columnSelector a function that accepts the source table and returns a column or expression.
* @return a [Map] associating the key of each group with the max value in the group.
*/
public inline fun <E : Any, T : BaseTable<E>, K, C> EntityGrouping<E, T, K>.eachMaxBy(
columnSelector: (T) -> ColumnDeclaring<C>
): Map<K?, C?> where K : Any, C : Comparable<C> {
return eachMaxByTo(LinkedHashMap(), columnSelector)
}
/**
* Group elements from the source sequence by key and get the max value of the columns or expressions provided by the
* [columnSelector] function for elements in each group, then store the results in the [destination] map.
*
* The key for each group is provided by the [EntityGrouping.keySelector] function, and the generated SQL is like:
* `select key, max(column) from source group by key`.
*
* @param destination a [MutableMap] used to store the results.
* @param columnSelector a function that accepts the source table and returns a column or expression.
* @return a [destination] map associating the key of each group with the max value in the group.
*/
public inline fun <E : Any, T : BaseTable<E>, K, C, M> EntityGrouping<E, T, K>.eachMaxByTo(
destination: M,
columnSelector: (T) -> ColumnDeclaring<C>
): M where K : Any, C : Comparable<C>, M : MutableMap<in K?, in C?> {
return aggregateColumnsTo(destination) { max(columnSelector(it)) }
}
/**
* Group elements from the source sequence by key and get the min value of the columns or expressions provided by the
* [columnSelector] function for elements in each group.
*
* The key for each group is provided by the [EntityGrouping.keySelector] function, and the generated SQL is like:
* `select key, min(column) from source group by key`.
*
* @param columnSelector a function that accepts the source table and returns a column or expression.
* @return a [Map] associating the key of each group with the min value in the group.
*/
public inline fun <E : Any, T : BaseTable<E>, K, C> EntityGrouping<E, T, K>.eachMinBy(
columnSelector: (T) -> ColumnDeclaring<C>
): Map<K?, C?> where K : Any, C : Comparable<C> {
return eachMinByTo(LinkedHashMap(), columnSelector)
}
/**
* Group elements from the source sequence by key and get the min value of the columns or expressions provided by the
* [columnSelector] function for elements in each group, then store the results in the [destination] map.
*
* The key for each group is provided by the [EntityGrouping.keySelector] function, and the generated SQL is like:
* `select key, min(column) from source group by key`.
*
* @param destination a [MutableMap] used to store the results.
* @param columnSelector a function that accepts the source table and returns a column or expression.
* @return a [destination] map associating the key of each group with the min value in the group.
*/
public inline fun <E : Any, T : BaseTable<E>, K, C, M> EntityGrouping<E, T, K>.eachMinByTo(
destination: M,
columnSelector: (T) -> ColumnDeclaring<C>
): M where K : Any, C : Comparable<C>, M : MutableMap<in K?, in C?> {
return aggregateColumnsTo(destination) { min(columnSelector(it)) }
}
/**
* Group elements from the source sequence by key and average the columns or expressions provided by the
* [columnSelector] function for elements in each group.
*
* The key for each group is provided by the [EntityGrouping.keySelector] function, and the generated SQL is like:
* `select key, avg(column) from source group by key`.
*
* @param columnSelector a function that accepts the source table and returns the column or expression for averaging.
* @return a [Map] associating the key of each group with the averaging result in the group.
*/
public inline fun <E : Any, T : BaseTable<E>, K> EntityGrouping<E, T, K>.eachAverageBy(
columnSelector: (T) -> ColumnDeclaring<out Number>
): Map<K?, Double?> where K : Any {
return eachAverageByTo(LinkedHashMap(), columnSelector)
}
/**
* Group elements from the source sequence by key and average the columns or expressions provided by the
* [columnSelector] function for elements in each group, then store the results in the [destination] map.
*
* The key for each group is provided by the [EntityGrouping.keySelector] function, and the generated SQL is like:
* `select key, avg(column) from source group by key`.
*
* @param destination a [MutableMap] used to store the results.
* @param columnSelector a function that accepts the source table and returns the column or expression for averaging.
* @return the [destination] map associating the key of each group with the averaging result in the group.
*/
public inline fun <E : Any, T : BaseTable<E>, K, M> EntityGrouping<E, T, K>.eachAverageByTo(
destination: M,
columnSelector: (T) -> ColumnDeclaring<out Number>
): M where K : Any, M : MutableMap<in K?, in Double?> {
return aggregateColumnsTo(destination) { avg(columnSelector(it)) }
}
/**
* Groups elements from the source sequence by key and applies [operation] to the elements of each group sequentially,
* passing the previously accumulated value and the current element as arguments, and stores the results in a new map.
*
* This function is delegated to [Grouping.aggregate], more details can be found in its documentation.
*/
public inline fun <E : Any, K : Any, R> EntityGrouping<E, *, K>.aggregate(
operation: (key: K?, accumulator: R?, element: E, first: Boolean) -> R
): Map<K?, R> {
return aggregateTo(LinkedHashMap(), operation)
}
/**
* Groups elements from the source sequence by key and applies [operation] to the elements of each group sequentially,
* passing the previously accumulated value and the current element as arguments, and stores the results in the given
* [destination] map.
*
* This function is delegated to [Grouping.aggregateTo], more details can be found in its documentation.
*/
public inline fun <E : Any, K : Any, R, M : MutableMap<in K?, R>> EntityGrouping<E, *, K>.aggregateTo(
destination: M,
operation: (key: K?, accumulator: R?, element: E, first: Boolean) -> R
): M {
val grouping = asKotlinGrouping()
for (element in grouping.sourceIterator()) {
val key = grouping.keyOf(element)
val accumulator = destination[key]
destination[key] = operation(key, accumulator, element, accumulator == null && !destination.containsKey(key))
}
return destination
}
/**
* Groups elements from the source sequence by key and applies [operation] to the elements of each group sequentially,
* passing the previously accumulated value and the current element as arguments, and stores the results in a new map.
* An initial value of accumulator is provided by [initialValueSelector] function.
*
* This function is delegated to [Grouping.fold], more details can be found in its documentation.
*/
public inline fun <E : Any, K : Any, R> EntityGrouping<E, *, K>.fold(
initialValueSelector: (key: K?, element: E) -> R,
operation: (key: K?, accumulator: R, element: E) -> R
): Map<K?, R> {
return foldTo(LinkedHashMap(), initialValueSelector, operation)
}
/**
* Groups elements from the source sequence by key and applies [operation] to the elements of each group sequentially,
* passing the previously accumulated value and the current element as arguments, and stores the results in the given
* [destination] map. An initial value of accumulator is provided by [initialValueSelector] function.
*
* This function is delegated to [Grouping.foldTo], more details can be found in its documentation.
*/
@Suppress("UNCHECKED_CAST")
public inline fun <E : Any, K : Any, R, M : MutableMap<in K?, R>> EntityGrouping<E, *, K>.foldTo(
destination: M,
initialValueSelector: (key: K?, element: E) -> R,
operation: (key: K?, accumulator: R, element: E) -> R
): M {
return aggregateTo(destination) { key, accumulator, element, first ->
val acc = if (first) initialValueSelector(key, element) else accumulator as R
operation(key, acc, element)
}
}
/**
* Groups elements from the source sequence by key and applies [operation] to the elements of each group sequentially,
* passing the previously accumulated value and the current element as arguments, and stores the results in a new map.
* An initial value of accumulator is the same [initialValue] for each group.
*
* This function is delegated to [Grouping.fold], more details can be found in its documentation.
*/
public inline fun <E : Any, K : Any, R> EntityGrouping<E, *, K>.fold(
initialValue: R,
operation: (accumulator: R, element: E) -> R
): Map<K?, R> {
return foldTo(LinkedHashMap(), initialValue, operation)
}
/**
* Groups elements from the source sequence by key and applies [operation] to the elements of each group sequentially,
* passing the previously accumulated value and the current element as arguments, and stores the results in the given
* [destination] map. An initial value of accumulator is the same [initialValue] for each group.
*
* This function is delegated to [Grouping.foldTo], more details can be found in its documentation.
*/
@Suppress("UNCHECKED_CAST")
public inline fun <E : Any, K : Any, R, M : MutableMap<in K?, R>> EntityGrouping<E, *, K>.foldTo(
destination: M,
initialValue: R,
operation: (accumulator: R, element: E) -> R
): M {
return aggregateTo(destination) { _, accumulator, element, first ->
val acc = if (first) initialValue else accumulator as R
operation(acc, element)
}
}
/**
* Groups elements from the source sequence by key and applies the reducing [operation] to the elements of each group
* sequentially starting from the second element of the group, passing the previously accumulated value and the current
* element as arguments, and stores the results in a new map. An initial value of accumulator is the first element of
* the group.
*
* This function is delegated to [Grouping.reduce], more details can be found in its documentation.
*/
public inline fun <E : Any, K : Any> EntityGrouping<E, *, K>.reduce(
operation: (key: K?, accumulator: E, element: E) -> E
): Map<K?, E> {
return reduceTo(LinkedHashMap(), operation)
}
/**
* Groups elements from the source sequence by key and applies the reducing [operation] to the elements of each group
* sequentially starting from the second element of the group, passing the previously accumulated value and the current
* element as arguments, and stores the results in the given [destination] map. An initial value of accumulator is the
* first element of the group.
*
* This function is delegated to [Grouping.reduceTo], more details can be found in its documentation.
*/
public inline fun <E : Any, K : Any, M : MutableMap<in K?, E>> EntityGrouping<E, *, K>.reduceTo(
destination: M,
operation: (key: K?, accumulator: E, element: E) -> E
): M {
return aggregateTo(destination) { key, accumulator, element, first ->
if (first) element else operation(key, accumulator as E, element)
}
}