From 6a8ebf4016b16dfd6108a17a4398e976c0227957 Mon Sep 17 00:00:00 2001 From: Hasan Raza Date: Thu, 31 Oct 2019 12:23:12 +0500 Subject: [PATCH] compatible with Swift5 and Data conversion issue fixed. Data insertion was causing a crash at line number 1307 --- SwiftData.swift | 1085 +++++++++++++++++++++++------------------------ 1 file changed, 535 insertions(+), 550 deletions(-) diff --git a/SwiftData.swift b/SwiftData.swift index c3e7ad2..5f78c60 100644 --- a/SwiftData.swift +++ b/SwiftData.swift @@ -21,7 +21,6 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. - import Foundation import UIKit @@ -37,20 +36,20 @@ public struct SwiftData { // 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? { + 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 = { @@ -67,30 +66,29 @@ public struct SwiftData { } /** - 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? { - + 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() { @@ -106,19 +104,16 @@ public struct SwiftData { } /** - 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? { + 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 = { @@ -129,8 +124,8 @@ public struct SwiftData { 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)\"") + if let index = sqlArr.firstIndex(of: sqlStr) {//find(sqlArr, sqlStr) { + print("Error occurred on array item: \(index) -> \"\(sqlStr)\"") } error = err return @@ -144,25 +139,24 @@ public struct SwiftData { } /** - 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?) { + 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 @@ -180,24 +174,20 @@ public struct SwiftData { } /** - 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?) { - + 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 = { @@ -212,28 +202,23 @@ public struct SwiftData { 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? { - + /** + 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: @escaping ()->Void) -> Int? { + var error: Int? = nil let task: ()->Void = { if let err = SQLiteDB.sharedInstance.openWithFlags(flags.toSQL()) { @@ -250,31 +235,31 @@ public struct SwiftData { 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 { + 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 { + 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) } @@ -282,20 +267,17 @@ public struct SwiftData { // 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? { + 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 = { @@ -312,17 +294,15 @@ public struct SwiftData { } /** - 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? { + 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 = { @@ -339,15 +319,13 @@ public struct SwiftData { } /** - 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 - */ + 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] () @@ -367,39 +345,34 @@ public struct SwiftData { // 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 { + 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 - */ + /** + 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 - */ + 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 @@ -418,16 +391,13 @@ public struct SwiftData { } /** - 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 - */ + 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 @@ -449,21 +419,19 @@ public struct SwiftData { // 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? { + 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 = { @@ -480,17 +448,15 @@ public struct SwiftData { } /** - 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? { + 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 = { @@ -507,15 +473,13 @@ public struct SwiftData { } /** - 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 - */ + 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] () @@ -534,18 +498,16 @@ public struct SwiftData { } /** - 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?) { + 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 @@ -566,20 +528,18 @@ public struct SwiftData { // 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? { + 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: @escaping ()->Bool) -> Int? { var error: Int? = nil let task: ()->Void = { @@ -609,22 +569,20 @@ public struct SwiftData { } /** - 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? { - + 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: @escaping ()->Bool) -> Int? { + var error: Int? = nil let task: ()->Void = { if let err = SQLiteDB.sharedInstance.open() { @@ -642,8 +600,8 @@ public struct SwiftData { } } else { if let err = SQLiteDB.sharedInstance.rollbackSavepoint() { - println("Error rolling back to savepoint") - --SQLiteDB.sharedInstance.savepointsOpen + print("Error rolling back to savepoint") + SQLiteDB.sharedInstance.savepointsOpen -= 1 SQLiteDB.sharedInstance.close() error = err return @@ -660,53 +618,78 @@ public struct SwiftData { } /** - 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") + 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(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]; + let imageDirPath = docsPath.appendingFormat("/%@", "SwiftDataImages"); //docsPath.stringByAppendingPathComponent("SwiftDataImages") + if !FileManager.default.fileExists(atPath: imageDirPath) { + do + { + try FileManager.default.createDirectory(atPath: imageDirPath, withIntermediateDirectories: false, attributes: nil); + }catch _ as NSError + { + print("Error creating SwiftData image folder") + return nil + + } + + // if !NSFileManager.defaultManager().createDirectoryAtPath(imageDirPath, withIntermediateDirectories: false, attributes: nil, error: nil) { + // print("Error creating SwiftData image folder") + // return nil + // } + } + let imageID = UUID().uuidString + let imagePath = imageDirPath.appendingFormat("/%@", imageID); //imageDirPath.stringByAppendingPathComponent(imageID) + let imageAsData = image.pngData() + if let _ = imageAsData + { + if !((try? imageAsData!.write(to: URL(fileURLWithPath: imagePath), options: [.atomic])) != nil) { + print("Error saving image") 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 + else + { + 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) + 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(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]; + let imageDirPath = docsPath.appendingFormat("/%@", "SwiftDataImages"); //stringByAppendingPathComponent("SwiftDataImages") + let fullPath = imageDirPath.appendingFormat("/%@", id); // stringByAppendingPathComponent(id) + do + { + try FileManager.default.removeItem(atPath: fullPath); + return true; + } + catch _ as NSError + { + return false; + } + //return NSFileManager.defaultManager().removeItemAtPath(fullPath, error: nil) } // MARK: - SQLiteDB Class - private class SQLiteDB { + fileprivate class SQLiteDB { class var sharedInstance: SQLiteDB { struct Singleton { @@ -714,32 +697,32 @@ public struct SwiftData { } return Singleton.instance } - var sqliteDB: COpaquePointer = nil + var sqliteDB: OpaquePointer? = 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) + let queue = DispatchQueue(label: "SwiftData.DatabaseQueue", attributes: []) // 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) + let status = sqlite3_open(dbPath.cString(using: String.Encoding.utf8)!, &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)") + print("SwiftData Error -> During: Opening Database") + print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) + if let errMsg = String(validatingUTF8: sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { + print(" -> Details: \(errMsg)") } return Int(status) } @@ -749,34 +732,34 @@ public struct SwiftData { } //open a connection to the sqlite3 database with flags - func openWithFlags(flags: Int32) -> Int? { + 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") + print("SwiftData Error -> During: Opening Database with Flags") + print(" -> 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") + print("SwiftData Error -> During: Opening Database with Flags") + print(" -> 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") + print("SwiftData Error -> During: Opening Database with Flags") + print(" -> 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") + print("SwiftData Error -> During: Opening Database with Flags") + print(" -> Code: 301 - A custom connection is already open") return 301 } - let status = sqlite3_open_v2(dbPath.cStringUsingEncoding(NSUTF8StringEncoding)!, &sqliteDB, flags, nil) + let status = sqlite3_open_v2(dbPath.cString(using: String.Encoding.utf8)!, &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)") + print("SwiftData Error -> During: Opening Database with Flags") + print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) + if let errMsg = String(validatingUTF8: sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { + print(" -> Details: \(errMsg)") } return Int(status) } @@ -788,7 +771,7 @@ public struct SwiftData { //close the connection to to the sqlite3 database func close() { - + if inTransaction || openWithFlags || savepointsOpen > 0 { return } @@ -797,10 +780,10 @@ public struct SwiftData { } 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)") + print("SwiftData Error -> During: Closing Database") + print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) + if let errMsg = String(validatingUTF8: sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { + print(" -> Details: \(errMsg)") } } sqliteDB = nil @@ -808,22 +791,22 @@ public struct SwiftData { } - //close a custom connection to the sqlite3 database + //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") + print("SwiftData Error -> During: Closing Database with Flags") + print(" -> 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") + print("SwiftData Error -> During: Closing Database with Flags") + print(" -> 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") + print("SwiftData Error -> During: Closing Database with Flags") + print(" -> Code: 304 - A custom connection is not currently open") return 304 } let status = sqlite3_close(sqliteDB) @@ -831,10 +814,10 @@ public struct SwiftData { 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)") + print("SwiftData Error -> During: Closing Database with Flags") + print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) + if let errMsg = String(validatingUTF8: sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { + print(" -> Details: \(errMsg)") } return Int(status) } @@ -845,9 +828,9 @@ public struct SwiftData { //create the database path class func createPath() -> String { - let docsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as String + let docsPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] let databaseStr = "SwiftData.sqlite" - let dbPath = docsPath.stringByAppendingPathComponent(databaseStr) + let dbPath = docsPath.appendingFormat("/%@", databaseStr); //stringByAppendingPathComponent(databaseStr) return dbPath } @@ -856,13 +839,13 @@ public struct SwiftData { func beginTransaction() -> Int? { if savepointsOpen > 0 { - println("SwiftData Error -> During: Beginning Transaction") - println(" -> Code: 501 - Cannot begin a transaction within a savepoint") + print("SwiftData Error -> During: Beginning Transaction") + print(" -> 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") + print("SwiftData Error -> During: Beginning Transaction") + print(" -> Code: 502 - Cannot begin a transaction within another transaction") return 502 } if let error = executeChange("BEGIN EXCLUSIVE") { @@ -901,7 +884,7 @@ public struct SwiftData { if let error = executeChange("SAVEPOINT 'savepoint\(savepointsOpen + 1)'") { return error } - ++savepointsOpen + savepointsOpen += 1 return nil } @@ -915,7 +898,7 @@ public struct SwiftData { func releaseSavepoint() -> Int? { let error = executeChange("RELEASE 'savepoint\(savepointsOpen)'") - --savepointsOpen + savepointsOpen -= 1 return error } @@ -932,55 +915,68 @@ public struct SwiftData { } //return value of column - func getColumnValue(statement: COpaquePointer, index: Int32, type: String) -> AnyObject? { + func getColumnValue(_ statement: OpaquePointer, 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)) + return Int(sqlite3_column_int(statement, index)) as AnyObject? case "CHARACTER(20)", "VARCHAR(255)", "VARYING CHARACTER(255)", "NCHAR(55)", "NATIVE CHARACTER", "NVARCHAR(100)", "TEXT", "CLOB": - let text = UnsafePointer(sqlite3_column_text(statement, index)) - return String.fromCString(text) + let text = sqlite3_column_text(statement, index) + return String(cString: text!) as AnyObject? 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 Data(bytes: blob!, count: Int(size)) as AnyObject? + } 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)) + return Double(sqlite3_column_double(statement, index)) as AnyObject? case "BOOLEAN": if sqlite3_column_type(statement, index) == SQLITE_NULL { return nil } - return sqlite3_column_int(statement, index) != 0 + let val = sqlite3_column_int(statement, index) + return NSNumber(value: val) case "DATE", "DATETIME": - let dateFormatter = NSDateFormatter() + let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" - let text = UnsafePointer(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") + let text = sqlite3_column_text(statement, index) as AnyObject +// if let string = String(validatingUTF8: text as! UnsafePointer) { +// return dateFormatter.date(from: string) as AnyObject? +// } +// let utf8String = String(cString: text) as AnyObject? +// if let string = String(validatingUTF8: utf8String as! UnsafePointer) { +// return dateFormatter.date(from: string) as AnyObject? +// } + + print("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") + print("SwiftData Warning -> Column: \(index) is of an unrecognized type, returning nil") return nil } } + // func getColumnValue(_ statement: OpaquePointer, index: Int32, type: String) -> AnyObject? { + // let val = sqlite3_column_int(statement, index) + // return NSNumber(value: val) + // } + // MARK: SQLite Execution Functions //execute a SQLite update from a SQL String - func executeChange(sqlStr: String, withArgs: [AnyObject]? = nil) -> Int? { + func executeChange(_ sqlStr: String, withArgs: [AnyObject]? = nil) -> Int? { var sql = sqlStr if let args = withArgs { @@ -991,23 +987,23 @@ public struct SwiftData { sql = result.string } } - var pStmt: COpaquePointer = nil + var pStmt: OpaquePointer? = 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)") + print("SwiftData Error -> During: SQL Prepare") + print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) + if let errMsg = String(validatingUTF8: sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { + print(" -> Details: \(errMsg)") } sqlite3_finalize(pStmt) return Int(status) } status = sqlite3_step(pStmt) if status != SQLITE_DONE && status != SQLITE_OK { - println("SwiftData Error -> During: SQL Step") - println(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) - if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { - println(" -> Details: \(errMsg)") + print("SwiftData Error -> During: SQL Step") + print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) + if let errMsg = String(validatingUTF8: sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { + print(" -> Details: \(errMsg)") } sqlite3_finalize(pStmt) return Int(status) @@ -1018,7 +1014,7 @@ public struct SwiftData { } //execute a SQLite query from a SQL String - func executeQuery(sqlStr: String, withArgs: [AnyObject]? = nil) -> (result: [SDRow], error: Int?) { + func executeQuery(_ sqlStr: String, withArgs: [AnyObject]? = nil) -> (result: [SDRow], error: Int?) { var resultSet = [SDRow]() var sql = sqlStr @@ -1030,13 +1026,13 @@ public struct SwiftData { sql = result.string } } - var pStmt: COpaquePointer = nil + var pStmt: OpaquePointer? = 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)") + print("SwiftData Error -> During: SQL Prepare") + print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) + if let errMsg = String(validatingUTF8: sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { + print(" -> Details: \(errMsg)") } sqlite3_finalize(pStmt) return (resultSet, Int(status)) @@ -1048,10 +1044,11 @@ public struct SwiftData { if status == SQLITE_ROW { columnCount = sqlite3_column_count(pStmt) var row = SDRow() - for var i: Int32 = 0; i < columnCount; ++i { - let columnName = String.fromCString(sqlite3_column_name(pStmt, i))! - if let columnType = String.fromCString(sqlite3_column_decltype(pStmt, i))?.uppercaseString { - if let columnValue: AnyObject = getColumnValue(pStmt, index: i, type: columnType) { + for i: Int32 in 0 ..< columnCount { + let columnName = String(cString: sqlite3_column_name(pStmt, i)) + + if let columnType = String(validatingUTF8: sqlite3_column_decltype(pStmt, i))?.uppercased() { + if let columnValue: AnyObject = getColumnValue(pStmt!, index: i, type: columnType) { row[columnName] = SDColumn(obj: columnValue) } } else { @@ -1072,7 +1069,7 @@ public struct SwiftData { default: columnType = "NULL" } - if let columnValue: AnyObject = getColumnValue(pStmt, index: i, type: columnType) { + if let columnValue: AnyObject = getColumnValue(pStmt!, index: i, type: columnType) { row[columnName] = SDColumn(obj: columnValue) } } @@ -1081,10 +1078,10 @@ public struct SwiftData { } else if status == SQLITE_DONE { next = false } else { - println("SwiftData Error -> During: SQL Step") - println(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) - if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { - println(" -> Details: \(errMsg)") + print("SwiftData Error -> During: SQL Step") + print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) + if let errMsg = String(validatingUTF8: sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { + print(" -> Details: \(errMsg)") } sqlite3_finalize(pStmt) return (resultSet, Int(status)) @@ -1101,7 +1098,7 @@ public struct SwiftData { // MARK: - SDRow public struct SDRow { - + var values = [String: SDColumn]() public subscript(key: String) -> SDColumn? { get { @@ -1125,99 +1122,91 @@ public struct SwiftData { } //return value by type - + /** - Return the column value as a String - - :returns: An Optional String corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as a String, or the value is NULL - */ + Return the column value as a String + :returns: An Optional String corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as a String, or the value is NULL + */ public func asString() -> String? { return value as? String } - + /** - Return the column value as an Int - - :returns: An Optional Int corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as a Int, or the value is NULL - */ + Return the column value as an Int + :returns: An Optional Int corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as a Int, or the value is NULL + */ public func asInt() -> Int? { return value as? Int } - + /** - Return the column value as a Double - - :returns: An Optional Double corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as a Double, or the value is NULL - */ + Return the column value as a Double + :returns: An Optional Double corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as a Double, or the value is NULL + */ public func asDouble() -> Double? { return value as? Double } - + /** - Return the column value as a Bool - - :returns: An Optional Bool corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as a Bool, or the value is NULL - */ + Return the column value as a Bool + :returns: An Optional Bool corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as a Bool, or the value is NULL + */ public func asBool() -> Bool? { return value as? Bool } - + /** - Return the column value as NSData - - :returns: An Optional NSData object corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as NSData, or the value is NULL - */ - public func asData() -> NSData? { - return value as? NSData + Return the column value as NSData + :returns: An Optional NSData object corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as NSData, or the value is NULL + */ + public func asData() -> Data? { + return value as? Data } - + /** - Return the column value as an NSDate - - :returns: An Optional NSDate corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as an NSDate, or the value is NULL - */ - public func asDate() -> NSDate? { - return value as? NSDate + Return the column value as an NSDate + :returns: An Optional NSDate corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as an NSDate, or the value is NULL + */ + public func asDate() -> Date? { + return value as? Date } - + /** - Return the column value as an AnyObject - - :returns: An Optional AnyObject corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as an AnyObject, or the value is NULL - */ + Return the column value as an AnyObject + :returns: An Optional AnyObject corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as an AnyObject, or the value is NULL + */ public func asAnyObject() -> AnyObject? { return value } /** - Return the column value path as a UIImage - - :returns: An Optional UIImage corresponding to the path of the apprioriate column value. Will be nil if: the column name does not exist, the value of the specified path cannot be cast as a UIImage, or the value is NULL - */ + Return the column value path as a UIImage + :returns: An Optional UIImage corresponding to the path of the apprioriate column value. Will be nil if: the column name does not exist, the value of the specified path cannot be cast as a UIImage, or the value is NULL + */ public func asUIImage() -> UIImage? { if let path = value as? String{ - let docsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as String - let imageDirPath = docsPath.stringByAppendingPathComponent("SwiftDataImages") - let fullPath = imageDirPath.stringByAppendingPathComponent(path) - if !NSFileManager.defaultManager().fileExistsAtPath(fullPath) { - println("SwiftData Error -> Invalid image ID provided") + let docsPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] + let imageDirPath = docsPath.appendingFormat("/%@", "SwiftDataImages");//stringByAppendingPathComponent("SwiftDataImages") + let fullPath = imageDirPath.appendingFormat("/%@", path);//stringByAppendingPathComponent(path) + if !FileManager.default.fileExists(atPath: fullPath) { + print("SwiftData Error -> Invalid image ID provided") return nil } - if let imageAsData = NSData(contentsOfFile: fullPath) { + if let imageAsData = try? Data(contentsOf: URL(fileURLWithPath: fullPath)) { return UIImage(data: imageAsData) } } return nil } - + } // MARK: - Error Handling - private struct SDError { + fileprivate struct SDError { } @@ -1228,11 +1217,11 @@ public struct SwiftData { extension SwiftData { - private static func putOnThread(task: ()->Void) { + fileprivate static func putOnThread(_ task: ()->Void) { if SQLiteDB.sharedInstance.inTransaction || SQLiteDB.sharedInstance.savepointsOpen > 0 || SQLiteDB.sharedInstance.openWithFlags { task() } else { - dispatch_sync(SQLiteDB.sharedInstance.queue) { + SQLiteDB.sharedInstance.queue.sync { task() } } @@ -1244,17 +1233,17 @@ extension SwiftData { // MARK: - Escaping And Binding Functions extension SwiftData.SQLiteDB { - - func bind(objects: [AnyObject], toSQL sql: String) -> (string: String, error: Int?) { - + + func bind(_ objects: [AnyObject], toSQL sql: String) -> (string: String, error: Int?) { + var newSql = "" var bindIndex = 0 var i = false for char in sql { if char == "?" { if bindIndex > objects.count - 1 { - println("SwiftData Error -> During: Object Binding") - println(" -> Code: 201 - Not enough objects to bind provided") + print("SwiftData Error -> During: Object Binding") + print(" -> Code: 201 - Not enough objects to bind provided") return ("", 201) } var obj = "" @@ -1262,16 +1251,16 @@ extension SwiftData.SQLiteDB { if let str = objects[bindIndex] as? String { obj = escapeIdentifier(str) } else { - println("SwiftData Error -> During: Object Binding") - println(" -> Code: 203 - Object to bind as identifier must be a String at array location: \(bindIndex)") + print("SwiftData Error -> During: Object Binding") + print(" -> Code: 203 - Object to bind as identifier must be a String at array location: \(bindIndex)") return ("", 203) } - newSql = newSql.substringToIndex(newSql.endIndex.predecessor()) + newSql = newSql.substring(to: newSql.index(before: newSql.endIndex)) } else { obj = escapeValue(objects[bindIndex]) } newSql += obj - ++bindIndex + bindIndex += 1 } else { newSql.append(char) } @@ -1282,8 +1271,8 @@ extension SwiftData.SQLiteDB { } } if bindIndex != objects.count { - println("SwiftData Error -> During: Object Binding") - println(" -> Code: 202 - Too many objects to bind provided") + print("SwiftData Error -> During: Object Binding") + print(" -> Code: 202 - Too many objects to bind provided") return ("", 202) } return (newSql, nil) @@ -1291,45 +1280,40 @@ extension SwiftData.SQLiteDB { } //return escaped String value of AnyObject - func escapeValue(obj: AnyObject?) -> String { + func escapeValue(_ obj: AnyObject?) -> String { if let obj: AnyObject = obj { if obj is String { - return "'\(escapeStringValue(obj as String))'" + return "'\(escapeStringValue(obj as! String))'" } if obj is Double || obj is Int { return "\(obj)" } if obj is Bool { - if obj as Bool { + if obj as! Bool { return "1" } else { return "0" } } - if obj is NSData { - let str = "\(obj)" - var newStr = "" - for char in str { - if char != "<" && char != ">" && char != " " { - newStr.append(char) - } - } + if obj is Data { + let data = obj as! Data + let newStr = data.map { String(format: "%02.2hhx", $0) }.joined() return "X'\(newStr)'" } - if obj is NSDate { - let dateFormatter = NSDateFormatter() + if obj is Date { + let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" - return "\(escapeValue(dateFormatter.stringFromDate(obj as NSDate)))" + return "\(escapeValue(dateFormatter.string(from: obj as! Date) as AnyObject?))" } if obj is UIImage { - if let imageID = SD.saveUIImage(obj as UIImage) { + if let imageID = SD.saveUIImage(obj as! UIImage) { return "'\(escapeStringValue(imageID))'" } - println("SwiftData Warning -> Cannot save image, NULL will be inserted into the database") + print("SwiftData Warning -> Cannot save image, NULL will be inserted into the database") return "NULL" } - println("SwiftData Warning -> Object \"\(obj)\" is not a supported type and will be inserted into the database as NULL") + print("SwiftData Warning -> Object \"\(obj)\" is not a supported type and will be inserted into the database as NULL") return "NULL" } else { return "NULL" @@ -1338,13 +1322,13 @@ extension SwiftData.SQLiteDB { } //return escaped String identifier - func escapeIdentifier(obj: String) -> String { + func escapeIdentifier(_ obj: String) -> String { return "\"\(escapeStringIdentifier(obj))\"" } - + //escape string - func escapeStringValue(str: String) -> String { + func escapeStringValue(_ str: String) -> String { var escapedStr = "" for char in str { if char == "'" { @@ -1356,7 +1340,7 @@ extension SwiftData.SQLiteDB { } //escape string - func escapeStringIdentifier(str: String) -> String { + func escapeStringIdentifier(_ str: String) -> String { var escapedStr = "" for char in str { if char == "\"" { @@ -1375,40 +1359,40 @@ extension SwiftData.SQLiteDB { extension SwiftData { /** - Column Data Types - - :param: StringVal A column with type String, corresponds to SQLite type "TEXT" - :param: IntVal A column with type Int, corresponds to SQLite type "INTEGER" - :param: DoubleVal A column with type Double, corresponds to SQLite type "DOUBLE" - :param: BoolVal A column with type Bool, corresponds to SQLite type "BOOLEAN" - :param: DataVal A column with type NSdata, corresponds to SQLite type "BLOB" - :param: DateVal A column with type NSDate, corresponds to SQLite type "DATE" - :param: UIImageVal A column with type String (the path value of saved UIImage), corresponds to SQLite type "TEXT" - */ + Column Data Types + + :param: StringVal A column with type String, corresponds to SQLite type "TEXT" + :param: IntVal A column with type Int, corresponds to SQLite type "INTEGER" + :param: DoubleVal A column with type Double, corresponds to SQLite type "DOUBLE" + :param: BoolVal A column with type Bool, corresponds to SQLite type "BOOLEAN" + :param: DataVal A column with type NSdata, corresponds to SQLite type "BLOB" + :param: DateVal A column with type NSDate, corresponds to SQLite type "DATE" + :param: UIImageVal A column with type String (the path value of saved UIImage), corresponds to SQLite type "TEXT" + */ public enum DataType { - case StringVal - case IntVal - case DoubleVal - case BoolVal - case DataVal - case DateVal - case UIImageVal + case stringVal + case intVal + case doubleVal + case boolVal + case dataVal + case dateVal + case uiImageVal - private func toSQL() -> String { + fileprivate func toSQL() -> String { switch self { - case .StringVal, .UIImageVal: + case .stringVal, .uiImageVal: return "TEXT" - case .IntVal: + case .intVal: return "INTEGER" - case .DoubleVal: + case .doubleVal: return "DOUBLE" - case .BoolVal: + case .boolVal: return "BOOLEAN" - case .DataVal: + case .dataVal: return "BLOB" - case .DateVal: + case .dateVal: return "DATE" } } @@ -1416,41 +1400,41 @@ extension SwiftData { } /** - Flags for custom connection to the SQLite database - - :param: ReadOnly Opens the SQLite database with the flag "SQLITE_OPEN_READONLY" - :param: ReadWrite Opens the SQLite database with the flag "SQLITE_OPEN_READWRITE" - :param: ReadWriteCreate Opens the SQLite database with the flag "SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE" - */ + Flags for custom connection to the SQLite database + + :param: ReadOnly Opens the SQLite database with the flag "SQLITE_OPEN_READONLY" + :param: ReadWrite Opens the SQLite database with the flag "SQLITE_OPEN_READWRITE" + :param: ReadWriteCreate Opens the SQLite database with the flag "SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE" + */ public enum Flags { - case ReadOnly - case ReadWrite - case ReadWriteCreate - - private func toSQL() -> Int32 { + case readOnly + case readWrite + case readWriteCreate + + fileprivate func toSQL() -> Int32 { switch self { - case .ReadOnly: + case .readOnly: return SQLITE_OPEN_READONLY - case .ReadWrite: + case .readWrite: return SQLITE_OPEN_READWRITE - case .ReadWriteCreate: + case .readWriteCreate: return SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE } } } - + } extension SwiftData.SQLiteDB { //create a table - func createSQLTable(table: String, withColumnsAndTypes values: [String: SwiftData.DataType]) -> Int? { - + func createSQLTable(_ table: String, withColumnsAndTypes values: [String: SwiftData.DataType]) -> Int? { + var sqlStr = "CREATE TABLE \(table) (ID INTEGER PRIMARY KEY AUTOINCREMENT, " var firstRun = true for value in values { @@ -1467,7 +1451,7 @@ extension SwiftData.SQLiteDB { } //delete a table - func deleteSQLTable(table: String) -> Int? { + func deleteSQLTable(_ table: String) -> Int? { let sqlStr = "DROP TABLE \(table)" return executeChange(sqlStr) } @@ -1484,8 +1468,8 @@ extension SwiftData.SQLiteDB { if let table = row["name"]?.asString() { tableArr.append(table) } else { - println("SwiftData Error -> During: Finding Existing Tables") - println(" -> Code: 403 - Error extracting table names from sqlite_master") + print("SwiftData Error -> During: Finding Existing Tables") + print(" -> Code: 403 - Error extracting table names from sqlite_master") return (tableArr, 403) } } @@ -1493,11 +1477,11 @@ extension SwiftData.SQLiteDB { } //create an index - func createIndex(name: String, columns: [String], table: String, unique: Bool) -> Int? { + func createIndex(_ name: String, columns: [String], table: String, unique: Bool) -> Int? { if columns.count < 1 { - println("SwiftData Error -> During: Creating Index") - println(" -> Code: 401 - At least one column name must be provided") + print("SwiftData Error -> During: Creating Index") + print(" -> Code: 401 - At least one column name must be provided") return 401 } var sqlStr = "" @@ -1521,7 +1505,7 @@ extension SwiftData.SQLiteDB { } //remove an index - func removeIndex(name: String) -> Int? { + func removeIndex(_ name: String) -> Int? { let sqlStr = "DROP INDEX \(name)" return executeChange(sqlStr) } @@ -1539,9 +1523,9 @@ extension SwiftData.SQLiteDB { if let index = res["name"]?.asString() { indexArr.append(index) } else { - println("SwiftData Error -> During: Finding Existing Indexes") - println(" -> Code: 402 - Error extracting index names from sqlite_master") - println("Error finding existing indexes -> Error extracting index names from sqlite_master") + print("SwiftData Error -> During: Finding Existing Indexes") + print(" -> Code: 402 - Error extracting index names from sqlite_master") + print("Error finding existing indexes -> Error extracting index names from sqlite_master") return (indexArr, 402) } } @@ -1550,7 +1534,7 @@ extension SwiftData.SQLiteDB { } //obtain list of existing indexes for a specific table - func existingIndexesForTable(table: String) -> (result: [String], error: Int?) { + func existingIndexesForTable(_ table: String) -> (result: [String], error: Int?) { let sqlStr = "SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = '\(table)'" var indexArr = [String]() @@ -1562,8 +1546,8 @@ extension SwiftData.SQLiteDB { if let index = res["name"]?.asString() { indexArr.append(index) } else { - println("SwiftData Error -> During: Finding Existing Indexes for a Table") - println(" -> Code: 402 - Error extracting index names from sqlite_master") + print("SwiftData Error -> During: Finding Existing Indexes for a Table") + print(" -> Code: 402 - Error extracting index names from sqlite_master") return (indexArr, 402) } } @@ -1579,11 +1563,11 @@ extension SwiftData.SQLiteDB { extension SwiftData.SDError { //get the error message from the error code - private static func errorMessageFromCode(errorCode: Int) -> String { + fileprivate static func errorMessageFromCode(_ errorCode: Int) -> String { switch errorCode { - //no error + //no error case -1: return "No error" @@ -1652,9 +1636,9 @@ extension SwiftData.SDError { case 101: return "sqlite3_step() has finished executing" - //custom SwiftData errors - - //->binding errors + //custom SwiftData errors + + //->binding errors case 201: return "Not enough objects to bind provided" @@ -1662,9 +1646,9 @@ extension SwiftData.SDError { return "Too many objects to bind provided" case 203: return "Object to bind as identifier must be a String" - - //->custom connection errors - + + //->custom connection errors + case 301: return "A custom connection is already open" case 302: @@ -1677,24 +1661,24 @@ extension SwiftData.SDError { return "Cannot close a custom connection inside a transaction" case 306: return "Cannot close a custom connection inside a savepoint" - - //->index and table errors - + + //->index and table errors + case 401: return "At least one column name must be provided" case 402: return "Error extracting index names from sqlite_master" case 403: return "Error extracting table names from sqlite_master" - - //->transaction and savepoint errors - + + //->transaction and savepoint errors + case 501: return "Cannot begin a transaction within a savepoint" case 502: return "Cannot begin a transaction within another transaction" - - //unknown error + + //unknown error default: //what the fuck happened?!? @@ -1705,4 +1689,5 @@ extension SwiftData.SDError { } -public typealias SD = SwiftData \ No newline at end of file +public typealias SD = SwiftData +