diff --git a/README.md b/README.md index c905ce7..6c50ca2 100644 --- a/README.md +++ b/README.md @@ -1,448 +1,4 @@ -SwiftData -========= +# SwiftData +Simple and Effective SQLite Handling in Swift -Working with SQLite is a pain in Swift - that's where SwiftData comes in. - -SwiftData is a simple and effective wrapper around the SQLite3 C API written completely in Swift. - - -##Features - -- Execute SQL statements directly -- Bind objects conveniently to a string of SQL -- Queries return an easy to use array -- Support for transactions and savepoints -- Inline error handling -- Completely thread-safe by default -- Convenience functions for common tasks, including table and index creation/deletion/querying -- Database connection operations (opening/closing) are automatically handled - - -##Installation - -Currently, it's as easy as adding the file 'SwiftData.swift' as a git submodule, and dragging it into your project. -Ensure that you've added 'libsqlite3.dylib' as a linked framework and that you've added `#import "sqlite3.h"` to your Briding-Header.h file. - - -##System Requirements - -Xcode Version: - -- Xcode 6 - -Can be used in applications with operating systems: - -- iOS 7.0+ -- Mac OS X 10.9+ - - -##Usage - -This section runs through some sample usage of SwiftData. - -The full API documentation can be found [here](http://ryanfowler.github.io/SwiftData) - - -###Table Creation - -By default, SwiftData creates and uses a database called 'SwiftData.sqlite' in the 'Documents' folder of the application. - -To create a table in the database, you may use the convenience function: - -```swift -if let err = SD.createTable("Cities", withColumnNamesAndTypes: ["Name": .StringVal, "Population": .IntVal, "IsWarm": .BoolVal, "FoundedIn": .DateVal]) { - //there was an error during this function, handle it here -} else { - //no error, the table was created successfully -} -``` - -Similar convenience functions are provided for: - -- deleting a table: -```swift -let err = SD.deleteTable("TableName") -``` -- finding all existing tables in the database: -```swift -let (tables, err) = SD.existingTables() -``` - -Alternatively, a table could be created using a SQL statement directly, as shown in the 'Execute A Change' section below. - - -================= -###Execute A Change - -The `SD.executeChange()` function can be used to execute any non-query SQL statement (e.g. INSERT, UPDATE, DELETE, CREATE, etc.). - -To create a table using this function, you could use the following: - -```swift -if let err = SD.executeChange("CREATE TABLE Cities (ID INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Population INTEGER, IsWarm BOOLEAN, FoundedIn DATE)") { - //there was an error during this function, handle it here -} else { - //no error, the table was created successfully -} -``` - -The table created by this function call is the equivalent of the convenience function used in the earlier section. - -Now that we've created our table, "Cities", we can insert a row into it like so: - -```swift -if let err = SD.executeChange("INSERT INTO Cities (Name, Population, IsWarm, FoundedIn) VALUES ('Toronto', 2615060, 0, '1793-08-27')") { - //there was an error during the insert, handle it here -} else { - //no error, the row was inserted successfully -} -``` - -#####Binding Values - -Alternatively, we could insert a row with object binding: - -```swift -//from user input -let name: String = //user input -let population: Int = //user input -let isWarm: Bool = //user input -let foundedIn: NSDate = //user input - -if let err = SD.executeChange("INSERT INTO Cities (Name, Population, IsWarm, FoundedIn) VALUES (?, ?, ?, ?)", withArgs: [name, population, isWarm, foundedIn]) { - //there was an error during the insert, handle it here -} else { - //no error, the row was inserted successfully -} -``` - -The provided objects will be escaped and will bind to the '?' characters (in order) in the string of SQL. - -Be aware that although this uses similar syntax to prepared statements, it actually uses the public function: -```swift -let escValue = SD.escapeValue(object) -``` -to escape objects internally, which you may also use yourself. -This means that the objects will attempt to bind to *ALL* '?'s in the string of SQL, including those in strings and comments. - -The objects are escaped and will bind to a SQL string in the following manner: - -- A String object is escaped and surrounded by single quotes (e.g. 'sample string') -- An Int object is left untouched (e.g. 10) -- A Double object is left untouched (e.g. 10.8) -- A Bool object is converted to 0 for false, or 1 for true (e.g. 1) -- An NSDate object is converted to a string with format 'yyyy-MM-dd HH:mm:ss' and surrounded by single quotes (e.g. '2014-08-26 10:30:28') -- An NSData object is prefaced with an 'X' and converted to a hexadecimal string surrounded by single quotes (e.g. X'1956a76c') -- A UIImage object is saved to disk, and the ID for retrieval is saved as a string surrounded by single quotes (e.g. 'a98af5ca-7700-4abc-97fb-60737a7b6583') - -All other object types will bind to the SQL string as 'NULL', and a warning message will be printed to the console. - -#####Binding Identifiers - -If an identifier (e.g. table or column name) is provided by the user and needs to be escaped, you can use the characters 'i?' to bind the objects like so: - -```swift -//from user input -let columnName1 = //user input -let columnName2 = //user input - -if let err = SD.executeChange("INSERT INTO Cities (Name, Population, i?, i?) VALUES (?, ?, ?, ?)", withArgs: [columnName1, columnName2, name, population, isWarm, foundedIn]) { - //there was an error during the insert, handle it here -} else { - //no error, the row was inserted successfully -} -``` - -The objects 'columnName1' and 'columnName2' will bind to the characters 'i?' in the string of SQL as identifiers. Double quotes will be placed around each identifier. -You may escape an identifier string yourself using the function: -```swift -let escIdentifier = SD.escapeIdentifier(identifier) -``` -Objects provided to bind as identifiers must be of type String. - - -==================== -###Execute A Query - -Now that our table has some data, we can query it: - -```swift -let (resultSet, err) = SD.executeQuery("SELECT * FROM Cities") -if err != nil { - //there was an error during the query, handle it here -} else { - for row in resultSet { - if let name = row["Name"]?.asString() { - println("The City name is: \(name)") - } - if let population = row["Population"]?.asInt() { - println("The population is: \(population)") - } - if let isWarm = row["IsWarm"]?.asBool() { - if isWarm { - println("The city is warm") - } else { - println("The city is cold") - } - } - if let foundedIn = row["FoundedIn"]?.asDate() { - println("The city was founded in: \(foundedIn)") - } - } -} -``` - -A query function returns a tuple of: - -- the result set as an Array of SDRow objects -- the error code as an Optional Int - -An SDRow contains a number of corresponding SDColumn objects. -The values for each column can be obtained by using the column name in subscript format, much like a Dictionary. -In order to obtain the column value in the correct data type, you may use the convenience functions: - -- asString() -- asInt() -- asDouble() -- asBool() -- asDate() -- asData() -- asAnyObject() -- asUIImage() - -If one of the above functions is not used, the value will be an SDColumn object. - -For example, if you want the string value for the column "Name": - -```swift -if let name = row["Name"]?.asString() { - //the value for column "Name" exists as a String -} else - //the value is nil, cannot be cast as a String, or the column requested does not exist -} -``` - -You may also execute a query using object binding, similar to the row insert example in an earlier section: - -```swift -let (resultSet, err) = SD.executeQuery("SELECT * FROM Cities WHERE Name = ?", withArgs: ["Toronto"]) -if err != nil { - //there was an error during the query, handle it here -} else { - for row in resultSet { - if let name = row["Name"]?.asString() { - println("The City name is: \(name)") //should be "Toronto" - } - if let population = row["Population"]?.asInt() { - println("The population is: \(population)") - } - if let isWarm = row["IsWarm"]?.asBool() { - if isWarm { - println("The city is warm") - } else { - println("The city is cold") - } - } - if let foundedIn = row["FoundedIn"]?.asDate() { - println("The city was founded in: \(foundedIn)") - } - } -} -``` - -The same binding rules apply as described in the 'Execute a Change' section. - - -================= -###Error Handling - -You have probably noticed that almost all SwiftData functions return an 'error' value. - -This error value is an Optional Int corresponding to the appropriate error message, which can be obtained by calling the function: - -```swift -let errMsg = SD.errorMessageForCode(err) -``` - -It is recommended to compare the error value with nil to see if there was an error during the operation, or if the operation was executed successfully. - -By default, error and warning messages are printed to the console when they are encountered. - - -================= -###Creating An Index - -To create an index, you may use the provided convenience function: - -```swift -if let err = SD.createIndex("NameIndex", onColumns: ["Name"], inTable: "Cities", isUnique: true) { - //there was an error creating the index, handle it here -} else { - //the index was created successfully -} -``` - -Similar convenience functions are provided for: -- removing an index: -```swift -let err = removeIndex("IndexName") -``` -- finding all existing indexes: -```swift -let (indexes, err) = existingIndexes() -``` -- finding all indexes for a specified table: -```swift -let (indexes, err) = existingIndexesForTable("TableName") -``` - - -================= -###Custom Connection - -You may create a custom connection to the database and execute a number of functions within a provided closure. -An example of this can be seen below: - -```swift -let task: ()->Void = { - if let err = SD.executeChange("INSERT INTO Cities VALUES ('Vancouver', 603502, 1, '1886-04-06')") { - println("Error inserting city") - } - if let err = SD.createIndex(name: "NameIndex", onColumns: ["Name"], inTable: "Cities", isUnique: true) { - println("Index creation failed") - } -} - -if let err = SD.executeWithConnection(.ReadWrite, task) { - //there was an error opening or closing the custom connection -} else { - //no error, the closure was executed -} -``` - -The available custom connection flags are: - -- .ReadOnly (SQLITE_OPEN_READONLY) -- .ReadWrite (SQLITE_OPEN_READWRITE) -- .ReadWriteCreate (SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE) - -All operations that occur within the provided closure are executed on the single custom connection. - -For more information, see the SQLite documentation for [opening a new database connection](http://www.sqlite.org/c3ref/open.html). - - -================= -###Transactions and Savepoints - -If we wanted to execute the above closure `task: ()->Void` inside an exclusive transaction, it could be done like so: - -```swift -if let err = transaction(task) { - //there was an error starting, closing, committing, or rolling back the transaction as per the error code -} else { - //the transaction was executed without errors -} -``` - -Similarly, a savepoint could be executed like so: - -```swift -if let err = savepoint(task) { - //there was an error starting, closing, releasing, or rolling back the savepoint as per the error code -} else { - //the savepoint was executed without errors -} -``` - -It should be noted that transactions *cannot* be embedded into another transaction or savepoint. -Unlike transactions, savepoints may be embedded into other savepoints or transactions. - -For more information, see the SQLite documentation for [transactions](http://sqlite.org/lang_transaction.html) and [savepoints](http://www.sqlite.org/lang_savepoint.html). - - -================= -###Using UIImages - -Convenience functions are provided for working with UIImages. - -To easily save a UIImage to disk and insert the corresponding ID into the database: - -```swift -let image = UIImage(named:"SampleImage") -if let imageID = SD.saveUIImage(image) { - if let err = SD.executeChange("INSERT INTO SampleImageTable (Name, Image) VALUES (?, ?)", withArgs: ["SampleImageName", imageID]) { - //there was an error inserting the new row, handle it here - } -} else { - //there was an error saving the image to disk -} -``` - -Alternatively, object binding can also be used: - -```swift -let image = UIImage(named:"SampleImage") -if let err = SD.executeChange("INSERT INTO SampleImageTable (Name, Image) VALUES (?, ?)", withArgs: ["SampleImageName", image]) { - //there was an error inserting the new row, handle it here -} else { - //the image was saved to disk, and the ID was inserted into the database as a String -} -``` - -In the examples above, a UIImage is saved to disk and the returned ID is inserted into the database as a String. -In order to easily obtain the UIImage from the database, the function '.asUIImage()' called on an SDColumn object may be used: - -```swift -let (resultSet, err) = SD.executeQuery("SELECT * FROM SampleImageTable") -if err != nil { - //there was an error with the query, handle it here -} else { - for row in resultSet { - if let image = row["Image"]?.asUIImage() { - //'image' contains the UIImage with the ID stored in this column - } else { - //the ID is invalid, or the image could not be initialized from the data at the specified path - } - } -} -``` - -The '.asUIImage()' function obtains the ID as a String and returns the UIImage associated with this ID (or will return nil if the ID was invalid or a UIImage could not be initialized). - -If you would like to delete the photo, you may call the function: - -```swift -if SD.deleteUIImageWithID(imageID) { - //image successfully deleted -} else { - //there was an error deleting the image with the specified ID -} -``` - -This function should be called to delete the image with the specified ID from disk *before* the row containing the image ID is removed. -Removing the row containing the image ID from the database does not delete the image stored on disk. - - -================= -###Thread Safety - -All SwiftData operations are placed on a custom serial queue and executed in a FIFO order. - -This means that you can access the SQLite database from multiple threads without the need to worry about causing errors. - - -##API Documentation - -Full API Documentation can be found [here](http://ryanfowler.github.io/SwiftData) - - -##Contact - -Please open an issue for any comments, concerns, ideas, or potential pull requests - all welcome :) - - -##License - -SwiftData is released under the MIT License. - -See the LICENSE file for full details. +Swift 2 version diff --git a/SwiftData.swift b/SwiftData.swift index c3e7ad2..df2d6dc 100644 --- a/SwiftData.swift +++ b/SwiftData.swift @@ -50,7 +50,7 @@ public struct SwiftData { :returns: An Int with the error code, or nil if there was no error */ - public static func executeChange(sqlStr: String) -> Int? { + public static func executeChange(_ sqlStr: String) -> Int? { var error: Int? = nil let task: ()->Void = { @@ -67,30 +67,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 +105,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 +125,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.index(of: sqlStr) {//find(sqlArr, sqlStr) { + print("Error occurred on array item: \(index) -> \"\(sqlStr)\"") } error = err return @@ -144,25 +140,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 +175,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 +203,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,7 +236,7 @@ public struct SwiftData { return error } - + // MARK: - Escaping Objects @@ -263,18 +249,18 @@ public struct SwiftData { :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 { + 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) } @@ -283,11 +269,8 @@ public struct SwiftData { /** 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 @@ -295,7 +278,7 @@ public struct SwiftData { :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? { + public static func createTable(_ table: String, withColumnNamesAndTypes values: [String: SwiftData.DataType]) -> Int? { var error: Int? = nil let task: ()->Void = { @@ -312,17 +295,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 +320,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 +346,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 { + 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 +392,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 @@ -450,9 +421,7 @@ public struct SwiftData { /** 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) @@ -463,7 +432,7 @@ public struct SwiftData { :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? { + public static func createIndex(name: String, onColumns: [String], inTable: String, isUnique: Bool = false) -> Int? { var error: Int? = nil let task: ()->Void = { @@ -480,17 +449,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 +474,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 +499,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 @@ -569,9 +532,7 @@ public struct SwiftData { 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) @@ -579,7 +540,7 @@ public struct SwiftData { :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? { + public static func transaction(_ transactionClosure: @escaping ()->Bool) -> Int? { var error: Int? = nil let task: ()->Void = { @@ -609,22 +570,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 +601,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 +619,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 = NSUUID().UUIDString - let imagePath = imageDirPath.stringByAppendingPathComponent(imageID) + let imageID = UUID().uuidString + let imagePath = imageDirPath.appendingFormat("/%@", imageID); //imageDirPath.stringByAppendingPathComponent(imageID) let imageAsData = UIImagePNGRepresentation(image) - if !imageAsData.writeToFile(imagePath, atomically: true) { - println("Error saving image") - return nil + if let _ = imageAsData + { + if !((try? imageAsData!.write(to: URL(fileURLWithPath: imagePath), options: [.atomic])) != nil) { + print("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 +698,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 +733,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 +772,7 @@ public struct SwiftData { //close the connection to to the sqlite3 database func close() { - + if inTransaction || openWithFlags || savepointsOpen > 0 { return } @@ -797,10 +781,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 +792,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 +815,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 +829,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 +840,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") { @@ -888,7 +872,7 @@ public struct SwiftData { let error = executeChange("COMMIT") inTransaction = false if let err = error { - rollbackTransaction() + _ = rollbackTransaction() return err } return nil @@ -901,7 +885,7 @@ public struct SwiftData { if let error = executeChange("SAVEPOINT 'savepoint\(savepointsOpen + 1)'") { return error } - ++savepointsOpen + savepointsOpen += 1 return nil } @@ -915,7 +899,7 @@ public struct SwiftData { func releaseSavepoint() -> Int? { let error = executeChange("RELEASE 'savepoint\(savepointsOpen)'") - --savepointsOpen + savepointsOpen -= 1 return error } @@ -932,55 +916,63 @@ 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) + let text = sqlite3_column_text(statement, index) as AnyObject + if let string = String(validatingUTF8: text as! UnsafePointer) { + return dateFormatter.date(from: string) as AnyObject? } - println("SwiftData Warning -> The text date at column: \(index) could not be cast as a String, returning nil") + 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 +983,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 +1010,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 +1022,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 +1040,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 +1065,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 +1074,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 +1094,7 @@ public struct SwiftData { // MARK: - SDRow public struct SDRow { - + var values = [String: SDColumn]() public subscript(key: String) -> SDColumn? { get { @@ -1125,99 +1118,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 */ 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 +1213,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 +1229,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 +1247,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 +1267,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,23 +1276,23 @@ 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 { + if obj is Data { let str = "\(obj)" var newStr = "" for char in str { @@ -1317,19 +1302,19 @@ extension SwiftData.SQLiteDB { } 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 +1323,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 +1341,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 +1360,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 +1401,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 +1452,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 +1469,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 +1478,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 +1506,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 +1524,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 +1535,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 +1547,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,16 +1564,16 @@ 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" - //SQLite error codes and descriptions as per: http://www.sqlite.org/c3ref/c_abort.html + //SQLite error codes and descriptions as per: http://www.sqlite.org/c3ref/c_abort.html case 0: return "Successful result" case 1: @@ -1652,9 +1637,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 +1647,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 +1662,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 +1690,4 @@ extension SwiftData.SDError { } -public typealias SD = SwiftData \ No newline at end of file +public typealias SD = SwiftData