-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathExpression.swift
319 lines (279 loc) · 9.15 KB
/
Expression.swift
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
import Foundation
import ReactiveSwift
import Schemata
/// A type-erased expression.
///
/// This represents the expressions representable in PersistDB. As such, this is a less general, but
/// more semantically meaningful, representation than `SQL.Expression`.
///
/// `AnyExpression`s can also generate new values, e.g. UUIDs, which are expressed as values in SQL.
/// These values are expressed as values within `AnyExpression`, but the act of generating the
/// corresponding `SQL.Expression` causes it to generate any such values.
internal indirect enum AnyExpression: Hashable {
internal enum UnaryOperator: String, Hashable {
case not
}
internal enum BinaryOperator: String, Hashable {
case and
case equal
case greaterThan
case greaterThanOrEqual
case lessThan
case lessThanOrEqual
case notEqual
case or
}
internal enum Function: Hashable {
case coalesce
case count
case length
case max
case min
}
case binary(BinaryOperator, AnyExpression, AnyExpression)
case function(Function, [AnyExpression])
case inList(AnyExpression, Set<AnyExpression>)
case keyPath([AnyProperty])
case now
case unary(UnaryOperator, AnyExpression)
case value(SQL.Value)
}
extension AnyExpression.UnaryOperator {
var sql: SQL.UnaryOperator {
switch self {
case .not:
return .not
}
}
}
extension AnyExpression.BinaryOperator {
var sql: SQL.BinaryOperator {
switch self {
case .and:
return .and
case .equal:
return .equal
case .greaterThan:
return .greaterThan
case .greaterThanOrEqual:
return .greaterThanOrEqual
case .lessThan:
return .lessThan
case .lessThanOrEqual:
return .lessThanOrEqual
case .notEqual:
return .notEqual
case .or:
return .or
}
}
}
extension AnyExpression {
init<Model: PersistDB.Model>(_ keyPath: PartialKeyPath<Model>) {
self = .keyPath(Model.anySchema.properties(for: keyPath))
}
init<V: ModelValue>(_ value: V) {
self = .value(V.anyValue.encode(value).sql)
}
init<V: ModelValue>(_ value: V?) {
self = .value(value.map(V.anyValue.encode)?.sql ?? .null)
}
}
extension AnyExpression.Function {
fileprivate var sql: SQL.Function {
switch self {
case .coalesce:
return .coalesce
case .count:
return .count
case .length:
return .length
case .max:
return .max
case .min:
return .min
}
}
}
extension SQL {
fileprivate static var now: SQL.Expression {
let seconds = SQL.Expression.function(
.strftime, [
.value(.text("%s")),
.value(.text("now")),
]
)
let subseconds = SQL.Expression.function(
.substr, [
.function(
.strftime, [
.value(.text("%f")),
.value(.text("now")),
]
),
.value(.integer(4)),
]
)
return .cast(
.binary(
.concatenate,
.binary(
.subtract,
seconds,
.value(.integer(Int(Date.timeIntervalBetween1970AndReferenceDate)))
),
.binary(
.concatenate,
.value(.text(".")),
subseconds
)
),
.real
)
}
}
private func makeSQL(for properties: [AnyProperty]) -> SQL.Expression {
func column(for property: AnyProperty) -> SQL.Column {
return SQL.Table(String(describing: property.model))[property.path]
}
var value: SQL.Expression = .column(column(for: properties.last!))
for property in properties.reversed().dropFirst() {
switch property.type {
case .toMany:
fatalError("Can't traverse to-many properties")
case let .toOne(model, _):
let rhs = SQL.Column(
table: SQL.Table(String(describing: model)),
name: "id"
)
value = .join(column(for: property), rhs, value)
case .value:
fatalError("Invalid scalar property in the middle of a KeyPath")
}
}
return value
}
extension AnyExpression {
var sql: SQL.Expression {
switch self {
case let .binary(.equal, .value(.null), rhs):
return .binary(.is, rhs.sql, .value(.null))
case let .binary(.equal, lhs, .value(.null)):
return .binary(.is, lhs.sql, .value(.null))
case let .binary(.notEqual, .value(.null), rhs):
return .binary(.isNot, rhs.sql, .value(.null))
case let .binary(.notEqual, lhs, .value(.null)):
return .binary(.isNot, lhs.sql, .value(.null))
case let .binary(op, lhs, rhs):
return .binary(op.sql, lhs.sql, rhs.sql)
case let .function(function, args):
return .function(function.sql, args.map { $0.sql })
case let .inList(expr, list):
return .inList(expr.sql, Set(list.map { $0.sql }))
case let .keyPath(properties):
return makeSQL(for: properties)
case .now:
return SQL.now
case let .unary(op, expr):
return .unary(op.sql, expr.sql)
case let .value(value):
return .value(value)
}
}
}
/// An expression that can be used in `Predicate`s, `Ordering`s, etc.
public struct Expression<Model, Value>: Hashable {
internal let expression: AnyExpression
internal init(_ expression: AnyExpression) {
self.expression = expression
}
}
extension Expression where Model: PersistDB.Model {
/// Create an expression from a keypath.
public init(_ keyPath: KeyPath<Model, Value>) {
expression = AnyExpression(keyPath)
}
}
extension Expression where Model == None, Value == Date {
/// An expression that evaluates to the current datetime.
public static var now: Expression {
return Expression(.now)
}
}
extension Expression where Model == None, Value: ModelValue {
public init(_ value: Value) {
expression = .value(Value.anyValue.encode(value).sql)
}
}
extension Expression where Model == None, Value: OptionalProtocol, Value.Wrapped: ModelValue {
public init(_ value: Value?) {
expression = .value(value.map(Value.Wrapped.anyValue.encode)?.sql ?? .null)
}
}
extension Expression where Value == String {
/// The number of characters in the string prior to the first null character.
public var count: Expression<Model, Int> {
return Expression<Model, Int>(.function(.length, [ expression ]))
}
}
// MARK: - Operators
internal func == (lhs: AnyExpression, rhs: AnyExpression) -> AnyExpression {
return .binary(.equal, lhs, rhs)
}
internal func != (lhs: AnyExpression, rhs: AnyExpression) -> AnyExpression {
return .binary(.notEqual, lhs, rhs)
}
internal func && (lhs: AnyExpression, rhs: AnyExpression) -> AnyExpression {
return .binary(.and, lhs, rhs)
}
internal func || (lhs: AnyExpression, rhs: AnyExpression) -> AnyExpression {
return .binary(.or, lhs, rhs)
}
internal prefix func ! (expression: AnyExpression) -> AnyExpression {
return .unary(.not, expression)
}
internal func < (lhs: AnyExpression, rhs: AnyExpression) -> AnyExpression {
return .binary(.lessThan, lhs, rhs)
}
internal func > (lhs: AnyExpression, rhs: AnyExpression) -> AnyExpression {
return .binary(.greaterThan, lhs, rhs)
}
internal func <= (lhs: AnyExpression, rhs: AnyExpression) -> AnyExpression {
return .binary(.lessThanOrEqual, lhs, rhs)
}
internal func >= (lhs: AnyExpression, rhs: AnyExpression) -> AnyExpression {
return .binary(.greaterThanOrEqual, lhs, rhs)
}
// MARK: - Aggregates
internal func max(_ expressions: [AnyExpression]) -> AnyExpression {
return .function(.max, expressions)
}
internal func max(_ expressions: AnyExpression...) -> AnyExpression {
return max(expressions)
}
internal func min(_ expressions: [AnyExpression]) -> AnyExpression {
return .function(.min, expressions)
}
internal func min(_ expressions: AnyExpression...) -> AnyExpression {
return min(expressions)
}
// MARK: - Collections
extension Collection where Iterator.Element: ModelValue {
/// An expression that tests whether the list contains the value of an
/// expression.
internal func contains(_ expression: AnyExpression) -> AnyExpression {
return .inList(expression, Set(map(AnyExpression.init)))
}
}
// MARK: - Functions
/// Evaluates to the first non-NULL argument, or NULL if all argumnets are NULL.
public func coalesce<Model: PersistDB.Model, Value>(
_ a: KeyPath<Model, Value?>,
_ b: KeyPath<Model, Value?>,
_ rest: KeyPath<Model, Value?>...
) -> Expression<Model, Value?> {
let args = ([a, b] + rest)
.map(Model.anySchema.properties(for:))
.map(AnyExpression.keyPath)
return Expression(.function(.coalesce, args))
}