-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSQLiteDatabaseConnection.swift
More file actions
84 lines (73 loc) · 2.24 KB
/
SQLiteDatabaseConnection.swift
File metadata and controls
84 lines (73 loc) · 2.24 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
//
// SQLiteDatabaseConnection.swift
// feather-sqlite-database
//
// Created by Tibor Bödecs on 2026. 01. 10.
//
import FeatherDatabase
import Logging
import SQLiteNIO
extension DatabaseQuery {
fileprivate struct SQLiteQuery {
var sql: String
var bindings: [SQLiteData]
}
fileprivate func toSQLiteQuery() -> SQLiteQuery {
var sqliteSQL = sql
var sqliteBindings: [SQLiteData] = []
for binding in bindings {
let idx = binding.index + 1
sqliteSQL =
sqliteSQL
.replacing("{{\(idx)}}", with: "?")
switch binding.binding {
case .int(let value):
sqliteBindings.append(.integer(value))
case .double(let value):
sqliteBindings.append(.float(value))
case .string(let value):
sqliteBindings.append(.text(value))
}
}
return .init(
sql: sqliteSQL,
bindings: sqliteBindings
)
}
}
public struct SQLiteDatabaseConnection: DatabaseConnection {
public typealias RowSequence = SQLiteDatabaseRowSequence
var connection: SQLiteConnection
public var logger: Logger
/// Execute a SQLite query on this connection.
///
/// This wraps `SQLiteNIO` query execution and maps errors.
/// - Parameters:
/// - query: The SQLite query to execute.
/// - handler: The handler to process the result sequence.
/// - Throws: A `DatabaseError` if the query fails.
/// - Returns: A query result containing the returned rows.
@discardableResult
public func run<T: Sendable>(
query: DatabaseQuery,
_ handler: (RowSequence) async throws -> T = { $0 }
) async throws(DatabaseError) -> T {
do {
let sqliteQuery = query.toSQLiteQuery()
let result = try await connection.query(
sqliteQuery.sql,
sqliteQuery.bindings
)
return try await handler(
SQLiteDatabaseRowSequence(
elements: result.map {
.init(row: $0)
}
)
)
}
catch {
throw .query(error)
}
}
}