forked from PerfectlySoft/Perfect
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSQLite.swift
More file actions
432 lines (365 loc) · 13.3 KB
/
Copy pathSQLite.swift
File metadata and controls
432 lines (365 loc) · 13.3 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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//
// SQLite.swift
// PerfectLib
//
// Created by Kyle Jessup on 7/14/15.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version, as supplemented by the
// Perfect Additional Terms.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License, as supplemented by the
// Perfect Additional Terms, for more details.
//
// You should have received a copy of the GNU Affero General Public License
// and the Perfect Additional Terms that immediately follow the terms and
// conditions of the GNU Affero General Public License along with this
// program. If not, see <http://www.perfect.org/AGPL_3_0_With_Perfect_Additional_Terms.txt>.
//
import SQLite3
#if os(Linux)
import SwiftGlibc
#endif
/// This enum type indicates an exception when dealing with a SQLite database
public enum SQLiteError : ErrorType {
/// A SQLite error code and message.
case Error(code: Int, msg: String)
}
/// A SQLite database
public class SQLite : Closeable {
let path: String
var sqlite3: COpaquePointer
/// Create or open a SQLite database given a file path.
public init(_ path: String, readOnly: Bool = false) throws {
self.path = path
self.sqlite3 = COpaquePointer()
let flags = readOnly ? SQLITE_OPEN_READONLY : SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE
let res = sqlite3_open_v2(path, &self.sqlite3, flags, nil)
if res != SQLITE_OK {
throw SQLiteError.Error(code: Int(res), msg: "Unable to open database "+path)
}
}
/// Close the SQLite database.
public func close() {
if self.sqlite3 != nil {
sqlite3_close(self.sqlite3)
self.sqlite3 = nil
}
}
deinit {
close()
}
/// Compile the SQL statement.
/// - returns: A SQLiteStmt object representing the compiled statement.
public func prepare(stat: String) throws -> SQLiteStmt {
var statPtr = COpaquePointer()
let tail = UnsafeMutablePointer<UnsafePointer<Int8>>()
let res = sqlite3_prepare_v2(self.sqlite3, stat, Int32(stat.utf8.count), &statPtr, tail)
try checkRes(res)
return SQLiteStmt(db: self.sqlite3, stat: statPtr)
}
/// Returns the value of `sqlite3_last_insert_rowid`.
public func lastInsertRowID() -> Int {
let res = sqlite3_last_insert_rowid(self.sqlite3)
return Int(res)
}
/// Returns the value of `sqlite3_total_changes`.
public func totalChanges() -> Int {
let res = sqlite3_total_changes(self.sqlite3)
return Int(res)
}
/// Returns the value of `sqlite3_changes`.
public func changes() -> Int {
let res = sqlite3_changes(self.sqlite3)
return Int(res)
}
/// Returns the value of `sqlite3_errcode`.
public func errCode() -> Int {
let res = sqlite3_errcode(self.sqlite3)
return Int(res)
}
/// Returns the value of `sqlite3_errmsg`.
public func errMsg() -> String {
return String.fromCString(sqlite3_errmsg(self.sqlite3))!
}
/// Execute the given statement. Assumes there will be no parameter binding or resulting row data.
public func execute(statement: String) throws {
try forEachRow(statement, doBindings: { (SQLiteStmt) throws -> () in () }) {
(SQLiteStmt) -> () in
// nothing
}
}
/// Execute the given statement. Calls the provided callback one time for parameter binding. Assumes there will be no resulting row data.
public func execute(statement: String, doBindings: (SQLiteStmt) throws -> ()) throws {
try forEachRow(statement, doBindings: doBindings) {
(SQLiteStmt) -> () in
// nothing
}
}
/// Execute the given statement `count` times. Calls the provided callback on each execution for parameter binding. Assumes there will be no resulting row data.
public func execute(statement: String, count: Int, doBindings: (SQLiteStmt, Int) throws -> ()) throws {
let stat = try prepare(statement)
defer { stat.finalize() }
for idx in 1...count {
try doBindings(stat, idx)
try forEachRowBody(stat) {
(SQLiteStmt) -> () in
// nothing
}
try stat.reset()
}
}
/// Executes a BEGIN, calls the provided closure and executes a ROLLBACK if an exception occurs or a COMMIT if no exception occurs.
public func doWithTransaction(closure: () throws -> ()) throws {
try execute("BEGIN")
do {
try closure()
try execute("COMMIT")
} catch let e {
try execute("ROLLBACK")
throw e
}
}
/// Executes the statement and calls the closure for each resulting row.
public func forEachRow(statement: String, handleRow: (SQLiteStmt, Int) -> ()) throws {
let stat = try prepare(statement)
defer { stat.finalize() }
try forEachRowBody(stat, handleRow: handleRow)
}
/// Executes the statement, calling `doBindings` to handle parameter bindings and calling `handleRow` for each resulting row.
public func forEachRow(statement: String, doBindings: (SQLiteStmt) throws -> (), handleRow: (SQLiteStmt, Int) -> ()) throws {
let stat = try prepare(statement)
defer { stat.finalize() }
try doBindings(stat)
try forEachRowBody(stat, handleRow: handleRow)
}
func forEachRowBody(stat: SQLiteStmt, handleRow: (SQLiteStmt, Int) -> ()) throws {
var r = stat.step()
if r == SQLITE_LOCKED || r == SQLITE_BUSY {
miniSleep(1)
if r == SQLITE_LOCKED {
try stat.reset()
}
r = stat.step()
var times = 1000000
while (r == SQLITE_LOCKED || r == SQLITE_BUSY) && times > 0 {
if r == SQLITE_LOCKED {
try stat.reset()
}
r = stat.step()
times -= 1
}
guard r != SQLITE_LOCKED && r != SQLITE_BUSY else {
try checkRes(r)
return
}
}
var rowNum = 1
while r == SQLITE_ROW {
handleRow(stat, rowNum)
rowNum += 1
r = stat.step()
}
}
func miniSleep(millis: Int) {
var tv = timeval()
tv.tv_sec = millis / 1000
#if os(Linux)
tv.tv_usec = Int((millis % 1000) * 1000)
#else
tv.tv_usec = Int32((millis % 1000) * 1000)
#endif
select(0, nil, nil, nil, &tv)
}
func checkRes(res: Int32) throws {
try checkRes(Int(res))
}
func checkRes(res: Int) throws {
if res != Int(SQLITE_OK) {
throw SQLiteError.Error(code: res, msg: String.fromCString(sqlite3_errmsg(self.sqlite3))!)
}
}
}
/// A compiled SQLite statement
public class SQLiteStmt : Closeable {
let db: COpaquePointer
var stat: COpaquePointer?
typealias sqlite_destructor = @convention(c) (UnsafeMutablePointer<Void>) -> Void
init(db: COpaquePointer, stat: COpaquePointer) {
self.db = db
self.stat = stat
}
/// Close or "finalize" the statement.
public func close() {
finalize()
}
/// Close the statement.
public func finalize() {
if self.stat != nil {
sqlite3_finalize(self.stat!)
self.stat = nil
}
}
/// Advance to the next row.
public func step() -> Int32 {
guard self.stat != nil else {
return SQLITE_MISUSE
}
return sqlite3_step(self.stat!)
}
/// Bind the Double value to the indicated parameter.
public func bind(position: Int, _ d: Double) throws {
try checkRes(sqlite3_bind_double(self.stat!, Int32(position), d))
}
/// Bind the Int32 value to the indicated parameter.
public func bind(position: Int, _ i: Int32) throws {
try checkRes(sqlite3_bind_int(self.stat!, Int32(position), Int32(i)))
}
/// Bind the Int value to the indicated parameter.
public func bind(position: Int, _ i: Int) throws {
try checkRes(sqlite3_bind_int64(self.stat!, Int32(position), Int64(i)))
}
/// Bind the Int64 value to the indicated parameter.
public func bind(position: Int, _ i: Int64) throws {
try checkRes(sqlite3_bind_int64(self.stat!, Int32(position), i))
}
/// Bind the String value to the indicated parameter.
public func bind(position: Int, _ s: String) throws {
try checkRes(sqlite3_bind_text(self.stat!, Int32(position), s, Int32(s.utf8.count), unsafeBitCast(COpaquePointer(bitPattern: -1), sqlite_destructor.self)))
}
/// Bind the [Int8] blob value to the indicated parameter.
public func bind(position: Int, _ b: [Int8]) throws {
try checkRes(sqlite3_bind_blob(self.stat!, Int32(position), b, Int32(b.count), unsafeBitCast(COpaquePointer(bitPattern: -1), sqlite_destructor.self)))
}
/// Bind the [UInt8] blob value to the indicated parameter.
public func bind(position: Int, _ b: [UInt8]) throws {
try checkRes(sqlite3_bind_blob(self.stat!, Int32(position), b, Int32(b.count), unsafeBitCast(COpaquePointer(bitPattern: -1), sqlite_destructor.self)))
}
/// Bind a blob of `count` zero values to the indicated parameter.
public func bindZeroBlob(position: Int, count: Int) throws {
try checkRes(sqlite3_bind_zeroblob(self.stat!, Int32(position), Int32(count)))
}
/// Bind a null to the indicated parameter.
public func bindNull(position: Int) throws {
try checkRes(sqlite3_bind_null(self.stat!, Int32(position)))
}
/// Bind the Double value to the indicated parameter.
public func bind(name: String, _ d: Double) throws {
try checkRes(sqlite3_bind_double(self.stat!, Int32(bindParameterIndex(name)), d))
}
/// Bind the Int32 value to the indicated parameter.
public func bind(name: String, _ i: Int32) throws {
try checkRes(sqlite3_bind_int(self.stat!, Int32(bindParameterIndex(name)), Int32(i)))
}
/// Bind the Int value to the indicated parameter.
public func bind(name: String, _ i: Int) throws {
try checkRes(sqlite3_bind_int64(self.stat!, Int32(bindParameterIndex(name)), Int64(i)))
}
/// Bind the Int64 value to the indicated parameter.
public func bind(name: String, _ i: Int64) throws {
try checkRes(sqlite3_bind_int64(self.stat!, Int32(bindParameterIndex(name)), i))
}
/// Bind the String value to the indicated parameter.
public func bind(name: String, _ s: String) throws {
try checkRes(sqlite3_bind_text(self.stat!, Int32(bindParameterIndex(name)), s, Int32(s.utf8.count), unsafeBitCast(COpaquePointer(bitPattern: -1), sqlite_destructor.self)))
}
/// Bind the [Int8] blob value to the indicated parameter.
public func bind(name: String, _ b: [Int8]) throws {
try checkRes(sqlite3_bind_text(self.stat!, Int32(bindParameterIndex(name)), b, Int32(b.count), unsafeBitCast(COpaquePointer(bitPattern: -1), sqlite_destructor.self)))
}
/// Bind a blob of `count` zero values to the indicated parameter.
public func bindZeroBlob(name: String, count: Int) throws {
try checkRes(sqlite3_bind_zeroblob(self.stat!, Int32(bindParameterIndex(name)), Int32(count)))
}
/// Bind a null to the indicated parameter.
public func bindNull(name: String) throws {
try checkRes(sqlite3_bind_null(self.stat!, Int32(bindParameterIndex(name))))
}
/// Returns the index for the named parameter.
public func bindParameterIndex(name: String) throws -> Int {
let idx = sqlite3_bind_parameter_index(self.stat!, name)
guard idx != 0 else {
throw SQLiteError.Error(code: Int(SQLITE_MISUSE), msg: "The indicated bind parameter name was not found.")
}
return Int(idx)
}
/// Resets the SQL statement.
public func reset() throws -> Int {
let res = sqlite3_reset(self.stat!)
try checkRes(res)
return Int(res)
}
/// Return the number of columns in mthe result set.
public func columnCount() -> Int {
let res = sqlite3_column_count(self.stat!)
return Int(res)
}
/// Returns the name for the indicated column.
public func columnName(position: Int) -> String {
return String.fromCString(sqlite3_column_name(self.stat!, Int32(position)))!
}
/// Returns the name of the declared type for the indicated column.
public func columnDeclType(position: Int) -> String {
return String.fromCString(sqlite3_column_decltype(self.stat!, Int32(position)))!
}
/// Returns the blob data for the indicated column.
public func columnBlob(position: Int) -> [Int8] {
let vp = sqlite3_column_blob(self.stat!, Int32(position))
let vpLen = sqlite3_column_bytes(self.stat!, Int32(position))
guard vpLen > 0 else {
return [Int8]()
}
var bytesPtr = UnsafePointer<Int8>(vp)
var ret = [Int8]()
for _ in 0..<vpLen {
ret.append(bytesPtr.memory)
bytesPtr = bytesPtr.successor()
}
return ret
}
/// Returns the Double value for the indicated column.
public func columnDouble(position: Int) -> Double {
return Double(sqlite3_column_double(self.stat!, Int32(position)))
}
/// Returns the Int value for the indicated column.
public func columnInt(position: Int) -> Int {
return Int(sqlite3_column_int64(self.stat!, Int32(position)))
}
/// Returns the Int32 value for the indicated column.
public func columnInt32(position: Int) -> Int32 {
return sqlite3_column_int(self.stat!, Int32(position))
}
/// Returns the Int64 value for the indicated column.
public func columnInt64(position: Int) -> Int64 {
return sqlite3_column_int64(self.stat!, Int32(position))
}
/// Returns the String value for the indicated column.
public func columnText(position: Int) -> String {
let res = sqlite3_column_text(self.stat!, Int32(position))
if res != nil {
return String.fromCString(UnsafePointer<CChar>(res))!
}
return ""
}
/// Returns the type for the indicated column.
public func columnType(position: Int) -> Int32 {
return sqlite3_column_type(self.stat!, Int32(position))
}
func checkRes(res: Int32) throws {
try checkRes(Int(res))
}
func checkRes(res: Int) throws {
if res != Int(SQLITE_OK) {
throw SQLiteError.Error(code: res, msg: String.fromCString(sqlite3_errmsg(self.db))!)
}
}
deinit {
finalize()
}
}