· 6 years ago · Mar 23, 2019, 07:10 PM
1/*
2 * @description: creates a table with the specified list of columns and value types
3 * @note statement example e.g."CREATE TABLE IF NOT EXISTS table_name (Title Text, Author Text, PublicationDate Date)"
4 * @param table name of the table to create
5 * @param columns list of TableColumn values to create the columns
6 * @param completion closure to be called when create is complete
7 */
8 static func create(table:String, columns:[TableColumn], completion:Completion) {
9 var sqlStatement = "CREATE TABLE IF NOT EXISTS \(table) (ID Integer Primary key AutoIncrement,"
10
11 for (index, column) in columns.enumerated() {
12 sqlStatement += " \(column.name) \(column.type)"
13 sqlStatement += (index == columns.count - 1) ? ");" :","
14 }
15
16 FMDBDatabase.update(sqlStatement: sqlStatement, completion: completion)
17 }
18
19 /*
20 * @description: All transactions in FMDB are an UPDATE if they are not a QUERY, this
21 * helper method is called by the CREATE, INSERT, and DELETE functions
22 * @param sqlStatement the complete SQL statement to execute
23 * @param values list of TableColumn or WhereConditions values to use in update
24 * @param completion closure to be called when update is complete
25 */
26 private static func update(sqlStatement:String, values:[Any]? = nil, completion:Completion) {
27
28 sharedQueue.inDeferredTransaction { (db, rollback) in
29 do {
30 if !sharedDatabase.isOpen {
31 sharedDatabase.open()
32 }
33 try sharedDatabase.executeUpdate(sqlStatement, values: values)
34 completion(true, nil)
35 sharedDatabase.close()
36 } catch {
37 print("failed: \(error.localizedDescription)")
38 completion(false, error)
39 sharedDatabase.close()
40 }
41 }
42 }