-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathSystemManager.swift
More file actions
351 lines (318 loc) · 13.1 KB
/
Copy pathSystemManager.swift
File metadata and controls
351 lines (318 loc) · 13.1 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
import Foundation
import PowerSync
func getAttachmentsDirectoryPath() throws -> String {
guard let documentsURL = FileManager.default.urls(
for: .documentDirectory,
in: .userDomainMask
).first else {
throw PowerSyncAttachmentError.invalidPath("Could not determine attachments directory path")
}
return documentsURL.appendingPathComponent("attachments").path
}
let logTag = "SystemManager"
/// We use the MainActor SupabaseConnector synchronously here, this requires specifying that SystemManager runs on the MainActor
/// We don't actually block the MainActor with anything
@Observable
@MainActor
final class SystemManager {
let connector = SupabaseConnector()
let schema = AppSchema
let db: PowerSyncDatabaseProtocol
let attachments: AttachmentQueue?
init() {
db = PowerSyncDatabase(
schema: schema,
dbFilename: "powersync-swift.sqlite"
)
attachments = Self.createAttachmentQueue(
db: db,
connector: connector
)
}
/// Creates an AttachmentQueue if a Supabase Storage bucket has been specified in the config
private static func createAttachmentQueue(
db: PowerSyncDatabaseProtocol,
connector: SupabaseConnector
) -> AttachmentQueue? {
guard let bucket = connector.getStorageBucket() else {
db.logger.info("No Supabase Storage bucket specified. Skipping attachment queue setup.", tag: logTag)
return nil
}
do {
let attachmentsDir = try getAttachmentsDirectoryPath()
return AttachmentQueue(
db: db,
remoteStorage: SupabaseRemoteStorage(storage: bucket),
attachmentsDirectory: attachmentsDir,
watchAttachments: { try db.watch(
options: WatchOptions(
sql: "SELECT photo_id FROM \(TODOS_TABLE) WHERE photo_id IS NOT NULL",
parameters: [],
mapper: { cursor in
try WatchedAttachmentItem(
id: cursor.getString(name: "photo_id"),
fileExtension: "jpg"
)
}
)
) }
)
} catch {
db.logger.error("Failed to initialize attachments queue: \(error)", tag: logTag)
return nil
}
}
func connect() async {
do {
// Passing a custom URL session is not required, but it can be used to intercept HTTP requests
// or to configure additional headers like shown here.
let config = URLSessionConfiguration.ephemeral
config.httpAdditionalHeaders = ["x-my-custom-header": "example"]
let session = URLSession(configuration: config)
try await db.connect(
connector: connector,
options: ConnectOptions(
clientConfiguration: SyncClientConfiguration(
requestLogger: SyncRequestLoggerConfiguration(
requestLevel: .headers
) { message in
self.db.logger.debug(message, tag: "SyncRequest")
},
urlSession: session
)
)
)
try await attachments?.startSync()
try await configureFts(db: db, schema: AppSchema)
} catch {
print("Unexpected error: \(error.localizedDescription)") // Catches any other error
}
}
func version() async -> String {
do {
return try await db.getPowerSyncVersion()
} catch {
return error.localizedDescription
}
}
func signOut() async throws {
try await db.disconnectAndClear()
try await connector.client.auth.signOut()
try await attachments?.stopSyncing()
try await attachments?.clearQueue()
}
func watchLists(_ callback: @escaping (_ lists: [ListContent]) -> Void) async {
do {
for try await lists in try db.watch(
options: WatchOptions(
sql: "SELECT * FROM \(LISTS_TABLE)",
mapper: { cursor in
try ListContent(
id: cursor.getString(name: "id"),
name: cursor.getString(name: "name"),
createdAt: cursor.getString(name: "created_at"),
ownerId: cursor.getString(name: "owner_id")
)
}
)
) {
callback(lists)
}
} catch {
print("Error in watch: \(error)")
}
}
func insertList(_ list: NewListContent) async throws {
_ = try await db.execute(
sql: "INSERT INTO \(LISTS_TABLE) (id, created_at, name, owner_id) VALUES (uuid(), datetime(), ?, ?)",
parameters: [list.name, connector.currentUserID]
)
}
func deleteList(id: String) async throws {
let attachmentIds = try await db.writeTransaction(callback: { transaction in
let attachmentIDs = try transaction.getAll(
sql: "SELECT photo_id FROM \(TODOS_TABLE) WHERE list_id = ? AND photo_id IS NOT NULL",
parameters: [id]
) { cursor in
try cursor.getString(index: 0)
}
_ = try transaction.execute(
sql: "DELETE FROM \(LISTS_TABLE) WHERE id = ?",
parameters: [id]
)
_ = try transaction.execute(
sql: "DELETE FROM \(TODOS_TABLE) WHERE list_id = ?",
parameters: [id]
)
return attachmentIDs
})
if let attachments {
for id in attachmentIds {
try await attachments.deleteFile(
attachmentId: id
) { _, _ in }
}
}
}
func watchTodos(_ listId: String, _ callback: @escaping (_ todos: [Todo]) -> Void) async {
do {
for try await todos in try db.watch(
sql: """
SELECT
t.*, a.local_uri
FROM
\(TODOS_TABLE) t
LEFT JOIN attachments a ON t.photo_id = a.id
WHERE
t.list_id = ?
ORDER BY t.id;
""",
parameters: [listId],
mapper: { cursor in
try Todo(
id: cursor.getString(name: "id"),
listId: cursor.getString(name: "list_id"),
photoId: cursor.getStringOptional(name: "photo_id"),
description: cursor.getString(name: "description"),
isComplete: cursor.getBoolean(name: "completed"),
createdAt: cursor.getString(name: "created_at"),
completedAt: cursor.getStringOptional(name: "completed_at"),
createdBy: cursor.getStringOptional(name: "created_by"),
completedBy: cursor.getStringOptional(name: "completed_by"),
photoUri: cursor.getStringOptional(name: "local_uri")
)
}
) {
callback(todos)
}
} catch {
print("Error in watch: \(error)")
}
}
func insertTodo(_ todo: NewTodo, _ listId: String) async throws {
_ = try await db.execute(
sql: "INSERT INTO \(TODOS_TABLE) (id, created_at, created_by, description, list_id, completed) VALUES (uuid(), datetime(), ?, ?, ?, ?)",
parameters: [connector.currentUserID, todo.description, listId, todo.isComplete]
)
}
func updateTodo(_ todo: Todo) async throws {
// Do this to avoid needing to handle date time from Swift to Kotlin
if todo.isComplete {
_ = try await db.execute(
sql: "UPDATE \(TODOS_TABLE) SET description = ?, completed = ?, completed_at = datetime(), completed_by = ? WHERE id = ?",
parameters: [todo.description, todo.isComplete, connector.currentUserID, todo.id]
)
} else {
_ = try await db.execute(
sql: "UPDATE \(TODOS_TABLE) SET description = ?, completed = ?, completed_at = NULL, completed_by = NULL WHERE id = ?",
parameters: [todo.description, todo.isComplete, todo.id]
)
}
}
func deleteTodo(todo: Todo) async throws {
if let attachments, let photoId = todo.photoId {
try await attachments.deleteFile(
attachmentId: photoId
) { transaction, _ in
try transaction.execute(
sql: "DELETE FROM \(TODOS_TABLE) WHERE id = ?",
parameters: [todo.id]
)
}
} else {
_ = try await db.writeTransaction { transaction in
try transaction.execute(
sql: "DELETE FROM \(TODOS_TABLE) WHERE id = ?",
parameters: [todo.id]
)
}
}
}
/// Searches across lists and todos using FTS.
///
/// - Parameter searchTerm: The text to search for.
/// - Returns: An array of search results, containing either `ListContent` or `Todo` objects.
/// - Throws: An error if the database query fails.
func searchListsAndTodos(searchTerm: String) async throws -> [AnyHashable] {
let preparedSearchTerm = createSearchTermWithOptions(searchTerm)
guard !preparedSearchTerm.isEmpty else {
print("[FTS] Prepared search term is empty, returning no results.")
return []
}
print("[FTS] Searching for term: \(preparedSearchTerm)")
var results: [AnyHashable] = []
// --- Search Lists ---
let listSql = """
SELECT l.*
FROM \(LISTS_TABLE) l
JOIN fts_\(LISTS_TABLE) fts ON l.id = fts.id
WHERE fts.fts_\(LISTS_TABLE) MATCH ? ORDER BY fts.rank
"""
do {
let listsFound = try await db.getAll(
sql: listSql,
parameters: [preparedSearchTerm],
mapper: { cursor in
try ListContent(
id: cursor.getString(name: "id"),
name: cursor.getString(name: "name"),
createdAt: cursor.getString(name: "created_at"),
ownerId: cursor.getString(name: "owner_id")
)
}
)
results.append(contentsOf: listsFound)
print("[FTS] Found \(listsFound.count) lists matching term.")
} catch {
print("[FTS] Error searching lists: \(error.localizedDescription)")
throw error
}
// --- Search Todos ---
let todoSql = """
SELECT t.*
FROM \(TODOS_TABLE) t
JOIN fts_\(TODOS_TABLE) fts ON t.id = fts.id
WHERE fts.fts_\(TODOS_TABLE) MATCH ? ORDER BY fts.rank
"""
do {
let todosFound = try await db.getAll(
sql: todoSql,
parameters: [preparedSearchTerm],
mapper: { cursor in
try Todo(
id: cursor.getString(name: "id"),
listId: cursor.getString(name: "list_id"),
photoId: cursor.getStringOptional(name: "photo_id"),
description: cursor.getString(name: "description"),
isComplete: cursor.getBoolean(name: "completed"),
createdAt: cursor.getString(name: "created_at"),
completedAt: cursor.getStringOptional(name: "completed_at"),
createdBy: cursor.getStringOptional(name: "created_by"),
completedBy: cursor.getStringOptional(name: "completed_by")
)
}
)
results.append(contentsOf: todosFound)
print("[FTS] Found \(todosFound.count) todos matching term.")
} catch {
print("[FTS] Error searching todos: \(error.localizedDescription)")
throw error
}
print("[FTS] Total results found: \(results.count)")
return results
}
private func deleteTodoInTX(id: String, tx: ConnectionContext) throws {
_ = try tx.execute(
sql: "DELETE FROM \(TODOS_TABLE) WHERE id = ?",
parameters: [id]
)
}
/// Helper function to prepare the search term for FTS5 query syntax.
private func createSearchTermWithOptions(_ searchTerm: String) -> String {
let trimmedSearchTerm = searchTerm.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmedSearchTerm.isEmpty else {
return ""
}
return "\(trimmedSearchTerm)*"
}
}