Skip to content

Commit d6fd7eb

Browse files
cleanup apis
1 parent dbaba58 commit d6fd7eb

32 files changed

+932
-247
lines changed

Sources/PowerSync/Kotlin/DatabaseLogger.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ private class KermitLogWriterAdapter: Kermit_coreLogWriter {
4444
///
4545
/// This class bridges Swift log writers with the Kotlin logging system and supports
4646
/// runtime configuration of severity levels and writer lists.
47-
internal class DatabaseLogger: LoggerProtocol {
47+
class DatabaseLogger: LoggerProtocol {
4848
/// The underlying Kermit logger instance provided by the PowerSyncKotlin SDK.
4949
public let kLogger = PowerSyncKotlin.generateLogger(logger: nil)
5050
public let logger: any LoggerProtocol

Sources/PowerSync/Kotlin/KotlinAdapter.swift

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import PowerSyncKotlin
22

3-
4-
internal struct KotlinAdapter {
3+
enum KotlinAdapter {
54
struct Index {
65
static func toKotlin(_ index: IndexProtocol) -> PowerSyncKotlin.Index {
76
PowerSyncKotlin.Index(
@@ -26,7 +25,7 @@ internal struct KotlinAdapter {
2625
static func toKotlin(_ table: TableProtocol) -> PowerSyncKotlin.Table {
2726
PowerSyncKotlin.Table(
2827
name: table.name,
29-
columns: table.columns.map {Column.toKotlin($0)},
28+
columns: table.columns.map { Column.toKotlin($0) },
3029
indexes: table.indexes.map { Index.toKotlin($0) },
3130
localOnly: table.localOnly,
3231
insertOnly: table.insertOnly,

Sources/PowerSync/Kotlin/KotlinPowerSyncDatabaseImpl.swift

Lines changed: 66 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -43,21 +43,20 @@ final class KotlinPowerSyncDatabaseImpl: PowerSyncDatabaseProtocol {
4343

4444
func connect(
4545
connector: PowerSyncBackendConnector,
46-
crudThrottleMs: Int64 = 1000,
47-
retryDelayMs: Int64 = 5000,
48-
params: JsonParam = [:]
46+
options: ConnectOptions?
4947
) async throws {
5048
let connectorAdapter = PowerSyncBackendConnectorAdapter(
5149
swiftBackendConnector: connector,
5250
db: self
5351
)
5452

53+
let resolvedOptions = options ?? ConnectOptions()
54+
5555
try await kotlinDatabase.connect(
5656
connector: connectorAdapter,
57-
crudThrottleMs: crudThrottleMs,
58-
retryDelayMs: retryDelayMs,
59-
// We map to basic values and use NSNull to avoid SKIEE thinking the values must be of Any type
60-
params: params.mapValues { $0.toValue() ?? NSNull() }
57+
crudThrottleMs: resolvedOptions.crudThrottleMs,
58+
retryDelayMs: resolvedOptions.retryDelayMs,
59+
params: resolvedOptions.params.mapValues { $0.toKotlinMap() }
6160
)
6261
}
6362

@@ -93,6 +92,7 @@ final class KotlinPowerSyncDatabaseImpl: PowerSyncDatabaseProtocol {
9392
)
9493
}
9594

95+
@discardableResult
9696
func execute(sql: String, parameters: [Any?]?) async throws -> Int64 {
9797
try await writeTransaction { ctx in
9898
try ctx.execute(
@@ -280,58 +280,85 @@ final class KotlinPowerSyncDatabaseImpl: PowerSyncDatabaseProtocol {
280280
func writeLock<R>(
281281
callback: @escaping (any ConnectionContext) throws -> R
282282
) async throws -> R {
283-
return try safeCast(
284-
await kotlinDatabase.writeLock(
285-
callback: LockCallback(
286-
callback: callback
287-
)
288-
),
289-
to: R.self
290-
)
283+
return try await wrapPowerSyncException {
284+
try safeCast(
285+
await kotlinDatabase.writeLock(
286+
callback: LockCallback(
287+
callback: callback
288+
)
289+
),
290+
to: R.self
291+
)
292+
}
291293
}
292294

293295
func writeTransaction<R>(
294296
callback: @escaping (any Transaction) throws -> R
295297
) async throws -> R {
296-
return try safeCast(
297-
await kotlinDatabase.writeTransaction(
298-
callback: TransactionCallback(
299-
callback: callback
300-
)
301-
),
302-
to: R.self
303-
)
298+
return try await wrapPowerSyncException {
299+
try safeCast(
300+
await kotlinDatabase.writeTransaction(
301+
callback: TransactionCallback(
302+
callback: callback
303+
)
304+
),
305+
to: R.self
306+
)
307+
}
304308
}
305309

306310
func readLock<R>(
307311
callback: @escaping (any ConnectionContext) throws -> R
308312
)
309313
async throws -> R
310314
{
311-
return try safeCast(
312-
await kotlinDatabase.readLock(
313-
callback: LockCallback(
314-
callback: callback
315-
)
316-
),
317-
to: R.self
318-
)
315+
return try await wrapPowerSyncException {
316+
try safeCast(
317+
await kotlinDatabase.readLock(
318+
callback: LockCallback(
319+
callback: callback
320+
)
321+
),
322+
to: R.self
323+
)
324+
}
319325
}
320326

321327
func readTransaction<R>(
322328
callback: @escaping (any Transaction) throws -> R
323329
) async throws -> R {
324-
return try safeCast(
325-
await kotlinDatabase.readTransaction(
326-
callback: TransactionCallback(
327-
callback: callback
328-
)
329-
),
330-
to: R.self
331-
)
330+
return try await wrapPowerSyncException {
331+
try safeCast(
332+
await kotlinDatabase.readTransaction(
333+
callback: TransactionCallback(
334+
callback: callback
335+
)
336+
),
337+
to: R.self
338+
)
339+
}
332340
}
333341

334342
func close() async throws {
335343
try await kotlinDatabase.close()
336344
}
345+
346+
/// Tries to convert Kotlin PowerSyncExceptions to Swift Exceptions
347+
private func wrapPowerSyncException<R>(
348+
handler: () async throws -> R)
349+
async throws -> R
350+
{
351+
do {
352+
return try await handler()
353+
} catch {
354+
// Try and parse errors back from the Kotlin side
355+
356+
if let mapperError = SqlCursorError.fromDescription(error.localizedDescription) {
357+
throw mapperError
358+
}
359+
360+
// Throw remaining errors as-is
361+
throw error
362+
}
363+
}
337364
}

Sources/PowerSync/Kotlin/KotlinTypes.swift

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,3 @@ import PowerSyncKotlin
33
typealias KotlinPowerSyncBackendConnector = PowerSyncKotlin.PowerSyncBackendConnector
44
typealias KotlinPowerSyncCredentials = PowerSyncKotlin.PowerSyncCredentials
55
typealias KotlinPowerSyncDatabase = PowerSyncKotlin.PowerSyncDatabase
6-

Sources/PowerSync/Kotlin/SafeCastError.swift

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,16 +12,16 @@ enum SafeCastError: Error, CustomStringConvertible {
1212
}
1313
}
1414

15-
internal func safeCast<T>(_ value: Any?, to type: T.Type) throws -> T {
15+
func safeCast<T>(_ value: Any?, to type: T.Type) throws -> T {
1616
// Special handling for nil when T is an optional type
17-
if value == nil || value is NSNull {
18-
// Check if T is an optional type that can accept nil
19-
let nilValue: Any? = nil
20-
if let nilAsT = nilValue as? T {
21-
return nilAsT
22-
}
23-
}
24-
17+
if value == nil || value is NSNull {
18+
// Check if T is an optional type that can accept nil
19+
let nilValue: Any? = nil
20+
if let nilAsT = nilValue as? T {
21+
return nilAsT
22+
}
23+
}
24+
2525
if let castedValue = value as? T {
2626
return castedValue
2727
} else {

Sources/PowerSync/Kotlin/TransactionCallback.swift

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import PowerSyncKotlin
22

3+
/// Internal Wrapper for Kotlin lock context lambdas
34
class LockCallback<R>: PowerSyncKotlin.ThrowableLockCallback {
45
let callback: (ConnectionContext) throws -> R
56

@@ -31,12 +32,15 @@ class LockCallback<R>: PowerSyncKotlin.ThrowableLockCallback {
3132
} catch {
3233
return PowerSyncKotlin.PowerSyncException(
3334
message: error.localizedDescription,
34-
cause: PowerSyncKotlin.KotlinThrowable(message: error.localizedDescription)
35+
cause: PowerSyncKotlin.KotlinThrowable(
36+
message: error.localizedDescription
37+
)
3538
)
3639
}
3740
}
3841
}
3942

43+
/// Internal Wrapper for Kotlin transaction context lambdas
4044
class TransactionCallback<R>: PowerSyncKotlin.ThrowableTransactionCallback {
4145
let callback: (Transaction) throws -> R
4246

@@ -54,7 +58,9 @@ class TransactionCallback<R>: PowerSyncKotlin.ThrowableTransactionCallback {
5458
} catch {
5559
return PowerSyncKotlin.PowerSyncException(
5660
message: error.localizedDescription,
57-
cause: PowerSyncKotlin.KotlinThrowable(message: error.localizedDescription)
61+
cause: PowerSyncKotlin.KotlinThrowable(
62+
message: error.localizedDescription
63+
)
5864
)
5965
}
6066
}

Sources/PowerSync/Kotlin/db/KotlinConnectionContext.swift

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,22 @@
11
import Foundation
22
import PowerSyncKotlin
33

4+
/// Extension of the `ConnectionContext` protocol which allows mixin of common logic required for Kotlin adapters
45
protocol KotlinConnectionContextProtocol: ConnectionContext {
6+
/// Implementations should provide access to a Kotlin context.
7+
/// The protocol extension will use this to provide shared implementation.
58
var ctx: PowerSyncKotlin.ConnectionContext { get }
69
}
710

11+
/// Implements most of `ConnectionContext` using the `ctx` provided.
812
extension KotlinConnectionContextProtocol {
913
func execute(sql: String, parameters: [Any?]?) throws -> Int64 {
1014
try ctx.execute(
1115
sql: sql,
1216
parameters: mapParameters(parameters)
1317
)
1418
}
15-
19+
1620
func getOptional<RowType>(
1721
sql: String,
1822
parameters: [Any?]?,
@@ -30,7 +34,7 @@ extension KotlinConnectionContextProtocol {
3034
resultType: RowType?.self
3135
)
3236
}
33-
37+
3438
func getAll<RowType>(
3539
sql: String,
3640
parameters: [Any?]?,
@@ -48,7 +52,7 @@ extension KotlinConnectionContextProtocol {
4852
resultType: [RowType].self
4953
)
5054
}
51-
55+
5256
func get<RowType>(
5357
sql: String,
5458
parameters: [Any?]?,
@@ -70,22 +74,22 @@ extension KotlinConnectionContextProtocol {
7074

7175
class KotlinConnectionContext: KotlinConnectionContextProtocol {
7276
let ctx: PowerSyncKotlin.ConnectionContext
73-
77+
7478
init(ctx: PowerSyncKotlin.ConnectionContext) {
7579
self.ctx = ctx
7680
}
7781
}
7882

7983
class KotlinTransactionContext: Transaction, KotlinConnectionContextProtocol {
8084
let ctx: PowerSyncKotlin.ConnectionContext
81-
85+
8286
init(ctx: PowerSyncKotlin.PowerSyncTransaction) {
8387
self.ctx = ctx
8488
}
8589
}
8690

8791
// Allows nil values to be passed to the Kotlin [Any] params
88-
internal func mapParameters(_ parameters: [Any?]?) -> [Any] {
92+
func mapParameters(_ parameters: [Any?]?) -> [Any] {
8993
parameters?.map { item in
9094
item ?? NSNull()
9195
} ?? []

Sources/PowerSync/Kotlin/db/KotlinCrudBatch.swift

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
11
import PowerSyncKotlin
22

3+
/// Implements `CrudBatch` using the Kotlin SDK
34
struct KotlinCrudBatch: CrudBatch {
45
let batch: PowerSyncKotlin.CrudBatch
56
let crud: [CrudEntry]
67

7-
init (batch: PowerSyncKotlin.CrudBatch) throws {
8+
init(
9+
batch: PowerSyncKotlin.CrudBatch)
10+
throws
11+
{
812
self.batch = batch
913
self.crud = try batch.crud.map { try KotlinCrudEntry(
1014
entry: $0
@@ -15,7 +19,9 @@ struct KotlinCrudBatch: CrudBatch {
1519
batch.hasMore
1620
}
1721

18-
func complete(writeCheckpoint: String?) async throws {
22+
func complete(
23+
writeCheckpoint: String?
24+
) async throws {
1925
_ = try await batch.complete.invoke(p1: writeCheckpoint)
2026
}
2127
}

Sources/PowerSync/Kotlin/db/KotlinCrudEntry.swift

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
import PowerSyncKotlin
22

3+
/// Implements `CrudEntry` using the KotlinSDK
34
struct KotlinCrudEntry : CrudEntry {
45
let entry: PowerSyncKotlin.CrudEntry
56
let op: UpdateType
67

7-
init (entry: PowerSyncKotlin.CrudEntry) throws {
8+
init (
9+
entry: PowerSyncKotlin.CrudEntry
10+
) throws {
811
self.entry = entry
912
self.op = try UpdateType.fromString(entry.op.name)
1013
}

Sources/PowerSync/Kotlin/db/KotlinCrudTransaction.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import PowerSyncKotlin
22

3+
/// Implements `CrudTransaction` using the Kotlin SDK
34
struct KotlinCrudTransaction: CrudTransaction {
45
let transaction: PowerSyncKotlin.CrudTransaction
56
let crud: [CrudEntry]
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import PowerSyncKotlin
2+
3+
/// Converts a Swift `JsonValue` to one accepted by the Kotlin SDK
4+
extension JsonValue {
5+
func toKotlinMap() -> PowerSyncKotlin.JsonParam {
6+
switch self {
7+
case .string(let value):
8+
return PowerSyncKotlin.JsonParam.String(value: value)
9+
case .int(let value):
10+
return PowerSyncKotlin.JsonParam.Number(value: value)
11+
case .double(let value):
12+
return PowerSyncKotlin.JsonParam.Number(value: value)
13+
case .bool(let value):
14+
return PowerSyncKotlin.JsonParam.Boolean(value: value)
15+
case .null:
16+
return PowerSyncKotlin.JsonParam.Null()
17+
case .array(let array):
18+
return PowerSyncKotlin.JsonParam.Collection(
19+
value: array.map { $0.toKotlinMap() }
20+
)
21+
case .object(let dict):
22+
var anyDict: [String: PowerSyncKotlin.JsonParam] = [:]
23+
for (key, value) in dict {
24+
anyDict[key] = value.toKotlinMap()
25+
}
26+
return PowerSyncKotlin.JsonParam.Map(value: anyDict)
27+
}
28+
}
29+
}

0 commit comments

Comments
 (0)