-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathKotlinPowerSyncDatabaseImpl.swift
More file actions
565 lines (508 loc) · 17.5 KB
/
KotlinPowerSyncDatabaseImpl.swift
File metadata and controls
565 lines (508 loc) · 17.5 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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
import CSQLite
import Foundation
import PowerSyncKotlin
final class KotlinPowerSyncDatabaseImpl: PowerSyncDatabaseProtocol,
// `PowerSyncKotlin.PowerSyncDatabase` cannot be marked as Sendable
@unchecked Sendable
{
let logger: any LoggerProtocol
private let kotlinDatabase: PowerSyncKotlin.PowerSyncDatabase
private let encoder = JSONEncoder()
let currentStatus: SyncStatus
private let dbFilename: String
private let dbDirectory: String?
init(
kotlinDatabase: PowerSyncKotlin.PowerSyncDatabase,
dbFilename: String,
dbDirectory: String? = nil,
logger: DatabaseLogger
) {
self.logger = logger
self.kotlinDatabase = kotlinDatabase
self.dbFilename = dbFilename
self.dbDirectory = dbDirectory
currentStatus = KotlinSyncStatus(
baseStatus: kotlinDatabase.currentStatus
)
}
func waitForFirstSync() async throws {
try await kotlinDatabase.waitForFirstSync()
}
func updateSchema(schema: any SchemaProtocol) async throws {
try await kotlinDatabase.updateSchema(
schema: KotlinAdapter.Schema.toKotlin(schema)
)
}
func waitForFirstSync(priority: Int32) async throws {
try await kotlinDatabase.waitForFirstSync(
priority: priority
)
}
func syncStream(name: String, params: JsonParam?) -> any SyncStream {
let rawStream = kotlinDatabase.syncStream(name: name, parameters: params?.mapValues { $0.toKotlinMap() })
return KotlinSyncStream(kotlinStream: rawStream)
}
func connect(
connector: PowerSyncBackendConnectorProtocol,
options: ConnectOptions?
) async throws {
let connectorAdapter = swiftBackendConnectorToPowerSyncConnector(connector: SwiftBackendConnectorBridge(
swiftBackendConnector: connector, db: self
))
let resolvedOptions = options ?? ConnectOptions()
try await kotlinDatabase.connect(
connector: connectorAdapter,
crudThrottleMs: Int64(resolvedOptions.crudThrottle * 1000),
retryDelayMs: Int64(resolvedOptions.retryDelay * 1000),
params: resolvedOptions.params.mapValues { $0.toKotlinMap() },
options: createSyncOptions(
newClient: resolvedOptions.newClientImplementation,
userAgent: userAgent(),
loggingConfig: resolvedOptions.clientConfiguration?.requestLogger?.toKotlinConfig()
),
appMetadata: resolvedOptions.appMetadata
)
}
func getCrudBatch(limit: Int32 = 100) async throws -> CrudBatch? {
guard let base = try await kotlinDatabase.getCrudBatch(limit: limit) else {
return nil
}
return try KotlinCrudBatch(
batch: base
)
}
func getCrudTransactions() -> any CrudTransactions {
return KotlinCrudTransactions(db: kotlinDatabase)
}
func getPowerSyncVersion() async throws -> String {
try await kotlinDatabase.getPowerSyncVersion()
}
func disconnect() async throws {
try await kotlinDatabase.disconnect()
}
func disconnectAndClear(clearLocal: Bool, soft: Bool) async throws {
try await kotlinDatabase.disconnectAndClear(
clearLocal: clearLocal,
soft: soft
)
}
@discardableResult
func execute(sql: String, parameters: [Sendable?]?) async throws -> Int64 {
try await writeTransaction { ctx in
try ctx.execute(
sql: sql,
parameters: parameters
)
}
}
func get<RowType: Sendable>(
sql: String,
parameters: [Sendable?]?,
mapper: @Sendable @escaping (SqlCursor) -> RowType
) async throws -> RowType {
try await readLock { ctx in
try ctx.get(
sql: sql,
parameters: parameters,
mapper: mapper
)
}
}
func get<RowType: Sendable>(
sql: String,
parameters: [Sendable?]?,
mapper: @Sendable @escaping (SqlCursor) throws -> RowType
) async throws -> RowType {
try await readLock { ctx in
try ctx.get(
sql: sql,
parameters: parameters,
mapper: mapper
)
}
}
func getAll<RowType: Sendable>(
sql: String,
parameters: [Sendable?]?,
mapper: @Sendable @escaping (SqlCursor) -> RowType
) async throws -> [RowType] {
try await readLock { ctx in
try ctx.getAll(
sql: sql,
parameters: parameters,
mapper: mapper
)
}
}
func getAll<RowType: Sendable>(
sql: String,
parameters: [Sendable?]?,
mapper: @Sendable @escaping (SqlCursor) throws -> RowType
) async throws -> [RowType] {
try await readLock { ctx in
try ctx.getAll(
sql: sql,
parameters: parameters,
mapper: mapper
)
}
}
func getOptional<RowType: Sendable>(
sql: String,
parameters: [Sendable?]?,
mapper: @Sendable @escaping (SqlCursor) -> RowType
) async throws -> RowType? {
try await readLock { ctx in
try ctx.getOptional(
sql: sql,
parameters: parameters,
mapper: mapper
)
}
}
func getOptional<RowType: Sendable>(
sql: String,
parameters: [Sendable?]?,
mapper: @Sendable @escaping (SqlCursor) throws -> RowType
) async throws -> RowType? {
try await readLock { ctx in
try ctx.getOptional(
sql: sql,
parameters: parameters,
mapper: mapper
)
}
}
func watch<RowType: Sendable>(
sql: String,
parameters: [Sendable?]?,
mapper: @Sendable @escaping (SqlCursor) -> RowType
) throws -> AsyncThrowingStream<[RowType], any Error> {
try watch(
options: WatchOptions(
sql: sql,
parameters: parameters,
mapper: mapper
)
)
}
func watch<RowType: Sendable>(
sql: String,
parameters: [Sendable?]?,
mapper: @Sendable @escaping (SqlCursor) throws -> RowType
) throws -> AsyncThrowingStream<[RowType], any Error> {
try watch(
options: WatchOptions(
sql: sql,
parameters: parameters,
mapper: mapper
)
)
}
func watch<RowType: Sendable>(
options: WatchOptions<RowType>
) throws -> AsyncThrowingStream<[RowType], Error> {
AsyncThrowingStream { continuation in
// Create an outer task to monitor cancellation
let task = Task {
do {
let watchedTables = try await self.getQuerySourceTables(
sql: options.sql,
parameters: options.parameters
)
// Watching for changes in the database
for try await _ in try self.kotlinDatabase.onChange(
tables: Set(watchedTables),
throttleMs: Int64(options.throttle * 1000),
triggerImmediately: true // Allows emitting the first result even if there aren't changes
) {
// Check if the outer task is cancelled
try Task.checkCancellation()
try continuation.yield(
safeCast(
await self.getAll(
sql: options.sql,
parameters: options.parameters,
mapper: options.mapper
),
to: [RowType].self
)
)
}
continuation.finish()
} catch {
if error is CancellationError {
continuation.finish()
} else {
continuation.finish(throwing: error)
}
}
}
// Propagate cancellation from the outer task to the inner task
continuation.onTermination = { @Sendable _ in
task.cancel() // This cancels the inner task when the stream is terminated
}
}
}
func writeLock<R: Sendable>(
callback: @Sendable @escaping (any ConnectionContext) throws -> R
) async throws -> R {
return try await wrapPowerSyncException {
try safeCast(
await kotlinDatabase.writeLock(
callback: wrapLockContext(callback: callback)
),
to: R.self
)
}
}
func writeTransaction<R: Sendable>(
callback: @Sendable @escaping (any Transaction) throws -> R
) async throws -> R {
return try await wrapPowerSyncException {
try safeCast(
await kotlinDatabase.writeTransaction(
callback: wrapTransactionContext(callback: callback)
),
to: R.self
)
}
}
func readLock<R: Sendable>(
callback: @Sendable @escaping (any ConnectionContext) throws -> R
)
async throws -> R
{
return try await wrapPowerSyncException {
try safeCast(
await kotlinDatabase.readLock(
callback: wrapLockContext(callback: callback)
),
to: R.self
)
}
}
func readTransaction<R: Sendable>(
callback: @Sendable @escaping (any Transaction) throws -> R
) async throws -> R {
return try await wrapPowerSyncException {
try safeCast(
await kotlinDatabase.readTransaction(
callback: wrapTransactionContext(callback: callback)
),
to: R.self
)
}
}
func close() async throws {
try await kotlinDatabase.close()
}
func close(deleteDatabase: Bool = false) async throws {
// Close the SQLite connections
try await close()
if deleteDatabase {
try await self.deleteDatabase()
}
}
private func deleteDatabase() async throws {
let directory: URL
if let dbDirectory {
directory = URL(fileURLWithPath: dbDirectory, isDirectory: true)
} else {
directory = try appleDefaultDatabaseDirectory()
}
try deleteSQLiteFiles(dbFilename: dbFilename, in: directory)
}
/// Tries to convert Kotlin PowerSyncExceptions to Swift Exceptions
private func wrapPowerSyncException<R: Sendable>(
handler: () async throws -> R)
async throws -> R
{
do {
return try await handler()
} catch {
// Try and parse errors back from the Kotlin side
if let mapperError = SqlCursorError.fromDescription(error.localizedDescription) {
throw mapperError
}
throw PowerSyncError.operationFailed(
underlyingError: error
)
}
}
private func getQuerySourceTables(
sql: String,
parameters: [Sendable?]
) async throws -> Set<String> {
let rows = try await getAll(
sql: "EXPLAIN \(sql)",
parameters: parameters,
mapper: { cursor in
try ExplainQueryResult(
addr: cursor.getString(index: 0),
opcode: cursor.getString(index: 1),
p1: cursor.getInt64(index: 2),
p2: cursor.getInt64(index: 3),
p3: cursor.getInt64(index: 4)
)
}
)
let rootPages = rows.compactMap { row in
if (row.opcode == "OpenRead" || row.opcode == "OpenWrite") &&
row.p3 == 0 && row.p2 != 0
{
return row.p2
}
return nil
}
do {
let pagesData = try encoder.encode(rootPages)
guard let pagesString = String(data: pagesData, encoding: .utf8) else {
throw PowerSyncError.operationFailed(
message: "Failed to convert pages data to UTF-8 string"
)
}
let tableRows = try await getAll(
sql: "SELECT tbl_name FROM sqlite_master WHERE rootpage IN (SELECT json_each.value FROM json_each(?))",
parameters: [
pagesString,
]
) { try $0.getString(index: 0) }
return Set(tableRows)
} catch {
throw PowerSyncError.operationFailed(
message: "Could not determine watched query tables",
underlyingError: error
)
}
}
}
func openKotlinDBDefault(
schema: Schema,
dbFilename: String,
dbDirectory: String? = nil,
logger: DatabaseLogger,
initialStatements: [String] = []
) -> PowerSyncDatabaseProtocol {
let rc = sqlite3_initialize()
if rc != 0 {
fatalError("Call to sqlite3_initialize() failed with \(rc)")
}
let factory = sqlite3DatabaseFactory(initialStatements: initialStatements)
return KotlinPowerSyncDatabaseImpl(
kotlinDatabase: PowerSyncDatabase(
factory: factory,
schema: KotlinAdapter.Schema.toKotlin(schema),
dbFilename: dbFilename,
logger: logger.kLogger,
dbDirectory: dbDirectory
),
dbFilename: dbFilename,
dbDirectory: dbDirectory,
logger: logger
)
}
func openKotlinDBWithPool(
schema: Schema,
pool: SQLiteConnectionPoolProtocol,
identifier: String,
logger: DatabaseLogger
) -> PowerSyncDatabaseProtocol {
return KotlinPowerSyncDatabaseImpl(
kotlinDatabase: openPowerSyncWithPool(
pool: pool.toKotlin(),
identifier: identifier,
schema: KotlinAdapter.Schema.toKotlin(schema),
logger: logger.kLogger
),
dbFilename: identifier,
logger: logger
)
}
private struct ExplainQueryResult {
let addr: String
let opcode: String
let p1: Int64
let p2: Int64
let p3: Int64
}
extension Error {
func toPowerSyncError() -> PowerSyncKotlin.PowerSyncException {
return PowerSyncKotlin.PowerSyncException(
message: localizedDescription,
cause: PowerSyncKotlin.KotlinThrowable(message: localizedDescription)
)
}
}
func wrapLockContext(
callback: @Sendable @escaping (any ConnectionContext) throws -> Any
) throws -> PowerSyncKotlin.ThrowableLockCallback {
PowerSyncKotlin.wrapContextHandler { kotlinContext in
do {
return try PowerSyncKotlin.PowerSyncResult.Success(
value: callback(
KotlinConnectionContext(
ctx: kotlinContext
)
))
} catch {
return PowerSyncKotlin.PowerSyncResult.Failure(
exception: error.toPowerSyncError()
)
}
}
}
func wrapTransactionContext(
callback: @Sendable @escaping (any Transaction) throws -> Any
) throws -> PowerSyncKotlin.ThrowableTransactionCallback {
PowerSyncKotlin.wrapTransactionContextHandler { kotlinContext in
do {
return try PowerSyncKotlin.PowerSyncResult.Success(
value: callback(
KotlinTransactionContext(
ctx: kotlinContext
)
))
} catch {
return PowerSyncKotlin.PowerSyncResult.Failure(
exception: error.toPowerSyncError()
)
}
}
}
/// This returns the default directory in which we store SQLite database files.
func appleDefaultDatabaseDirectory() throws -> URL {
let fileManager = FileManager.default
// Get the application support directory
guard let documentsDirectory = fileManager.urls(
for: .applicationSupportDirectory,
in: .userDomainMask
).first else {
throw PowerSyncError.operationFailed(message: "Unable to find application support directory")
}
return documentsDirectory.appendingPathComponent("databases")
}
/// Deletes all SQLite files for a given database filename in the specified directory.
/// This includes the main database file and WAL mode files (.wal, .shm, and .journal if present).
/// Throws an error if a file exists but could not be deleted. Files that don't exist are ignored.
func deleteSQLiteFiles(dbFilename: String, in directory: URL) throws {
let fileManager = FileManager.default
// SQLite files to delete:
// 1. Main database file: dbFilename
// 2. WAL file: dbFilename-wal
// 3. SHM file: dbFilename-shm
// 4. Journal file: dbFilename-journal (for rollback journal mode, though WAL mode typically doesn't use it)
let filesToDelete = [
dbFilename,
"\(dbFilename)-wal",
"\(dbFilename)-shm",
"\(dbFilename)-journal"
]
for filename in filesToDelete {
let fileURL = directory.appendingPathComponent(filename)
if fileManager.fileExists(atPath: fileURL.path) {
try fileManager.removeItem(at: fileURL)
}
// If file doesn't exist, we ignore it and continue
}
}