mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-30 04:28:44 +00:00
Robustness of Database.execute() with multiple statements. Remove Database.executeMultiStatement() introduced by #6.
This commit is contained in:
1 parent
aad3d5efa5
commit
589647ca20
9 files changed
+221
-187
No files matched your search
+6
-1
@@ -10,6 +10,7 @@ Release Notes
|
||||
|
||||
**New**
|
||||
|
||||
- `Database.execute()` can now execute several statements separated by a semicolon.
|
||||
- `Statement.validateArguments(_)` throws an error if the arguments parameter doesn't match the prepared statement:
|
||||
|
||||
```swift
|
||||
@@ -20,6 +21,10 @@ Release Notes
|
||||
try statement.validateArguments([1, 2])
|
||||
```
|
||||
|
||||
**Breaking Changes**
|
||||
|
||||
- `Database.executeMultiStatement(sql)` has been removed. To execute several SQL statements separated by a semicolon, use `Database.execute()` instead.
|
||||
|
||||
|
||||
## 0.36.0
|
||||
|
||||
@@ -505,7 +510,7 @@ Released August 18, 2015
|
||||
|
||||
- `RowModel.exists(db)` returns whether a row model has a matching row in the database.
|
||||
- `Statement.arguments` property gains a public setter.
|
||||
- `Database.executeMultiple(sql)` can execute several SQL statements separated by a semi-colon ([#6](http://github.com/groue/GRDB.swift/pull/6) by [peter-ss](https://github.com/peter-ss))
|
||||
- `Database.executeMultiStatement(sql)` can execute several SQL statements separated by a semi-colon ([#6](http://github.com/groue/GRDB.swift/pull/6) by [peter-ss](https://github.com/peter-ss))
|
||||
|
||||
**Breaking changes**
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ class DatabaseTests : GRDBTestCase {
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertFalse(db.tableExists("persons"))
|
||||
XCTAssertFalse(db.tableExists("pets"))
|
||||
try db.executeMultiStatement(
|
||||
try db.execute(
|
||||
"CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, age INT);" +
|
||||
"CREATE TABLE pets (id INTEGER PRIMARY KEY, name TEXT, age INT);")
|
||||
XCTAssertTrue(db.tableExists("persons"))
|
||||
|
||||
@@ -86,7 +86,7 @@ class DatabaseErrorTests: GRDBTestCase {
|
||||
func testDatabaseErrorThrownByExecuteMultiStatementContainSQL() {
|
||||
dbQueue.inDatabase { db in
|
||||
do {
|
||||
try db.executeMultiStatement(
|
||||
try db.execute(
|
||||
"CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, age INT);" +
|
||||
"CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT);" +
|
||||
"INSERT INTO pets (masterId, name) VALUES (1, 'Bobby')")
|
||||
@@ -94,8 +94,8 @@ class DatabaseErrorTests: GRDBTestCase {
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.code, 19) // SQLITE_CONSTRAINT
|
||||
XCTAssertEqual(error.message!, "FOREIGN KEY constraint failed")
|
||||
XCTAssertEqual(error.sql!, "CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, age INT);CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT);INSERT INTO pets (masterId, name) VALUES (1, \'Bobby\')")
|
||||
XCTAssertEqual(error.description, "SQLite error 19 with statement `CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, age INT);CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT);INSERT INTO pets (masterId, name) VALUES (1, \'Bobby\')`: FOREIGN KEY constraint failed")
|
||||
XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (1, 'Bobby')")
|
||||
XCTAssertEqual(error.description, "SQLite error 19 with statement `INSERT INTO pets (masterId, name) VALUES (1, 'Bobby')`: FOREIGN KEY constraint failed")
|
||||
} catch {
|
||||
XCTFail("\(error)")
|
||||
}
|
||||
|
||||
@@ -178,10 +178,19 @@ class UpdateStatementTests : GRDBTestCase {
|
||||
assertNoError {
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute(
|
||||
"INSERT INTO persons (name) VALUES (:name1);" +
|
||||
"INSERT INTO persons (name) VALUES (:name2);",
|
||||
arguments: ["name1": "Arthur", "name2": "Barbara"])
|
||||
XCTAssertEqual(String.fetchAll(db, "SELECT name FROM persons ORDER BY name"), ["Arthur", "Barbara"])
|
||||
"INSERT INTO persons (name, age) VALUES ('Arthur', :age1);" +
|
||||
"INSERT INTO persons (name, age) VALUES ('Arthur', :age2);",
|
||||
arguments: ["age1": 41, "age2": 32])
|
||||
XCTAssertEqual(Int.fetchAll(db, "SELECT age FROM persons ORDER BY age"), [32, 41])
|
||||
return .Rollback
|
||||
}
|
||||
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute(
|
||||
"INSERT INTO persons (name, age) VALUES ('Arthur', :age1);" +
|
||||
"INSERT INTO persons (name, age) VALUES ('Arthur', :age2);",
|
||||
arguments: [41, 32])
|
||||
XCTAssertEqual(Int.fetchAll(db, "SELECT age FROM persons ORDER BY age"), [32, 41])
|
||||
return .Rollback
|
||||
}
|
||||
|
||||
@@ -189,16 +198,43 @@ class UpdateStatementTests : GRDBTestCase {
|
||||
do {
|
||||
// Too few arguments
|
||||
try db.execute(
|
||||
"INSERT INTO persons (name) VALUES (:name1);" +
|
||||
"INSERT INTO persons (name) VALUES (:name2);",
|
||||
arguments: ["name1": "Arthur"])
|
||||
"INSERT INTO persons (name, age) VALUES ('Arthur', :age1);" +
|
||||
"INSERT INTO persons (name, age) VALUES ('Arthur', :age2);")
|
||||
XCTFail("Expected Error")
|
||||
} catch {
|
||||
// Global fail
|
||||
XCTAssertEqual(String.fetchAll(db, "SELECT name FROM persons ORDER BY name"), [String]())
|
||||
XCTAssertTrue(Int.fetchAll(db, "SELECT age FROM persons ORDER BY age").isEmpty)
|
||||
}
|
||||
return .Rollback
|
||||
}
|
||||
|
||||
try dbQueue.inTransaction { db in
|
||||
do {
|
||||
// Too few arguments
|
||||
try db.execute(
|
||||
"INSERT INTO persons (name, age) VALUES ('Arthur', :age1);" +
|
||||
"INSERT INTO persons (name, age) VALUES ('Arthur', :age2);",
|
||||
arguments: ["age1": 41])
|
||||
XCTFail("Expected Error")
|
||||
} catch {
|
||||
// Partial fail
|
||||
XCTAssertEqual(Int.fetchAll(db, "SELECT age FROM persons ORDER BY age"), [41])
|
||||
}
|
||||
return .Rollback
|
||||
}
|
||||
|
||||
try dbQueue.inTransaction { db in
|
||||
do {
|
||||
// Too many arguments
|
||||
try db.execute(
|
||||
"INSERT INTO persons (name, age) VALUES ('Arthur', :age1);" +
|
||||
"INSERT INTO persons (name, age) VALUES ('Arthur', :age2);",
|
||||
arguments: [41, 32, 17])
|
||||
XCTFail("Expected Error")
|
||||
} catch {
|
||||
// Partial fail
|
||||
XCTAssertEqual(Int.fetchAll(db, "SELECT age FROM persons ORDER BY age"), [32, 41])
|
||||
}
|
||||
return .Rollback
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -207,12 +243,25 @@ class UpdateStatementTests : GRDBTestCase {
|
||||
assertNoError {
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute(
|
||||
"INSERT INTO persons (name) VALUES (:name);" +
|
||||
"INSERT INTO persons (name) VALUES (:name);",
|
||||
arguments: ["name": "Arthur"])
|
||||
XCTAssertEqual(String.fetchAll(db, "SELECT name FROM persons"), ["Arthur", "Arthur"])
|
||||
"INSERT INTO persons (name, age) VALUES ('Arthur', :age);" +
|
||||
"INSERT INTO persons (name, age) VALUES ('Arthur', :age);",
|
||||
arguments: ["age": 41])
|
||||
XCTAssertEqual(Int.fetchAll(db, "SELECT age FROM persons"), [41, 41])
|
||||
return .Rollback
|
||||
}
|
||||
|
||||
// // The test below fails because 41 in consumed by the first statement,
|
||||
// // leaving no argument for the second statement.
|
||||
// //
|
||||
// // TODO? make it work
|
||||
// try dbQueue.inTransaction { db in
|
||||
// try db.execute(
|
||||
// "INSERT INTO persons (name, age) VALUES ('Arthur', :age);" +
|
||||
// "INSERT INTO persons (name, age) VALUES ('Arthur', :age);",
|
||||
// arguments: [41])
|
||||
// XCTAssertEqual(Int.fetchAll(db, "SELECT age FROM persons"), [41, 41])
|
||||
// return .Rollback
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,10 +269,10 @@ class UpdateStatementTests : GRDBTestCase {
|
||||
assertNoError {
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute(
|
||||
"INSERT INTO persons (name) VALUES (?);" +
|
||||
"INSERT INTO persons (name) VALUES (?);",
|
||||
arguments: ["Arthur", "Barbara"])
|
||||
XCTAssertEqual(String.fetchAll(db, "SELECT name FROM persons ORDER BY name"), ["Arthur", "Barbara"])
|
||||
"INSERT INTO persons (name, age) VALUES ('Arthur', ?);" +
|
||||
"INSERT INTO persons (name, age) VALUES ('Arthur', ?);",
|
||||
arguments: [41, 32])
|
||||
XCTAssertEqual(Int.fetchAll(db, "SELECT age FROM persons ORDER BY age"), [32, 41])
|
||||
return .Rollback
|
||||
}
|
||||
|
||||
@@ -231,13 +280,27 @@ class UpdateStatementTests : GRDBTestCase {
|
||||
do {
|
||||
// Too few arguments
|
||||
try db.execute(
|
||||
"INSERT INTO persons (name) VALUES (?);" +
|
||||
"INSERT INTO persons (name) VALUES (?);",
|
||||
arguments: ["Arthur"])
|
||||
"INSERT INTO persons (name, age) VALUES ('Arthur', ?);" +
|
||||
"INSERT INTO persons (name, age) VALUES ('Arthur', ?);")
|
||||
XCTFail("Expected Error")
|
||||
} catch {
|
||||
// Global fail
|
||||
XCTAssertEqual(String.fetchAll(db, "SELECT name FROM persons ORDER BY name"), [String]())
|
||||
XCTAssertTrue(Int.fetchAll(db, "SELECT age FROM persons ORDER BY age").isEmpty)
|
||||
}
|
||||
|
||||
return .Rollback
|
||||
}
|
||||
|
||||
try dbQueue.inTransaction { db in
|
||||
do {
|
||||
// Too few arguments
|
||||
try db.execute(
|
||||
"INSERT INTO persons (name, age) VALUES ('Arthur', ?);" +
|
||||
"INSERT INTO persons (name, age) VALUES ('Arthur', ?);",
|
||||
arguments: [41])
|
||||
XCTFail("Expected Error")
|
||||
} catch {
|
||||
// Partial fail
|
||||
XCTAssertEqual(Int.fetchAll(db, "SELECT age FROM persons ORDER BY age"), [41])
|
||||
}
|
||||
|
||||
return .Rollback
|
||||
@@ -247,13 +310,13 @@ class UpdateStatementTests : GRDBTestCase {
|
||||
do {
|
||||
// Too many arguments
|
||||
try db.execute(
|
||||
"INSERT INTO persons (name) VALUES (?);" +
|
||||
"INSERT INTO persons (name) VALUES (?);",
|
||||
arguments: ["Arthur", "Barbara", "Craig"])
|
||||
"INSERT INTO persons (name, age) VALUES ('Arthur', ?);" +
|
||||
"INSERT INTO persons (name, age) VALUES ('Arthur', ?);",
|
||||
arguments: [41, 32, 17])
|
||||
XCTFail("Expected Error")
|
||||
} catch {
|
||||
// Global fail
|
||||
XCTAssertEqual(String.fetchAll(db, "SELECT name FROM persons ORDER BY name"), [String]())
|
||||
// Partial fail
|
||||
XCTAssertEqual(Int.fetchAll(db, "SELECT age FROM persons ORDER BY age"), [32, 41])
|
||||
}
|
||||
return .Rollback
|
||||
}
|
||||
|
||||
+74
-85
@@ -50,9 +50,17 @@ public final class Database {
|
||||
return try UpdateStatement(database: self, sql: sql)
|
||||
}
|
||||
|
||||
/// Executes an update statement.
|
||||
/// Executes one or several SQL statements, separated by semi-colons.
|
||||
///
|
||||
/// db.excute("INSERT INTO persons (name) VALUES (?)", arguments: ["Arthur"])
|
||||
/// try db.execute(
|
||||
/// "INSERT INTO persons (name) VALUES (:name)",
|
||||
/// arguments: ["name": "Arthur"])
|
||||
///
|
||||
/// try db.execute(
|
||||
/// "INSERT INTO persons (name) VALUES (?);" +
|
||||
/// "INSERT INTO persons (name) VALUES (?);" +
|
||||
/// "INSERT INTO persons (name) VALUES (?);",
|
||||
/// arguments; ['Harry', 'Ron', 'Hermione'])
|
||||
///
|
||||
/// This method may throw a DatabaseError.
|
||||
///
|
||||
@@ -63,103 +71,84 @@ public final class Database {
|
||||
public func execute(sql: String, arguments: StatementArguments = StatementArguments.Default) throws -> DatabaseChanges {
|
||||
preconditionValidQueue()
|
||||
|
||||
|
||||
// Build statements
|
||||
|
||||
let sqlCodeUnits = sql.nulTerminatedUTF8
|
||||
var code: Int32 = 0
|
||||
var statements: [UpdateStatement] = []
|
||||
sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
|
||||
let sqlStart = UnsafePointer<Int8>(codeUnits.baseAddress)
|
||||
var statementStart = sqlStart
|
||||
while true {
|
||||
var statementEnd: UnsafePointer<Int8> = nil
|
||||
var sqliteStatement: SQLiteStatement = nil
|
||||
code = sqlite3_prepare_v2(sqliteConnection, statementStart, -1, &sqliteStatement, &statementEnd)
|
||||
guard code == SQLITE_OK else {
|
||||
break
|
||||
// The tricky part is to consume arguments as statements are executed.
|
||||
//
|
||||
// Here we return two functions:
|
||||
// - one that returns arguments for a statement
|
||||
// - one that validates the remaining arguments, in the same way as
|
||||
// Statement.validateArguments()
|
||||
let (consumeArguments, validateRemainingArguments) = { () -> (UpdateStatement -> StatementArguments, () throws -> ()) in
|
||||
switch arguments.kind {
|
||||
case .Array(let values):
|
||||
// Extract as many values as needed, statement after statement:
|
||||
var remainingValues = values
|
||||
let consumeArguments = { (statement: UpdateStatement) -> StatementArguments in
|
||||
defer {
|
||||
if remainingValues.count >= statement.sqliteArgumentCount {
|
||||
remainingValues = Array(remainingValues.suffixFrom(statement.sqliteArgumentCount))
|
||||
} else {
|
||||
remainingValues = []
|
||||
}
|
||||
}
|
||||
return StatementArguments(remainingValues.prefix(statement.sqliteArgumentCount))
|
||||
}
|
||||
let sql = NSString(bytes: statementStart, length: statementEnd - statementStart, encoding: NSUTF8StringEncoding)! as String
|
||||
statements.append(UpdateStatement(database: self, sql: sql, sqliteStatement: sqliteStatement))
|
||||
if statementEnd - sqlStart + 1 == sqlCodeUnits.count {
|
||||
break
|
||||
// It's not OK if there remains unused arguments:
|
||||
let validateRemainingArguments = {
|
||||
if !remainingValues.isEmpty {
|
||||
throw DatabaseError(code: SQLITE_ERROR, message: "Statement arguments mismatch: got \(values.count) argument(s) instead of \(values.count - remainingValues.count).", sql: sql, arguments: nil)
|
||||
}
|
||||
}
|
||||
statementStart = statementEnd
|
||||
return (consumeArguments, validateRemainingArguments)
|
||||
case .Dictionary, .Default:
|
||||
// Reuse the dictionary argument for all statements:
|
||||
let consumeArguments = { (_: UpdateStatement) -> StatementArguments in return arguments }
|
||||
let validateRemainingArguments = { () in }
|
||||
return (consumeArguments, validateRemainingArguments)
|
||||
}
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(code: code, message: lastErrorMessage, sql: sql)
|
||||
}
|
||||
|
||||
|
||||
// Validate arguments for all statements
|
||||
|
||||
switch arguments.kind {
|
||||
case .Array(let values):
|
||||
var remainingValues = values
|
||||
for statement in statements {
|
||||
let arguments = StatementArguments(remainingValues.prefix(statement.sqliteArgumentCount))
|
||||
try statement.validateArguments(arguments)
|
||||
statement.arguments = arguments
|
||||
if remainingValues.count >= statement.sqliteArgumentCount {
|
||||
remainingValues = Array(remainingValues.suffixFrom(statement.sqliteArgumentCount))
|
||||
} else {
|
||||
remainingValues = []
|
||||
}
|
||||
}
|
||||
if !remainingValues.isEmpty {
|
||||
throw DatabaseError(code: SQLITE_ERROR, message: "Statement arguments mismatch: got \(values.count) argument(s) instead of \(values.count - remainingValues.count).", sql: sql, arguments: nil)
|
||||
}
|
||||
case .Dictionary:
|
||||
for statement in statements {
|
||||
try statement.validateArguments(arguments)
|
||||
statement.arguments = arguments
|
||||
}
|
||||
case .Default:
|
||||
break
|
||||
}
|
||||
|
||||
}()
|
||||
|
||||
|
||||
// Execute statements
|
||||
|
||||
let changedRowsBefore = sqlite3_total_changes(sqliteConnection)
|
||||
for statement in statements {
|
||||
try statement.execute()
|
||||
let sqlCodeUnits = sql.nulTerminatedUTF8
|
||||
let length = sqlCodeUnits.count
|
||||
var error: ErrorType?
|
||||
sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
|
||||
let sqlStart = UnsafePointer<Int8>(codeUnits.baseAddress)
|
||||
let sqlEnd = sqlStart + length
|
||||
var statementStart = sqlStart
|
||||
while statementStart < sqlEnd - 1 {
|
||||
var statementEnd: UnsafePointer<Int8> = nil
|
||||
var sqliteStatement: SQLiteStatement = nil
|
||||
let code = sqlite3_prepare_v2(sqliteConnection, statementStart, -1, &sqliteStatement, &statementEnd)
|
||||
guard code == SQLITE_OK else {
|
||||
error = DatabaseError(code: code, message: lastErrorMessage, sql: sql)
|
||||
break
|
||||
}
|
||||
let sql = NSString(bytes: statementStart, length: statementEnd - statementStart, encoding: NSUTF8StringEncoding)! as String
|
||||
let statement = UpdateStatement(database: self, sql: sql, sqliteStatement: sqliteStatement)
|
||||
|
||||
do {
|
||||
try statement.execute(arguments: consumeArguments(statement))
|
||||
} catch let statementError {
|
||||
error = statementError
|
||||
break
|
||||
}
|
||||
|
||||
statementStart = statementEnd
|
||||
}
|
||||
}
|
||||
if let error = error {
|
||||
throw error
|
||||
}
|
||||
try validateRemainingArguments()
|
||||
let changedRowsAfter = sqlite3_total_changes(sqliteConnection)
|
||||
|
||||
let lastInsertedRowID = sqlite3_last_insert_rowid(sqliteConnection)
|
||||
let insertedRowID: Int64? = (lastInsertedRowID == 0) ? nil : lastInsertedRowID
|
||||
return DatabaseChanges(changedRowCount: changedRowsAfter - changedRowsBefore, insertedRowID: insertedRowID)
|
||||
}
|
||||
|
||||
/// Executes multiple SQL statements, separated by semi-colons.
|
||||
///
|
||||
/// try db.executeMultiStatement(
|
||||
/// "INSERT INTO persons (name) VALUES ('Harry');" +
|
||||
/// "INSERT INTO persons (name) VALUES ('Ron');" +
|
||||
/// "INSERT INTO persons (name) VALUES ('Hermione');")
|
||||
///
|
||||
/// This method may throw a DatabaseError.
|
||||
///
|
||||
/// - parameter sql: SQL containing multiple statements separated by
|
||||
/// semi-colons.
|
||||
/// - returns: A DatabaseChanges. Note that insertedRowID will always be nil.
|
||||
/// - throws: A DatabaseError whenever a SQLite error occurs.
|
||||
public func executeMultiStatement(sql: String) throws -> DatabaseChanges {
|
||||
preconditionValidQueue()
|
||||
|
||||
let changedRowsBefore = sqlite3_total_changes(sqliteConnection)
|
||||
|
||||
let code = sqlite3_exec(sqliteConnection, sql, nil, nil, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(code: code, message: lastErrorMessage, sql: sql, arguments: nil)
|
||||
}
|
||||
|
||||
let changedRowsAfter = sqlite3_total_changes(sqliteConnection)
|
||||
return DatabaseChanges(changedRowCount: changedRowsAfter - changedRowsBefore, insertedRowID: nil)
|
||||
}
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - Transactions
|
||||
|
||||
+41
-32
@@ -15,31 +15,8 @@ public class Statement {
|
||||
|
||||
/// The query arguments
|
||||
public var arguments: StatementArguments? {
|
||||
didSet {
|
||||
reset()
|
||||
clearBindings()
|
||||
let bindings = try! self.bindings(arguments)
|
||||
for (index, databaseValue) in bindings.enumerate() {
|
||||
let bindingIndex = Int32(index + 1)
|
||||
let code: Int32
|
||||
switch databaseValue.storage {
|
||||
case .Null:
|
||||
code = sqlite3_bind_null(sqliteStatement, bindingIndex)
|
||||
case .Int64(let int64):
|
||||
code = sqlite3_bind_int64(sqliteStatement, bindingIndex, int64)
|
||||
case .Double(let double):
|
||||
code = sqlite3_bind_double(sqliteStatement, bindingIndex, double)
|
||||
case .String(let string):
|
||||
code = sqlite3_bind_text(sqliteStatement, bindingIndex, string, -1, SQLITE_TRANSIENT)
|
||||
case .Blob(let data):
|
||||
code = sqlite3_bind_blob(sqliteStatement, bindingIndex, data.bytes, Int32(data.length), SQLITE_TRANSIENT)
|
||||
}
|
||||
|
||||
if code != SQLITE_OK {
|
||||
fatalError(DatabaseError(code: code, message: database.lastErrorMessage, sql: sql).description)
|
||||
}
|
||||
}
|
||||
}
|
||||
get { return _arguments }
|
||||
set { try! setArguments(newValue) }
|
||||
}
|
||||
|
||||
// MARK: Not public
|
||||
@@ -78,7 +55,7 @@ public class Statement {
|
||||
}
|
||||
|
||||
guard consumedCharactersCount == sqlCodeUnits.count else {
|
||||
throw DatabaseError(code: SQLITE_ERROR, message: "Invalid SQL string: multiple statements found. To execute multiple statements, use Database.executeMultiStatement() instead.", sql: sql, arguments: nil)
|
||||
throw DatabaseError(code: SQLITE_ERROR, message: "Invalid SQL string: multiple statements found. To execute multiple statements, use Database.execute() instead.", sql: sql, arguments: nil)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,6 +76,8 @@ public class Statement {
|
||||
|
||||
// MARK: Arguments
|
||||
|
||||
var _arguments: StatementArguments?
|
||||
|
||||
lazy var sqliteArgumentCount: Int = {
|
||||
Int(sqlite3_bind_parameter_count(self.sqliteStatement))
|
||||
}()
|
||||
@@ -116,6 +95,36 @@ public class Statement {
|
||||
}
|
||||
}()
|
||||
|
||||
private func setArguments(arguments: StatementArguments?) throws {
|
||||
// Validate
|
||||
let bindings = try self.bindings(arguments)
|
||||
_arguments = arguments
|
||||
|
||||
// Apply
|
||||
reset()
|
||||
clearBindings()
|
||||
for (index, databaseValue) in bindings.enumerate() {
|
||||
let bindingIndex = Int32(index + 1)
|
||||
let code: Int32
|
||||
switch databaseValue.storage {
|
||||
case .Null:
|
||||
code = sqlite3_bind_null(sqliteStatement, bindingIndex)
|
||||
case .Int64(let int64):
|
||||
code = sqlite3_bind_int64(sqliteStatement, bindingIndex, int64)
|
||||
case .Double(let double):
|
||||
code = sqlite3_bind_double(sqliteStatement, bindingIndex, double)
|
||||
case .String(let string):
|
||||
code = sqlite3_bind_text(sqliteStatement, bindingIndex, string, -1, SQLITE_TRANSIENT)
|
||||
case .Blob(let data):
|
||||
code = sqlite3_bind_blob(sqliteStatement, bindingIndex, data.bytes, Int32(data.length), SQLITE_TRANSIENT)
|
||||
}
|
||||
|
||||
if code != SQLITE_OK {
|
||||
throw DatabaseError(code: code, message: database.lastErrorMessage, sql: sql)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Throws a DatabaseError of code SQLITE_ERROR if arguments don't fill all
|
||||
/// statement arguments.
|
||||
public func validateArguments(arguments: StatementArguments?) throws {
|
||||
@@ -221,12 +230,11 @@ public class Statement {
|
||||
}
|
||||
}
|
||||
|
||||
private func prepareWithArguments(arguments: StatementArguments) {
|
||||
private func prepareWithArguments(arguments: StatementArguments) throws {
|
||||
if !arguments.kind.isDefault {
|
||||
self.arguments = arguments
|
||||
try setArguments(arguments)
|
||||
} else {
|
||||
// try! for consistency with SelectStatement
|
||||
try! validateArguments(self.arguments)
|
||||
try validateArguments(self.arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -260,7 +268,7 @@ public final class SelectStatement : Statement {
|
||||
|
||||
/// The DatabaseSequence builder.
|
||||
func fetch<T>(arguments arguments: StatementArguments, yield: () -> T) -> DatabaseSequence<T> {
|
||||
prepareWithArguments(arguments)
|
||||
try! prepareWithArguments(arguments)
|
||||
return DatabaseSequence(statement: self, yield: yield)
|
||||
}
|
||||
|
||||
@@ -355,11 +363,12 @@ public final class UpdateStatement : Statement {
|
||||
/// - returns: A DatabaseChanges.
|
||||
/// - throws: A DatabaseError whenever a SQLite error occurs.
|
||||
public func execute(arguments arguments: StatementArguments = StatementArguments.Default) throws -> DatabaseChanges {
|
||||
prepareWithArguments(arguments)
|
||||
try prepareWithArguments(arguments)
|
||||
reset()
|
||||
|
||||
let changes: DatabaseChanges
|
||||
let code = sqlite3_step(sqliteStatement)
|
||||
|
||||
switch code {
|
||||
case SQLITE_DONE:
|
||||
let changedRowCount = Int(sqlite3_changes(database.sqliteConnection))
|
||||
|
||||
@@ -58,7 +58,7 @@ public struct DatabaseMigrator {
|
||||
///
|
||||
/// // Add a NOT NULL constraint on persons.name:
|
||||
/// migrator.registerMigration("AddNotNullCheckOnName", withDisabledForeignKeyChecks: true) { db in
|
||||
/// try db.executeMultiStatement(
|
||||
/// try db.execute(
|
||||
/// "CREATE TABLE new_persons (id INTEGER PRIMARY KEY, name TEXT NOT NULL);" +
|
||||
/// "INSERT INTO new_persons SELECT * FROM persons;" +
|
||||
/// "DROP TABLE persons;" +
|
||||
|
||||
@@ -1267,11 +1267,9 @@ migrator.registerMigration("createTables") { db in
|
||||
|
||||
// v2.0 database
|
||||
migrator.registerMigration("AddAgeToPersons") { db in
|
||||
try db.execute("ALTER TABLE persons ADD COLUMN age INT")
|
||||
}
|
||||
|
||||
migrator.registerMigration("AddYearToBooks") { db in
|
||||
try db.execute("ALTER TABLE books ADD COLUMN year INT")
|
||||
try db.execute(
|
||||
"ALTER TABLE persons ADD COLUMN age INT; " +
|
||||
"ALTER TABLE books ADD COLUMN year INT")
|
||||
}
|
||||
|
||||
// (Insert migrations for future versions here)
|
||||
@@ -1283,32 +1281,6 @@ try migrator.migrate(dbQueue)
|
||||
|
||||
**The memory of applied migrations is stored in the database itself** (in a reserved table). When you are tuning your migrations, you may need to execute one several times. All you need then is to feed your application with a database file from a previous state.
|
||||
|
||||
You might use Database.executeMultiStatement(): this method takes an SQL string containing multiple statements separated by semi-colons:
|
||||
|
||||
```swift
|
||||
migrator.registerMigration("createTables") { db in
|
||||
try db.executeMultiStatement(
|
||||
"CREATE TABLE persons (...);" +
|
||||
"CREATE TABLE books (...);" +
|
||||
"...")
|
||||
}
|
||||
```
|
||||
|
||||
You might even store your migrations as bundle resources:
|
||||
|
||||
```swift
|
||||
// Execute migration01.sql, migration02.sql, etc.
|
||||
NSBundle.mainBundle()
|
||||
.pathsForResourcesOfType("sql", inDirectory: "databaseMigrations")
|
||||
.sort()
|
||||
.forEach { path in
|
||||
let migrationName = (path as NSString).lastPathComponent
|
||||
migrator.registerMigration(migrationName) { db in
|
||||
let sql = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
|
||||
try db.executeMultiStatement(sql)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Advanced Database Schema Changes
|
||||
|
||||
@@ -1319,7 +1291,7 @@ Yet any kind of schema change is still possible. The SQLite documentation explai
|
||||
```swift
|
||||
// Add a NOT NULL constraint on persons.name:
|
||||
migrator.registerMigration("AddNotNullCheckOnName", withDisabledForeignKeyChecks: true) { db in
|
||||
try db.executeMultiStatement(
|
||||
try db.execute(
|
||||
"CREATE TABLE new_persons (id INTEGER PRIMARY KEY, name TEXT NOT NULL);" +
|
||||
"INSERT INTO new_persons SELECT * FROM persons;" +
|
||||
"DROP TABLE persons;" +
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
- [ ] Throw statement validation errors from methods that throw.
|
||||
- [ ] Remove executeMultiStatement()
|
||||
- [ ] Try to remove DefaultArgument.
|
||||
- [ ] Move DatabaseErrorFromStatementCreationTests.swift to tests of public APIs, now that prepared statement factory methods can throw errors.
|
||||
- [ ] "SELECT * FROM table WHERE id = ?" should not accept an empty dictionary as an argument.
|
||||
- [ ] Can we deal with parameter names that are reused several times in the same query?
|
||||
|
||||
Not sure:
|
||||
|
||||
|
||||
Reference in new issue
Block a user