forked from vapor/sqlite-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSQLiteConnection+SQLKit.swift
More file actions
282 lines (243 loc) · 10.4 KB
/
Copy pathSQLiteConnection+SQLKit.swift
File metadata and controls
282 lines (243 loc) · 10.4 KB
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
import SQLKit
import SQLiteNIO
import Logging
// Hint: Yes, I know what default arguments are. This ridiculous spelling out of each alternative avoids public API
// breakage from adding the defaults.
extension SQLiteDatabase {
/// Shorthand for ``sql(encoder:decoder:queryLogLevel:)``.
@inlinable
public func sql() -> any SQLDatabase {
self.sql(encoder: .init(), decoder: .init(), queryLogLevel: .debug)
}
/// Shorthand for ``sql(encoder:decoder:queryLogLevel:)``.
@inlinable
public func sql(encoder: SQLiteDataEncoder) -> any SQLDatabase {
self.sql(encoder: encoder, decoder: .init(), queryLogLevel: .debug)
}
/// Shorthand for ``sql(encoder:decoder:queryLogLevel:)``.
@inlinable
public func sql(decoder: SQLiteDataDecoder) -> any SQLDatabase {
self.sql(encoder: .init(), decoder: decoder, queryLogLevel: .debug)
}
/// Shorthand for ``sql(encoder:decoder:queryLogLevel:)``.
@inlinable
public func sql(encoder: SQLiteDataEncoder, decoder: SQLiteDataDecoder) -> any SQLDatabase {
self.sql(encoder: encoder, decoder: decoder, queryLogLevel: .debug)
}
/// Shorthand for ``sql(encoder:decoder:queryLogLevel:)``.
@inlinable
public func sql(queryLogLevel: Logger.Level?) -> any SQLDatabase {
self.sql(encoder: .init(), decoder: .init(), queryLogLevel: queryLogLevel)
}
/// Shorthand for ``sql(encoder:decoder:queryLogLevel:)``.
@inlinable
public func sql(encoder: SQLiteDataEncoder, queryLogLevel: Logger.Level?) -> any SQLDatabase {
self.sql(encoder: encoder, decoder: .init(), queryLogLevel: queryLogLevel)
}
/// Shorthand for ``sql(encoder:decoder:queryLogLevel:)``.
@inlinable
public func sql(decoder: SQLiteDataDecoder, queryLogLevel: Logger.Level?) -> any SQLDatabase {
self.sql(encoder: .init(), decoder: decoder, queryLogLevel: queryLogLevel)
}
/// Return an object allowing access to this database via the `SQLDatabase` interface.
///
/// - Parameters:
/// - encoder: An ``SQLiteDataEncoder`` used to translate bound query parameters into `SQLiteData` values.
/// - decoder: An ``SQLiteDataDecoder`` used to translate `SQLiteData` values into output values in `SQLRow`s.
/// - queryLogLevel: The level at which SQL queries issued through the SQLKit interface will be logged.
/// - Returns: An instance of `SQLDatabase` which accesses the same database as `self`.
@inlinable
public func sql(
encoder: SQLiteDataEncoder,
decoder: SQLiteDataDecoder,
queryLogLevel: Logger.Level?
) -> any SQLDatabase {
SQLiteSQLDatabase(database: self, encoder: encoder, decoder: decoder, queryLogLevel: queryLogLevel)
}
}
struct SQLiteDatabaseVersion: SQLDatabaseReportedVersion {
/// The numeric value of the version.
///
/// The value is laid out identicallly to [the `SQLITE_VERSION_NUMBER` constant](c_source_id).
///
/// [c_source_id]: https://sqlite.org/c3ref/c_source_id.html
let intValue: Int
/// The string representation of the version.
///
/// The string is formatted identically to [the `SQLITE_VERSION` constant](c_source_id).
///
/// [c_source_id]: https://sqlite.org/c3ref/c_source_id.html
///
/// This value is not used for equality or ordering comparisons; it is really only useful for display. We
/// maintain a stored property for it rather than generating it as-needed from the numeric value in order to
/// preserve any additional information the original value may contain.
///
/// > Note: The string value should always represent the same version as the numeric value. This requirement is
/// > asserted in debug builds, but is not otherwise enforced.
let stringValue: String
/// Separates an appropriately formatted numeric value into its individual components.
static func components(of intValue: Int) -> (major: Int, minor: Int, patch: Int) {
(
major: intValue / 1_000_000,
minor: intValue % 1_000_000 / 1_000,
patch: intValue % 1_000
)
}
/// Get the runtime version of the SQLite3 library in use.
static var runtimeVersion: Self {
self.init(
intValue: Int(SQLiteConnection.libraryVersion()),
stringValue: SQLiteConnection.libraryVersionString()
)
}
/// Build a version value from individual components and synthesize the approiate string value.
init(major: Int, minor: Int, patch: Int) {
self.init(intValue: major * 1_000_000 + minor * 1_000 + patch)
}
/// Designated initializer. Build a version value from the combined numeric value and a corresponding string value.
/// If the string value is omitted, it is synthesized
init(intValue: Int, stringValue: String? = nil) {
let components = Self.components(of: intValue)
self.intValue = intValue
if let stringValue {
assert(
stringValue.hasPrefix("\(components.major).\(components.minor).\(components.patch)"),
"SQLite version string '\(stringValue)' must prefix-match numeric version '\(intValue)'"
)
self.stringValue = stringValue
} else {
self.stringValue = "\(components.major).\(components.major).\(components.patch)"
}
}
/// The major version number.
///
/// This is likely to be 3 for a long time to come yet.
var majorVersion: Int {
Self.components(of: self.intValue).major
}
/// The minor version number.
var minorVersion: Int {
Self.components(of: self.intValue).minor
}
/// The patch version number.
var patchVersion: Int {
Self.components(of: self.intValue).patch
}
#if !hasFeature(Embedded)
// `as? Self` is a cast to a generic type, which Embedded Swift forbids. On embedded we fall back to
// the `SQLDatabaseReportedVersion` protocol's default `stringValue`-based comparison implementations.
// See `SQLDatabaseReportedVersion.isEqual(to:)`.
func isEqual(to otherVersion: any SQLDatabaseReportedVersion) -> Bool {
(otherVersion as? Self).map { $0.intValue == self.intValue } ?? false
}
// See `SQLDatabaseReportedVersion.isOlder(than:)`.
func isOlder(than otherVersion: any SQLDatabaseReportedVersion) -> Bool {
(otherVersion as? Self).map {
(self.majorVersion != $0.majorVersion ? self.majorVersion < $0.majorVersion :
(self.minorVersion != $0.minorVersion ? self.minorVersion < $0.minorVersion :
(self.patchVersion < $0.patchVersion)))
} ?? false
}
#endif
}
/// Wraps a `SQLiteDatabase` with the `SQLDatabase` protocol.
@usableFromInline
/*private*/ struct SQLiteSQLDatabase<D: SQLiteDatabase>: SQLDatabase {
/// The underlying database.
@usableFromInline
let database: D
/// An ``SQLiteDataEncoder`` used to translate bindings into `SQLiteData` values.
@usableFromInline
let encoder: SQLiteDataEncoder
/// An ``SQLiteDataDecoder`` used to translate `SQLiteData` values into output values in `SQLRow`s.
@usableFromInline
let decoder: SQLiteDataDecoder
#if !NativeConcurrency
// See `SQLDatabase.eventLoop`.
@usableFromInline
var eventLoop: any EventLoop {
self.database.eventLoop
}
#endif
// See `SQLDatabase.version`.
@usableFromInline
var version: (any SQLDatabaseReportedVersion)? {
SQLiteDatabaseVersion.runtimeVersion
}
// See `SQLDatabase.logger`.
@usableFromInline
var logger: Logger {
self.database.logger
}
// See `SQLDatabase.dialect`.
@usableFromInline
var dialect: any SQLDialect {
SQLiteDialect()
}
// See `SQLDatabase.queryLogLevel`.
@usableFromInline
let queryLogLevel: Logger.Level?
@inlinable
init(database: D, encoder: SQLiteDataEncoder, decoder: SQLiteDataDecoder, queryLogLevel: Logger.Level?) {
self.database = database
self.encoder = encoder
self.decoder = decoder
self.queryLogLevel = queryLogLevel
}
#if !NativeConcurrency
// See `SQLDatabase.execute(sql:_:)`.
@usableFromInline
func execute(
sql query: any SQLExpression,
_ onRow: @escaping @Sendable (any SQLRow) -> ()
) -> EventLoopFuture<Void> {
let (sql, rawBinds) = self.serialize(query)
if let queryLogLevel = self.queryLogLevel {
self.logger.log(level: queryLogLevel, "Executing query", metadata: ["sql": .string(sql), "binds": .array(rawBinds.map { .string("\($0)") })])
}
let binds: [SQLiteData]
do {
binds = try rawBinds.map { try self.encoder.encode($0) }
} catch {
return self.eventLoop.makeFailedFuture(error)
}
return self.database.query(
sql,
binds,
{ onRow($0.sql(decoder: self.decoder)) }
)
}
#endif
// See `SQLDatabase.execute(sql:_:)`.
@usableFromInline
func execute(
sql query: any SQLExpression,
_ onRow: @escaping @Sendable (any SQLRow) -> ()
) async throws {
let (sql, rawBinds) = self.serialize(query)
if let queryLogLevel = self.queryLogLevel {
// Embedded Swift has no reflection, so bound values cannot be string-interpolated for logging.
#if hasFeature(Embedded)
self.logger.log(level: queryLogLevel, "Executing query", metadata: ["sql": .string(sql)])
#else
self.logger.log(level: queryLogLevel, "Executing query", metadata: ["sql": .string(sql), "binds": .array(rawBinds.map { .string("\($0)") })])
#endif
}
try await self.database.query(
sql,
rawBinds.map { try self.encoder.encode($0) },
{ onRow($0.sql(decoder: self.decoder)) }
)
}
#if !NativeConcurrency
// `withSession(_:)` rides sqlite-nio's protocol-level `withConnection`, which is concrete-only
// on the NativeConcurrency build (SQLKit's default `withSession` applies there instead).
// See `SQLDatabase.withSession(_:)`.
@usableFromInline
func withSession<R>(_ closure: @escaping @Sendable (any SQLDatabase) async throws -> R) async throws -> R {
try await self.database.withConnection {
try await closure($0.sql(encoder: self.encoder, decoder: self.decoder, queryLogLevel: self.queryLogLevel))
}
}
#endif
}