forked from kotlin-orm/ktorm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate-tuples.gradle
235 lines (202 loc) · 10.3 KB
/
generate-tuples.gradle
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
def generatedSourceDir = "${project.buildDir.absolutePath}/generated/source/main/kotlin"
def maxTupleNumber = 9
def generateTuple(Writer writer, int tupleNumber) {
def typeParams = (1..tupleNumber).collect { "out E$it" }.join(", ")
def propertyDefinitions = (1..tupleNumber).collect { "val element$it: E$it" }.join(",\n ")
def toStringTemplate = (1..tupleNumber).collect { "\$element$it" }.join(", ")
writer.write("""
/**
* Represents a tuple of $tupleNumber values.
*
* There is no meaning attached to values in this class, it can be used for any purpose.
* Two tuples are equal if all the components are equal.
*/
data class Tuple$tupleNumber<$typeParams>(
$propertyDefinitions
) : Serializable {
override fun toString(): String {
return \"($toStringTemplate)\"
}
}
""".stripIndent())
}
def generateMapColumns(Writer writer, int tupleNumber) {
def typeParams = (1..tupleNumber).collect { "C$it : Any" }.join(", ")
def columnDeclarings = (1..tupleNumber).collect { "ColumnDeclaring<C$it>" }.join(", ")
def resultTypes = (1..tupleNumber).collect { "C$it?" }.join(", ")
def variableNames = (1..tupleNumber).collect { "c$it" }.join(", ")
def resultExtractors = (1..tupleNumber).collect { "c${it}.sqlType.getResult(row, $it)" }.join(", ")
writer.write("""
/**
* Customize the selected columns of the internal query by the given [columnSelector] function, and return a [List]
* containing the query results.
*
* See [EntitySequence.mapColumns] for more details.
*
* The operation is terminal.
*
* @param isDistinct specify if the query is distinct, the generated SQL becomes `select distinct` if it's set to true.
* @param columnSelector a function in which we should return a tuple of columns or expressions to be selected.
* @return a list of the query results.
*/
inline fun <E : Entity<E>, T : Table<E>, $typeParams> EntitySequence<E, T>.mapColumns$tupleNumber(
isDistinct: Boolean = false,
columnSelector: (T) -> Tuple$tupleNumber<$columnDeclarings>
): List<Tuple$tupleNumber<$resultTypes>> {
return mapColumns${tupleNumber}To(ArrayList(), isDistinct, columnSelector)
}
/**
* Customize the selected columns of the internal query by the given [columnSelector] function, and append the query
* results to the given [destination].
*
* See [EntitySequence.mapColumnsTo] for more details.
*
* The operation is terminal.
*
* @param destination a [MutableCollection] used to store the results.
* @param isDistinct specify if the query is distinct, the generated SQL becomes `select distinct` if it's set to true.
* @param columnSelector a function in which we should return a tuple of columns or expressions to be selected.
* @return the [destination] collection of the query results.
*/
inline fun <E : Entity<E>, T : Table<E>, $typeParams, R> EntitySequence<E, T>.mapColumns${tupleNumber}To(
destination: R,
isDistinct: Boolean = false,
columnSelector: (T) -> Tuple$tupleNumber<$columnDeclarings>
): R where R : MutableCollection<in Tuple$tupleNumber<$resultTypes>> {
val ($variableNames) = columnSelector(sourceTable)
val expr = expression.copy(
columns = listOf($variableNames).map { ColumnDeclaringExpression(it.asExpression()) },
isDistinct = isDistinct
)
return Query(expr).mapTo(destination) { row -> Tuple$tupleNumber($resultExtractors) }
}
""".stripIndent())
}
def generateAggregateColumns(Writer writer, int tupleNumber) {
def typeParams = (1..tupleNumber).collect { "C$it : Any" }.join(", ")
def columnDeclarings = (1..tupleNumber).collect { "ColumnDeclaring<C$it>" }.join(", ")
def resultTypes = (1..tupleNumber).collect { "C$it?" }.join(", ")
def variableNames = (1..tupleNumber).collect { "c$it" }.join(", ")
def resultExtractors = (1..tupleNumber).collect { "c${it}.sqlType.getResult(rowSet, $it)" }.join(", ")
writer.write("""
/**
* Perform a tuple of aggregations given by [aggregationSelector] for all elements in the sequence,
* and return the aggregate results.
*
* See [EntitySequence.aggregateColumns] for more details.
*
* The operation is terminal.
*
* @param aggregationSelector a function that accepts the source table and returns a tuple of aggregate expressions.
* @return a tuple of the aggregate results.
*/
inline fun <E : Entity<E>, T : Table<E>, $typeParams> EntitySequence<E, T>.aggregateColumns$tupleNumber(
aggregationSelector: (T) -> Tuple$tupleNumber<$columnDeclarings>
): Tuple$tupleNumber<$resultTypes> {
val ($variableNames) = aggregationSelector(sourceTable)
val expr = expression.copy(
columns = listOf($variableNames).map { ColumnDeclaringExpression(it.asExpression()) }
)
val rowSet = Query(expr).rowSet
if (rowSet.size() == 1) {
check(rowSet.next())
return Tuple$tupleNumber($resultExtractors)
} else {
val (sql, _) = Database.global.formatExpression(expr, beautifySql = true)
throw IllegalStateException("Expected 1 row but \${rowSet.size()} returned from sql: \\n\\n\$sql")
}
}
""".stripIndent())
}
def generateGroupingAggregateColumns(Writer writer, int tupleNumber) {
def typeParams = (1..tupleNumber).collect { "C$it : Any" }.join(", ")
def columnDeclarings = (1..tupleNumber).collect { "ColumnDeclaring<C$it>" }.join(", ")
def resultTypes = (1..tupleNumber).collect { "C$it?" }.join(", ")
def variableNames = (1..tupleNumber).collect { "c$it" }.join(", ")
def resultExtractors = (1..tupleNumber).collect { "c${it}.sqlType.getResult(row, ${it + 1})" }.join(", ")
writer.write("""
/**
* Group elements from the source sequence by key and perform the given aggregations for elements in each group,
* then store the results in a new [Map].
*
* See [EntityGrouping.aggregateColumns] for more details.
*
* @param aggregationSelector a function that accepts the source table and returns a tuple of aggregate expressions.
* @return a [Map] associating the key of each group with the results of aggregations of the group elements.
*/
inline fun <E : Entity<E>, T : Table<E>, K : Any, $typeParams> EntityGrouping<E, T, K>.aggregateColumns$tupleNumber(
aggregationSelector: (T) -> Tuple$tupleNumber<$columnDeclarings>
): Map<K?, Tuple$tupleNumber<$resultTypes>> {
return aggregateColumns${tupleNumber}To(LinkedHashMap(), aggregationSelector)
}
/**
* Group elements from the source sequence by key and perform the given aggregations for elements in each group,
* then store the results in the [destination] map.
*
* See [EntityGrouping.aggregateColumnsTo] for more details.
*
* @param destination a [MutableMap] used to store the results.
* @param aggregationSelector a function that accepts the source table and returns a tuple of aggregate expressions.
* @return the [destination] map associating the key of each group with the result of aggregations of the group elements.
*/
inline fun <E : Entity<E>, T : Table<E>, K : Any, $typeParams, M> EntityGrouping<E, T, K>.aggregateColumns${tupleNumber}To(
destination: M,
aggregationSelector: (T) -> Tuple$tupleNumber<$columnDeclarings>
): M where M : MutableMap<in K?, in Tuple$tupleNumber<$resultTypes>> {
val keyColumn = keySelector(sequence.sourceTable)
val ($variableNames) = aggregationSelector(sequence.sourceTable)
val expr = sequence.expression.copy(
columns = listOf(keyColumn, $variableNames).map { ColumnDeclaringExpression(it.asExpression()) },
groupBy = listOf(keyColumn.asExpression())
)
for (row in Query(expr)) {
val key = keyColumn.sqlType.getResult(row, 1)
destination[key] = Tuple$tupleNumber($resultExtractors)
}
return destination
}
""".stripIndent())
}
task generateTuples {
doLast {
def outputFile = file("$generatedSourceDir/me/liuwj/ktorm/entity/Tuples.kt")
outputFile.parentFile.mkdirs()
outputFile.withWriter { writer ->
writer.write(project.licenseHeaderText)
writer.write("""
// This file is auto-generated by generate-tuples.gradle, DO NOT EDIT!
package me.liuwj.ktorm.entity
import me.liuwj.ktorm.database.Database
import me.liuwj.ktorm.dsl.Query
import me.liuwj.ktorm.expression.ColumnDeclaringExpression
import me.liuwj.ktorm.schema.ColumnDeclaring
import me.liuwj.ktorm.schema.Table
import java.io.Serializable
/**
* Set a typealias `Tuple2` for `Pair`.
*/
typealias Tuple2<E1, E2> = Pair<E1, E2>
/**
* Set a typealias `Tuple3` for `Triple`.
*/
typealias Tuple3<E1, E2, E3> = Triple<E1, E2, E3>
""".stripIndent())
(4..maxTupleNumber).each { num ->
generateTuple(writer, num)
}
(2..maxTupleNumber).each { num ->
generateMapColumns(writer, num)
}
(2..maxTupleNumber).each { num ->
generateAggregateColumns(writer, num)
}
(2..maxTupleNumber).each { num ->
generateGroupingAggregateColumns(writer, num)
}
}
}
}
sourceSets {
main.kotlin.srcDirs += generatedSourceDir
}
compileKotlin.dependsOn(generateTuples)