-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathSQLiteStORM.swift
More file actions
306 lines (258 loc) · 8.15 KB
/
SQLiteStORM.swift
File metadata and controls
306 lines (258 loc) · 8.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
//
// SQLiteStORM.swift
// SQLiteStORM
//
// Created by Jonathan Guthrie on 2016-10-03.
//
//
import StORM
import PerfectSQLite
import PerfectLogger
/// SQLiteConnector sets the connection parameters for the SQLite3 database file access
/// Usage:
/// SQLiteConnector.db = "XXXXXX"
public struct SQLiteConnector {
private init(){}
/// Holds the location of the db file.
public static var db = ""
}
/// SuperClass that inherits from the foundation "StORM" class.
/// Provides SQLite-specific ORM functionality to child classes.
open class SQLiteStORM: StORM {
open var connection = SQLiteConnect()
/// Table that the child object relates to in the database.
/// Defined as "open" as it is meant to be overridden by the child class.
open func table() -> String {
let m = Mirror(reflecting: self)
return ("\(m.subjectType)").lowercased()
}
/// Empty initializer. This is the default action.
override public init() {
super.init()
}
/// Alternate initializer, allows supply of a custom SQLiteConnect object.
public init(_ connect: SQLiteConnect) {
super.init()
self.connection = connect
}
private func printDebug(_ statement: String, _ params: [String]) {
if StORMDebug.active { LogFile.debug("StORM Debug: \(statement) : \(params.joined(separator: ", "))", logFile: StORMDebug.location) }
}
// Internal function which executes statements
func exec(_ smt: String) throws {
printDebug(smt, [])
if !SQLiteConnector.db.isEmpty {
self.connection.database = SQLiteConnector.db
}
do {
let db = try self.connection.open()
try db.execute(statement: smt)
self.connection.close(db)
} catch {
throw StORMError.error(errorMsg)
}
}
// Internal function which executes statements, with parameter binding
// Returns an id
@discardableResult
func execReturnID(_ smt: String, params: [String]) throws -> Any {
printDebug(smt, params)
if !SQLiteConnector.db.isEmpty {
self.connection.database = SQLiteConnector.db
}
do {
let db = try self.connection.open()
try db.execute(statement: smt, doBindings: {
(statement: SQLiteStmt) -> () in
for i in 0..<params.count {
try statement.bind(position: i+1, params[i])
}
})
let x = db.lastInsertRowID()
self.connection.close(db)
return x
} catch {
print(error)
throw StORMError.error(errorMsg)
}
}
func execStatement(_ smt: String) throws {
printDebug(smt, [])
if !SQLiteConnector.db.isEmpty {
self.connection.database = SQLiteConnector.db
}
do {
let db = try self.connection.open()
try db.execute(statement: smt)
self.connection.close(db)
} catch {
throw StORMError.error("\(error)")
}
}
// Internal function which executes statements, with parameter binding
// Returns an array of SQLiteStmt
@discardableResult
func exec(_ smt: String, params: [String]) throws -> [SQLiteStmt] {
printDebug(smt, params)
if !SQLiteConnector.db.isEmpty {
self.connection.database = SQLiteConnector.db
}
var results = [SQLiteStmt]()
do {
let db = try self.connection.open()
try db.forEachRow(statement: smt, doBindings: {
(statement: SQLiteStmt) -> () in
for i in 0..<params.count {
try statement.bind(position: i+1, params[i])
}
}, handleRow: {(statement: SQLiteStmt, i:Int) -> () in
results.append(statement)
})
defer {
self.connection.close(db)
}
} catch {
throw StORMError.error(errorMsg)
}
return results
}
// Internal function which executes statements, with parameter binding
// Returns a processed row set
@discardableResult
func execRows(_ smt: String, params: [String]) throws -> [StORMRow] {
printDebug(smt, params)
if !SQLiteConnector.db.isEmpty {
self.connection.database = SQLiteConnector.db
}
var rows = [StORMRow]()
// let results = try exec(smt, params: params)
// print(results[0].columnCount())
// rows = parseRows(results)
do {
let db = try self.connection.open()
try db.forEachRow(statement: smt, doBindings: {
(statement: SQLiteStmt) -> () in
for i in 0..<params.count {
try statement.bind(position: i+1, params[i])
}
}, handleRow: {(statement: SQLiteStmt, i:Int) -> () in
rows.append(parseRow(statement))
// print(statement.columnCount())
// results.append(statement)
})
defer {
self.connection.close(db)
}
} catch {
throw StORMError.error(errorMsg)
}
return rows
}
/// Generic "to" function
/// Defined as "open" as it is meant to be overridden by the child class.
///
/// Sample usage:
/// id = this.data["id"] as? Int ?? 0
/// firstname = this.data["firstname"] as? String ?? ""
/// lastname = this.data["lastname"] as? String ?? ""
/// email = this.data["email"] as? String ?? ""
open func to(_ this: StORMRow) {
}
/// Generic "makeRow" function
/// Defined as "open" as it is meant to be overridden by the child class.
open func makeRow() {
self.to(self.results.rows[0])
}
/// Standard "Save" function.
/// Designed as "open" so it can be overriden and customized.
/// If an ID has been defined, save() will perform an updae, otherwise a new document is created.
/// On error can throw a StORMError error.
@discardableResult
open func save() throws -> Any {
do {
if keyIsEmpty() {
return try insert(asData(1))
} else {
let (idname, idval) = firstAsKey()
try update(data: asData(1), idName: idname, idValue: idval)
}
} catch {
LogFile.error("Error msg: \(error)", logFile: StORMDebug.location)
throw StORMError.error("\(error)")
}
return 0
}
/// Alternate "Save" function.
/// This save method will use the supplied "set" to assign or otherwise process the returned id.
/// Designed as "open" so it can be overriden and customized.
/// If an ID has been defined, save() will perform an updae, otherwise a new document is created.
/// On error can throw a StORMError error.
open func save(set: (_ id: Any)->Void) throws {
do {
if keyIsEmpty() {
let setId = try insert(asData(1))
set(setId)
} else {
let (idname, idval) = firstAsKey()
try update(data: asData(1), idName: idname, idValue: idval)
}
} catch {
LogFile.error("Error msg: \(error)", logFile: StORMDebug.location)
throw StORMError.error("\(error)")
}
}
/// Unlike the save() methods, create() mandates the addition of a new document, regardless of whether an ID has been set or specified.
override open func create() throws {
do {
try insert(asData())
} catch {
LogFile.error("Error msg: \(error)", logFile: StORMDebug.location)
throw StORMError.error("\(error)")
}
}
/// Table Creation (alias for setup)
open func setupTable() throws {
try setup()
}
/// Table Creation
/// Requires the connection to be configured, as well as a valid "table" property to have been set in the class
/// Creates the table by inspecting the object. Columns will be created that relate to the assigned type of the property. Properties beginning with an underscore or "internal_" will be ignored.
open func setup() throws {
LogFile.info("Running setup: \(table())", logFile: StORMDebug.location)
var opt = [String]()
for child in Mirror(reflecting: self).children {
guard let key = child.label else {
continue
}
var verbage = ""
if !key.hasPrefix("internal_") && !key.hasPrefix("_") {
verbage = "\(key) "
if child.value is Int {
verbage += "INTEGER"
} else if child.value is Double {
verbage += "REAL"
} else if child.value is Double {
verbage += "REAL"
} else if child.value is UInt || child.value is UInt8 || child.value is UInt16 || child.value is UInt32 || child.value is UInt64 {
verbage += "BLOB"
} else {
verbage += "TEXT"
}
if opt.count == 0 && child.value is Int {
verbage += " PRIMARY KEY AUTOINCREMENT NOT NULL"
} else if opt.count == 0 {
verbage += " PRIMARY KEY NOT NULL"
}
opt.append(verbage)
}
}
let createStatement = "CREATE TABLE IF NOT EXISTS \(table()) (\(opt.joined(separator: ", ")))"
if StORMDebug.active { LogFile.info("createStatement: \(createStatement)", logFile: StORMDebug.location) }
do {
try sqlExec(createStatement)
} catch {
LogFile.error("Error msg: \(error)", logFile: StORMDebug.location)
throw StORMError.error("\(error)")
}
}
}