forked from scribe-org/Scribe-iOS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLanguageDBManager.swift
More file actions
477 lines (405 loc) · 14.1 KB
/
Copy pathLanguageDBManager.swift
File metadata and controls
477 lines (405 loc) · 14.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
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
// SPDX-License-Identifier: GPL-3.0-or-later
/// Functions for loading in data to the keyboards.
import Foundation
import GRDB
import SwiftyJSON
class LanguageDBManager {
static let shared = LanguageDBManager(translate: false)
static let translations = LanguageDBManager(translate: true)
private var database: DatabaseQueue?
private var cachedHasGrammaticalCase: Bool?
private init(translate: Bool) {
if translate {
database = openDBQueue("TranslationData")
} else {
database = openDownloadedDBQueue("\(getControllerLanguageAbbr().uppercased())LanguageData")
}
}
/// Makes a connection to the language database given the value for controllerLanguage.
private func openDBQueue(_ dbName: String) -> DatabaseQueue {
let dbResourcePath = Bundle.main.path(forResource: dbName, ofType: "sqlite")!
let fileManager = FileManager.default
do {
let dbPath = try fileManager
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("\(dbName).sqlite")
.path
if fileManager.fileExists(atPath: dbPath) {
try fileManager.removeItem(atPath: dbPath)
}
try fileManager.copyItem(atPath: dbResourcePath, toPath: dbPath)
let dbQueue = try DatabaseQueue(path: dbPath)
return dbQueue
} catch {
print("An error occurred: UILexicon not available")
let dbQueue = try! DatabaseQueue(path: dbResourcePath)
return dbQueue
}
}
/// Opens a connection to the downloaded language database for the current language.
private func openDownloadedDBQueue(_ dbName: String) -> DatabaseQueue? {
let fileManager = FileManager.default
guard let containerURL = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.be.scri.userDefaultsContainer") else {
print("App group container not found")
return nil
}
let dbPath = containerURL.appendingPathComponent("\(dbName).sqlite").path
guard fileManager.fileExists(atPath: dbPath) else {
print("\(dbName).sqlite not found in app group container")
return nil
}
return try? DatabaseQueue(path: dbPath)
}
/// Loads a JSON file that contains grammatical information into a dictionary.
///
/// - Parameters
/// - filename: the name of the JSON file to be loaded.
func loadJSON(filename fileName: String) -> JSON {
let url = Bundle.main.url(forResource: fileName, withExtension: "json")!
let data = NSData(contentsOf: url)
let jsonData = try! JSON(data: data! as Data)
return jsonData
}
/// Returns a row from the language database given a query and arguments.
///
/// - Parameters
/// - query: the query to run against the language database.
/// - outputCols: the columns from which the values should come.
/// - args: arguments to pass to `query`.
private func queryDBRow(query: String, outputCols: [String], args: StatementArguments) -> [String] {
var outputValues = [String]()
do {
try database?.read { db in
if let row = try Row.fetchOne(db, sql: query, arguments: args) {
for col in outputCols {
if let stringValue = row[col] as? String {
outputValues.append(stringValue)
} else {
outputValues.append("") // default to empty string if NULL or wrong type
}
}
}
}
} catch let error as DatabaseError {
let errorMessage = error.message
let errorSQL = error.sql
let errorArguments = error.arguments
print(
"An error '\(String(describing: errorMessage))' occurred in the query: \(String(describing: errorSQL)) (\(String(describing: errorArguments)))"
)
} catch {}
if outputValues.isEmpty {
// Append an empty string so that we can check for it and trigger commandState = .invalid.
outputValues.append("")
}
return outputValues
}
/// Returns rows from the language database given a query and arguments.
///
/// - Parameters:
/// - query: the query to run against the language database.
/// - outputCols: the columns from which the values should come.
/// - args: arguments to pass to `query`.
private func queryDBRows(query: String, outputCols: [String], args: StatementArguments) -> [String] {
var outputValues = [String]()
do {
guard let languageDB = database else { return [] }
let rows = try languageDB.read { db in
try Row.fetchAll(db, sql: query, arguments: args)
}
for r in rows {
// Loop through all columns.
for col in outputCols {
if let value = r[col] as? String,
!value.trimmingCharacters(in: .whitespaces).isEmpty {
outputValues.append(value)
}
}
}
} catch let error as DatabaseError {
let errorMessage = error.message
let errorSQL = error.sql
let errorArguments = error.arguments
print(
"An error '\(String(describing: errorMessage))' occurred in the query: \(String(describing: errorSQL)) (\(String(describing: errorArguments)))"
)
} catch {}
if outputValues == [String]() {
// Append an empty string so that we can check for it and trigger commandState = .invalid.
outputValues.append("")
}
return outputValues
}
/// Writes a row of a language database table given a query and arguments.
///
/// - Parameters
/// - query: the query to run against the language database.
/// - args: arguments to pass to `query`.
private func writeDBRow(query: String, args: StatementArguments) {
do {
try database?.write { db in
try db.execute(sql: query, arguments: args)
}
} catch let error as DatabaseError {
let errorMessage = error.message
let errorSQL = error.sql
let errorArguments = error.arguments
print(
"An error '\(String(describing: errorMessage))' occurred in the query: \(String(describing: errorSQL)) (\(String(describing: errorArguments)))"
)
} catch {}
}
/// Deletes rows from the language database given a query and arguments.
///
/// - Parameters:
/// - query: the query to run against the language database.
/// - args: arguments to pass to `query`.
private func deleteDBRow(query: String, args: StatementArguments? = nil) {
do {
try database?.write { db in
guard let args = args else {
try db.execute(sql: query)
return
}
try db.execute(sql: query, arguments: args)
}
} catch let error as DatabaseError {
let errorMessage = error.message
let errorSQL = error.sql
print(
"An error '\(String(describing: errorMessage))' occurred in the query: \(String(describing: errorSQL))"
)
} catch {}
}
}
// MARK: Database operations
extension LanguageDBManager {
/// Delete non-unique values in case the lexicon has added words that were already present.
func deleteNonUniqueAutocompletions() {
let query = """
DELETE FROM
autocomplete_lexicon
WHERE rowid NOT IN (
SELECT
MIN(rowid)
FROM
autocomplete_lexicon
GROUP BY
word
)
"""
deleteDBRow(query: query)
}
/// Add words to autocompletions.
func insertAutocompleteLexicon(of word: String) {
let query = """
INSERT OR IGNORE INTO
autocomplete_lexicon (word)
VALUES (?)
"""
let args = [word]
writeDBRow(query: query, args: StatementArguments(args))
}
/// Returns the next three words in the `autocomplete_lexicon` that follow a given word.
///
/// - Parameters
/// - word: the word that autosuggestions should be returned for.
func queryAutocompletions(word: String) -> [String] {
let autocompletionsQuery = """
SELECT
word
FROM
autocomplete_lexicon
WHERE
LOWER(word) LIKE ?
ORDER BY
word COLLATE NOCASE ASC
LIMIT
3
"""
let outputCols = ["word"]
let args = ["\(word.lowercased())%"]
return queryDBRows(query: autocompletionsQuery, outputCols: outputCols, args: StatementArguments(args))
}
/// Query the suggestion of word in `autosuggestions`.
func queryAutosuggestions(of word: String) -> [String] {
let query = """
SELECT
*
FROM
autosuggestions
WHERE
word = ?
"""
let args = [word]
let outputCols = ["autosuggestion_0", "autosuggestion_1", "autosuggestion_2"]
return queryDBRow(query: query, outputCols: outputCols, args: StatementArguments(args))
}
/// Query emojis of word in `emoji_keywords`.
func queryEmojis(of word: String) -> [String] {
let query = """
SELECT
*
FROM
emoji_keywords
WHERE
word = ?
"""
let outputCols = ["emoji_keyword_0", "emoji_keyword_1", "emoji_keyword_2"]
let args = [word]
return queryDBRow(query: query, outputCols: outputCols, args: StatementArguments(args))
}
/// Query the noun form of word in `nonuns`.
func queryNounForm(of word: String) -> [String] {
let language = getControllerLanguageAbbr()
let contract = ContractManager.shared.loadContract(language: language)
var allGenders: [String] = []
let queries = GenderManager.shared.buildGenderQueries(word: word, contract: contract)
for queryInfo in queries {
let results = queryDBRows(
query: queryInfo.query,
outputCols: queryInfo.outputCols,
args: StatementArguments(queryInfo.args)
)
// For canonical gender: results are the actual genders.
if queryInfo.fallbackGender == nil {
for gender in results where !gender.isEmpty {
if !allGenders.contains(gender) {
allGenders.append(gender)
}
}
}
// For masculine/feminine: if any result, use fallback.
else {
if !results.isEmpty && !results[0].isEmpty,
let fallback = queryInfo.fallbackGender,
!allGenders.contains(fallback) {
allGenders.append(fallback)
}
}
}
return allGenders.isEmpty ? [""] : [allGenders.joined(separator: "/")]
}
/// Query the plural form of word in `nouns`.
func queryNounPlural(of word: String) -> [String] {
let language = getControllerLanguageAbbr()
let contract = ContractManager.shared.loadContract(language: language)
let queryInfos = PluralManager.shared.buildPluralQuery(
word: word,
contract: contract
)
// Try each query until we find a result.
for queryInfo in queryInfos {
let result = queryDBRow(
query: queryInfo.query,
outputCols: queryInfo.outputCols,
args: StatementArguments(queryInfo.args)
)
// If we found a result, return it.
if result.count >= 2 && !result[1].isEmpty {
return [result[1]]
}
}
return []
}
/// Query all plural forms for the current language.
func queryAllPluralForms() -> [String]? {
let language = getControllerLanguageAbbr()
let contract = ContractManager.shared.loadContract(language: language)
guard let queryInfo = PluralManager.shared.buildAllPluralsQuery(contract: contract) else {
return nil
}
let result = queryDBRows(
query: queryInfo.query,
outputCols: queryInfo.outputCols,
args: StatementArguments()
)
return result == [""] ? nil : result
}
/// Query preposition form of word in `prepositions`.
func queryPrepForm(of word: String) -> [String] {
// Check if this language's database has grammaticalCase column.
guard hasGrammaticalCaseColumn() else {
return [""]
}
let query = """
SELECT grammaticalCase
FROM prepositions
WHERE preposition = ?
"""
let outputCols = ["grammaticalCase"]
let args = [word]
return queryDBRow(query: query, outputCols: outputCols, args: StatementArguments(args))
}
/// Check if the prepositions table has a grammaticalCase column.
/// Result is cached to avoid repeated PRAGMA queries.
private func hasGrammaticalCaseColumn() -> Bool {
if let cached = cachedHasGrammaticalCase {
return cached
}
var hasColumn = false
do {
try database?.read { db in
let columns = try Row.fetchAll(db, sql: "PRAGMA table_info(prepositions)")
hasColumn = columns.contains { row in
(row["name"] as? String) == "grammaticalCase"
}
}
} catch {
hasColumn = false
}
cachedHasGrammaticalCase = hasColumn
return hasColumn
}
/// Query the translation of word in the current language. Only works with the `translations` manager.
func queryTranslation(of word: String) -> [String] {
let translateLanguage = getKeyInDict(givenValue: getControllerTranslateLangCode(), dict: languagesAbbrDict)
let query = """
SELECT
*
FROM
\(translateLanguage)
WHERE
word = ?
"""
let outputCols = [getControllerLanguageAbbr()]
let args = [word]
return queryDBRow(query: query, outputCols: outputCols, args: StatementArguments(args))
}
/// Query the verb form of word in `verbs`.
/// - Parameters:
/// - word: The value to search for.
func queryVerb(of word: String) -> [String] {
let columnName = (controllerLanguage == "Swedish") ? "verb" : "infinitive"
let query = """
SELECT
*
FROM
verbs
WHERE
\(columnName) = ?
"""
let outputCols = [columnName]
let args = [word]
return queryDBRow(query: query, outputCols: outputCols, args: StatementArguments(args))
}
/// Query specific form of word in `verbs`.
///
/// - Parameters:
/// - word: The value to search for
/// - identifierColumn: The column to search in (default: "infinitive" or "verb" for Swedish)
/// - outputCols: Specific form want to output
func queryVerb(of word: String, identifierColumn: String? = nil, with outputCols: [String]) -> [String] {
let columnName = identifierColumn ?? ((controllerLanguage == "Swedish") ? "verb" : "infinitive")
let query = """
SELECT
*
FROM
verbs
WHERE
\(columnName) = ?
"""
let args = [word]
return queryDBRow(query: query, outputCols: outputCols, args: StatementArguments(args))
}
}