-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabase.swift
More file actions
895 lines (773 loc) · 25.6 KB
/
Database.swift
File metadata and controls
895 lines (773 loc) · 25.6 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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
import Foundation
private let SQLITE_STATIC = unsafeBitCast(0, to: sqlite3_destructor_type.self)
private let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
class Database {
let file: URL
init(file: URL) throws {
self.file = file
try open()
}
deinit {
close()
}
func open() throws {
if sqlite3_open_v2(file.path, &_handle, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX, nil) != SQLITE_OK {
throw DatabaseError(_handle!)
}
}
func close() {
if _handle != nil {
sqlite3_close(_handle)
_handle = nil
}
}
var schemaVersion: Int {
return try! Int(selectInteger("pragma schema_version"))
}
var userVersion: Int {
get {
return try! Int(selectInteger("pragma user_version"))
}
set {
try! execute("pragma user_version = \(newValue)")
}
}
var lastInsertID: Int64 {
return sqlite3_last_insert_rowid(handle)
}
var affectedRows: Int {
return Int(sqlite3_changes(handle))
}
var changes: Int {
return Int(sqlite3_changes(handle))
}
var totalChanges: Int {
return Int(sqlite3_total_changes(handle))
}
var foreignKeysEnabled = false {
didSet {
if foreignKeysEnabled != oldValue {
let value = foreignKeysEnabled ? "on" : "off"
try! execute("pragma foreign_keys = \(value)")
}
}
}
var writeAheadLogEnabled: Bool {
get {
if let mode = try! selectString("pragma journal_mode") {
return mode == "wal"
}
return false
}
set(value) {
let mode = value ? "wal" : "delete"
try! execute("pragma journal_mode = \(mode)")
}
}
static func drop(_ name: String) {
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let file = path + "/" + name
do {
try FileManager.default.removeItem(atPath: file)
} catch {
print("Cannot drop database \(file): \(error)")
}
}
func upgradeSchema(targetVersion: Int, upgradeToVersion: (Int) throws -> Void) throws {
let foreignKeys = foreignKeysEnabled
foreignKeysEnabled = false
defer { foreignKeysEnabled = foreignKeys }
try transaction {
var version = userVersion
if version == 0 {
try upgradeToVersion(0)
userVersion = targetVersion
} else {
while version < targetVersion {
version += 1
try upgradeToVersion(version)
userVersion = version
}
}
}
}
@discardableResult
func transaction<T>(_ block: () throws -> T) throws -> T {
return try serializeWriteAccess {
let insideTransaction = transactionDepth > 0
transactionDepth += 1
let savepoint = "s\(transactionDepth)"
try execute(insideTransaction ? "savepoint \(savepoint)" : "begin")
do {
let result = try block()
try execute(insideTransaction ? "release savepoint \(savepoint)" : "commit")
transactionDepth -= 1
return result
} catch {
try execute(insideTransaction ? "rollback to savepoint \(savepoint)" : "rollback")
transactionDepth -= 1
throw error
}
}
}
func quote(_ str: String) -> String {
return "'" + str.replacingOccurrences(of: "'", with: "''") + "'"
}
func applyWriteAheadLog() {
try! execute("pragma wal_checkpoint(truncate)")
}
func selectInteger(_ sql: String) throws -> Int64 {
let stmt = try createStmt(handle, sql)
defer { sqlite3_finalize(stmt) }
if sqlite3_step(stmt) == SQLITE_ROW {
return sqlite3_column_int64(stmt, 0)
} else {
throw DatabaseError(handle)
}
}
func selectInteger(_ sql: String, _ params: Param...) throws -> Int64 {
let stmt = try prepare(sql)
stmt.bind(params)
return try stmt.int()
}
func selectString(_ sql: String) throws -> String? {
let stmt = try createStmt(handle, sql)
defer { sqlite3_finalize(stmt) }
if sqlite3_step(stmt) == SQLITE_ROW {
return String(cString: UnsafePointer(sqlite3_column_text(stmt, Int32(0))))
} else {
throw DatabaseError(handle)
}
}
func selectString(_ sql: String, _ params: Param...) throws -> String? {
let stmt = try prepare(sql)
stmt.bind(params)
return try stmt.string()
}
func selectDate(_ sql: String) throws -> Date? {
if let str = try selectString(sql) {
return dateFromString(str)
}
return nil
}
func prepare(_ sql: String) throws -> DatabaseStatement {
return try DatabaseStatement(handle, sql)
}
func execute(_ sql: String) throws {
try serializeWriteAccess {
if sqlite3_exec(handle, sql, nil, nil, nil) != SQLITE_OK {
throw DatabaseError(handle)
}
}
}
func execute(_ sql: String, _ params: Param...) throws {
try serializeWriteAccess {
let stmt = try prepare(sql)
stmt.bind(params)
try stmt.execute()
}
}
func query(_ sql: String, _ params: Param...) throws -> DatabaseRows {
let stmt = try prepare(sql)
stmt.bind(params)
return stmt.query()
}
func insert(into table: String, values: ContentValues) throws -> Int64 {
var names = ""
var params = ""
for (index, value) in values.values.enumerated() {
if index > 0 {
names += ", "
params += ", "
}
names += value.name
params += ":" + value.name
}
let sql = "insert into \(table) (\(names)) values (\(params))"
return try serializeWriteAccess {
let stmt = try prepare(sql)
for value in values.values {
switch value.value {
case nil:
stmt.bindNull(value.name)
case let val as String:
stmt.bind(value.name, val)
case let val as Int32:
stmt.bind(value.name, val)
case let val as Int64:
stmt.bind(value.name, val)
case let val as Double:
stmt.bind(value.name, val)
default:
stmt.bind(value.name, String(describing: value.value!))
}
}
try stmt.execute()
return lastInsertID
}
}
func update(into table: String, values: ContentValues, where whereClause: String, with whereArgs: ContentValue...) throws -> Int {
return try serializeWriteAccess {
return try update(into: table, values: values, where: whereClause, with: whereArgs)
}
}
func update(into table: String, values: ContentValues, where whereClause: String, with whereArgs: [ContentValue]) throws -> Int {
var params = ""
for (index, value) in values.values.enumerated() {
if index > 0 {
params += ", "
}
params += value.name + "=:" + value.name
}
let sql = "update \(table) set \(params) where \(whereClause)"
return try serializeWriteAccess {
let stmt = try prepare(sql)
values.add(whereArgs)
for value in values.values {
switch value.value {
case nil:
stmt.bindNull(value.name)
case let val as String:
stmt.bind(value.name, val)
case let val as Int32:
stmt.bind(value.name, val)
case let val as Int64:
stmt.bind(value.name, val)
case let val as Float:
stmt.bind(value.name, val)
case let val as Double:
stmt.bind(value.name, val)
default:
stmt.bind(value.name, String(describing: value.value!))
}
}
try stmt.execute()
return affectedRows
}
}
func save(into table: String, values: ContentValues, where whereClause: String, with whereArgs: ContentValue...) throws -> Int64? {
return try serializeWriteAccess {
let affectedRows = try update(into: table, values: values, where: whereClause, with: whereArgs)
if affectedRows == 0 {
return try insert(into: table, values: values)
}
return nil
}
}
func upsert(into table: String, values: ContentValues, idName: String) throws -> Int64 {
return try serializeWriteAccess {
if let value = values[idName] as? NSNumber {
let id = value.int64Value
let count = try update(into: table, values: values, where: "\(idName) = \(id)")
if count == 0 {
return try insert(into: table, values: values)
}
return id
}
return try insert(into: table, values: values)
}
}
private var _handle: OpaquePointer?
private var handle: OpaquePointer {
if _handle == nil {
try! open()
}
return _handle!
}
private let semaphore = DispatchSemaphore(value: 1)
private var transactionDepth = 0
private func serializeWriteAccess<T>(_ block: () throws -> T) throws -> T {
let semaphoreAcquired = Thread.current.threadDictionary["acquired"] as? Bool ?? false
defer {
if !semaphoreAcquired {
Thread.current.threadDictionary["acquired"] = false
semaphore.signal()
}
}
if !semaphoreAcquired {
Thread.current.threadDictionary["acquired"] = true
semaphore.wait()
}
return try block()
}
}
class DatabaseStatement {
private var dbHandle: OpaquePointer
fileprivate var handle: OpaquePointer?
private(set) var closed = false
fileprivate init(_ db: OpaquePointer, _ sql: String) throws {
dbHandle = db
if sqlite3_prepare_v2(db, sql, -1, &handle, nil) != SQLITE_OK {
throw DatabaseError(db)
}
}
deinit {
close()
}
func close() {
if !closed {
sqlite3_finalize(handle)
closed = true
}
}
func reset() {
if !closed {
sqlite3_reset(handle)
}
}
func bindNull(_ name: String) {
let index = sqlite3_bind_parameter_index(handle, ":" + name)
assert(index > 0, "Invalid parameter name \"\(name)\"")
sqlite3_bind_null(handle, index)
}
func bind(_ name: String, _ value: Int?) {
let index = sqlite3_bind_parameter_index(handle, ":" + name)
assert(index > 0, "Invalid parameter name \"\(name)\"")
if let value = value {
#if CGFLOAT_IS_DOUBLE
sqlite3_bind_int64(handle, index, sqlite3_int64(value))
#else
sqlite3_bind_int(handle, index, Int32(value))
#endif
} else {
sqlite3_bind_null(handle, index)
}
}
func bind(_ name: String, _ value: Int32?) {
let index = sqlite3_bind_parameter_index(handle, ":" + name)
assert(index > 0, "Invalid parameter name \"\(name)\"")
if let value = value {
sqlite3_bind_int(handle, index, Int32(value))
} else {
sqlite3_bind_null(handle, index)
}
}
func bind(_ name: String, _ value: Int64?) {
let index = sqlite3_bind_parameter_index(handle, ":" + name)
assert(index > 0, "Invalid parameter name \"\(name)\"")
if let value = value {
sqlite3_bind_int64(handle, index, sqlite3_int64(value))
} else {
sqlite3_bind_null(handle, index)
}
}
func bind(_ name: String, _ value: Float?) {
let index = sqlite3_bind_parameter_index(handle, ":" + name)
assert(index > 0, "Invalid parameter name \"\(name)\"")
if let value = value {
sqlite3_bind_double(handle, index, Double(value))
} else {
sqlite3_bind_null(handle, index)
}
}
func bind(_ name: String, _ value: Double?) {
let index = sqlite3_bind_parameter_index(handle, ":" + name)
assert(index > 0, "Invalid parameter name \"\(name)\"")
if let value = value {
sqlite3_bind_double(handle, index, value)
} else {
sqlite3_bind_null(handle, index)
}
}
func bind(_ name: String, _ value: Bool?) {
let index = sqlite3_bind_parameter_index(handle, ":" + name)
assert(index > 0, "Invalid parameter name \"\(name)\"")
if let value = value {
sqlite3_bind_int(handle, index, value ? 1 : 0)
} else {
sqlite3_bind_null(handle, index)
}
}
func bind(_ name: String, _ value: String?) {
let index = sqlite3_bind_parameter_index(handle, ":" + name)
assert(index > 0, "Invalid parameter name \"\(name)\"")
if let value = value {
sqlite3_bind_text(handle, index, value, -1, SQLITE_TRANSIENT)
} else {
sqlite3_bind_null(handle, index)
}
}
func bind(_ name: String, _ value: Date?) {
let index = sqlite3_bind_parameter_index(handle, ":" + name)
assert(index > 0, "Invalid parameter name \"\(name)\"")
if let value = value {
sqlite3_bind_text(handle, index, dateToString(value), -1, SQLITE_TRANSIENT)
} else {
sqlite3_bind_null(handle, index)
}
}
func bind(_ params: [Param]) {
for param in params {
let name = param.name
let value = param.value
switch value {
case let value as Int: bind(name, value)
case let value as Int32: bind(name, value)
case let value as Int64: bind(name, value)
case let value as Float: bind(name, value)
case let value as Double: bind(name, value)
case let value as Bool: bind(name, value)
case let value as String: bind(name, value)
case let value as Date: bind(name, value)
default:
let type = String(describing: value)
let value = value.debugDescription
fatalError("Cannot bind value \(value) of type \(type) to placeholder \"\(name)\"")
}
}
}
func execute() throws {
if sqlite3_step(handle) != SQLITE_DONE {
throw DatabaseError(dbHandle)
}
sqlite3_reset(handle)
}
func query() -> DatabaseRows {
return DatabaseRows(self)
}
func string() throws -> String? {
let result = sqlite3_step(handle)
if result == SQLITE_DONE {
return nil
} else if result == SQLITE_ROW {
if sqlite3_column_type(handle, Int32(0)) == SQLITE_NULL {
return nil
} else {
return String(cString: UnsafePointer(sqlite3_column_text(handle, Int32(0))))
}
} else {
throw DatabaseError(dbHandle)
}
}
func int() throws -> Int64 {
if sqlite3_step(handle) == SQLITE_ROW {
return sqlite3_column_int64(handle, 0)
} else {
throw DatabaseError(dbHandle)
}
}
}
class DatabaseRows {
init(_ stmt: DatabaseStatement) {
self.stmt = stmt
}
deinit {
close()
}
private(set) var hasRow = false
@discardableResult
func next() throws -> Bool {
let res = sqlite3_step(stmt.handle)
if res == SQLITE_DONE {
close()
return false
} else if res == SQLITE_ROW {
hasRow = true
return true
} else {
throw DatabaseError(sqlite3_db_handle(stmt.handle))
}
}
func rewind() {
sqlite3_reset(stmt.handle)
hasRow = false
}
func close() {
hasRow = false
}
func index(_ column: String) -> Int {
if let index = nameToIndex[column] {
return index
}
assertionFailure("Invalid column name \"\(column)\"")
return 0
}
func null(_ column: Int) -> Bool {
return sqlite3_column_type(stmt.handle, Int32(column)) == SQLITE_NULL
}
func null(_ column: String) -> Bool {
if let index = nameToIndex[column] {
return null(index)
}
assertionFailure("Invalid column name \"\(column)\"")
return false
}
func int(_ column: Int) -> Int? {
if sqlite3_column_type(stmt.handle, Int32(column)) == SQLITE_NULL {
return nil
} else {
return Int(sqlite3_column_int64(stmt.handle, Int32(column)))
}
}
func int(_ column: String) -> Int? {
if let index = nameToIndex[column] {
return int(index)
}
assertionFailure("Invalid column name \"\(column)\"")
return nil
}
func int<T>(_ column: Int, convert: (Int) -> T?) -> T? {
if let value = int(column) {
return convert(value)
}
return nil
}
func int<T>(_ column: String, convert: (Int) -> T?) -> T? {
if let value = int(column) {
return convert(value)
}
return nil
}
func int64(_ column: Int) -> Int64? {
if sqlite3_column_type(stmt.handle, Int32(column)) == SQLITE_NULL {
return nil
} else {
return sqlite3_column_int64(stmt.handle, Int32(column))
}
}
func int64(_ column: String) -> Int64? {
if let index = nameToIndex[column] {
return int64(index)
}
assertionFailure("Invalid column name \"\(column)\"")
return nil
}
func int64<T>(_ column: Int, convert: (Int64) -> T?) -> T? {
if let value = int64(column) {
return convert(value)
}
return nil
}
func int64<T>(_ column: String, convert: (Int64) -> T?) -> T? {
if let value = int64(column) {
return convert(value)
}
return nil
}
func float(_ column: Int) -> Float? {
if sqlite3_column_type(stmt.handle, Int32(column)) == SQLITE_NULL {
return nil
} else {
return Float(sqlite3_column_double(stmt.handle, Int32(column)))
}
}
func float(_ column: String) -> Float? {
if let index = nameToIndex[column] {
return float(index)
}
assertionFailure("Invalid column name \"\(column)\"")
return nil
}
func double(_ column: Int) -> Double? {
if sqlite3_column_type(stmt.handle, Int32(column)) == SQLITE_NULL {
return nil
} else {
return sqlite3_column_double(stmt.handle, Int32(column))
}
}
func double(_ column: String) -> Double? {
if let index = nameToIndex[column] {
return double(index)
}
assertionFailure("Invalid column name \"\(column)\"")
return nil
}
func bool(_ column: Int) -> Bool? {
if sqlite3_column_type(stmt.handle, Int32(column)) == SQLITE_NULL {
return nil
} else {
return sqlite3_column_int(stmt.handle, Int32(column)) == 1
}
}
func bool(_ column: String) -> Bool? {
if let index = nameToIndex[column] {
return bool(index)
}
assertionFailure("Invalid column name \"\(column)\"")
return nil
}
func string(_ column: Int) -> String? {
if sqlite3_column_type(stmt.handle, Int32(column)) == SQLITE_NULL {
return nil
} else {
return String(cString: UnsafePointer(sqlite3_column_text(stmt.handle, Int32(column))))
}
}
func string(_ column: String) -> String? {
if let index = nameToIndex[column] {
return string(index)
}
assertionFailure("Invalid column name \"\(column)\"")
return nil
}
func string<T>(_ column: Int, convert: (String) throws -> T?) rethrows -> T? {
if let value = string(column) {
return try convert(value)
}
return nil
}
func string<T>(_ column: String, convert: (String) throws -> T?) rethrows -> T? {
if let value = string(column) {
return try convert(value)
}
return nil
}
func date(_ column: Int) -> Date? {
if sqlite3_column_type(stmt.handle, Int32(column)) == SQLITE_NULL {
return nil
} else {
let str = String(cString: sqlite3_column_text(stmt.handle, Int32(column)))
return dateFromString(str)
}
}
func date(_ column: String) -> Date? {
if let index = nameToIndex[column] {
return date(index)
}
assertionFailure("Invalid column name \"\(column)\"")
return nil
}
// MARK: - Private
private var stmt: DatabaseStatement
private var closed = false
private lazy var nameToIndex: [String: Int] = {
var map = [String: Int]()
let count = Int(sqlite3_column_count(self.stmt.handle))
for i in 0..<count {
let name = String(cString: sqlite3_column_name(self.stmt.handle, Int32(i))) as String?
map[name!] = i
}
return map
}()
}
struct Param {
init(_ name: String, _ value: Any?) {
self.name = name
self.value = value
}
let name: String
let value: Any?
}
struct ContentValue {
init(_ name: String, _ value: Any?) {
self.name = name
self.value = value
}
let name: String
let value: Any?
}
class ContentValues {
fileprivate var values = [ContentValue]()
func clear() {
values.removeAll()
}
func putNull(_ name: String) {
values.append(ContentValue(name, nil))
}
func put(_ name: String, _ value: String?) {
if let value = value {
values.append(ContentValue(name, value))
} else {
values.append(ContentValue(name, nil))
}
}
func put(_ name: String, _ value: Int?) {
if let value = value {
#if CGFLOAT_IS_DOUBLE
values.append(ContentValue(name, Int64(value)))
#else
values.append(ContentValue(name, Int32(value)))
#endif
} else {
values.append(ContentValue(name, nil))
}
}
func put(_ name: String, _ value: Int32?) {
if let value = value {
values.append(ContentValue(name, value))
} else {
values.append(ContentValue(name, nil))
}
}
func put(_ name: String, _ value: Int64?) {
if let value = value {
values.append(ContentValue(name, value))
} else {
values.append(ContentValue(name, nil))
}
}
func put(_ name: String, _ value: Float?) {
if let value = value {
values.append(ContentValue(name, value))
} else {
values.append(ContentValue(name, nil))
}
}
func put(_ name: String, _ value: Double?) {
if let value = value {
values.append(ContentValue(name, value))
} else {
values.append(ContentValue(name, nil))
}
}
func put(_ name: String, _ value: Bool?) {
if let value = value {
let value: Int32 = value ? 1 : 0
values.append(ContentValue(name, value))
} else {
values.append(ContentValue(name, nil))
}
}
func put(_ name: String, _ value: Date?) {
if let value = value {
values.append(ContentValue(name, dateToString(value)))
} else {
values.append(ContentValue(name, nil))
}
}
func add(_ args: [ContentValue]) {
values += args
}
subscript(name: String) -> Any? {
for value in values {
if value.name == name {
return value.value
}
}
return nil
}
}
class DatabaseError: Error, CustomStringConvertible {
let code: Int
let message: String
init(_ db: OpaquePointer) {
code = Int(sqlite3_errcode(db))
message = String(cString: sqlite3_errmsg(db))
}
var description: String {
return "\(message) (error code: \(code))"
}
}
private func createStmt(_ db: OpaquePointer, _ sql: String) throws -> OpaquePointer {
var stmt: OpaquePointer?
if sqlite3_prepare_v2(db, sql, -1, &stmt, nil) != SQLITE_OK {
throw DatabaseError(db)
}
return stmt!
}
private func quote(_ str: String) -> String {
return str.replacingOccurrences(of: "'", with: "''")
}
private func dateToString(_ date: Date) -> String {
return dateFormatter.string(from: date)
}
private func dateFromString(_ str: String) -> Date? {
return dateFormatter.date(from: str)
}
private var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(abbreviation: "UTC")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
return formatter
}()