Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
main ▾

Modern-Apps.git / apple / FindFamily / FindFamilyiOS / Persistence / Database.swift

Database.swift605 lines · 24.9 KiBRaw
1import Foundation
2import Combine
3import SQLite3
4
5/// Lightweight SQLite wrapper providing CRUD + Combine publishers for each entity.
6/// All access is serialized through a single dispatch queue to keep things simple and safe.
7final class Database {
8 static let shared = Database()
9
10 private let queue = DispatchQueue(label: "cc.findfamily.db", qos: .userInitiated)
11 private var db: OpaquePointer?
12
13 // Publishers for live data. Each subject re-emits when the underlying table changes.
14 let usersSubject = CurrentValueSubject<[User], Never>([])
15 let waypointsSubject = CurrentValueSubject<[Waypoint], Never>([])
16 let temporaryLinksSubject = CurrentValueSubject<[TemporaryLink], Never>([])
17 let locationValuesSubject = CurrentValueSubject<[LocationValue], Never>([])
18 let latestLocationsSubject = CurrentValueSubject<[Int64: LocationValue], Never>([:])
19
20 private init() {
21 open()
22 migrate()
23 reloadAll()
24 }
25
26 // MARK: - Open / migrate
27
28 private var dbPath: String {
29 let dir = try! FileManager.default.url(
30 for: .applicationSupportDirectory, in: .userDomainMask,
31 appropriateFor: nil, create: true
32 )
33 return dir.appendingPathComponent("findfamily.sqlite").path
34 }
35
36 private func open() {
37 if sqlite3_open(dbPath, &db) != SQLITE_OK {
38 fatalError("Could not open SQLite at \(dbPath)")
39 }
40 exec("PRAGMA foreign_keys = ON;")
41 exec("PRAGMA journal_mode = WAL;")
42 }
43
44 private func migrate() {
45 exec("""
46 CREATE TABLE IF NOT EXISTS users (
47 id INTEGER PRIMARY KEY NOT NULL,
48 name TEXT NOT NULL,
49 photo TEXT,
50 locationName TEXT NOT NULL,
51 sendingEnabled INTEGER NOT NULL,
52 requestStatus TEXT NOT NULL,
53 lastLocationChangeTime INTEGER NOT NULL,
54 encryptionKey TEXT
55 );
56 """)
57 // Idempotent add-column migration. SQLite has no `ADD COLUMN IF NOT EXISTS`;
58 // we check the schema first so the migration is silent on subsequent launches.
59 if !columnExists(table: "users", column: "platform") {
60 exec("ALTER TABLE users ADD COLUMN platform TEXT;")
61 }
62 if !columnExists(table: "users", column: "pqcEncryptionKey") {
63 // PQC bundle cache (base64 of [4B kemLen][kemPubDer][dsaPubDer]) — same format as Office.
64 exec("ALTER TABLE users ADD COLUMN pqcEncryptionKey TEXT;")
65 }
66 if !columnExists(table: "users", column: "lastWaypointId") {
67 // Waypoint enter/exit hysteresis state (nullable). Additive migration only.
68 exec("ALTER TABLE users ADD COLUMN lastWaypointId INTEGER;")
69 }
70 if !columnExists(table: "users", column: "sharingAutoToggleAt") {
71 // Auto-toggle deadline in epoch seconds (nullable = "Never"). Additive migration only.
72 exec("ALTER TABLE users ADD COLUMN sharingAutoToggleAt INTEGER;")
73 }
74 exec("""
75 CREATE TABLE IF NOT EXISTS waypoints (
76 id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
77 name TEXT NOT NULL,
78 range REAL NOT NULL,
79 lat REAL NOT NULL,
80 lon REAL NOT NULL
81 );
82 """)
83 exec("""
84 CREATE TABLE IF NOT EXISTS locationValues (
85 id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
86 userid INTEGER NOT NULL,
87 lat REAL NOT NULL,
88 lon REAL NOT NULL,
89 speed REAL NOT NULL,
90 acc REAL NOT NULL,
91 timestamp INTEGER NOT NULL,
92 battery REAL NOT NULL
93 );
94 """)
95 exec("CREATE INDEX IF NOT EXISTS index_LocationValue_timestamp ON locationValues (timestamp);")
96 exec("CREATE INDEX IF NOT EXISTS index_LocationValue_userid_timestamp ON locationValues (userid, timestamp);")
97 exec("""
98 CREATE TABLE IF NOT EXISTS temporaryLinks (
99 id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
100 name TEXT NOT NULL,
101 key TEXT NOT NULL,
102 publicKey TEXT NOT NULL,
103 deleteAt INTEGER NOT NULL
104 );
105 """)
106 if !columnExists(table: "temporaryLinks", column: "pqcPublicKey") {
107 exec("ALTER TABLE temporaryLinks ADD COLUMN pqcPublicKey TEXT;")
108 }
109 if !columnExists(table: "temporaryLinks", column: "pqcKey") {
110 exec("ALTER TABLE temporaryLinks ADD COLUMN pqcKey TEXT;")
111 }
112 if !columnExists(table: "temporaryLinks", column: "pqcSeed") {
113 exec("ALTER TABLE temporaryLinks ADD COLUMN pqcSeed TEXT;")
114 }
115 }
116
117 // MARK: - Reload helpers
118
119 func reloadAll() {
120 queue.async { [weak self] in
121 guard let self = self else { return }
122 self.usersSubject.send(self.loadUsers())
123 self.waypointsSubject.send(self.loadWaypoints())
124 self.temporaryLinksSubject.send(self.loadTemporaryLinks())
125 let locs = self.loadLocationValues()
126 self.locationValuesSubject.send(locs)
127 self.latestLocationsSubject.send(Self.computeLatest(locs))
128 }
129 }
130
131 private func reloadLocations() {
132 let locs = loadLocationValues()
133 locationValuesSubject.send(locs)
134 latestLocationsSubject.send(Self.computeLatest(locs))
135 }
136
137 private static func computeLatest(_ locs: [LocationValue]) -> [Int64: LocationValue] {
138 var out: [Int64: LocationValue] = [:]
139 for l in locs {
140 if let cur = out[l.userid] {
141 if l.timestamp > cur.timestamp { out[l.userid] = l }
142 } else {
143 out[l.userid] = l
144 }
145 }
146 return out
147 }
148
149 // MARK: - Users
150
151 func upsertUser(_ u: User) {
152 queue.sync {
153 let sql = """
154 INSERT OR REPLACE INTO users (id, name, photo, locationName, sendingEnabled, requestStatus, lastLocationChangeTime, encryptionKey, platform, pqcEncryptionKey, lastWaypointId, sharingAutoToggleAt)
155 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
156 """
157 var stmt: OpaquePointer?
158 sqlite3_prepare_v2(db, sql, -1, &stmt, nil)
159 sqlite3_bind_int64(stmt, 1, u.id)
160 bindText(stmt, 2, u.name)
161 bindOptionalText(stmt, 3, u.photo)
162 bindText(stmt, 4, u.locationName)
163 sqlite3_bind_int(stmt, 5, u.sendingEnabled ? 1 : 0)
164 bindText(stmt, 6, u.requestStatus.rawValue)
165 sqlite3_bind_int64(stmt, 7, Int64(u.lastLocationChangeTime.timeIntervalSince1970))
166 bindOptionalText(stmt, 8, u.encryptionKey)
167 bindOptionalText(stmt, 9, u.platform)
168 bindOptionalText(stmt, 10, u.pqcEncryptionKey)
169 bindOptionalInt64(stmt, 11, u.lastWaypointId)
170 bindOptionalInt64(stmt, 12, u.sharingAutoToggleAt.map { Int64($0.timeIntervalSince1970) })
171 sqlite3_step(stmt)
172 sqlite3_finalize(stmt)
173 usersSubject.send(loadUsers())
174 }
175 }
176
177 // MARK: - Atomic partial updates
178 //
179 // These mirror Android's UserDao partial-update queries. Whole-row `upsertUser`
180 // from a stale snapshot would clobber columns another path just wrote
181 // (e.g. `sharingAutoToggleAt` / `sendingEnabled`), so hot paths use these instead.
182
183 /// Atomically update location display metadata without touching sharing/toggle columns.
184 func updateLocationMeta(id: Int64, locationName: String, lastWaypointId: Int64?, lastLocationChangeTime: Date) {
185 queue.sync {
186 let sql = "UPDATE users SET locationName = ?, lastWaypointId = ?, lastLocationChangeTime = ? WHERE id = ?;"
187 var stmt: OpaquePointer?
188 sqlite3_prepare_v2(db, sql, -1, &stmt, nil)
189 bindText(stmt, 1, locationName)
190 bindOptionalInt64(stmt, 2, lastWaypointId)
191 sqlite3_bind_int64(stmt, 3, Int64(lastLocationChangeTime.timeIntervalSince1970))
192 sqlite3_bind_int64(stmt, 4, id)
193 sqlite3_step(stmt)
194 sqlite3_finalize(stmt)
195 usersSubject.send(loadUsers())
196 }
197 }
198
199 /// Atomically set the learned peer platform tag.
200 func setPlatform(id: Int64, platform: String) {
201 queue.sync {
202 let sql = "UPDATE users SET platform = ? WHERE id = ?;"
203 var stmt: OpaquePointer?
204 sqlite3_prepare_v2(db, sql, -1, &stmt, nil)
205 bindText(stmt, 1, platform)
206 sqlite3_bind_int64(stmt, 2, id)
207 sqlite3_step(stmt)
208 sqlite3_finalize(stmt)
209 usersSubject.send(loadUsers())
210 }
211 }
212
213 /// Atomically cache a peer's RSA public key (base64 PEM).
214 func setEncryptionKey(id: Int64, encryptionKey: String) {
215 queue.sync {
216 let sql = "UPDATE users SET encryptionKey = ? WHERE id = ?;"
217 var stmt: OpaquePointer?
218 sqlite3_prepare_v2(db, sql, -1, &stmt, nil)
219 bindText(stmt, 1, encryptionKey)
220 sqlite3_bind_int64(stmt, 2, id)
221 sqlite3_step(stmt)
222 sqlite3_finalize(stmt)
223 usersSubject.send(loadUsers())
224 }
225 }
226
227 /// Atomically cache a peer's PQC public bundle (base64).
228 func setPqcEncryptionKey(id: Int64, pqcEncryptionKey: String) {
229 queue.sync {
230 let sql = "UPDATE users SET pqcEncryptionKey = ? WHERE id = ?;"
231 var stmt: OpaquePointer?
232 sqlite3_prepare_v2(db, sql, -1, &stmt, nil)
233 bindText(stmt, 1, pqcEncryptionKey)
234 sqlite3_bind_int64(stmt, 2, id)
235 sqlite3_step(stmt)
236 sqlite3_finalize(stmt)
237 usersSubject.send(loadUsers())
238 }
239 }
240
241 /// Atomically set only the auto-toggle deadline (nil = "Never"). Avoids clobbering other columns.
242 func setSharingAutoToggleAt(id: Int64, at: Date?) {
243 queue.sync {
244 let sql = "UPDATE users SET sharingAutoToggleAt = ? WHERE id = ?;"
245 var stmt: OpaquePointer?
246 sqlite3_prepare_v2(db, sql, -1, &stmt, nil)
247 bindOptionalInt64(stmt, 1, at.map { Int64($0.timeIntervalSince1970) })
248 sqlite3_bind_int64(stmt, 2, id)
249 sqlite3_step(stmt)
250 sqlite3_finalize(stmt)
251 usersSubject.send(loadUsers())
252 }
253 }
254
255 /// Atomically set sharing enabled AND clear any pending auto-toggle (manual toggle path).
256 func setSendingEnabledAndClearToggle(id: Int64, enabled: Bool) {
257 queue.sync {
258 let sql = "UPDATE users SET sendingEnabled = ?, sharingAutoToggleAt = NULL WHERE id = ?;"
259 var stmt: OpaquePointer?
260 sqlite3_prepare_v2(db, sql, -1, &stmt, nil)
261 sqlite3_bind_int(stmt, 1, enabled ? 1 : 0)
262 sqlite3_bind_int64(stmt, 2, id)
263 sqlite3_step(stmt)
264 sqlite3_finalize(stmt)
265 usersSubject.send(loadUsers())
266 }
267 }
268
269 /// Atomically flip sharing for every row whose timer is due, clearing the timer.
270 /// The WHERE clause guards against TOCTOU races: if the user manually cleared (NULL)
271 /// or rescheduled to the future, the row no longer matches. Returns rows flipped.
272 @discardableResult
273 func applyDueAutoToggles(now: Date) -> Int {
274 queue.sync {
275 let nowEpoch = Int64(now.timeIntervalSince1970)
276 let sql = "UPDATE users SET sendingEnabled = CASE WHEN sendingEnabled THEN 0 ELSE 1 END, sharingAutoToggleAt = NULL WHERE sharingAutoToggleAt IS NOT NULL AND sharingAutoToggleAt <= ?;"
277 var stmt: OpaquePointer?
278 sqlite3_prepare_v2(db, sql, -1, &stmt, nil)
279 sqlite3_bind_int64(stmt, 1, nowEpoch)
280 sqlite3_step(stmt)
281 sqlite3_finalize(stmt)
282 let changed = Int(sqlite3_changes(db))
283 if changed > 0 {
284 usersSubject.send(loadUsers())
285 }
286 return changed
287 }
288 }
289
290 func deleteUser(_ u: User) {
291 queue.sync {
292 exec("DELETE FROM users WHERE id = \(u.id);")
293 exec("DELETE FROM locationValues WHERE userid = \(u.id);")
294 usersSubject.send(loadUsers())
295 reloadLocations()
296 }
297 }
298
299 private func loadUsers() -> [User] {
300 var out: [User] = []
301 // pqcEncryptionKey/lastWaypointId/sharingAutoToggleAt columns added via idempotent
302 // migrations; SELECT explicitly to handle older dbs (see rc-fallback below).
303 let sql = "SELECT id, name, photo, locationName, sendingEnabled, requestStatus, lastLocationChangeTime, encryptionKey, platform, pqcEncryptionKey, lastWaypointId, sharingAutoToggleAt FROM users;"
304 var stmt: OpaquePointer?
305 let rc = sqlite3_prepare_v2(db, sql, -1, &stmt, nil)
306 if rc != SQLITE_OK {
307 // Fallback: older schema without the newer columns (should be migrated, but be safe during dev).
308 sqlite3_finalize(stmt)
309 let sql2 = "SELECT id, name, photo, locationName, sendingEnabled, requestStatus, lastLocationChangeTime, encryptionKey, platform FROM users;"
310 sqlite3_prepare_v2(db, sql2, -1, &stmt, nil)
311 while sqlite3_step(stmt) == SQLITE_ROW {
312 out.append(User(
313 id: sqlite3_column_int64(stmt, 0),
314 name: text(stmt, 1) ?? "",
315 photo: text(stmt, 2),
316 locationName: text(stmt, 3) ?? "",
317 sendingEnabled: sqlite3_column_int(stmt, 4) != 0,
318 requestStatus: RequestStatus(rawValue: text(stmt, 5) ?? "MUTUAL_CONNECTION") ?? .mutualConnection,
319 lastLocationChangeTime: Date(timeIntervalSince1970: TimeInterval(sqlite3_column_int64(stmt, 6))),
320 encryptionKey: text(stmt, 7),
321 platform: text(stmt, 8),
322 pqcEncryptionKey: nil,
323 lastWaypointId: nil,
324 sharingAutoToggleAt: nil
325 ))
326 }
327 sqlite3_finalize(stmt)
328 return out
329 }
330 while sqlite3_step(stmt) == SQLITE_ROW {
331 out.append(User(
332 id: sqlite3_column_int64(stmt, 0),
333 name: text(stmt, 1) ?? "",
334 photo: text(stmt, 2),
335 locationName: text(stmt, 3) ?? "",
336 sendingEnabled: sqlite3_column_int(stmt, 4) != 0,
337 requestStatus: RequestStatus(rawValue: text(stmt, 5) ?? "MUTUAL_CONNECTION") ?? .mutualConnection,
338 lastLocationChangeTime: Date(timeIntervalSince1970: TimeInterval(sqlite3_column_int64(stmt, 6))),
339 encryptionKey: text(stmt, 7),
340 platform: text(stmt, 8),
341 pqcEncryptionKey: text(stmt, 9),
342 lastWaypointId: optInt64(stmt, 10),
343 sharingAutoToggleAt: optInt64(stmt, 11).map { Date(timeIntervalSince1970: TimeInterval($0)) }
344 ))
345 }
346 sqlite3_finalize(stmt)
347 return out
348 }
349
350 func user(id: Int64) -> User? {
351 usersSubject.value.first { $0.id == id }
352 }
353
354 // MARK: - Waypoints
355
356 func upsertWaypoint(_ w: Waypoint) -> Waypoint {
357 var result = w
358 queue.sync {
359 if w.id == 0 {
360 let sql = "INSERT INTO waypoints (name, range, lat, lon) VALUES (?, ?, ?, ?);"
361 var stmt: OpaquePointer?
362 sqlite3_prepare_v2(db, sql, -1, &stmt, nil)
363 bindText(stmt, 1, w.name)
364 sqlite3_bind_double(stmt, 2, w.range)
365 sqlite3_bind_double(stmt, 3, w.coord.lat)
366 sqlite3_bind_double(stmt, 4, w.coord.lon)
367 sqlite3_step(stmt)
368 sqlite3_finalize(stmt)
369 result.id = sqlite3_last_insert_rowid(db)
370 } else {
371 let sql = "INSERT OR REPLACE INTO waypoints (id, name, range, lat, lon) VALUES (?, ?, ?, ?, ?);"
372 var stmt: OpaquePointer?
373 sqlite3_prepare_v2(db, sql, -1, &stmt, nil)
374 sqlite3_bind_int64(stmt, 1, w.id)
375 bindText(stmt, 2, w.name)
376 sqlite3_bind_double(stmt, 3, w.range)
377 sqlite3_bind_double(stmt, 4, w.coord.lat)
378 sqlite3_bind_double(stmt, 5, w.coord.lon)
379 sqlite3_step(stmt)
380 sqlite3_finalize(stmt)
381 }
382 waypointsSubject.send(loadWaypoints())
383 }
384 return result
385 }
386
387 func deleteWaypoint(_ w: Waypoint) {
388 queue.sync {
389 exec("DELETE FROM waypoints WHERE id = \(w.id);")
390 waypointsSubject.send(loadWaypoints())
391 }
392 }
393
394 private func loadWaypoints() -> [Waypoint] {
395 var out: [Waypoint] = []
396 let sql = "SELECT id, name, range, lat, lon FROM waypoints;"
397 var stmt: OpaquePointer?
398 sqlite3_prepare_v2(db, sql, -1, &stmt, nil)
399 while sqlite3_step(stmt) == SQLITE_ROW {
400 out.append(Waypoint(
401 id: sqlite3_column_int64(stmt, 0),
402 name: text(stmt, 1) ?? "",
403 range: sqlite3_column_double(stmt, 2),
404 coord: Coord(lat: sqlite3_column_double(stmt, 3), lon: sqlite3_column_double(stmt, 4))
405 ))
406 }
407 sqlite3_finalize(stmt)
408 return out
409 }
410
411 // MARK: - LocationValues
412
413 func insertLocationValue(_ l: LocationValue) {
414 queue.sync {
415 let sql = "INSERT INTO locationValues (userid, lat, lon, speed, acc, timestamp, battery) VALUES (?, ?, ?, ?, ?, ?, ?);"
416 var stmt: OpaquePointer?
417 sqlite3_prepare_v2(db, sql, -1, &stmt, nil)
418 sqlite3_bind_int64(stmt, 1, l.userid)
419 sqlite3_bind_double(stmt, 2, l.coord.lat)
420 sqlite3_bind_double(stmt, 3, l.coord.lon)
421 sqlite3_bind_double(stmt, 4, Double(l.speed))
422 sqlite3_bind_double(stmt, 5, Double(l.acc))
423 sqlite3_bind_int64(stmt, 6, Int64(l.timestamp.timeIntervalSince1970))
424 sqlite3_bind_double(stmt, 7, Double(l.battery))
425 sqlite3_step(stmt)
426 sqlite3_finalize(stmt)
427 reloadLocations()
428 }
429 }
430
431 func deleteLocationValuesOlderThan(_ cutoff: Date) {
432 queue.sync {
433 exec("DELETE FROM locationValues WHERE timestamp < \(Int64(cutoff.timeIntervalSince1970));")
434 reloadLocations()
435 }
436 }
437
438 func locationsFor(userid: Int64) -> [LocationValue] {
439 locationValuesSubject.value.filter { $0.userid == userid }
440 }
441
442 private func loadLocationValues() -> [LocationValue] {
443 var out: [LocationValue] = []
444 let sql = "SELECT id, userid, lat, lon, speed, acc, timestamp, battery FROM locationValues;"
445 var stmt: OpaquePointer?
446 sqlite3_prepare_v2(db, sql, -1, &stmt, nil)
447 while sqlite3_step(stmt) == SQLITE_ROW {
448 out.append(LocationValue(
449 id: sqlite3_column_int64(stmt, 0),
450 userid: sqlite3_column_int64(stmt, 1),
451 coord: Coord(lat: sqlite3_column_double(stmt, 2), lon: sqlite3_column_double(stmt, 3)),
452 speed: Float(sqlite3_column_double(stmt, 4)),
453 acc: Float(sqlite3_column_double(stmt, 5)),
454 timestamp: Date(timeIntervalSince1970: TimeInterval(sqlite3_column_int64(stmt, 6))),
455 battery: Float(sqlite3_column_double(stmt, 7))
456 ))
457 }
458 sqlite3_finalize(stmt)
459 return out
460 }
461
462 // MARK: - Temporary links
463
464 func upsertTemporaryLink(_ link: TemporaryLink) -> TemporaryLink {
465 var result = link
466 queue.sync {
467 if link.id == 0 {
468 let sql = "INSERT INTO temporaryLinks (name, key, publicKey, deleteAt, pqcPublicKey, pqcKey, pqcSeed) VALUES (?, ?, ?, ?, ?, ?, ?);"
469 var stmt: OpaquePointer?
470 sqlite3_prepare_v2(db, sql, -1, &stmt, nil)
471 bindText(stmt, 1, link.name)
472 bindText(stmt, 2, link.key)
473 bindText(stmt, 3, link.publicKey)
474 sqlite3_bind_int64(stmt, 4, Int64(link.deleteAt.timeIntervalSince1970))
475 bindOptionalText(stmt, 5, link.pqcPublicKey)
476 bindOptionalText(stmt, 6, link.pqcKey)
477 bindOptionalText(stmt, 7, link.pqcSeed)
478 sqlite3_step(stmt)
479 sqlite3_finalize(stmt)
480 result.id = sqlite3_last_insert_rowid(db)
481 } else {
482 let sql = "INSERT OR REPLACE INTO temporaryLinks (id, name, key, publicKey, deleteAt, pqcPublicKey, pqcKey, pqcSeed) VALUES (?, ?, ?, ?, ?, ?, ?, ?);"
483 var stmt: OpaquePointer?
484 sqlite3_prepare_v2(db, sql, -1, &stmt, nil)
485 sqlite3_bind_int64(stmt, 1, link.id)
486 bindText(stmt, 2, link.name)
487 bindText(stmt, 3, link.key)
488 bindText(stmt, 4, link.publicKey)
489 sqlite3_bind_int64(stmt, 5, Int64(link.deleteAt.timeIntervalSince1970))
490 bindOptionalText(stmt, 6, link.pqcPublicKey)
491 bindOptionalText(stmt, 7, link.pqcKey)
492 bindOptionalText(stmt, 8, link.pqcSeed)
493 sqlite3_step(stmt)
494 sqlite3_finalize(stmt)
495 }
496 temporaryLinksSubject.send(loadTemporaryLinks())
497 }
498 return result
499 }
500
501 func deleteTemporaryLink(_ link: TemporaryLink) {
502 queue.sync {
503 exec("DELETE FROM temporaryLinks WHERE id = \(link.id);")
504 temporaryLinksSubject.send(loadTemporaryLinks())
505 }
506 }
507
508 private func loadTemporaryLinks() -> [TemporaryLink] {
509 var out: [TemporaryLink] = []
510 // Try new schema first; fallback to old if column missing.
511 let sql = "SELECT id, name, key, publicKey, deleteAt, pqcPublicKey, pqcKey, pqcSeed FROM temporaryLinks;"
512 var stmt: OpaquePointer?
513 let rc = sqlite3_prepare_v2(db, sql, -1, &stmt, nil)
514 if rc != SQLITE_OK {
515 sqlite3_finalize(stmt)
516 let sql2 = "SELECT id, name, key, publicKey, deleteAt FROM temporaryLinks;"
517 sqlite3_prepare_v2(db, sql2, -1, &stmt, nil)
518 while sqlite3_step(stmt) == SQLITE_ROW {
519 out.append(TemporaryLink(
520 id: sqlite3_column_int64(stmt, 0),
521 name: text(stmt, 1) ?? "",
522 key: text(stmt, 2) ?? "",
523 publicKey: text(stmt, 3) ?? "",
524 deleteAt: Date(timeIntervalSince1970: TimeInterval(sqlite3_column_int64(stmt, 4))),
525 pqcPublicKey: nil,
526 pqcKey: nil,
527 pqcSeed: nil
528 ))
529 }
530 sqlite3_finalize(stmt)
531 return out
532 }
533 while sqlite3_step(stmt) == SQLITE_ROW {
534 out.append(TemporaryLink(
535 id: sqlite3_column_int64(stmt, 0),
536 name: text(stmt, 1) ?? "",
537 key: text(stmt, 2) ?? "",
538 publicKey: text(stmt, 3) ?? "",
539 deleteAt: Date(timeIntervalSince1970: TimeInterval(sqlite3_column_int64(stmt, 4))),
540 pqcPublicKey: text(stmt, 5),
541 pqcKey: text(stmt, 6),
542 pqcSeed: text(stmt, 7)
543 ))
544 }
545 sqlite3_finalize(stmt)
546 return out
547 }
548
549 // MARK: - SQLite helpers
550
551 private func exec(_ sql: String) {
552 var err: UnsafeMutablePointer<Int8>?
553 if sqlite3_exec(db, sql, nil, nil, &err) != SQLITE_OK {
554 let msg = err.map { String(cString: $0) } ?? "?"
555 print("SQLite error executing [\(sql)]: \(msg)")
556 sqlite3_free(err)
557 }
558 }
559
560 /// Returns true if `column` already exists on `table`. Used to make ALTER TABLE
561 /// migrations idempotent across launches (SQLite has no ADD COLUMN IF NOT EXISTS).
562 private func columnExists(table: String, column: String) -> Bool {
563 let sql = "PRAGMA table_info(\(table));"
564 var stmt: OpaquePointer?
565 guard sqlite3_prepare_v2(db, sql, -1, &stmt, nil) == SQLITE_OK else { return false }
566 defer { sqlite3_finalize(stmt) }
567 while sqlite3_step(stmt) == SQLITE_ROW {
568 if let cstr = sqlite3_column_text(stmt, 1), String(cString: cstr) == column {
569 return true
570 }
571 }
572 return false
573 }
574
575 private func text(_ stmt: OpaquePointer?, _ idx: Int32) -> String? {
576 guard let cstr = sqlite3_column_text(stmt, idx) else { return nil }
577 return String(cString: cstr)
578 }
579
580 /// Reads a nullable INTEGER column, returning nil for SQL NULL.
581 private func optInt64(_ stmt: OpaquePointer?, _ idx: Int32) -> Int64? {
582 if sqlite3_column_type(stmt, idx) == SQLITE_NULL { return nil }
583 return sqlite3_column_int64(stmt, idx)
584 }
585
586 private func bindText(_ stmt: OpaquePointer?, _ idx: Int32, _ s: String) {
587 sqlite3_bind_text(stmt, idx, (s as NSString).utf8String, -1, unsafeBitCast(-1, to: sqlite3_destructor_type.self))
588 }
589
590 private func bindOptionalText(_ stmt: OpaquePointer?, _ idx: Int32, _ s: String?) {
591 if let s = s {
592 bindText(stmt, idx, s)
593 } else {
594 sqlite3_bind_null(stmt, idx)
595 }
596 }
597
598 private func bindOptionalInt64(_ stmt: OpaquePointer?, _ idx: Int32, _ v: Int64?) {
599 if let v = v {
600 sqlite3_bind_int64(stmt, idx, v)
601 } else {
602 sqlite3_bind_null(stmt, idx)
603 }
604 }
605}