From e5d6cc61042871b0e4914fe80f4d63705b8ee703 Mon Sep 17 00:00:00 2001 From: Fernando Ransanz Date: Mon, 14 Sep 2015 09:25:14 +0200 Subject: [PATCH 01/10] eliminar README.md --- README.md | 448 ------------------------------------------------------ 1 file changed, 448 deletions(-) delete mode 100644 README.md diff --git a/README.md b/README.md deleted file mode 100644 index c905ce7..0000000 --- a/README.md +++ /dev/null @@ -1,448 +0,0 @@ -SwiftData -========= - -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. From 1653f1f3ba5d659337f9775eabad7cc0cf206ad8 Mon Sep 17 00:00:00 2001 From: Fernando Ransanz Date: Fri, 6 Nov 2015 09:28:47 +0100 Subject: [PATCH 02/10] swift2 - control --- SwiftData.swift | 284 ++++++++++++++++++++++++------------------------ 1 file changed, 142 insertions(+), 142 deletions(-) diff --git a/SwiftData.swift b/SwiftData.swift index c3e7ad2..0332dcd 100644 --- a/SwiftData.swift +++ b/SwiftData.swift @@ -46,9 +46,9 @@ public struct SwiftData { - SQLite errors (0 - 101) - :param: sqlStr The non-query string of SQL to be executed (INSERT, UPDATE, DELETE, etc.) + - parameter 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 + - returns: An Int with the error code, or nil if there was no error */ public static func executeChange(sqlStr: String) -> Int? { @@ -84,10 +84,10 @@ public struct SwiftData { - 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 + - parameter sqlStr: The non-query string of SQL to be executed (INSERT, UPDATE, DELETE, etc.) + - parameter 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 + - returns: An Int with the error code, or nil if there was no error */ public static func executeChange(sqlStr: String, withArgs: [AnyObject]) -> Int? { @@ -114,9 +114,9 @@ public struct SwiftData { - SQLite errors (0 - 101) - :param: sqlArr An array of non-query strings of SQL to be executed (INSERT, UPDATE, DELETE, etc.) + - parameter 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 + - returns: An Int with the error code, or nil if there was no error */ public static func executeMultipleChanges(sqlArr: [String]) -> Int? { @@ -129,8 +129,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.indexOf(sqlStr) { + print("Error occurred on array item: \(index) -> \"\(sqlStr)\"") } error = err return @@ -158,9 +158,9 @@ public struct SwiftData { - SQLite errors (0 - 101) - :param: sqlStr The query String of SQL to be executed (e.g. SELECT) + - parameter 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 + - 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?) { @@ -191,10 +191,10 @@ public struct SwiftData { - 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. + - parameter sqlStr: The query String of SQL to be executed (e.g. SELECT) + - parameter 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 + - 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?) { @@ -223,14 +223,14 @@ public struct SwiftData { - custom connection errors (301 - 306) - :param: flags The custom flag associated with the connection. Can be either: + - parameter 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 + - parameter 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 + - returns: An Int with the error code, or nil if there was no error */ public static func executeWithConnection(flags: SD.Flags, closure: ()->Void) -> Int? { @@ -259,9 +259,9 @@ public struct SwiftData { 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 + - parameter 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. + - 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) @@ -270,9 +270,9 @@ public struct SwiftData { /** 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. + - parameter 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. + - 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) @@ -290,10 +290,10 @@ public struct SwiftData { - 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 + - parameter table: The table name to be created + - parameter 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 + - 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? { @@ -318,9 +318,9 @@ public struct SwiftData { - SQLite errors (0 - 101) - :param: table The table name to be deleted + - parameter table: The table name to be deleted - :returns: An Int with the error code, or nil if there was no error + - returns: An Int with the error code, or nil if there was no error */ public static func deleteTable(table: String) -> Int? { @@ -346,7 +346,7 @@ public struct SwiftData { - 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 + - 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?) { @@ -372,9 +372,9 @@ public struct SwiftData { /** Obtain the error message relating to the provided error code - :param: code The error code provided + - parameter code: The error code provided - :returns: The error message relating to the provided error code + - returns: The error message relating to the provided error code */ public static func errorMessageForCode(code: Int) -> String { return SwiftData.SDError.errorMessageFromCode(code) @@ -383,7 +383,7 @@ public struct SwiftData { /** Obtain the database path - :returns: The path to the SwiftData database + - returns: The path to the SwiftData database */ public static func databasePath() -> String { return SQLiteDB.sharedInstance.dbPath @@ -398,7 +398,7 @@ public struct SwiftData { - 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 + - 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?) { @@ -426,7 +426,7 @@ public struct SwiftData { - 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 + - 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?) { @@ -456,14 +456,14 @@ public struct SwiftData { - 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) + - parameter name: The index name that is being created + - parameter onColumns: An array of column names that the index will be applied to (must be one column or greater) + - parameter inTable: The table name where the index is being created + - parameter 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 + - 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 name: String, onColumns: [String], inTable: String, isUnique: Bool = false) -> Int? { var error: Int? = nil let task: ()->Void = { @@ -486,9 +486,9 @@ public struct SwiftData { - SQLite errors (0 - 101) - :param: indexName The name of the index to be removed + - parameter indexName: The name of the index to be removed - :returns: An Int with the error code, or nil if there was no error + - returns: An Int with the error code, or nil if there was no error */ public static func removeIndex(indexName: String) -> Int? { @@ -514,7 +514,7 @@ public struct SwiftData { - 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 + - 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?) { @@ -541,9 +541,9 @@ public struct SwiftData { - SQLite errors (0 - 101) - Index error (402) - :param: table The name of the table that is being queried for indexes + - parameter 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 + - 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?) { @@ -575,9 +575,9 @@ public struct SwiftData { - 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. + - parameter 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 + - 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? { @@ -619,9 +619,9 @@ public struct SwiftData { - 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. + - parameter 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 + - 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? { @@ -642,7 +642,7 @@ public struct SwiftData { } } else { if let err = SQLiteDB.sharedInstance.rollbackSavepoint() { - println("Error rolling back to savepoint") + print("Error rolling back to savepoint") --SQLiteDB.sharedInstance.savepointsOpen SQLiteDB.sharedInstance.close() error = err @@ -662,9 +662,9 @@ public struct SwiftData { /** Convenience function to save a UIImage to disk and return the ID - :param: image The UIImage to be saved + - parameter 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 + - 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? { @@ -672,7 +672,7 @@ public struct SwiftData { 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") + print("Error creating SwiftData image folder") return nil } } @@ -680,7 +680,7 @@ public struct SwiftData { let imagePath = imageDirPath.stringByAppendingPathComponent(imageID) let imageAsData = UIImagePNGRepresentation(image) if !imageAsData.writeToFile(imagePath, atomically: true) { - println("Error saving image") + print("Error saving image") return nil } return imageID @@ -690,9 +690,9 @@ public struct SwiftData { /** Convenience function to delete a UIImage with the specified ID - :param: id The id of the UIImage + - parameter id: The id of the UIImage - :returns: True if the image was successfully deleted, or false if there was an error during the deletion + - 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 { @@ -736,10 +736,10 @@ public struct SwiftData { } let status = sqlite3_open(dbPath.cStringUsingEncoding(NSUTF8StringEncoding)!, &sqliteDB) if status != SQLITE_OK { - println("SwiftData Error -> During: Opening Database") - println(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) + print("SwiftData Error -> During: Opening Database") + print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { - println(" -> Details: \(errMsg)") + print(" -> Details: \(errMsg)") } return Int(status) } @@ -752,31 +752,31 @@ public struct SwiftData { 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) if status != SQLITE_OK { - println("SwiftData Error -> During: Opening Database with Flags") - println(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) + print("SwiftData Error -> During: Opening Database with Flags") + print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { - println(" -> Details: \(errMsg)") + print(" -> Details: \(errMsg)") } return Int(status) } @@ -797,10 +797,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))) + print("SwiftData Error -> During: Closing Database") + print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { - println(" -> Details: \(errMsg)") + print(" -> Details: \(errMsg)") } } sqliteDB = nil @@ -812,18 +812,18 @@ public struct SwiftData { 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 +831,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))) + print("SwiftData Error -> During: Closing Database with Flags") + print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { - println(" -> Details: \(errMsg)") + print(" -> Details: \(errMsg)") } return Int(status) } @@ -856,13 +856,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") { @@ -967,10 +967,10 @@ public struct SwiftData { 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") + 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 } @@ -994,20 +994,20 @@ public struct SwiftData { var pStmt: COpaquePointer = nil var status = sqlite3_prepare_v2(SQLiteDB.sharedInstance.sqliteDB, sql, -1, &pStmt, nil) if status != SQLITE_OK { - println("SwiftData Error -> During: SQL Prepare") - println(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) + print("SwiftData Error -> During: SQL Prepare") + print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { - println(" -> Details: \(errMsg)") + 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))) + print("SwiftData Error -> During: SQL Step") + print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { - println(" -> Details: \(errMsg)") + print(" -> Details: \(errMsg)") } sqlite3_finalize(pStmt) return Int(status) @@ -1033,10 +1033,10 @@ public struct SwiftData { var pStmt: COpaquePointer = nil var status = sqlite3_prepare_v2(SQLiteDB.sharedInstance.sqliteDB, sql, -1, &pStmt, nil) if status != SQLITE_OK { - println("SwiftData Error -> During: SQL Prepare") - println(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) + print("SwiftData Error -> During: SQL Prepare") + print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { - println(" -> Details: \(errMsg)") + print(" -> Details: \(errMsg)") } sqlite3_finalize(pStmt) return (resultSet, Int(status)) @@ -1081,10 +1081,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))) + print("SwiftData Error -> During: SQL Step") + print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { - println(" -> Details: \(errMsg)") + print(" -> Details: \(errMsg)") } sqlite3_finalize(pStmt) return (resultSet, Int(status)) @@ -1129,7 +1129,7 @@ public struct SwiftData { /** 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 + - 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 @@ -1138,7 +1138,7 @@ public struct SwiftData { /** 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 + - 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 @@ -1147,7 +1147,7 @@ public struct SwiftData { /** 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 + - 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 @@ -1156,7 +1156,7 @@ public struct SwiftData { /** 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 + - 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 @@ -1165,7 +1165,7 @@ public struct SwiftData { /** 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 + - 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 @@ -1174,7 +1174,7 @@ public struct SwiftData { /** 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 + - 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 @@ -1183,7 +1183,7 @@ public struct SwiftData { /** 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 + - 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 @@ -1192,7 +1192,7 @@ public struct SwiftData { /** 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 + - 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? { @@ -1201,7 +1201,7 @@ public struct SwiftData { let imageDirPath = docsPath.stringByAppendingPathComponent("SwiftDataImages") let fullPath = imageDirPath.stringByAppendingPathComponent(path) if !NSFileManager.defaultManager().fileExistsAtPath(fullPath) { - println("SwiftData Error -> Invalid image ID provided") + print("SwiftData Error -> Invalid image ID provided") return nil } if let imageAsData = NSData(contentsOfFile: fullPath) { @@ -1250,11 +1250,11 @@ extension SwiftData.SQLiteDB { var newSql = "" var bindIndex = 0 var i = false - for char in sql { + for char in sql.characters { 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,8 +1262,8 @@ 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()) @@ -1282,8 +1282,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) @@ -1295,13 +1295,13 @@ extension SwiftData.SQLiteDB { 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" @@ -1310,7 +1310,7 @@ extension SwiftData.SQLiteDB { if obj is NSData { let str = "\(obj)" var newStr = "" - for char in str { + for char in str.characters { if char != "<" && char != ">" && char != " " { newStr.append(char) } @@ -1320,16 +1320,16 @@ extension SwiftData.SQLiteDB { if obj is NSDate { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" - return "\(escapeValue(dateFormatter.stringFromDate(obj as NSDate)))" + return "\(escapeValue(dateFormatter.stringFromDate(obj as! NSDate)))" } 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" @@ -1346,7 +1346,7 @@ extension SwiftData.SQLiteDB { //escape string func escapeStringValue(str: String) -> String { var escapedStr = "" - for char in str { + for char in str.characters { if char == "'" { escapedStr += "'" } @@ -1358,7 +1358,7 @@ extension SwiftData.SQLiteDB { //escape string func escapeStringIdentifier(str: String) -> String { var escapedStr = "" - for char in str { + for char in str.characters { if char == "\"" { escapedStr += "\"" } @@ -1377,13 +1377,13 @@ 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" + - parameter StringVal: A column with type String, corresponds to SQLite type "TEXT" + - parameter IntVal: A column with type Int, corresponds to SQLite type "INTEGER" + - parameter DoubleVal: A column with type Double, corresponds to SQLite type "DOUBLE" + - parameter BoolVal: A column with type Bool, corresponds to SQLite type "BOOLEAN" + - parameter DataVal: A column with type NSdata, corresponds to SQLite type "BLOB" + - parameter DateVal: A column with type NSDate, corresponds to SQLite type "DATE" + - parameter UIImageVal: A column with type String (the path value of saved UIImage), corresponds to SQLite type "TEXT" */ public enum DataType { @@ -1418,9 +1418,9 @@ 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" + - parameter ReadOnly: Opens the SQLite database with the flag "SQLITE_OPEN_READONLY" + - parameter ReadWrite: Opens the SQLite database with the flag "SQLITE_OPEN_READWRITE" + - parameter ReadWriteCreate: Opens the SQLite database with the flag "SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE" */ public enum Flags { @@ -1484,8 +1484,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) } } @@ -1496,8 +1496,8 @@ extension SwiftData.SQLiteDB { 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 = "" @@ -1539,9 +1539,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) } } @@ -1562,8 +1562,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) } } From b72475c9f4c28e6388a1e314cba34951d7942d0a Mon Sep 17 00:00:00 2001 From: Fernando Ransanz Date: Fri, 6 Nov 2015 12:27:58 +0100 Subject: [PATCH 03/10] swift2 - migrado a swift2 --- SwiftData.swift | 75 +++++++++++++++++++++++++++++++------------------ 1 file changed, 47 insertions(+), 28 deletions(-) diff --git a/SwiftData.swift b/SwiftData.swift index 0332dcd..942d63e 100644 --- a/SwiftData.swift +++ b/SwiftData.swift @@ -386,7 +386,7 @@ public struct SwiftData { - returns: The path to the SwiftData database */ public static func databasePath() -> String { - return SQLiteDB.sharedInstance.dbPath + return SQLiteDB.sharedInstance.dbPath! } /** @@ -668,21 +668,27 @@ public struct SwiftData { */ 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) { - print("Error creating SwiftData image folder") - return nil - } + ////////// + let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]) + let imageDirPath = documentsPath.URLByAppendingPathComponent("SwiftDataImages") + + + do { + try NSFileManager.defaultManager().createDirectoryAtPath(imageDirPath.path!, withIntermediateDirectories: true, attributes: nil) + } catch let error as NSError { + NSLog("Unable to create directory \(error.debugDescription)") } + ////////// + + let imageID = NSUUID().UUIDString - let imagePath = imageDirPath.stringByAppendingPathComponent(imageID) + let imagePath = imageDirPath.URLByAppendingPathComponent(imageID) let imageAsData = UIImagePNGRepresentation(image) - if !imageAsData.writeToFile(imagePath, atomically: true) { + if !imageAsData!.writeToURL(imagePath, atomically: true){ print("Error saving image") return nil } + return imageID } @@ -694,12 +700,19 @@ public struct SwiftData { - 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 { + public static func deleteUIImageWithID(id: String) { + + let docsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]) + let imageDirPath = docsPath.URLByAppendingPathComponent("SwiftDataImages") + let fullPath = imageDirPath.URLByAppendingPathComponent(id) + + do { + return try NSFileManager.defaultManager().removeItemAtURL(fullPath) + } catch let error as NSError { + NSLog("Unable to create directory \(error.debugDescription)") + } + - 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) } @@ -715,7 +728,7 @@ public struct SwiftData { return Singleton.instance } var sqliteDB: COpaquePointer = nil - var dbPath = SQLiteDB.createPath() + var dbPath = SQLiteDB.createPath().path var inTransaction = false var isConnected = false var openWithFlags = false @@ -734,7 +747,7 @@ public struct SwiftData { if sqliteDB != nil || isConnected { return nil } - let status = sqlite3_open(dbPath.cStringUsingEncoding(NSUTF8StringEncoding)!, &sqliteDB) + let status = sqlite3_open(dbPath!.cStringUsingEncoding(NSUTF8StringEncoding)!, &sqliteDB) if status != SQLITE_OK { print("SwiftData Error -> During: Opening Database") print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) @@ -771,7 +784,7 @@ public struct SwiftData { 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!.cStringUsingEncoding(NSUTF8StringEncoding)!, &sqliteDB, flags, nil) if status != SQLITE_OK { print("SwiftData Error -> During: Opening Database with Flags") print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) @@ -843,11 +856,11 @@ public struct SwiftData { } //create the database path - class func createPath() -> String { + class func createPath() -> NSURL { - let docsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as String + let docsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]) let databaseStr = "SwiftData.sqlite" - let dbPath = docsPath.stringByAppendingPathComponent(databaseStr) + let dbPath = docsPath.URLByAppendingPathComponent(databaseStr) return dbPath } @@ -1197,14 +1210,20 @@ public struct SwiftData { 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) { - print("SwiftData Error -> Invalid image ID provided") - return nil + let docsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]) + let imageDirPath = docsPath.URLByAppendingPathComponent("SwiftDataImages") + let fullPath = imageDirPath.URLByAppendingPathComponent(path) + + do { + if !NSFileManager.defaultManager().fileExistsAtPath(fullPath.path!){ + print("SwiftData Error -> Invalid image ID provided") + return nil + } } - if let imageAsData = NSData(contentsOfFile: fullPath) { + + + + if let imageAsData = NSData(contentsOfFile: fullPath.path!) { return UIImage(data: imageAsData) } } From 7e3161de577eb2be1fe9761a4cac907d1728c27b Mon Sep 17 00:00:00 2001 From: Fernando Ransanz Date: Fri, 27 Nov 2015 08:10:22 +0100 Subject: [PATCH 04/10] Create README.md --- README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..6b8b389 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# SwiftData +Simple and Effective SQLite Handling in Swift +Swift 2 version From 1b393a8f7ab5768948756bf68da4eba57b34746c Mon Sep 17 00:00:00 2001 From: Fernando Ransanz Date: Fri, 27 Nov 2015 08:41:50 +0100 Subject: [PATCH 05/10] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 6b8b389..6c50ca2 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,4 @@ # SwiftData Simple and Effective SQLite Handling in Swift + Swift 2 version From fd37c33b9f8d1cf0901008a49a5fa17bf981e90a Mon Sep 17 00:00:00 2001 From: "fernando.ransanz" Date: Wed, 9 Dec 2015 14:12:56 +0100 Subject: [PATCH 06/10] swift 2- actualizado a swift 2.1 desde el fork de alimysoyang --- SwiftData.swift | 667 ++++++++++++++++++++++-------------------------- 1 file changed, 312 insertions(+), 355 deletions(-) diff --git a/SwiftData.swift b/SwiftData.swift index 942d63e..e5d2662 100644 --- a/SwiftData.swift +++ b/SwiftData.swift @@ -46,9 +46,9 @@ public struct SwiftData { - SQLite errors (0 - 101) - - parameter sqlStr: The non-query string of SQL to be executed (INSERT, UPDATE, DELETE, etc.) + :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 + :returns: An Int with the error code, or nil if there was no error */ public static func executeChange(sqlStr: String) -> Int? { @@ -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) - - - parameter sqlStr: The non-query string of SQL to be executed (INSERT, UPDATE, DELETE, etc.) - - parameter 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 - */ + 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,18 +105,15 @@ 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) - - - parameter 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 - */ + 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 @@ -129,7 +125,7 @@ public struct SwiftData { for sqlStr in sqlArr { if let err = SQLiteDB.sharedInstance.executeChange(sqlStr) { SQLiteDB.sharedInstance.close() - if let index = sqlArr.indexOf(sqlStr) { + if let index = sqlArr.indexOf(sqlStr) {//find(sqlArr, sqlStr) { print("Error occurred on array item: \(index) -> \"\(sqlStr)\"") } error = err @@ -144,24 +140,23 @@ 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) - - - parameter 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 - */ + 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] () @@ -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) - - - parameter sqlStr: The query String of SQL to be executed (e.g. SELECT) - - parameter 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 - */ + 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) - - - parameter flags: The custom flag associated with the connection. Can be either: - - .ReadOnly - - .ReadWrite - - .ReadWriteCreate - - - parameter 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 - */ + /** + Execute functions in a closure on a single custom connection + + + Note: This function cannot be nested within itself, or inside a transaction/savepoint. + Possible errors returned by this function are: + - custom connection errors (301 - 306) + :param: flags The custom flag associated with the connection. Can be either: + - .ReadOnly + - .ReadWrite + - .ReadWriteCreate + :param: closure A closure containing functions that will be executed on the custom connection + :returns: An Int with the error code, or nil if there was no error + */ public static func executeWithConnection(flags: SD.Flags, closure: ()->Void) -> Int? { - + var error: Int? = nil let task: ()->Void = { if let err = SQLiteDB.sharedInstance.openWithFlags(flags.toSQL()) { @@ -250,7 +236,7 @@ public struct SwiftData { return error } - + // MARK: - Escaping Objects @@ -259,21 +245,21 @@ public struct SwiftData { 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. - - parameter obj: The value to be escaped + :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. + :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) - - - parameter 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. - */ + 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,17 +269,14 @@ 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) - - parameter table: The table name to be created - - parameter columnNamesAndTypes: A dictionary where the key = column name, and the value = data type + :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 + :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? { @@ -312,16 +295,14 @@ public struct SwiftData { } /** - Delete a SQLite table by name - - Possible errors returned by this function are: - - - SQLite errors (0 - 101) - - - parameter table: The table name to be deleted - - - returns: An Int with the error code, or nil if there was no error - */ + Delete a SQLite table by name + Possible errors returned by this function are: + - SQLite errors (0 - 101) + + :param: table The table name to be deleted + + :returns: An Int with the error code, or nil if there was no error + */ public static func deleteTable(table: String) -> Int? { var error: Int? = nil @@ -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 - - - parameter code: The error code provided - - - returns: 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! + 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,18 +421,16 @@ 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) - - parameter name: The index name that is being created - - parameter onColumns: An array of column names that the index will be applied to (must be one column or greater) - - parameter inTable: The table name where the index is being created - - parameter isUnique: True if the index should be unique, false if it should not be unique (defaults to false) + :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 + :returns: An Int with the error code, or nil if there was no error */ public static func createIndex(name name: String, onColumns: [String], inTable: String, isUnique: Bool = false) -> Int? { @@ -480,16 +449,14 @@ public struct SwiftData { } /** - Remove a SQLite index by its name - - Possible errors returned by this function are: - - - SQLite errors (0 - 101) - - - parameter indexName: The name of the index to be removed - - - returns: An Int with the error code, or nil if there was no error - */ + Remove a SQLite index by its name + Possible errors returned by this function are: + - SQLite errors (0 - 101) + + :param: indexName The name of the index to be removed + + :returns: An Int with the error code, or nil if there was no error + */ public static func removeIndex(indexName: String) -> Int? { var error: Int? = nil @@ -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,17 +499,15 @@ 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) - - - parameter 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 - */ + 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] () @@ -569,15 +532,13 @@ 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) - - parameter 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. + :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 + :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? { @@ -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) - - - parameter 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 - */ + Execute commands within a single savepoint + + A connection to the database is opened and is not closed until the end of the savepoint (or the end of the last savepoint, if embedded). + + NOTE: Unlike transactions, savepoints may be embedded into other savepoints or transactions. + Possible errors returned by this function are: + - SQLite errors (0 - 101) + + :param: savepointClosure A closure containing commands that will execute as part of a single savepoint. If the savepointClosure returns true, the changes made within the closure will be released. If false, the changes will be rolled back and will not be saved. + + :returns: An Int with the error code, or nil if there was no error releasing or rolling back the savepoint + */ public static func savepoint(savepointClosure: ()->Bool) -> Int? { - + var error: Int? = nil let task: ()->Void = { if let err = SQLiteDB.sharedInstance.open() { @@ -660,59 +619,71 @@ public struct SwiftData { } /** - Convenience function to save a UIImage to disk and return the ID - - - parameter 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 - */ + 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 documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]) - let imageDirPath = documentsPath.URLByAppendingPathComponent("SwiftDataImages") - - - do { - try NSFileManager.defaultManager().createDirectoryAtPath(imageDirPath.path!, withIntermediateDirectories: true, attributes: nil) - } catch let error as NSError { - NSLog("Unable to create directory \(error.debugDescription)") + let docsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]; + let imageDirPath = docsPath.stringByAppendingFormat("/%@", "SwiftDataImages"); //docsPath.stringByAppendingPathComponent("SwiftDataImages") + if !NSFileManager.defaultManager().fileExistsAtPath(imageDirPath) { + do + { + try NSFileManager.defaultManager().createDirectoryAtPath(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.URLByAppendingPathComponent(imageID) + let imagePath = imageDirPath.stringByAppendingFormat("/%@", imageID); //imageDirPath.stringByAppendingPathComponent(imageID) let imageAsData = UIImagePNGRepresentation(image) - if !imageAsData!.writeToURL(imagePath, atomically: true){ - print("Error saving image") - return nil + if let _ = imageAsData + { + if !(imageAsData!.writeToFile(imagePath, atomically: true)) { + print("Error saving image") + return nil + } + } + else + { + return nil; } return imageID - + } /** - Convenience function to delete a UIImage with the specified ID - - - parameter 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) { - - let docsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]) - let imageDirPath = docsPath.URLByAppendingPathComponent("SwiftDataImages") - let fullPath = imageDirPath.URLByAppendingPathComponent(id) - - do { - return try NSFileManager.defaultManager().removeItemAtURL(fullPath) - } catch let error as NSError { - NSLog("Unable to create directory \(error.debugDescription)") - } - - + 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]; + let imageDirPath = docsPath.stringByAppendingFormat("/%@", "SwiftDataImages"); //stringByAppendingPathComponent("SwiftDataImages") + let fullPath = imageDirPath.stringByAppendingFormat("/%@", id); // stringByAppendingPathComponent(id) + do + { + try NSFileManager.defaultManager().removeItemAtPath(fullPath); + return true; + } + catch _ as NSError + { + return false; + } + //return NSFileManager.defaultManager().removeItemAtPath(fullPath, error: nil) } @@ -728,7 +699,7 @@ public struct SwiftData { return Singleton.instance } var sqliteDB: COpaquePointer = nil - var dbPath = SQLiteDB.createPath().path + var dbPath = SQLiteDB.createPath() var inTransaction = false var isConnected = false var openWithFlags = false @@ -740,14 +711,14 @@ public struct SwiftData { //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.cStringUsingEncoding(NSUTF8StringEncoding)!, &sqliteDB) if status != SQLITE_OK { print("SwiftData Error -> During: Opening Database") print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) @@ -784,7 +755,7 @@ public struct SwiftData { 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.cStringUsingEncoding(NSUTF8StringEncoding)!, &sqliteDB, flags, nil) if status != SQLITE_OK { print("SwiftData Error -> During: Opening Database with Flags") print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) @@ -801,7 +772,7 @@ public struct SwiftData { //close the connection to to the sqlite3 database func close() { - + if inTransaction || openWithFlags || savepointsOpen > 0 { return } @@ -821,7 +792,7 @@ public struct SwiftData { } - //close a custom connection to the sqlite3 database + //close a custom connection to the sqlite3 database func closeCustomConnection() -> Int? { if inTransaction { @@ -856,11 +827,11 @@ public struct SwiftData { } //create the database path - class func createPath() -> NSURL { + class func createPath() -> String { - let docsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]) + let docsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] let databaseStr = "SwiftData.sqlite" - let dbPath = docsPath.URLByAppendingPathComponent(databaseStr) + let dbPath = docsPath.stringByAppendingFormat("/%@", databaseStr); //stringByAppendingPathComponent(databaseStr) return dbPath } @@ -1114,7 +1085,7 @@ public struct SwiftData { // MARK: - SDRow public struct SDRow { - + var values = [String: SDColumn]() public subscript(key: String) -> SDColumn? { get { @@ -1138,99 +1109,85 @@ 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 + :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 - */ + 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 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 - */ + 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 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 = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]) - let imageDirPath = docsPath.URLByAppendingPathComponent("SwiftDataImages") - let fullPath = imageDirPath.URLByAppendingPathComponent(path) - - do { - if !NSFileManager.defaultManager().fileExistsAtPath(fullPath.path!){ - print("SwiftData Error -> Invalid image ID provided") - return nil - } + let docsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] + let imageDirPath = docsPath.stringByAppendingFormat("/%@", "SwiftDataImages");//stringByAppendingPathComponent("SwiftDataImages") + let fullPath = imageDirPath.stringByAppendingFormat("/%@", path);//stringByAppendingPathComponent(path) + if !NSFileManager.defaultManager().fileExistsAtPath(fullPath) { + print("SwiftData Error -> Invalid image ID provided") + return nil } - - - - if let imageAsData = NSData(contentsOfFile: fullPath.path!) { + if let imageAsData = NSData(contentsOfFile: fullPath) { return UIImage(data: imageAsData) } } return nil } - + } @@ -1263,9 +1220,9 @@ extension SwiftData { // MARK: - Escaping And Binding Functions extension SwiftData.SQLiteDB { - + func bind(objects: [AnyObject], toSQL sql: String) -> (string: String, error: Int?) { - + var newSql = "" var bindIndex = 0 var i = false @@ -1360,7 +1317,7 @@ extension SwiftData.SQLiteDB { func escapeIdentifier(obj: String) -> String { return "\"\(escapeStringIdentifier(obj))\"" } - + //escape string func escapeStringValue(str: String) -> String { @@ -1394,16 +1351,16 @@ extension SwiftData.SQLiteDB { extension SwiftData { /** - Column Data Types - - - parameter StringVal: A column with type String, corresponds to SQLite type "TEXT" - - parameter IntVal: A column with type Int, corresponds to SQLite type "INTEGER" - - parameter DoubleVal: A column with type Double, corresponds to SQLite type "DOUBLE" - - parameter BoolVal: A column with type Bool, corresponds to SQLite type "BOOLEAN" - - parameter DataVal: A column with type NSdata, corresponds to SQLite type "BLOB" - - parameter DateVal: A column with type NSDate, corresponds to SQLite type "DATE" - - parameter 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 @@ -1435,18 +1392,18 @@ extension SwiftData { } /** - Flags for custom connection to the SQLite database - - - parameter ReadOnly: Opens the SQLite database with the flag "SQLITE_OPEN_READONLY" - - parameter ReadWrite: Opens the SQLite database with the flag "SQLITE_OPEN_READWRITE" - - parameter 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 { switch self { @@ -1461,7 +1418,7 @@ extension SwiftData { } } - + } @@ -1469,7 +1426,7 @@ extension SwiftData.SQLiteDB { //create a table 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 { @@ -1602,12 +1559,12 @@ extension SwiftData.SDError { 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: @@ -1671,9 +1628,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" @@ -1681,9 +1638,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: @@ -1696,24 +1653,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?!? From 1a348969584dd91b2369bd5432185485b0f207b2 Mon Sep 17 00:00:00 2001 From: "fernando.ransanz" Date: Fri, 2 Sep 2016 09:10:59 +0200 Subject: [PATCH 07/10] swift2 - actualizar a swift 2.2 --- SwiftData.swift | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/SwiftData.swift b/SwiftData.swift index e5d2662..92ca866 100644 --- a/SwiftData.swift +++ b/SwiftData.swift @@ -602,7 +602,7 @@ public struct SwiftData { } else { if let err = SQLiteDB.sharedInstance.rollbackSavepoint() { print("Error rolling back to savepoint") - --SQLiteDB.sharedInstance.savepointsOpen + SQLiteDB.sharedInstance.savepointsOpen -= 1 SQLiteDB.sharedInstance.close() error = err return @@ -885,7 +885,7 @@ public struct SwiftData { if let error = executeChange("SAVEPOINT 'savepoint\(savepointsOpen + 1)'") { return error } - ++savepointsOpen + savepointsOpen += 1 return nil } @@ -899,7 +899,7 @@ public struct SwiftData { func releaseSavepoint() -> Int? { let error = executeChange("RELEASE 'savepoint\(savepointsOpen)'") - --savepointsOpen + savepointsOpen -= 1 return error } @@ -1032,7 +1032,7 @@ public struct SwiftData { if status == SQLITE_ROW { columnCount = sqlite3_column_count(pStmt) var row = SDRow() - for var i: Int32 = 0; i < columnCount; ++i { + for i: Int32 in 0 ..< columnCount { 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) { @@ -1247,7 +1247,7 @@ extension SwiftData.SQLiteDB { obj = escapeValue(objects[bindIndex]) } newSql += obj - ++bindIndex + bindIndex += 1 } else { newSql.append(char) } From be55de7aae532a0ba7de00484f84313d26b3b111 Mon Sep 17 00:00:00 2001 From: "fernando.ransanz" Date: Tue, 27 Dec 2016 10:35:59 +0100 Subject: [PATCH 08/10] swift2 - Actualizado a swift 3 --- SwiftData.swift | 239 +++++++++++++++++++++++++----------------------- 1 file changed, 124 insertions(+), 115 deletions(-) diff --git a/SwiftData.swift b/SwiftData.swift index 92ca866..a1255ea 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 = { @@ -88,7 +88,7 @@ public struct SwiftData { :returns: An Int with the error code, or nil if there was no error */ - public static func executeChange(sqlStr: String, withArgs: [AnyObject]) -> Int? { + public static func executeChange(_ sqlStr: String, withArgs: [AnyObject]) -> Int? { var error: Int? = nil let task: ()->Void = { @@ -114,7 +114,7 @@ public struct SwiftData { :returns: An Int with the error code, or nil if there was no error */ - public static func executeMultipleChanges(sqlArr: [String]) -> Int? { + public static func executeMultipleChanges(_ sqlArr: [String]) -> Int? { var error: Int? = nil let task: ()->Void = { @@ -125,7 +125,7 @@ public struct SwiftData { for sqlStr in sqlArr { if let err = SQLiteDB.sharedInstance.executeChange(sqlStr) { SQLiteDB.sharedInstance.close() - if let index = sqlArr.indexOf(sqlStr) {//find(sqlArr, sqlStr) { + if let index = sqlArr.index(of: sqlStr) {//find(sqlArr, sqlStr) { print("Error occurred on array item: \(index) -> \"\(sqlStr)\"") } error = err @@ -157,7 +157,7 @@ public struct SwiftData { :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?) { + public static func executeQuery(_ sqlStr: String) -> (result: [SDRow], error: Int?) { var result = [SDRow] () var error: Int? = nil @@ -187,7 +187,7 @@ public struct SwiftData { :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?) { + public static func executeQuery(_ sqlStr: String, withArgs: [AnyObject]) -> (result: [SDRow], error: Int?) { var result = [SDRow] () var error: Int? = nil @@ -218,7 +218,7 @@ public struct SwiftData { :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? { + public static func executeWithConnection(_ flags: SD.Flags, closure: @escaping ()->Void) -> Int? { var error: Int? = nil let task: ()->Void = { @@ -249,7 +249,7 @@ 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) } @@ -260,7 +260,7 @@ public struct SwiftData { :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 { + public static func escapeIdentifier(_ obj: String) -> String { return SQLiteDB.sharedInstance.escapeIdentifier(obj) } @@ -278,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 = { @@ -303,7 +303,7 @@ public struct SwiftData { :returns: An Int with the error code, or nil if there was no error */ - public static func deleteTable(table: String) -> Int? { + public static func deleteTable(_ table: String) -> Int? { var error: Int? = nil let task: ()->Void = { @@ -353,7 +353,7 @@ public struct SwiftData { :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) } @@ -432,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 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 = { @@ -457,7 +457,7 @@ public struct SwiftData { :returns: An Int with the error code, or nil if there was no error */ - public static func removeIndex(indexName: String) -> Int? { + public static func removeIndex(_ indexName: String) -> Int? { var error: Int? = nil let task: ()->Void = { @@ -508,7 +508,7 @@ public struct SwiftData { :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?) { + public static func existingIndexesForTable(_ table: String) -> (result: [String], error: Int?) { var result = [String] () var error: Int? = nil @@ -540,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 = { @@ -582,7 +582,7 @@ public struct SwiftData { :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? { + public static func savepoint(_ savepointClosure: @escaping ()->Bool) -> Int? { var error: Int? = nil let task: ()->Void = { @@ -623,14 +623,14 @@ public struct SwiftData { :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? { + public static func saveUIImage(_ image: UIImage) -> String? { - let docsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]; - let imageDirPath = docsPath.stringByAppendingFormat("/%@", "SwiftDataImages"); //docsPath.stringByAppendingPathComponent("SwiftDataImages") - if !NSFileManager.defaultManager().fileExistsAtPath(imageDirPath) { + 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 NSFileManager.defaultManager().createDirectoryAtPath(imageDirPath, withIntermediateDirectories: false, attributes: nil); + try FileManager.default.createDirectory(atPath: imageDirPath, withIntermediateDirectories: false, attributes: nil); }catch _ as NSError { print("Error creating SwiftData image folder") @@ -643,12 +643,12 @@ public struct SwiftData { // return nil // } } - let imageID = NSUUID().UUIDString - let imagePath = imageDirPath.stringByAppendingFormat("/%@", imageID); //imageDirPath.stringByAppendingPathComponent(imageID) + let imageID = UUID().uuidString + let imagePath = imageDirPath.appendingFormat("/%@", imageID); //imageDirPath.stringByAppendingPathComponent(imageID) let imageAsData = UIImagePNGRepresentation(image) if let _ = imageAsData { - if !(imageAsData!.writeToFile(imagePath, atomically: true)) { + if !((try? imageAsData!.write(to: URL(fileURLWithPath: imagePath), options: [.atomic])) != nil) { print("Error saving image") return nil } @@ -669,14 +669,14 @@ public struct SwiftData { :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 { + public static func deleteUIImageWithID(_ id: String) -> Bool { - let docsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]; - let imageDirPath = docsPath.stringByAppendingFormat("/%@", "SwiftDataImages"); //stringByAppendingPathComponent("SwiftDataImages") - let fullPath = imageDirPath.stringByAppendingFormat("/%@", id); // stringByAppendingPathComponent(id) + 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 NSFileManager.defaultManager().removeItemAtPath(fullPath); + try FileManager.default.removeItem(atPath: fullPath); return true; } catch _ as NSError @@ -690,7 +690,7 @@ public struct SwiftData { // MARK: - SQLiteDB Class - private class SQLiteDB { + fileprivate class SQLiteDB { class var sharedInstance: SQLiteDB { struct Singleton { @@ -698,13 +698,13 @@ 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 @@ -718,11 +718,11 @@ public struct SwiftData { 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 { print("SwiftData Error -> During: Opening Database") print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) - if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { + if let errMsg = String(validatingUTF8: sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { print(" -> Details: \(errMsg)") } return Int(status) @@ -733,7 +733,7 @@ public struct SwiftData { } //open a connection to the sqlite3 database with flags - func openWithFlags(flags: Int32) -> Int? { + func openWithFlags(_ flags: Int32) -> Int? { if inTransaction { print("SwiftData Error -> During: Opening Database with Flags") @@ -755,11 +755,11 @@ public struct SwiftData { 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 { print("SwiftData Error -> During: Opening Database with Flags") print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) - if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { + if let errMsg = String(validatingUTF8: sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { print(" -> Details: \(errMsg)") } return Int(status) @@ -783,7 +783,7 @@ public struct SwiftData { if status != SQLITE_OK { print("SwiftData Error -> During: Closing Database") print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) - if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { + if let errMsg = String(validatingUTF8: sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { print(" -> Details: \(errMsg)") } } @@ -817,7 +817,7 @@ public struct SwiftData { if status != SQLITE_OK { print("SwiftData Error -> During: Closing Database with Flags") print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) - if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { + if let errMsg = String(validatingUTF8: sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { print(" -> Details: \(errMsg)") } return Int(status) @@ -829,9 +829,9 @@ public struct SwiftData { //create the database path class func createPath() -> String { - let docsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] + let docsPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] let databaseStr = "SwiftData.sqlite" - let dbPath = docsPath.stringByAppendingFormat("/%@", databaseStr); //stringByAppendingPathComponent(databaseStr) + let dbPath = docsPath.appendingFormat("/%@", databaseStr); //stringByAppendingPathComponent(databaseStr) return dbPath } @@ -916,40 +916,43 @@ 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? } print("SwiftData Warning -> The text date at column: \(index) could not be cast as a String, returning nil") return nil @@ -960,11 +963,16 @@ public struct SwiftData { } +// 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 { @@ -975,12 +983,12 @@ 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 { print("SwiftData Error -> During: SQL Prepare") print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) - if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { + if let errMsg = String(validatingUTF8: sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { print(" -> Details: \(errMsg)") } sqlite3_finalize(pStmt) @@ -990,7 +998,7 @@ public struct SwiftData { if status != SQLITE_DONE && status != SQLITE_OK { print("SwiftData Error -> During: SQL Step") print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) - if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { + if let errMsg = String(validatingUTF8: sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { print(" -> Details: \(errMsg)") } sqlite3_finalize(pStmt) @@ -1002,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 @@ -1014,12 +1022,12 @@ 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 { print("SwiftData Error -> During: SQL Prepare") print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) - if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { + if let errMsg = String(validatingUTF8: sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { print(" -> Details: \(errMsg)") } sqlite3_finalize(pStmt) @@ -1033,9 +1041,10 @@ public struct SwiftData { columnCount = sqlite3_column_count(pStmt) var row = SDRow() for i: Int32 in 0 ..< columnCount { - 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) { + 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 { @@ -1056,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) } } @@ -1067,7 +1076,7 @@ public struct SwiftData { } else { print("SwiftData Error -> During: SQL Step") print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status))) - if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { + if let errMsg = String(validatingUTF8: sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) { print(" -> Details: \(errMsg)") } sqlite3_finalize(pStmt) @@ -1146,16 +1155,16 @@ public struct SwiftData { 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 + 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 + public func asDate() -> Date? { + return value as? Date } /** @@ -1173,14 +1182,14 @@ public struct SwiftData { public func asUIImage() -> UIImage? { if let path = value as? String{ - let docsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] - let imageDirPath = docsPath.stringByAppendingFormat("/%@", "SwiftDataImages");//stringByAppendingPathComponent("SwiftDataImages") - let fullPath = imageDirPath.stringByAppendingFormat("/%@", path);//stringByAppendingPathComponent(path) - if !NSFileManager.defaultManager().fileExistsAtPath(fullPath) { + 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) } } @@ -1193,7 +1202,7 @@ public struct SwiftData { // MARK: - Error Handling - private struct SDError { + fileprivate struct SDError { } @@ -1204,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() } } @@ -1221,7 +1230,7 @@ extension SwiftData { 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 @@ -1242,7 +1251,7 @@ extension SwiftData.SQLiteDB { 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.characters.index(before: newSql.endIndex)) } else { obj = escapeValue(objects[bindIndex]) } @@ -1267,7 +1276,7 @@ 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 { @@ -1283,7 +1292,7 @@ extension SwiftData.SQLiteDB { return "0" } } - if obj is NSData { + if obj is Data { let str = "\(obj)" var newStr = "" for char in str.characters { @@ -1293,10 +1302,10 @@ 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) { @@ -1314,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.characters { if char == "'" { @@ -1332,7 +1341,7 @@ extension SwiftData.SQLiteDB { } //escape string - func escapeStringIdentifier(str: String) -> String { + func escapeStringIdentifier(_ str: String) -> String { var escapedStr = "" for char in str.characters { if char == "\"" { @@ -1363,28 +1372,28 @@ extension SwiftData { */ 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" } } @@ -1400,18 +1409,18 @@ extension SwiftData { */ public enum Flags { - case ReadOnly - case ReadWrite - case ReadWriteCreate + case readOnly + case readWrite + case readWriteCreate - private func toSQL() -> Int32 { + 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 } @@ -1425,7 +1434,7 @@ extension SwiftData { 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 @@ -1443,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) } @@ -1469,7 +1478,7 @@ 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 { print("SwiftData Error -> During: Creating Index") @@ -1497,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) } @@ -1526,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]() @@ -1555,7 +1564,7 @@ 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 { @@ -1681,4 +1690,4 @@ extension SwiftData.SDError { } -public typealias SD = SwiftData \ No newline at end of file +public typealias SD = SwiftData From 85f06937435ee0a581124f068ee035056e872bdc Mon Sep 17 00:00:00 2001 From: "fernando.ransanz" Date: Wed, 18 Jan 2017 11:19:26 +0100 Subject: [PATCH 09/10] swift3 - quitar warning en rollbackTransaction() --- SwiftData.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SwiftData.swift b/SwiftData.swift index a1255ea..fccf06a 100644 --- a/SwiftData.swift +++ b/SwiftData.swift @@ -872,7 +872,7 @@ public struct SwiftData { let error = executeChange("COMMIT") inTransaction = false if let err = error { - rollbackTransaction() + _ = rollbackTransaction() return err } return nil From c0462b46b851d29889e519664fe0969d09ba293a Mon Sep 17 00:00:00 2001 From: "fernando.ransanz" Date: Fri, 18 May 2018 14:25:01 +0200 Subject: [PATCH 10/10] Silenciar warnings en Xcode 9 --- SwiftData.swift | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/SwiftData.swift b/SwiftData.swift index fccf06a..df2d6dc 100644 --- a/SwiftData.swift +++ b/SwiftData.swift @@ -1235,7 +1235,7 @@ extension SwiftData.SQLiteDB { var newSql = "" var bindIndex = 0 var i = false - for char in sql.characters { + for char in sql { if char == "?" { if bindIndex > objects.count - 1 { print("SwiftData Error -> During: Object Binding") @@ -1251,7 +1251,7 @@ extension SwiftData.SQLiteDB { print(" -> Code: 203 - Object to bind as identifier must be a String at array location: \(bindIndex)") return ("", 203) } - newSql = newSql.substring(to: newSql.characters.index(before: newSql.endIndex)) + newSql = newSql.substring(to: newSql.index(before: newSql.endIndex)) } else { obj = escapeValue(objects[bindIndex]) } @@ -1295,7 +1295,7 @@ extension SwiftData.SQLiteDB { if obj is Data { let str = "\(obj)" var newStr = "" - for char in str.characters { + for char in str { if char != "<" && char != ">" && char != " " { newStr.append(char) } @@ -1331,7 +1331,7 @@ extension SwiftData.SQLiteDB { //escape string func escapeStringValue(_ str: String) -> String { var escapedStr = "" - for char in str.characters { + for char in str { if char == "'" { escapedStr += "'" } @@ -1343,7 +1343,7 @@ extension SwiftData.SQLiteDB { //escape string func escapeStringIdentifier(_ str: String) -> String { var escapedStr = "" - for char in str.characters { + for char in str { if char == "\"" { escapedStr += "\"" }