diff --git a/GRDB Tests/Public/Database/DatabaseTests.swift b/GRDB Tests/Public/Database/DatabaseTests.swift index ce075d6e9..06a9746fd 100644 --- a/GRDB Tests/Public/Database/DatabaseTests.swift +++ b/GRDB Tests/Public/Database/DatabaseTests.swift @@ -46,7 +46,7 @@ class DatabaseTests : GRDBTestCase { try dbQueue.inDatabase { db in XCTAssertFalse(db.tableExists("persons")) XCTAssertFalse(db.tableExists("pets")) - try db.execute( + try db.executeMultiStatement( "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")) @@ -100,7 +100,7 @@ class DatabaseTests : GRDBTestCase { } } } - + func testDatabaseExecute() { assertNoError { try dbQueue.inDatabase { db in diff --git a/GRDB Tests/Public/DatabaseError/DatabaseErrorTests.swift b/GRDB Tests/Public/DatabaseError/DatabaseErrorTests.swift index 21c6ac72c..179e94d44 100644 --- a/GRDB Tests/Public/DatabaseError/DatabaseErrorTests.swift +++ b/GRDB Tests/Public/DatabaseError/DatabaseErrorTests.swift @@ -66,31 +66,6 @@ class DatabaseErrorTests: GRDBTestCase { } } - func testDatabaseErrorContainMutipleSQLStatements() { - dbQueue.inDatabase { db in - do { - try db.execute( - "CREATE TABLE persons (id INTEGER PRIMARY KEY);" + - "CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT);" + - "INSERT INTO pets (masterId, name) VALUES (1, 'Bobby')") - XCTFail() - } catch let error as DatabaseError { - XCTAssertEqual(error.code, Int(SQLITE_CONSTRAINT)) - XCTAssertEqual(error.message!, "FOREIGN KEY constraint failed") - XCTAssertEqual(error.sql!, "CREATE TABLE persons (id INTEGER PRIMARY KEY);" + - "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);" + - "CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT);" + - "INSERT INTO pets (masterId, name) VALUES (1, 'Bobby')`: " + - "FOREIGN KEY constraint failed") - } catch { - XCTFail("\(error)") - } - } - } - func testDatabaseErrorThrownByUpdateStatementContainSQLAndArguments() { dbQueue.inDatabase { db in do { @@ -108,4 +83,27 @@ class DatabaseErrorTests: GRDBTestCase { } } } + + func testDatabaseErrorThrownByExecuteMultiStatementContainSQL() { + dbQueue.inDatabase { db in + do { + XCTAssertFalse(db.tableExists("persons")) + XCTAssertFalse(db.tableExists("pets")) + try db.executeMultiStatement( + "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')") + + XCTFail() + } catch let error as DatabaseError { + XCTAssertEqual(error.code, Int(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") + } catch { + XCTFail("\(error)") + } + } + } + } diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 040750cd5..ec32f846f 100644 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -96,6 +96,8 @@ 56F0B9901B6001C600A2F135 /* DatabaseDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98D1B6001C600A2F135 /* DatabaseDateComponentsTests.swift */; }; 56F0B9911B6001C600A2F135 /* DatabaseDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* DatabaseDateTests.swift */; }; 56F0B9921B6001C600A2F135 /* DatabaseDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* DatabaseDateTests.swift */; }; + 9E903FA81B82729400A63DA0 /* DatabaseChanges.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E903FA71B82729400A63DA0 /* DatabaseChanges.swift */; }; + 9E903FA91B82741C00A63DA0 /* DatabaseChanges.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E903FA71B82729400A63DA0 /* DatabaseChanges.swift */; }; DC2393C81ABE35F8003FF113 /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; }; DC3773F919C8CBB3004FCF85 /* GRDB.h in Headers */ = {isa = PBXBuildFile; fileRef = DC3773F819C8CBB3004FCF85 /* GRDB.h */; settings = {ATTRIBUTES = (Public, ); }; }; DC70AC991AC2331000371524 /* libsqlite3.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = DC37744219C8DC91004FCF85 /* libsqlite3.dylib */; }; @@ -168,6 +170,7 @@ 56E5D7F91B4D422D00430942 /* GRDBTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 56F0B98D1B6001C600A2F135 /* DatabaseDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateComponentsTests.swift; sourceTree = ""; }; 56F0B98E1B6001C600A2F135 /* DatabaseDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDateTests.swift; sourceTree = ""; }; + 9E903FA71B82729400A63DA0 /* DatabaseChanges.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseChanges.swift; sourceTree = ""; }; DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = ""; }; DC3773F319C8CBB3004FCF85 /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; DC3773F719C8CBB3004FCF85 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = ../GRDB/Info.plist; sourceTree = ""; }; @@ -400,6 +403,7 @@ children = ( 56CC3C921B43BF0100A9A534 /* Configuration.swift */, 565E191D1B42B2B600D32814 /* Database.swift */, + 9E903FA71B82729400A63DA0 /* DatabaseChanges.swift */, 5645E69C1B5E76D30045DC8F /* DatabaseDate.swift */, 564E0B131B4D8FC100EBC9F6 /* DatabaseError.swift */, 56CC3C941B43C0E600A9A534 /* DatabaseMigrator.swift */, @@ -621,6 +625,7 @@ 56B8F44A1B4E1C8600C24296 /* DatabaseValue.swift in Sources */, 56E5D8331B4D43FA00430942 /* Row.swift in Sources */, 56E5D8321B4D43FA00430942 /* DatabaseQueue.swift in Sources */, + 9E903FA91B82741C00A63DA0 /* DatabaseChanges.swift in Sources */, 56E5D8381B4D43FA00430942 /* Statement.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -712,6 +717,7 @@ 5699AE5B1B42D3DC00C35172 /* SelectStatement.swift in Sources */, 56CC3C9B1B4464AE00A9A534 /* RowModel.swift in Sources */, 56E4BB811B45373600FD324B /* QueryArguments.swift in Sources */, + 9E903FA81B82729400A63DA0 /* DatabaseChanges.swift in Sources */, 564E0B141B4D8FC100EBC9F6 /* DatabaseError.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/GRDB/Database.swift b/GRDB/Database.swift index 9df2ba445..f74753cad 100644 --- a/GRDB/Database.swift +++ b/GRDB/Database.swift @@ -87,12 +87,47 @@ public final class Database { - returns: A UpdateStatement.Changes. - throws: A DatabaseError whenever a SQLite error occurs. */ - public func execute(sql: String, arguments: QueryArguments? = nil) throws -> UpdateStatement.Changes { + public func execute(sql: String, arguments: QueryArguments? = nil) throws -> DatabaseChanges { let statement = try updateStatement(sql) return try statement.execute(arguments: arguments) } + /** + Executes multiple SQL statements (separated by a semi-colon). + + let rowsAffected = 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 UpdateStatement.Changes. Note that insertedRowID will always be nil. + - throws: A DatabaseError whenever a SQLite error occurs. + */ + public func executeMultiStatement(sql: String) throws -> DatabaseChanges { + + if let trace = self.configuration.trace { + trace(sql: sql, arguments: nil) + } + + let changedRowsBefore = sqlite3_total_changes(self.sqliteConnection) + + var errMsg:UnsafeMutablePointer = nil + let code = sqlite3_exec(self.sqliteConnection, sql, nil, nil, &errMsg) + guard code == SQLITE_OK else { + throw DatabaseError(code: code, message: self.lastErrorMessage, sql: sql, arguments: nil) + } + + let changedRowsAfter = sqlite3_total_changes(self.sqliteConnection) + + let changes = DatabaseChanges(changedRowCount: changedRowsAfter - changedRowsBefore, insertedRowID: nil) + + return changes + } + + // MARK: - Transactions /// A SQLite transaction type. See https://www.sqlite.org/lang_transaction.html diff --git a/GRDB/DatabaseChanges.swift b/GRDB/DatabaseChanges.swift new file mode 100644 index 000000000..9a4960037 --- /dev/null +++ b/GRDB/DatabaseChanges.swift @@ -0,0 +1,36 @@ +// +// GRDB.swift +// https://github.com/groue/GRDB.swift +// Copyright (c) 2015 Gwendal Roué +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + + +/** +Represents the various changes made to the database via execution of one or more SQL statements. +*/ +public struct DatabaseChanges { + + /// The number of rows affected by the statement(s) + public let changedRowCount: Int + + /// The inserted Row ID. Relevant if and only if the statement is an + /// INSERT statement. + public let insertedRowID: Int64? +} diff --git a/GRDB/Statement.swift b/GRDB/Statement.swift index 01febb973..d95541728 100644 --- a/GRDB/Statement.swift +++ b/GRDB/Statement.swift @@ -83,7 +83,7 @@ public class Statement { switch code { case SQLITE_OK: if consumedCharactersCount != sqlCodeUnits.count { - fatalError("Invalid SQL string: multiple statements found.") + fatalError("Invalid SQL string: multiple statements found. To execute multiple statements, use Database.executeMultiStatement() instead.") } default: throw DatabaseError(code: code, message: database.lastErrorMessage, sql: sql) diff --git a/GRDB/UpdateStatement.swift b/GRDB/UpdateStatement.swift index 5c4cf14ce..296f9a2d0 100644 --- a/GRDB/UpdateStatement.swift +++ b/GRDB/UpdateStatement.swift @@ -35,25 +35,14 @@ You create UpdateStatement with the Database.updateStatement() method: } */ public final class UpdateStatement : Statement { - - /// The changes performed by an UpdateStatement. - public struct Changes { - /// The number of rows changed by the statement. - public let changedRowCount: Int - - /// The inserted Row ID. Relevant if and only if the statement is an - /// INSERT statement. - public let insertedRowID: Int64? - } - /** Executes the SQL query. - parameter arguments: Optional query arguments. - throws: A DatabaseError whenever a SQLite error occurs. */ - public func execute(arguments arguments: QueryArguments? = nil) throws -> Changes { + public func execute(arguments arguments: QueryArguments? = nil) throws -> DatabaseChanges { if let arguments = arguments { self.arguments = arguments } @@ -72,6 +61,6 @@ public final class UpdateStatement : Statement { let changedRowCount = Int(sqlite3_changes(database.sqliteConnection)) let lastInsertedRowID = sqlite3_last_insert_rowid(database.sqliteConnection) let insertedRowID: Int64? = (lastInsertedRowID == 0) ? nil : lastInsertedRowID - return Changes(changedRowCount: changedRowCount, insertedRowID: insertedRowID) + return DatabaseChanges(changedRowCount: changedRowCount, insertedRowID: insertedRowID) } } diff --git a/README.md b/README.md index 8e821fa11..1a174fda1 100644 --- a/README.md +++ b/README.md @@ -740,6 +740,29 @@ migrator.registerMigration("AddAgeToPersons") { db in try migrator.migrate(dbQueue) ``` +If you have larger migrations, you might prefer to use Database.executeMultiStatement(). This method takes a SQL string containing multiple statements separated by semi-colons. + +```swift +migrator.registerMigration("createBooks") { db in + try db.executeMultiStatement( + "CREATE TABLE persons (name TEXT NOT NULL);" + + "INSERT INTO persons (name) VALUES ('Harry');" + + "INSERT INTO persons (name) VALUES ('Ron');" + + "INSERT INTO persons (name) VALUES ('Hermione');") +} +``` + +You might even store your migration scripts in a text file: + +```swift +migrator.registerMigration("initialSchema") { (db) -> Void in + if let filePath = NSBundle.mainBundle().pathForResource("dbMigration01", ofType: "txt") { + let migrationSql = try String(contentsOfFile: filePath) + let dbChanges = try db.executeMultiStatement(migrationSql) + print("Rows affected: \(dbChanges.changedRowCount)") + } +} +``` ## Row Models