This repository has been archived by the owner on Jul 20, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 93
/
SwiftData.swift
1708 lines (1373 loc) · 60.7 KB
/
SwiftData.swift
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
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// SwiftData.swift
//
// Copyright (c) 2015 Ryan Fowler
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
// MARK: - SwiftData
public struct SwiftData {
// MARK: - Public SwiftData Functions
// MARK: - Execute Statements
/**
Execute a non-query SQL statement (e.g. INSERT, UPDATE, DELETE, etc.)
This function will execute the provided SQL and return an Int with the error code, or nil if there was no error.
It is recommended to always verify that the return value is nil to ensure that the operation was successful.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
:param: sqlStr The non-query string of SQL to be executed (INSERT, UPDATE, DELETE, etc.)
:returns: An Int with the error code, or nil if there was no error
*/
public static func executeChange(sqlStr: String) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
error = SQLiteDB.sharedInstance.executeChange(sqlStr)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Execute a non-query SQL statement (e.g. INSERT, UPDATE, DELETE, etc.) along with arguments to be bound to the characters "?" (for values) and "i?" (for identifiers e.g. table or column names).
The objects in the provided array of arguments will be bound, in order, to the "i?" and "?" characters in the SQL string.
The quantity of "i?"s and "?"s in the SQL string must be equal to the quantity of arguments provided.
Objects that are to bind as an identifier ("i?") must be of type String.
Identifiers should be bound and escaped if provided by the user.
If "nil" is provided as an argument, the NULL value will be bound to the appropriate value in the SQL string.
For more information on how the objects will be escaped, refer to the functions "escapeValue()" and "escapeIdentifier()".
Note that the "escapeValue()" and "escapeIdentifier()" include the necessary quotations ' ' or " " to the arguments when being bound to the SQL.
It is recommended to always verify that the return value is nil to ensure that the operation was successful.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- binding errors (201 - 203)
:param: sqlStr The non-query string of SQL to be executed (INSERT, UPDATE, DELETE, etc.)
:param: withArgs An array of objects to bind to the "?" and "i?" characters in the sqlStr
:returns: An Int with the error code, or nil if there was no error
*/
public static func executeChange(sqlStr: String, withArgs: [AnyObject]) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
error = SQLiteDB.sharedInstance.executeChange(sqlStr, withArgs: withArgs)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Execute multiple SQL statements (non-queries e.g. INSERT, UPDATE, DELETE, etc.)
This function will execute each SQL statment in the provided array, in order, and return an Int with the error code, or nil if there was no error.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
:param: sqlArr An array of non-query strings of SQL to be executed (INSERT, UPDATE, DELETE, etc.)
:returns: An Int with the error code, or nil if there was no error
*/
public static func executeMultipleChanges(sqlArr: [String]) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
for sqlStr in sqlArr {
if let err = SQLiteDB.sharedInstance.executeChange(sqlStr) {
SQLiteDB.sharedInstance.close()
if let index = find(sqlArr, sqlStr) {
println("Error occurred on array item: \(index) -> \"\(sqlStr)\"")
}
error = err
return
}
}
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Execute a SQLite query statement (e.g. SELECT)
This function will execute the provided SQL and return a tuple of:
- an Array of SDRow objects
- an Int with the error code, or nil if there was no error
The value for each column in an SDRow can be obtained using the column name in the subscript format similar to a Dictionary, along with the function to obtain the value in the appropriate type (.asString(), .asDate(), .asData(), .asInt(), .asDouble(), and .asBool()).
Without the function call to return a specific type, the SDRow will return an object with type AnyObject.
Note: NULL values in the SQLite database will be returned as 'nil'.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
:param: sqlStr The query String of SQL to be executed (e.g. SELECT)
:returns: A tuple containing an Array of "SDRow"s, and an Int with the error code or nil if there was no error
*/
public static func executeQuery(sqlStr: String) -> (result: [SDRow], error: Int?) {
var result = [SDRow] ()
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
(result, error) = SQLiteDB.sharedInstance.executeQuery(sqlStr)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return (result, error)
}
/**
Execute a SQL query statement (e.g. SELECT) with arguments to be bound to the characters "?" (for values) and "i?" (for identifiers e.g. table or column names).
See the "executeChange(sqlStr: String, withArgs: [AnyObject?])" function for more information on the arguments provided and binding.
See the "executeQuery(sqlStr: String)" function for more information on the return value.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- binding errors (201 - 203)
:param: sqlStr The query String of SQL to be executed (e.g. SELECT)
:param: withArgs An array of objects that will be bound, in order, to the characters "?" (for values) and "i?" (for identifiers, e.g. table or column names) in the sqlStr.
:returns: A tuple containing an Array of "SDRow"s, and an Int with the error code or nil if there was no error
*/
public static func executeQuery(sqlStr: String, withArgs: [AnyObject]) -> (result: [SDRow], error: Int?) {
var result = [SDRow] ()
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
(result, error) = SQLiteDB.sharedInstance.executeQuery(sqlStr, withArgs: withArgs)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return (result, error)
}
/**
Execute functions in a closure on a single custom connection
Note: This function cannot be nested within itself, or inside a transaction/savepoint.
Possible errors returned by this function are:
- custom connection errors (301 - 306)
:param: flags The custom flag associated with the connection. Can be either:
- .ReadOnly
- .ReadWrite
- .ReadWriteCreate
:param: closure A closure containing functions that will be executed on the custom connection
:returns: An Int with the error code, or nil if there was no error
*/
public static func executeWithConnection(flags: SD.Flags, closure: ()->Void) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.openWithFlags(flags.toSQL()) {
error = err
return
}
closure()
if let err = SQLiteDB.sharedInstance.closeCustomConnection() {
error = err
return
}
}
putOnThread(task)
return error
}
// MARK: - Escaping Objects
/**
Escape an object to be inserted into a SQLite statement as a value
NOTE: Supported object types are: String, Int, Double, Bool, NSData, NSDate, and nil. All other data types will return the String value "NULL", and a warning message will be printed.
:param: obj The value to be escaped
:returns: The escaped value as a String, ready to be inserted into a SQL statement. Note: Single quotes (') will be placed around the entire value, if necessary.
*/
public static func escapeValue(obj: AnyObject?) -> String {
return SQLiteDB.sharedInstance.escapeValue(obj)
}
/**
Escape a string to be inserted into a SQLite statement as an indentifier (e.g. table or column name)
:param: obj The identifier to be escaped. NOTE: This object must be of type String.
:returns: The escaped identifier as a String, ready to be inserted into a SQL statement. Note: Double quotes (") will be placed around the entire identifier.
*/
public static func escapeIdentifier(obj: String) -> String {
return SQLiteDB.sharedInstance.escapeIdentifier(obj)
}
// MARK: - Tables
/**
Create A Table With The Provided Column Names and Types
Note: The ID field is created automatically as "INTEGER PRIMARY KEY AUTOINCREMENT"
Possible errors returned by this function are:
- SQLite errors (0 - 101)
:param: table The table name to be created
:param: columnNamesAndTypes A dictionary where the key = column name, and the value = data type
:returns: An Int with the error code, or nil if there was no error
*/
public static func createTable(table: String, withColumnNamesAndTypes values: [String: SwiftData.DataType]) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
error = SQLiteDB.sharedInstance.createSQLTable(table, withColumnsAndTypes: values)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Delete a SQLite table by name
Possible errors returned by this function are:
- SQLite errors (0 - 101)
:param: table The table name to be deleted
:returns: An Int with the error code, or nil if there was no error
*/
public static func deleteTable(table: String) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
error = SQLiteDB.sharedInstance.deleteSQLTable(table)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Obtain a list of the existing SQLite table names
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- Table query error (403)
:returns: A tuple containing an Array of all existing SQLite table names, and an Int with the error code or nil if there was no error
*/
public static func existingTables() -> (result: [String], error: Int?) {
var result = [String] ()
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
(result, error) = SQLiteDB.sharedInstance.existingTables()
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return (result, error)
}
// MARK: - Misc
/**
Obtain the error message relating to the provided error code
:param: code The error code provided
:returns: The error message relating to the provided error code
*/
public static func errorMessageForCode(code: Int) -> String {
return SwiftData.SDError.errorMessageFromCode(code)
}
/**
Obtain the database path
:returns: The path to the SwiftData database
*/
public static func databasePath() -> String {
return SQLiteDB.sharedInstance.dbPath
}
/**
Obtain the last inserted row id
Note: Care should be taken when the database is being accessed from multiple threads. The value could possibly return the last inserted row ID for another operation if another thread executes after your intended operation but before this function call.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
:returns: A tuple of he ID of the last successfully inserted row's, and an Int of the error code or nil if there was no error
*/
public static func lastInsertedRowID() -> (rowID: Int, error: Int?) {
var result = 0
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
result = SQLiteDB.sharedInstance.lastInsertedRowID()
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return (result, error)
}
/**
Obtain the number of rows modified by the most recently completed SQLite statement (INSERT, UPDATE, or DELETE)
Note: Care should be taken when the database is being accessed from multiple threads. The value could possibly return the number of rows modified for another operation if another thread executes after your intended operation but before this function call.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
:returns: A tuple of the number of rows modified by the most recently completed SQLite statement, and an Int with the error code or nil if there was no error
*/
public static func numberOfRowsModified() -> (rowID: Int, error: Int?) {
var result = 0
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
result = SQLiteDB.sharedInstance.numberOfRowsModified()
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return (result, error)
}
// MARK: - Indexes
/**
Create a SQLite index on the specified table and column(s)
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- Index error (401)
:param: name The index name that is being created
:param: onColumns An array of column names that the index will be applied to (must be one column or greater)
:param: inTable The table name where the index is being created
:param: isUnique True if the index should be unique, false if it should not be unique (defaults to false)
:returns: An Int with the error code, or nil if there was no error
*/
public static func createIndex(#name: String, onColumns: [String], inTable: String, isUnique: Bool = false) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
error = SQLiteDB.sharedInstance.createIndex(name, columns: onColumns, table: inTable, unique: isUnique)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Remove a SQLite index by its name
Possible errors returned by this function are:
- SQLite errors (0 - 101)
:param: indexName The name of the index to be removed
:returns: An Int with the error code, or nil if there was no error
*/
public static func removeIndex(indexName: String) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
error = SQLiteDB.sharedInstance.removeIndex(indexName)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Obtain a list of all existing indexes
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- Index error (402)
:returns: A tuple containing an Array of all existing index names on the SQLite database, and an Int with the error code or nil if there was no error
*/
public static func existingIndexes() -> (result: [String], error: Int?) {
var result = [String] ()
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
(result, error) = SQLiteDB.sharedInstance.existingIndexes()
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return (result, error)
}
/**
Obtain a list of all existing indexes on a specific table
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- Index error (402)
:param: table The name of the table that is being queried for indexes
:returns: A tuple containing an Array of all existing index names in the table, and an Int with the error code or nil if there was no error
*/
public static func existingIndexesForTable(table: String) -> (result: [String], error: Int?) {
var result = [String] ()
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
(result, error) = SQLiteDB.sharedInstance.existingIndexesForTable(table)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return (result, error)
}
// MARK: - Transactions and Savepoints
/**
Execute commands within a single exclusive transaction
A connection to the database is opened and is not closed until the end of the transaction. A transaction cannot be embedded into another transaction or savepoint.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- Transaction errors (501 - 502)
:param: transactionClosure A closure containing commands that will execute as part of a single transaction. If the transactionClosure returns true, the changes made within the closure will be committed. If false, the changes will be rolled back and will not be saved.
:returns: An Int with the error code, or nil if there was no error committing or rolling back the transaction
*/
public static func transaction(transactionClosure: ()->Bool) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
if let err = SQLiteDB.sharedInstance.beginTransaction() {
SQLiteDB.sharedInstance.close()
error = err
return
}
if transactionClosure() {
if let err = SQLiteDB.sharedInstance.commitTransaction() {
error = err
}
} else {
if let err = SQLiteDB.sharedInstance.rollbackTransaction() {
error = err
}
}
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Execute commands within a single savepoint
A connection to the database is opened and is not closed until the end of the savepoint (or the end of the last savepoint, if embedded).
NOTE: Unlike transactions, savepoints may be embedded into other savepoints or transactions.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
:param: savepointClosure A closure containing commands that will execute as part of a single savepoint. If the savepointClosure returns true, the changes made within the closure will be released. If false, the changes will be rolled back and will not be saved.
:returns: An Int with the error code, or nil if there was no error releasing or rolling back the savepoint
*/
public static func savepoint(savepointClosure: ()->Bool) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
if let err = SQLiteDB.sharedInstance.beginSavepoint() {
SQLiteDB.sharedInstance.close()
error = err
return
}
if savepointClosure() {
if let err = SQLiteDB.sharedInstance.releaseSavepoint() {
error = err
}
} else {
if let err = SQLiteDB.sharedInstance.rollbackSavepoint() {
println("Error rolling back to savepoint")
--SQLiteDB.sharedInstance.savepointsOpen
SQLiteDB.sharedInstance.close()
error = err
return
}
if let err = SQLiteDB.sharedInstance.releaseSavepoint() {
error = err
}
}
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Convenience function to save a UIImage to disk and return the ID
:param: image The UIImage to be saved
:returns: The ID of the saved image as a String, or nil if there was an error saving the image to disk
*/
public static func saveUIImage(image: UIImage) -> String? {
let docsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as String
let imageDirPath = docsPath.stringByAppendingPathComponent("SwiftDataImages")
if !NSFileManager.defaultManager().fileExistsAtPath(imageDirPath) {
if !NSFileManager.defaultManager().createDirectoryAtPath(imageDirPath, withIntermediateDirectories: false, attributes: nil, error: nil) {
println("Error creating SwiftData image folder")
return nil
}
}
let imageID = NSUUID().UUIDString
let imagePath = imageDirPath.stringByAppendingPathComponent(imageID)
let imageAsData = UIImagePNGRepresentation(image)
if !imageAsData.writeToFile(imagePath, atomically: true) {
println("Error saving image")
return nil
}
return imageID
}
/**
Convenience function to delete a UIImage with the specified ID
:param: id The id of the UIImage
:returns: True if the image was successfully deleted, or false if there was an error during the deletion
*/
public static func deleteUIImageWithID(id: String) -> Bool {
let docsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as String
let imageDirPath = docsPath.stringByAppendingPathComponent("SwiftDataImages")
let fullPath = imageDirPath.stringByAppendingPathComponent(id)
return NSFileManager.defaultManager().removeItemAtPath(fullPath, error: nil)
}
// MARK: - SQLiteDB Class
private class SQLiteDB {
class var sharedInstance: SQLiteDB {
struct Singleton {
static let instance = SQLiteDB()
}
return Singleton.instance
}
var sqliteDB: COpaquePointer = nil
var dbPath = SQLiteDB.createPath()
var inTransaction = false
var isConnected = false
var openWithFlags = false
var savepointsOpen = 0
let queue = dispatch_queue_create("SwiftData.DatabaseQueue", DISPATCH_QUEUE_SERIAL)
// MARK: - Database Handling Functions
//open a connection to the sqlite3 database
func open() -> Int? {
if inTransaction || openWithFlags || savepointsOpen > 0 {
return nil
}
if sqliteDB != nil || isConnected {
return nil
}
let status = sqlite3_open(dbPath.cStringUsingEncoding(NSUTF8StringEncoding)!, &sqliteDB)
if status != SQLITE_OK {
println("SwiftData Error -> During: Opening Database")
println(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status)))
if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) {
println(" -> Details: \(errMsg)")
}
return Int(status)
}
isConnected = true
return nil
}
//open a connection to the sqlite3 database with flags
func openWithFlags(flags: Int32) -> Int? {
if inTransaction {
println("SwiftData Error -> During: Opening Database with Flags")
println(" -> Code: 302 - Cannot open a custom connection inside a transaction")
return 302
}
if openWithFlags {
println("SwiftData Error -> During: Opening Database with Flags")
println(" -> Code: 301 - A custom connection is already open")
return 301
}
if savepointsOpen > 0 {
println("SwiftData Error -> During: Opening Database with Flags")
println(" -> Code: 303 - Cannot open a custom connection inside a savepoint")
return 303
}
if isConnected {
println("SwiftData Error -> During: Opening Database with Flags")
println(" -> Code: 301 - A custom connection is already open")
return 301
}
let status = sqlite3_open_v2(dbPath.cStringUsingEncoding(NSUTF8StringEncoding)!, &sqliteDB, flags, nil)
if status != SQLITE_OK {
println("SwiftData Error -> During: Opening Database with Flags")
println(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status)))
if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) {
println(" -> Details: \(errMsg)")
}
return Int(status)
}
isConnected = true
openWithFlags = true
return nil
}
//close the connection to to the sqlite3 database
func close() {
if inTransaction || openWithFlags || savepointsOpen > 0 {
return
}
if sqliteDB == nil || !isConnected {
return
}
let status = sqlite3_close(sqliteDB)
if status != SQLITE_OK {
println("SwiftData Error -> During: Closing Database")
println(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status)))
if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) {
println(" -> Details: \(errMsg)")
}
}
sqliteDB = nil
isConnected = false
}
//close a custom connection to the sqlite3 database
func closeCustomConnection() -> Int? {
if inTransaction {
println("SwiftData Error -> During: Closing Database with Flags")
println(" -> Code: 305 - Cannot close a custom connection inside a transaction")
return 305
}
if savepointsOpen > 0 {
println("SwiftData Error -> During: Closing Database with Flags")
println(" -> Code: 306 - Cannot close a custom connection inside a savepoint")
return 306
}
if !openWithFlags {
println("SwiftData Error -> During: Closing Database with Flags")
println(" -> Code: 304 - A custom connection is not currently open")
return 304
}
let status = sqlite3_close(sqliteDB)
sqliteDB = nil
isConnected = false
openWithFlags = false
if status != SQLITE_OK {
println("SwiftData Error -> During: Closing Database with Flags")
println(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status)))
if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) {
println(" -> Details: \(errMsg)")
}
return Int(status)
}
return nil
}
//create the database path
class func createPath() -> String {
let docsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as String
let databaseStr = "SwiftData.sqlite"
let dbPath = docsPath.stringByAppendingPathComponent(databaseStr)
return dbPath
}
//begin a transaction
func beginTransaction() -> Int? {
if savepointsOpen > 0 {
println("SwiftData Error -> During: Beginning Transaction")
println(" -> Code: 501 - Cannot begin a transaction within a savepoint")
return 501
}
if inTransaction {
println("SwiftData Error -> During: Beginning Transaction")
println(" -> Code: 502 - Cannot begin a transaction within another transaction")
return 502
}
if let error = executeChange("BEGIN EXCLUSIVE") {
return error
}
inTransaction = true
return nil
}
//rollback a transaction
func rollbackTransaction() -> Int? {
let error = executeChange("ROLLBACK")
inTransaction = false
return error
}
//commit a transaction
func commitTransaction() -> Int? {
let error = executeChange("COMMIT")
inTransaction = false
if let err = error {
rollbackTransaction()
return err
}
return nil
}
//begin a savepoint
func beginSavepoint() -> Int? {
if let error = executeChange("SAVEPOINT 'savepoint\(savepointsOpen + 1)'") {
return error
}
++savepointsOpen
return nil
}
//rollback a savepoint
func rollbackSavepoint() -> Int? {
return executeChange("ROLLBACK TO 'savepoint\(savepointsOpen)'")
}
//release a savepoint
func releaseSavepoint() -> Int? {
let error = executeChange("RELEASE 'savepoint\(savepointsOpen)'")
--savepointsOpen
return error
}
//get last inserted row id
func lastInsertedRowID() -> Int {
let id = sqlite3_last_insert_rowid(sqliteDB)
return Int(id)
}
//number of rows changed by last update
func numberOfRowsModified() -> Int {
return Int(sqlite3_changes(sqliteDB))
}
//return value of column
func getColumnValue(statement: COpaquePointer, index: Int32, type: String) -> AnyObject? {
switch type {
case "INT", "INTEGER", "TINYINT", "SMALLINT", "MEDIUMINT", "BIGINT", "UNSIGNED BIG INT", "INT2", "INT8":
if sqlite3_column_type(statement, index) == SQLITE_NULL {
return nil
}
return Int(sqlite3_column_int(statement, index))
case "CHARACTER(20)", "VARCHAR(255)", "VARYING CHARACTER(255)", "NCHAR(55)", "NATIVE CHARACTER", "NVARCHAR(100)", "TEXT", "CLOB":
let text = UnsafePointer<Int8>(sqlite3_column_text(statement, index))
return String.fromCString(text)
case "BLOB", "NONE":
let blob = sqlite3_column_blob(statement, index)
if blob != nil {
let size = sqlite3_column_bytes(statement, index)
return NSData(bytes: blob, length: Int(size))
}
return nil
case "REAL", "DOUBLE", "DOUBLE PRECISION", "FLOAT", "NUMERIC", "DECIMAL(10,5)":
if sqlite3_column_type(statement, index) == SQLITE_NULL {
return nil
}
return Double(sqlite3_column_double(statement, index))
case "BOOLEAN":
if sqlite3_column_type(statement, index) == SQLITE_NULL {
return nil
}
return sqlite3_column_int(statement, index) != 0
case "DATE", "DATETIME":
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let text = UnsafePointer<Int8>(sqlite3_column_text(statement, index))
if let string = String.fromCString(text) {
return dateFormatter.dateFromString(string)
}
println("SwiftData Warning -> The text date at column: \(index) could not be cast as a String, returning nil")
return nil
default:
println("SwiftData Warning -> Column: \(index) is of an unrecognized type, returning nil")
return nil
}
}
// MARK: SQLite Execution Functions
//execute a SQLite update from a SQL String
func executeChange(sqlStr: String, withArgs: [AnyObject]? = nil) -> Int? {
var sql = sqlStr
if let args = withArgs {
let result = bind(args, toSQL: sql)
if let error = result.error {
return error
} else {
sql = result.string
}
}
var pStmt: COpaquePointer = nil
var status = sqlite3_prepare_v2(SQLiteDB.sharedInstance.sqliteDB, sql, -1, &pStmt, nil)
if status != SQLITE_OK {
println("SwiftData Error -> During: SQL Prepare")
println(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status)))
if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) {
println(" -> Details: \(errMsg)")