|
1 | 1 | @_exported import StructuredQueriesCore |
| 2 | + |
| 3 | +// --- |
| 4 | +import Foundation |
| 5 | + |
| 6 | +// @CustomFunction // @DatabaseFunction ? @ScalarFunction (_vs._ @AggregateFunction?) |
| 7 | +func dateTime(_ format: String? = nil) -> Date { |
| 8 | + Date() |
| 9 | +} |
| 10 | + |
| 11 | +// Macro expansion: |
| 12 | +@available(macOS 14, *) |
| 13 | +@_disfavoredOverload // Or can/should this be applied the the above? |
| 14 | +func dateTime( |
| 15 | + _ format: some QueryExpression<String?> = String?.none |
| 16 | +) -> some QueryExpression<Date> { |
| 17 | + _$dateTime(format) |
| 18 | +} |
| 19 | + |
| 20 | +@available(macOS 14, *) |
| 21 | +var _$dateTime: CustomFunction<String?, Date> { |
| 22 | + CustomFunction("dateTime", isDeterministic: false, body: dateTime(_:)) |
| 23 | +} |
| 24 | +// --- |
| 25 | + |
| 26 | +import SQLite3 |
| 27 | + |
| 28 | +@available(macOS 14, *) |
| 29 | +struct CustomFunction<each Input, Output: QueryBindable> { |
| 30 | + let name: String |
| 31 | + let isDeterministic: Bool |
| 32 | +// private let body: Body |
| 33 | + |
| 34 | + init( |
| 35 | + _ name: String, |
| 36 | + isDeterministic: Bool, |
| 37 | + body: @escaping (repeat each Input) -> Output |
| 38 | + ) { |
| 39 | + self.name = name |
| 40 | + self.isDeterministic = isDeterministic |
| 41 | +// self.body = Body(body) |
| 42 | + } |
| 43 | + |
| 44 | + func callAsFunction<each T>(_ input: repeat each T) -> SQLQueryExpression<Output> |
| 45 | + where repeat each T: QueryExpression<each Input> { |
| 46 | + var arguments: [QueryFragment] = [] |
| 47 | + for input in repeat each input { |
| 48 | + arguments.append(input.queryFragment) |
| 49 | + } |
| 50 | + return SQLQueryExpression("\(quote: name)(\(arguments.joined(separator: ", "))") |
| 51 | + } |
| 52 | + |
| 53 | +// func install(_ db: OpaquePointer) { |
| 54 | +// // TODO: Should this be `-1`? |
| 55 | +// var count: Int32 = 0 |
| 56 | +// for _ in repeat (each Input).self { |
| 57 | +// count += 1 |
| 58 | +// } |
| 59 | +// let body = Unmanaged.passRetained(body).toOpaque() |
| 60 | +// sqlite3_create_function_v2( |
| 61 | +// db, |
| 62 | +// name, |
| 63 | +// count, |
| 64 | +// SQLITE_UTF8 | (isDeterministic ? SQLITE_DETERMINISTIC : 0), |
| 65 | +// body, |
| 66 | +// { ctx, argc, argv in |
| 67 | +//// let body = Unmanaged<Body> |
| 68 | +//// .fromOpaque(sqlite3_user_data(ctx)) |
| 69 | +//// .takeUnretainedValue() |
| 70 | +// }, |
| 71 | +// nil, |
| 72 | +// nil, |
| 73 | +// { ctx in |
| 74 | +//// Unmanaged<AnyObject>.fromOpaque(body).release() |
| 75 | +// } |
| 76 | +// ) |
| 77 | +// } |
| 78 | +} |
| 79 | + |
| 80 | + |
| 81 | +private final class Body { |
| 82 | + let body: ([Any]) -> Any |
| 83 | + init<each Input, Output: QueryBindable>(_ body: @escaping (repeat each Input) -> Output) { |
| 84 | + fatalError() |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | + |
0 commit comments