|
| 1 | +import Foundation |
| 2 | +#if SQLITE_SWIFT_STANDALONE |
| 3 | +import sqlite3 |
| 4 | +#elseif SQLITE_SWIFT_SQLCIPHER |
| 5 | +import SQLCipher |
| 6 | +#elseif os(Linux) |
| 7 | +import CSQLite |
| 8 | +#else |
| 9 | +import SQLite3 |
| 10 | +#endif |
| 11 | + |
| 12 | +extension Connection { |
| 13 | + private typealias Aggregate = @convention(block) (Int, Context, Int32, Argv) -> Void |
| 14 | + |
| 15 | + /// Creates or redefines a custom SQL aggregate. |
| 16 | + /// |
| 17 | + /// - Parameters: |
| 18 | + /// |
| 19 | + /// - aggregate: The name of the aggregate to create or redefine. |
| 20 | + /// |
| 21 | + /// - argumentCount: The number of arguments that the aggregate takes. If |
| 22 | + /// `nil`, the aggregate may take any number of arguments. |
| 23 | + /// |
| 24 | + /// Default: `nil` |
| 25 | + /// |
| 26 | + /// - deterministic: Whether or not the aggregate is deterministic (_i.e._ |
| 27 | + /// the aggregate always returns the same result for a given input). |
| 28 | + /// |
| 29 | + /// Default: `false` |
| 30 | + /// |
| 31 | + /// - step: A block of code to run for each row of an aggregation group. |
| 32 | + /// The block is called with an array of raw SQL values mapped to the |
| 33 | + /// aggregate’s parameters, and an UnsafeMutablePointer to a state |
| 34 | + /// variable. |
| 35 | + /// |
| 36 | + /// - final: A block of code to run after each row of an aggregation group |
| 37 | + /// is processed. The block is called with an UnsafeMutablePointer to a |
| 38 | + /// state variable, and should return a raw SQL value (or nil). |
| 39 | + /// |
| 40 | + /// - state: A block of code to run to produce a fresh state variable for |
| 41 | + /// each aggregation group. The block should return an |
| 42 | + /// UnsafeMutablePointer to the fresh state variable. |
| 43 | + public func createAggregation<T>( |
| 44 | + _ functionName: String, |
| 45 | + argumentCount: UInt? = nil, |
| 46 | + deterministic: Bool = false, |
| 47 | + step: @escaping ([Binding?], UnsafeMutablePointer<T>) -> Void, |
| 48 | + final: @escaping (UnsafeMutablePointer<T>) -> Binding?, |
| 49 | + state: @escaping () -> UnsafeMutablePointer<T>) { |
| 50 | + |
| 51 | + let argc = argumentCount.map { Int($0) } ?? -1 |
| 52 | + let box: Aggregate = { (stepFlag: Int, context: Context, argc: Int32, argv: Argv) in |
| 53 | + let nBytes = Int32(MemoryLayout<UnsafeMutablePointer<Int64>>.size) |
| 54 | + guard let aggregateContext = sqlite3_aggregate_context(context, nBytes) else { |
| 55 | + fatalError("Could not get aggregate context") |
| 56 | + } |
| 57 | + let mutablePointer = aggregateContext.assumingMemoryBound(to: UnsafeMutableRawPointer.self) |
| 58 | + if stepFlag > 0 { |
| 59 | + let arguments = argv.getBindings(argc: argc) |
| 60 | + if aggregateContext.assumingMemoryBound(to: Int64.self).pointee == 0 { |
| 61 | + mutablePointer.pointee = UnsafeMutableRawPointer(mutating: state()) |
| 62 | + } |
| 63 | + step(arguments, mutablePointer.pointee.assumingMemoryBound(to: T.self)) |
| 64 | + } else { |
| 65 | + let result = final(mutablePointer.pointee.assumingMemoryBound(to: T.self)) |
| 66 | + context.set(result: result) |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + func xStep(context: Context, argc: Int32, value: Argv) { |
| 71 | + unsafeBitCast(sqlite3_user_data(context), to: Aggregate.self)(1, context, argc, value) |
| 72 | + } |
| 73 | + |
| 74 | + func xFinal(context: Context) { |
| 75 | + unsafeBitCast(sqlite3_user_data(context), to: Aggregate.self)(0, context, 0, nil) |
| 76 | + } |
| 77 | + |
| 78 | + let flags = SQLITE_UTF8 | (deterministic ? SQLITE_DETERMINISTIC : 0) |
| 79 | + let resultCode = sqlite3_create_function_v2( |
| 80 | + handle, |
| 81 | + functionName, |
| 82 | + Int32(argc), |
| 83 | + flags, |
| 84 | + /* pApp */ unsafeBitCast(box, to: UnsafeMutableRawPointer.self), |
| 85 | + /* xFunc */ nil, xStep, xFinal, /* xDestroy */ nil |
| 86 | + ) |
| 87 | + if let result = Result(errorCode: resultCode, connection: self) { |
| 88 | + fatalError("Error creating function: \(result)") |
| 89 | + } |
| 90 | + register(functionName, argc: argc, value: box) |
| 91 | + } |
| 92 | + |
| 93 | + func createAggregation<T: AnyObject>( |
| 94 | + _ aggregate: String, |
| 95 | + argumentCount: UInt? = nil, |
| 96 | + deterministic: Bool = false, |
| 97 | + initialValue: T, |
| 98 | + reduce: @escaping (T, [Binding?]) -> T, |
| 99 | + result: @escaping (T) -> Binding? |
| 100 | + ) { |
| 101 | + let step: ([Binding?], UnsafeMutablePointer<UnsafeMutableRawPointer>) -> Void = { (bindings, ptr) in |
| 102 | + let pointer = ptr.pointee.assumingMemoryBound(to: T.self) |
| 103 | + let current = Unmanaged<T>.fromOpaque(pointer).takeRetainedValue() |
| 104 | + let next = reduce(current, bindings) |
| 105 | + ptr.pointee = Unmanaged.passRetained(next).toOpaque() |
| 106 | + } |
| 107 | + |
| 108 | + let final: (UnsafeMutablePointer<UnsafeMutableRawPointer>) -> Binding? = { ptr in |
| 109 | + let pointer = ptr.pointee.assumingMemoryBound(to: T.self) |
| 110 | + let obj = Unmanaged<T>.fromOpaque(pointer).takeRetainedValue() |
| 111 | + let value = result(obj) |
| 112 | + ptr.deallocate() |
| 113 | + return value |
| 114 | + } |
| 115 | + |
| 116 | + let state: () -> UnsafeMutablePointer<UnsafeMutableRawPointer> = { |
| 117 | + let pointer = UnsafeMutablePointer<UnsafeMutableRawPointer>.allocate(capacity: 1) |
| 118 | + pointer.pointee = Unmanaged.passRetained(initialValue).toOpaque() |
| 119 | + return pointer |
| 120 | + } |
| 121 | + |
| 122 | + createAggregation(aggregate, step: step, final: final, state: state) |
| 123 | + } |
| 124 | + |
| 125 | + func createAggregation<T>( |
| 126 | + _ aggregate: String, |
| 127 | + argumentCount: UInt? = nil, |
| 128 | + deterministic: Bool = false, |
| 129 | + initialValue: T, |
| 130 | + reduce: @escaping (T, [Binding?]) -> T, |
| 131 | + result: @escaping (T) -> Binding? |
| 132 | + ) { |
| 133 | + |
| 134 | + let step: ([Binding?], UnsafeMutablePointer<T>) -> Void = { (bindings, pointer) in |
| 135 | + let current = pointer.pointee |
| 136 | + let next = reduce(current, bindings) |
| 137 | + pointer.pointee = next |
| 138 | + } |
| 139 | + |
| 140 | + let final: (UnsafeMutablePointer<T>) -> Binding? = { pointer in |
| 141 | + let value = result(pointer.pointee) |
| 142 | + pointer.deallocate() |
| 143 | + return value |
| 144 | + } |
| 145 | + |
| 146 | + let state: () -> UnsafeMutablePointer<T> = { |
| 147 | + let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1) |
| 148 | + pointer.initialize(to: initialValue) |
| 149 | + return pointer |
| 150 | + } |
| 151 | + |
| 152 | + createAggregation(aggregate, step: step, final: final, state: state) |
| 153 | + } |
| 154 | + |
| 155 | +} |
0 commit comments