From cc495e3fd5295554eb6fedb8eabd8a6ce318624e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 25 Feb 2020 22:11:18 +0100 Subject: [PATCH 01/46] Failing test for literal expression function --- Tests/GRDBTests/SQLLiteralTests.swift | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Tests/GRDBTests/SQLLiteralTests.swift b/Tests/GRDBTests/SQLLiteralTests.swift index ddb3c3278..b722c1728 100644 --- a/Tests/GRDBTests/SQLLiteralTests.swift +++ b/Tests/GRDBTests/SQLLiteralTests.swift @@ -473,6 +473,18 @@ extension SQLLiteralTests { SELECT * FROM "player" WHERE (DATE("createdAt")) = '2020-01-23' """) } + + do { + // Here we test that users can define functions that return literal expressions + func date(_ value: SQLExpressible) -> SQLExpression { + SQLLiteral("DATE(\(value))").sqlExpression + } + let createdAt = Column("createdAt") + let request = Player.filter(date(createdAt) == "2020-01-23") + try assertEqualSQL(db, request, """ + SELECT * FROM "player" WHERE (DATE("createdAt")) = '2020-01-23' + """) + } } } } From eb6f6e57ffe0c3539e38de47077fe244e8e883ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 25 Feb 2020 22:13:17 +0100 Subject: [PATCH 02/46] Fix failing test for literal expression function --- .../SQLInterpolation+QueryInterface.swift | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift index 9320d24c5..d4de32ea1 100644 --- a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift @@ -57,7 +57,16 @@ extension SQLInterpolation { /// let request: SQLRequest = """ /// SELECT score + \(bonus) FROM player /// """ - public mutating func appendInterpolation(_ expressible: T?) { + /// + /// You can also derive literal expressions from other expressions: + /// + /// func date(_ value: SQLExpressible) -> SQLExpression { + /// SQLLiteral("DATE(\(value))").sqlExpression + /// } + /// + /// // SELECT * FROM player WHERE DATE(createdAt) = '2020-02-25' + /// let request = Player.filter(date(Column("createdAt")) == "2020-02-25") + public mutating func appendInterpolation(_ expressible: SQLExpressible?) { if let expressible = expressible { elements.append(.expression(expressible.sqlExpression)) } else { From bad8d857293ab068895484690996246d4e5201de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 25 Feb 2020 22:18:16 +0100 Subject: [PATCH 03/46] Add test for legacy literal expression function --- Tests/GRDBTests/SQLLiteralTests.swift | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/Tests/GRDBTests/SQLLiteralTests.swift b/Tests/GRDBTests/SQLLiteralTests.swift index b722c1728..81c2d7144 100644 --- a/Tests/GRDBTests/SQLLiteralTests.swift +++ b/Tests/GRDBTests/SQLLiteralTests.swift @@ -475,7 +475,8 @@ extension SQLLiteralTests { } do { - // Here we test that users can define functions that return literal expressions + // Here we test that users can define functions that return + // literal expressions. func date(_ value: SQLExpressible) -> SQLExpression { SQLLiteral("DATE(\(value))").sqlExpression } @@ -485,6 +486,20 @@ extension SQLLiteralTests { SELECT * FROM "player" WHERE (DATE("createdAt")) = '2020-01-23' """) } + + do { + // Here we test that users can still define functions that + // return literal expressions with the previously + // supported technique. + func date(_ value: SQLExpressible) -> SQLExpression { + SQLLiteral("DATE(\(value.sqlExpression))").sqlExpression + } + let createdAt = Column("createdAt") + let request = Player.filter(date(createdAt) == "2020-01-23") + try assertEqualSQL(db, request, """ + SELECT * FROM "player" WHERE (DATE("createdAt")) = '2020-01-23' + """) + } } } } From b46a8c897ac45450a3e7760221c447c59decd8ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 25 Feb 2020 22:21:32 +0100 Subject: [PATCH 04/46] Update SQLLiteral documentation --- Documentation/SQLInterpolation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/SQLInterpolation.md b/Documentation/SQLInterpolation.md index ca51511ec..259648c60 100644 --- a/Documentation/SQLInterpolation.md +++ b/Documentation/SQLInterpolation.md @@ -152,7 +152,7 @@ Such literal expressions can be returned by Swift functions: ```swift func date(_ value: SQLExpressible) -> SQLExpression { - SQLLiteral("DATE(\(lhs.sqlExpression))").sqlExpression + SQLLiteral("DATE(\(value))").sqlExpression } // SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23' From 0a8001a1288cb1bc852f3d2abd8c934ef2c4c6b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 25 Feb 2020 22:25:36 +0100 Subject: [PATCH 05/46] CHANGELOG --- CHANGELOG.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 86f9fe9a3..b867bdbe3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,9 +6,7 @@ All notable changes to this project will be documented in this file. GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library. - #### 4.x Releases @@ -63,9 +61,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [0.110.0](#01100), ... - + +**New** + +- [#706](https://github.com/groue/GRDB.swift/pull/706): Enhance SQLLiteral and SQL interpolation again ## 4.10.0 From 9400e7f5d5c7d98d769a60980a41804a0c502b1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 26 Feb 2020 08:17:48 +0100 Subject: [PATCH 06/46] Fix tests for Xcode 10.3 --- Tests/GRDBTests/SQLLiteralTests.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/GRDBTests/SQLLiteralTests.swift b/Tests/GRDBTests/SQLLiteralTests.swift index 81c2d7144..a2fe9fd60 100644 --- a/Tests/GRDBTests/SQLLiteralTests.swift +++ b/Tests/GRDBTests/SQLLiteralTests.swift @@ -478,7 +478,7 @@ extension SQLLiteralTests { // Here we test that users can define functions that return // literal expressions. func date(_ value: SQLExpressible) -> SQLExpression { - SQLLiteral("DATE(\(value))").sqlExpression + return SQLLiteral("DATE(\(value))").sqlExpression } let createdAt = Column("createdAt") let request = Player.filter(date(createdAt) == "2020-01-23") @@ -492,7 +492,7 @@ extension SQLLiteralTests { // return literal expressions with the previously // supported technique. func date(_ value: SQLExpressible) -> SQLExpression { - SQLLiteral("DATE(\(value.sqlExpression))").sqlExpression + return SQLLiteral("DATE(\(value.sqlExpression))").sqlExpression } let createdAt = Column("createdAt") let request = Player.filter(date(createdAt) == "2020-01-23") From 8557d113a348dd40801b2c25a7c40f9c7beab70b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 26 Feb 2020 13:57:14 +0100 Subject: [PATCH 07/46] Deprecate registerMigrationWithDeferredForeignKeyCheck This method is now equivalent to registerMigration, starting SQLite 3.7.16 --- GRDB/Migration/DatabaseMigrator.swift | 51 +++---------------------- GRDB/Migration/Migration.swift | 54 ++++++++++++--------------- 2 files changed, 29 insertions(+), 76 deletions(-) diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 14a4218f8..ccfacfcf2 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -91,66 +91,27 @@ public struct DatabaseMigrator { registerMigration(Migration(identifier: identifier, migrate: migrate)) } - #if GRDBCUSTOMSQLITE || GRDBCIPHER - /// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter + /// Registers a migration. /// - /// // Add a NOT NULL constraint on players.name: - /// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in - /// try db.create(table: "new_player") { t in + /// migrator.registerMigration("createAuthors") { db in + /// try db.create(table: "author") { t in /// t.autoIncrementedPrimaryKey("id") + /// t.column("creationDate", .datetime) /// t.column("name", .text).notNull() /// } - /// try db.execute(sql: "INSERT INTO new_player SELECT * FROM player") - /// try db.drop(table: "player") - /// try db.rename(table: "new_player", to: "player") /// } /// - /// While your migration code runs with disabled foreign key checks, those - /// are re-enabled and checked at the end of the migration, regardless of - /// eventual errors. - /// /// - parameters: /// - identifier: The migration identifier. /// - block: The migration block that performs SQL statements. /// - precondition: No migration with the same same as already been registered. - /// - /// :nodoc: + @available(*, deprecated, renamed: "registerMigration(_:migrate:)") public mutating func registerMigrationWithDeferredForeignKeyCheck( _ identifier: String, migrate: @escaping (Database) throws -> Void) { - registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate)) + registerMigration(identifier, migrate: migrate) } - #else - @available(OSX 10.10, *) - /// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter - /// - /// // Add a NOT NULL constraint on players.name: - /// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in - /// try db.create(table: "new_player") { t in - /// t.autoIncrementedPrimaryKey("id") - /// t.column("name", .text).notNull() - /// } - /// try db.execute(sql: "INSERT INTO new_player SELECT * FROM player") - /// try db.drop(table: "player") - /// try db.rename(table: "new_player", to: "player") - /// } - /// - /// While your migration code runs with disabled foreign key checks, those - /// are re-enabled and checked at the end of the migration, regardless of - /// eventual errors. - /// - /// - parameters: - /// - identifier: The migration identifier. - /// - block: The migration block that performs SQL statements. - /// - precondition: No migration with the same same as already been registered. - public mutating func registerMigrationWithDeferredForeignKeyCheck( - _ identifier: String, - migrate: @escaping (Database) throws -> Void) - { - registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate)) - } - #endif /// Iterate migrations in the same order as they were registered. If a /// migration has not yet been applied, its block is executed in diff --git a/GRDB/Migration/Migration.swift b/GRDB/Migration/Migration.swift index 24f44b3e0..0673c7aca 100644 --- a/GRDB/Migration/Migration.swift +++ b/GRDB/Migration/Migration.swift @@ -1,36 +1,19 @@ /// An internal struct that defines a migration. struct Migration { let identifier: String - let disabledForeignKeyChecks: Bool let migrate: (Database) throws -> Void - #if GRDBCUSTOMSQLITE || GRDBCIPHER - init(identifier: String, disabledForeignKeyChecks: Bool = false, migrate: @escaping (Database) throws -> Void) { - self.identifier = identifier - self.disabledForeignKeyChecks = disabledForeignKeyChecks - self.migrate = migrate - } - #else init(identifier: String, migrate: @escaping (Database) throws -> Void) { self.identifier = identifier - self.disabledForeignKeyChecks = false self.migrate = migrate } - @available(OSX 10.10, *) - // PRAGMA foreign_key_check was introduced in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16 - // It is available from iOS 8.2 and OS X 10.10 - // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - init(identifier: String, disabledForeignKeyChecks: Bool, migrate: @escaping (Database) throws -> Void) { - self.identifier = identifier - self.disabledForeignKeyChecks = disabledForeignKeyChecks - self.migrate = migrate - } - #endif - func run(_ db: Database) throws { - if try disabledForeignKeyChecks && (Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false) { - try runWithDisabledForeignKeys(db) + // PRAGMA foreign_key_check and SQLITE_CONSTRAINT_FOREIGNKEY were + // introduced in SQLite 3.7.16 + // http://www.sqlite.org/changes.html#version_3_7_16 + if try sqlite3_libversion_number() >= 3007016 && (Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false) { + try runWithDeferredForeignKeysChecks(db) } else { try runWithoutDisabledForeignKeys(db) } @@ -45,7 +28,7 @@ struct Migration { } } - private func runWithDisabledForeignKeys(_ db: Database) throws { + private func runWithDeferredForeignKeysChecks(_ db: Database) throws { // Support for database alterations described at // https://www.sqlite.org/lang_altertable.html#otheralter // @@ -60,18 +43,26 @@ struct Migration { try migrate(db) try insertAppliedIdentifier(db) - // > 10. If foreign key constraints were originally enabled then run PRAGMA - // > foreign_key_check to verify that the schema change did not break any foreign key - // > constraints. - if try Row.fetchOne(db, sql: "PRAGMA foreign_key_check") != nil { + // > 10. If foreign key constraints were originally enabled + // > then run PRAGMA foreign_key_check to verify that the + // > schema change did not break any foreign + // > key constraints. + if try db + .makeSelectStatement(sql: "PRAGMA foreign_key_check") + .makeCursor() + .next() != nil + { // https://www.sqlite.org/pragma.html#pragma_foreign_key_check // // PRAGMA foreign_key_check does not return an error, // but the list of violated foreign key constraints. // - // Let's turn any violation into an SQLITE_CONSTRAINT - // error, and rollback the transaction. - throw DatabaseError(resultCode: .SQLITE_CONSTRAINT, message: "FOREIGN KEY constraint failed") + // Let's turn any violation into an + // SQLITE_CONSTRAINT_FOREIGNKEY error, and rollback + // the transaction. + throw DatabaseError( + resultCode: .SQLITE_CONSTRAINT_FOREIGNKEY, + message: "FOREIGN KEY constraint failed") } // > 11. Commit the transaction started in step 2. @@ -79,7 +70,8 @@ struct Migration { } }, finally: { - // > 12. If foreign keys constraints were originally enabled, reenable them now. + // > 12. If foreign keys constraints were originally enabled, + // > reenable them now. try db.execute(sql: "PRAGMA foreign_keys = ON") }) } From 4f9878a1da3ab4ca5f83a17673b279a8c07e03a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 26 Feb 2020 13:57:49 +0100 Subject: [PATCH 08/46] Update tests for the deprecated registerMigrationWithDeferredForeignKeyCheck method --- Tests/GRDBTests/DatabaseMigratorTests.swift | 71 ++++++++++++++++++--- 1 file changed, 61 insertions(+), 10 deletions(-) diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index 95d5e8e58..155251dc7 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -141,13 +141,8 @@ class DatabaseMigratorTests : GRDBTestCase { } migrator.registerMigration("foreignKeyError") { db in try db.execute(sql: "INSERT INTO persons (name) VALUES ('Barbara')") - do { - // triggers immediate foreign key error: - try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [123, "Bobby"]) - XCTFail("Expected error") - } catch { - throw error - } + // triggers foreign key error: + try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [123, "Bobby"]) } let dbQueue = try makeDatabaseQueue() @@ -163,8 +158,6 @@ class DatabaseMigratorTests : GRDBTestCase { XCTAssert((error.resultCode == error.extendedResultCode) || error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version - XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)") - XCTAssertEqual(error.description.lowercased(), "sqlite error 19 with statement `insert into pets (masterid, name) values (?, ?)` arguments [123, \"bobby\"]: foreign key constraint failed") let names = try dbQueue.inDatabase { db in try String.fetchAll(db, sql: "SELECT name FROM persons") @@ -173,7 +166,65 @@ class DatabaseMigratorTests : GRDBTestCase { } } - func testMigrationWithoutForeignKeyChecks() throws { + func testForeignKeyViolation() throws { + #if !GRDBCUSTOMSQLITE && !GRDBCIPHER + guard #available(iOS 8.2, OSX 10.10, *) else { + return + } + #endif + var migrator = DatabaseMigrator() + migrator.registerMigration("createPersons") { db in + try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, tmp TEXT)") + try db.execute(sql: "CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT)") + try db.execute(sql: "INSERT INTO persons (name) VALUES ('Arthur')") + let personId = db.lastInsertedRowID + try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, 'Bobby')", arguments:[personId]) + } + migrator.registerMigration("removePersonTmpColumn") { db in + // Test the technique described at https://www.sqlite.org/lang_altertable.html#otheralter + try db.execute(sql: "CREATE TABLE new_persons (id INTEGER PRIMARY KEY, name TEXT)") + try db.execute(sql: "INSERT INTO new_persons SELECT id, name FROM persons") + try db.execute(sql: "DROP TABLE persons") + try db.execute(sql: "ALTER TABLE new_persons RENAME TO persons") + } + migrator.registerMigration("foreignKeyError") { db in + try db.execute(sql: "INSERT INTO persons (name) VALUES ('Barbara')") + // triggers foreign key error: + try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [123, "Bobby"]) + } + + let dbQueue = try makeDatabaseQueue() + do { + try migrator.migrate(dbQueue) + XCTFail("Expected error") + } catch let error as DatabaseError { + // Migration 1 and 2 should be committed. + // Migration 3 should not be committed. + + XCTAssert((error.resultCode == error.extendedResultCode) || error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) + XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) + XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version + + try dbQueue.inDatabase { db in + // Arthur inserted (migration 1), Barbara (migration 3) not inserted. + var rows = try Row.fetchAll(db, sql: "SELECT * FROM persons") + XCTAssertEqual(rows.count, 1) + var row = rows.first! + XCTAssertEqual(row["name"] as String, "Arthur") + + // persons table has no "tmp" column (migration 2) + XCTAssertEqual(Array(row.columnNames), ["id", "name"]) + + // Bobby inserted (migration 1), not deleted by migration 2. + rows = try Row.fetchAll(db, sql: "SELECT * FROM pets") + XCTAssertEqual(rows.count, 1) + row = rows.first! + XCTAssertEqual(row["name"] as String, "Bobby") + } + } + } + + func testMigrationWithDeferredForeignKeyChecksDeprecated() throws { #if !GRDBCUSTOMSQLITE && !GRDBCIPHER guard #available(iOS 8.2, OSX 10.10, *) else { return From e5c4fb7e30ebebdcb9bf8e461cc8035293a483f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 26 Feb 2020 13:59:04 +0100 Subject: [PATCH 09/46] Update DatabaseMigrator documentation --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 227b294bc..0c770b55d 100644 --- a/README.md +++ b/README.md @@ -4986,11 +4986,11 @@ The `eraseDatabaseOnSchemaChange` option triggers a recreation of the database i SQLite does not support many schema changes, and won't let you drop a table column with "ALTER TABLE ... DROP COLUMN ...", for example. -Yet any kind of schema change is still possible. The SQLite documentation explains in detail how to do so: https://www.sqlite.org/lang_altertable.html#otheralter. This technique requires the temporary disabling of foreign key checks, and is supported by the `registerMigrationWithDeferredForeignKeyCheck` function: +Yet any kind of schema change is still possible, by recreating tables: ```swift -// Add a NOT NULL constraint on player.name: -migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in +migrator.registerMigration("AddNotNullCheckOnName") { db in + // Add a NOT NULL constraint on player.name: try db.create(table: "new_player") { t in t.autoIncrementedPrimaryKey("id") t.column("name", .text).notNull() @@ -5001,7 +5001,7 @@ migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { } ``` -While your migration code runs with disabled foreign key checks, those are re-enabled and checked at the end of the migration, regardless of eventual errors. +> :point_up: **Note**: This technique requires SQLite 3.7.16+ (iOS 9.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ / [custom SQLite build] / [SQLCipher](#encryption)). ## Joined Queries Support From 98c4356638cc8c5094312c5a928bde75106d3458 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 26 Feb 2020 14:07:38 +0100 Subject: [PATCH 10/46] Cleanup --- GRDB/Migration/DatabaseMigrator.swift | 2 +- GRDB/Migration/Migration.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index ccfacfcf2..46532fdda 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -93,7 +93,7 @@ public struct DatabaseMigrator { /// Registers a migration. /// - /// migrator.registerMigration("createAuthors") { db in + /// migrator.registerMigrationWithDeferredForeignKeyCheck("createAuthors") { db in /// try db.create(table: "author") { t in /// t.autoIncrementedPrimaryKey("id") /// t.column("creationDate", .datetime) diff --git a/GRDB/Migration/Migration.swift b/GRDB/Migration/Migration.swift index 0673c7aca..bbe12c090 100644 --- a/GRDB/Migration/Migration.swift +++ b/GRDB/Migration/Migration.swift @@ -50,7 +50,7 @@ struct Migration { if try db .makeSelectStatement(sql: "PRAGMA foreign_key_check") .makeCursor() - .next() != nil + .isEmpty() == false { // https://www.sqlite.org/pragma.html#pragma_foreign_key_check // From f12436e55bce3d6470cc93edaa7656e07f697d76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 26 Feb 2020 14:09:24 +0100 Subject: [PATCH 11/46] CHANGELOG --- CHANGELOG.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 86f9fe9a3..df3d08659 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,9 +6,7 @@ All notable changes to this project will be documented in this file. GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library. - #### 4.x Releases @@ -63,9 +61,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [0.110.0](#01100), ... - + +**New** + +- [#709](https://github.com/groue/GRDB.swift/pull/709): Simplify DatabaseMigrator API ## 4.10.0 From bf89883ff5500ba3a8e3443a3faf771da8a8641c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 26 Feb 2020 22:26:29 +0100 Subject: [PATCH 12/46] Import SQLite C functions for SPM --- GRDB/Migration/Migration.swift | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/GRDB/Migration/Migration.swift b/GRDB/Migration/Migration.swift index bbe12c090..4efcb0590 100644 --- a/GRDB/Migration/Migration.swift +++ b/GRDB/Migration/Migration.swift @@ -1,3 +1,11 @@ +#if SWIFT_PACKAGE +import CSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + /// An internal struct that defines a migration. struct Migration { let identifier: String From 0d2ede4440170d31a7ebee165e1e3443090c488d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 27 Feb 2020 08:43:51 +0100 Subject: [PATCH 13/46] Document that migrations run with deferred foreign key checks --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 0c770b55d..768b36ece 100644 --- a/README.md +++ b/README.md @@ -4921,6 +4921,8 @@ migrator.registerMigration("v2") { db in **Each migration runs in a separate transaction.** Should one throw an error, its transaction is rollbacked, subsequent migrations do not run, and the error is eventually thrown by `migrator.migrate(dbQueue)`. +**Migrations run with deferred foreign key checks,** starting SQLite 3.7.16+ (iOS 9.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ / [custom SQLite build] / [SQLCipher](#encryption)). This means that eventual foreign key violations are only checked at the end of the migration (and they make the migration fail). + **The memory of applied migrations is stored in the database itself** (in a reserved table). You migrate the database up to the latest version with the `migrate(_:)` method: From ba02ba4237260eb551a1cdd0bb7bae03dc4a620a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 27 Feb 2020 19:25:55 +0100 Subject: [PATCH 14/46] CHANGELOG --- CHANGELOG.md | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c7f1f581e..672ce1c4f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -63,11 +63,37 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## Next Release -**New** +### New - [#706](https://github.com/groue/GRDB.swift/pull/706): Enhance SQLLiteral and SQL interpolation again + +### Breaking Change + - [#709](https://github.com/groue/GRDB.swift/pull/709): Simplify DatabaseMigrator API +Database migrations have a new behavior which is a breaking change. However, it is very unlikely to impact your application. + +In previous versions of GRDB, a foreign key violation would immediately prevent a migration from successfully complete. Now, foreign key checks are deferred until the end of each migration. This means that some migrations will change their behavior: + +```swift +// Used to fail, now succeeds +migrator.registerMigration(...) { db in + try violateForeignKeyConstraint(db) + try fixForeignKeyConstraint(db) +} + +// The catch clause is no longer called +migrator.registerMigration(...) { db in + do { + try performChanges(db) + } catch let error as DatabaseError where error.resultCode == .SQL_CONSTRAINT { + // Handle foreign key error + } +} +``` + +If your application happens to define migrations that are impacted by this change, please open an issue so that we find a way to restore the previous behavior. + ## 4.10.0 From 2ff8c66b9e407dddc9e373d910a035302f09b3b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 27 Feb 2020 19:29:21 +0100 Subject: [PATCH 15/46] TODO --- TODO.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/TODO.md b/TODO.md index cb33110ae..fcb1f5900 100644 --- a/TODO.md +++ b/TODO.md @@ -8,6 +8,11 @@ - [ ] Test NOT TESTED methods - [ ] Cancellation of a started ValueObservation. Context: https://github.com/groue/GRDB.swift/issues/601#issuecomment-524733140 - [ ] Remove submodules +- [ ] DatabaseMigrator.unappliedMigrations(in:upTo:), DatabaseMigrator.needsMigrate(in:). Update App Group sample code, so that read-only apps check the schema. +- [ ] DatabaseMigrator should always use dbWriter.writeBarrierWithoutTransaction +- [ ] Remove EmptyDatabaseSchemaCache, it is useless +- [ ] DatabasePool.databaseSchemaIsLocked = true (should forbid schema changes, and never reset dbPool readers' caches). Or can we invalidate reader's cache automatically from the writer connection? +- [ ] Database.clearSchemaCache() is fine, but what about dbPool readers? Can we invalidate the cache for a whole pool? ## Documentation From a17669b08250b74d65ea9317ba07a05eaf60e1de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 27 Feb 2020 20:50:25 +0100 Subject: [PATCH 16/46] DatabaseMigrator.hasUnappliedMigrations --- GRDB/Migration/DatabaseMigrator.swift | 71 +++++++++++++++++++++------ 1 file changed, 55 insertions(+), 16 deletions(-) diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 46532fdda..da1c500df 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -117,8 +117,8 @@ public struct DatabaseMigrator { /// migration has not yet been applied, its block is executed in /// a transaction. /// - /// - parameter db: A DatabaseWriter (DatabaseQueue or DatabasePool) where - /// migrations should apply. + /// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool) + /// where migrations should apply. /// - throws: An eventual error thrown by the registered migration blocks. public func migrate(_ writer: DatabaseWriter) throws { guard let lastMigration = migrations.last else { @@ -131,9 +131,9 @@ public struct DatabaseMigrator { /// provided target. If a migration has not yet been applied, its block is /// executed in a transaction. /// - /// - parameter db: A DatabaseWriter (DatabaseQueue or DatabasePool) where - /// migrations should apply. - /// - targetIdentifier: The identifier of a registered migration. + /// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool) + /// where migrations should apply. + /// - parameter targetIdentifier: The identifier of a registered migration. /// - throws: An eventual error thrown by the registered migration blocks. public func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) throws { if eraseDatabaseOnSchemaChange { @@ -173,12 +173,42 @@ public struct DatabaseMigrator { } /// Returns the set of applied migration identifiers. + /// + /// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool). + /// - parameter targetIdentifier: The identifier of a registered migration. + /// - throws: An eventual database error. public func appliedMigrations(in reader: DatabaseReader) throws -> Set { return try reader.read { db in return try appliedIdentifiers(db) } } + /// Returns true if there exist unapplied migrations. + /// + /// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool). + /// - throws: An eventual database error. + public func hasUnappliedMigrations(in reader: DatabaseReader) throws -> Bool { + guard let lastMigration = migrations.last else { + return false + } + return try hasUnappliedMigrations(in: reader, upTo: lastMigration.identifier) + } + + /// Returns true if there exist unapplied migrations, up to the + /// provided target. + /// + /// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool). + /// - parameter targetIdentifier: The identifier of a registered migration. + /// - throws: An eventual database error. + public func hasUnappliedMigrations(in reader: DatabaseReader, upTo targetIdentifier: String) throws -> Bool { + return try reader.read { db in + let appliedIdentifiers = try self.appliedIdentifiers(db) + let unappliedMigrations = self.unappliedMigrations( + upTo: targetIdentifier, + appliedIdentifiers: appliedIdentifiers) + return unappliedMigrations.isEmpty == false + } + } // MARK: - Non public @@ -203,10 +233,11 @@ public struct DatabaseMigrator { return try Set(String.fetchAll(db, sql: "SELECT identifier FROM grdb_migrations")) } - private func runMigrations(_ db: Database, upTo targetIdentifier: String) throws { - var prefixMigrations: [Migration] = [] + /// Returns unapplied migration identifier, + private func unappliedMigrations(upTo targetIdentifier: String, appliedIdentifiers: Set) -> [Migration] { + var expectedMigrations: [Migration] = [] for migration in migrations { - prefixMigrations.append(migration) + expectedMigrations.append(migration) if migration.identifier == targetIdentifier { break } @@ -214,19 +245,27 @@ public struct DatabaseMigrator { // targetIdentifier must refer to a registered migration GRDBPrecondition( - prefixMigrations.last?.identifier == targetIdentifier, + expectedMigrations.last?.identifier == targetIdentifier, "undefined migration: \(String(reflecting: targetIdentifier))") - // Subsequent migration must not be applied + return expectedMigrations.filter { !appliedIdentifiers.contains($0.identifier) } + } + + private func runMigrations(_ db: Database, upTo targetIdentifier: String) throws { let appliedIdentifiers = try self.appliedIdentifiers(db) - if prefixMigrations.count < migrations.count { - let nextIdentifier = migrations[prefixMigrations.count].identifier - GRDBPrecondition( - !appliedIdentifiers.contains(nextIdentifier), - "database is already migrated beyond migration \(String(reflecting: targetIdentifier))") + + // Subsequent migration must not be applied + if let index = migrations.firstIndex(where: { $0.identifier == targetIdentifier }), + migrations[(index + 1)...].contains(where: { appliedIdentifiers.contains($0.identifier) }) + { + fatalError("database is already migrated beyond migration \(String(reflecting: targetIdentifier))") } - for migration in prefixMigrations where !appliedIdentifiers.contains(migration.identifier) { + let unappliedMigrations = self.unappliedMigrations( + upTo: targetIdentifier, + appliedIdentifiers: appliedIdentifiers) + + for migration in unappliedMigrations { try migration.run(db) } } From 692af926be148b11dc59b77ac610237626ef5409 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 27 Feb 2020 20:51:44 +0100 Subject: [PATCH 17/46] Tests for DatabaseMigrator.hasUnappliedMigrations --- Tests/GRDBTests/DatabaseMigratorTests.swift | 31 +++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index 155251dc7..1cc7960d3 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -313,6 +313,37 @@ class DatabaseMigratorTests : GRDBTestCase { try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), ["1", "2"]) } + func testHasUnappliedMigrations() throws { + var migrator = DatabaseMigrator() + migrator.registerMigration("1") { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + t.column("score", .integer) + } + } + + migrator.registerMigration("2") { db in + try db.execute(sql: "INSERT INTO player (id, name, score) VALUES (NULL, 'Arthur', 1000)") + } + + // Apply migrator + let dbQueue = try makeDatabaseQueue() + try XCTAssertTrue(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "1")) + try XCTAssertTrue(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "2")) + try XCTAssertTrue(migrator.hasUnappliedMigrations(in: dbQueue)) + + try migrator.migrate(dbQueue, upTo: "1") + try XCTAssertFalse(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "1")) + try XCTAssertTrue(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "2")) + try XCTAssertTrue(migrator.hasUnappliedMigrations(in: dbQueue)) + + try migrator.migrate(dbQueue, upTo: "2") + try XCTAssertFalse(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "1")) + try XCTAssertFalse(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "2")) + try XCTAssertFalse(migrator.hasUnappliedMigrations(in: dbQueue)) + } + func testEraseDatabaseOnSchemaChange() throws { // 1st version of the migrator var migrator1 = DatabaseMigrator() From 92e8ef9b876847609160dd2bbb33f70388bdcc71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 27 Feb 2020 21:01:56 +0100 Subject: [PATCH 18/46] More DatabaseMigrator tests --- Tests/GRDBTests/DatabaseMigratorTests.swift | 94 +++++++++++++++------ 1 file changed, 68 insertions(+), 26 deletions(-) diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index 1cc7960d3..816b2070f 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -7,6 +7,12 @@ import XCTest class DatabaseMigratorTests : GRDBTestCase { + func testEmptyMigrator() throws { + let migrator = DatabaseMigrator() + let dbQueue = try makeDatabaseQueue() + try migrator.migrate(dbQueue) + } + func testMigratorDatabaseQueue() throws { let dbQueue = try makeDatabaseQueue() @@ -290,6 +296,15 @@ class DatabaseMigratorTests : GRDBTestCase { func testAppliedMigrations() throws { var migrator = DatabaseMigrator() + + // No migration + do { + let dbQueue = try makeDatabaseQueue() + try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), []) + } + + // One migration + migrator.registerMigration("1") { db in try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") @@ -297,24 +312,41 @@ class DatabaseMigratorTests : GRDBTestCase { t.column("score", .integer) } } + + do { + let dbQueue = try makeDatabaseQueue() + try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), []) + try migrator.migrate(dbQueue, upTo: "1") + try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), ["1"]) + } + + // Two migrations migrator.registerMigration("2") { db in try db.execute(sql: "INSERT INTO player (id, name, score) VALUES (NULL, 'Arthur', 1000)") } - - // Apply migrator - let dbQueue = try makeDatabaseQueue() - try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), []) - - try migrator.migrate(dbQueue, upTo: "1") - try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), ["1"]) - - try migrator.migrate(dbQueue, upTo: "2") - try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), ["1", "2"]) + + do { + let dbQueue = try makeDatabaseQueue() + try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), []) + try migrator.migrate(dbQueue, upTo: "1") + try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), ["1"]) + try migrator.migrate(dbQueue, upTo: "2") + try XCTAssertEqual(migrator.appliedMigrations(in: dbQueue), ["1", "2"]) + } } func testHasUnappliedMigrations() throws { var migrator = DatabaseMigrator() + + // No migration + do { + let dbQueue = try makeDatabaseQueue() + try XCTAssertFalse(migrator.hasUnappliedMigrations(in: dbQueue)) + } + + // One migration + migrator.registerMigration("1") { db in try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") @@ -322,26 +354,36 @@ class DatabaseMigratorTests : GRDBTestCase { t.column("score", .integer) } } + + do { + let dbQueue = try makeDatabaseQueue() + try XCTAssertTrue(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "1")) + try XCTAssertTrue(migrator.hasUnappliedMigrations(in: dbQueue)) + try migrator.migrate(dbQueue, upTo: "1") + try XCTAssertFalse(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "1")) + try XCTAssertFalse(migrator.hasUnappliedMigrations(in: dbQueue)) + } + + // Two migrations migrator.registerMigration("2") { db in try db.execute(sql: "INSERT INTO player (id, name, score) VALUES (NULL, 'Arthur', 1000)") } - - // Apply migrator - let dbQueue = try makeDatabaseQueue() - try XCTAssertTrue(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "1")) - try XCTAssertTrue(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "2")) - try XCTAssertTrue(migrator.hasUnappliedMigrations(in: dbQueue)) - - try migrator.migrate(dbQueue, upTo: "1") - try XCTAssertFalse(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "1")) - try XCTAssertTrue(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "2")) - try XCTAssertTrue(migrator.hasUnappliedMigrations(in: dbQueue)) - - try migrator.migrate(dbQueue, upTo: "2") - try XCTAssertFalse(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "1")) - try XCTAssertFalse(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "2")) - try XCTAssertFalse(migrator.hasUnappliedMigrations(in: dbQueue)) + + do { + let dbQueue = try makeDatabaseQueue() + try XCTAssertTrue(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "1")) + try XCTAssertTrue(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "2")) + try XCTAssertTrue(migrator.hasUnappliedMigrations(in: dbQueue)) + try migrator.migrate(dbQueue, upTo: "1") + try XCTAssertFalse(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "1")) + try XCTAssertTrue(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "2")) + try XCTAssertTrue(migrator.hasUnappliedMigrations(in: dbQueue)) + try migrator.migrate(dbQueue, upTo: "2") + try XCTAssertFalse(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "1")) + try XCTAssertFalse(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "2")) + try XCTAssertFalse(migrator.hasUnappliedMigrations(in: dbQueue)) + } } func testEraseDatabaseOnSchemaChange() throws { From 0c7e14eb9ba79514da252c8bee4725ce146a86d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 27 Feb 2020 21:02:17 +0100 Subject: [PATCH 19/46] Documentation for DatabaseMigrator.hasUnappliedMigrations --- README.md | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 768b36ece..0825f5562 100644 --- a/README.md +++ b/README.md @@ -4945,7 +4945,18 @@ try migrator.migrate(dbQueue, upTo: "v1") // fatal error: database is already migrated beyond migration "v1" ``` -Check if a migration has been applied: +Check if migrations are needed: + +```swift +if try migrator.hasUnappliedMigrations(in: dbQueue) { + // Some migrations have not been applied +} +if try migrator.hasUnappliedMigrations(in: dbQueue, upTo: "v2") { + // Some migrations have not been applied until "v2" +} +``` + +Check if a specific migration has been applied: ```swift let appliedMigrations = try migrator.appliedMigrations(in: dbQueue) From 0580705b1ea1ac0b115ec9fac97296cfdf395758 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 27 Feb 2020 21:10:35 +0100 Subject: [PATCH 20/46] Enhance App Group Container documentation with database schema check --- Documentation/AppGroupContainers.md | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/Documentation/AppGroupContainers.md b/Documentation/AppGroupContainers.md index 1a0d1d176..21e11721e 100644 --- a/Documentation/AppGroupContainers.md +++ b/Documentation/AppGroupContainers.md @@ -48,8 +48,10 @@ Since several processes may open the database at the same time, protect the crea private func openDatabase(at databaseURL: URL) throws -> DatabasePool { let dbPool = try DatabasePool(path: databaseURL.path) + // Perform here other database setups, such as defining // the database schema with a DatabaseMigrator. + try migrator.migrate(dbPool) return dbPool } ``` @@ -58,7 +60,8 @@ Since several processes may open the database at the same time, protect the crea ```swift /// Returns an initialized database pool at the shared location databaseURL, - /// or nil if the database was not created yet. + /// or nil if the database is not created yet, or does not have the required + /// schema version. func openSharedReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? { let coordinator = NSFileCoordinator(filePresenter: nil) var coordinatorError: NSError? @@ -81,7 +84,14 @@ Since several processes may open the database at the same time, protect the crea do { var configuration = Configuration() configuration.readonly = true - return try DatabasePool(path: databaseURL.path, configuration: configuration) + let dbPool = try DatabasePool(path: databaseURL.path, configuration: configuration) + + // Check here if the database schema is correct, for example + // with a DatabaseMigrator. + if try migrator.hasUnappliedMigrations(in: dbPool) { + return nil + } + return dbPool } catch { if FileManager.default.fileExists(atPath: databaseURL.path) { throw error From f09e0b5ed258447322f0b5efd9d1157f5a519ee5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 27 Feb 2020 21:19:57 +0100 Subject: [PATCH 21/46] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 672ce1c4f..934602902 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,6 +66,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ### New - [#706](https://github.com/groue/GRDB.swift/pull/706): Enhance SQLLiteral and SQL interpolation again +- [#710](https://github.com/groue/GRDB.swift/pull/710): Check if a DatabaseMigrator has unapplied migrations ### Breaking Change From 91a355728155cdf3af0be4f2e7a713f79ba92e86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 28 Feb 2020 07:40:19 +0100 Subject: [PATCH 22/46] Rename hasUnappliedMigrations to isMigrated --- Documentation/AppGroupContainers.md | 5 ++-- GRDB/Migration/DatabaseMigrator.swift | 15 +++++------ README.md | 10 +++---- Tests/GRDBTests/DatabaseMigratorTests.swift | 30 ++++++++++----------- 4 files changed, 30 insertions(+), 30 deletions(-) diff --git a/Documentation/AppGroupContainers.md b/Documentation/AppGroupContainers.md index 21e11721e..e08e7877d 100644 --- a/Documentation/AppGroupContainers.md +++ b/Documentation/AppGroupContainers.md @@ -88,10 +88,11 @@ Since several processes may open the database at the same time, protect the crea // Check here if the database schema is correct, for example // with a DatabaseMigrator. - if try migrator.hasUnappliedMigrations(in: dbPool) { + if try migrator.isMigrated(in: dbPool) { + return dbPool + } else { return nil } - return dbPool } catch { if FileManager.default.fileExists(atPath: databaseURL.path) { throw error diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index da1c500df..ece0eaf79 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -183,30 +183,29 @@ public struct DatabaseMigrator { } } - /// Returns true if there exist unapplied migrations. + /// Returns true if all migrations are applied. /// /// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool). /// - throws: An eventual database error. - public func hasUnappliedMigrations(in reader: DatabaseReader) throws -> Bool { + public func isMigrated(in reader: DatabaseReader) throws -> Bool { guard let lastMigration = migrations.last else { - return false + return true } - return try hasUnappliedMigrations(in: reader, upTo: lastMigration.identifier) + return try isMigrated(in: reader, upTo: lastMigration.identifier) } - /// Returns true if there exist unapplied migrations, up to the - /// provided target. + /// Returns true if all migrations up to the provided target are applied. /// /// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool). /// - parameter targetIdentifier: The identifier of a registered migration. /// - throws: An eventual database error. - public func hasUnappliedMigrations(in reader: DatabaseReader, upTo targetIdentifier: String) throws -> Bool { + public func isMigrated(in reader: DatabaseReader, upTo targetIdentifier: String) throws -> Bool { return try reader.read { db in let appliedIdentifiers = try self.appliedIdentifiers(db) let unappliedMigrations = self.unappliedMigrations( upTo: targetIdentifier, appliedIdentifiers: appliedIdentifiers) - return unappliedMigrations.isEmpty == false + return unappliedMigrations.isEmpty } } diff --git a/README.md b/README.md index 0825f5562..215759224 100644 --- a/README.md +++ b/README.md @@ -4945,14 +4945,14 @@ try migrator.migrate(dbQueue, upTo: "v1") // fatal error: database is already migrated beyond migration "v1" ``` -Check if migrations are needed: +Check if migrations have been applied: ```swift -if try migrator.hasUnappliedMigrations(in: dbQueue) { - // Some migrations have not been applied +if try migrator.isMigrated(in: dbQueue) { + // All migrations have been applied } -if try migrator.hasUnappliedMigrations(in: dbQueue, upTo: "v2") { - // Some migrations have not been applied until "v2" +if try migrator.isMigrated(in: dbQueue, upTo: "v2") { + // All migrations have been applied until "v2" } ``` diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index 816b2070f..6a7480419 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -336,13 +336,13 @@ class DatabaseMigratorTests : GRDBTestCase { } } - func testHasUnappliedMigrations() throws { + func testIsMigrated() throws { var migrator = DatabaseMigrator() // No migration do { let dbQueue = try makeDatabaseQueue() - try XCTAssertFalse(migrator.hasUnappliedMigrations(in: dbQueue)) + try XCTAssertTrue(migrator.isMigrated(in: dbQueue)) } // One migration @@ -357,11 +357,11 @@ class DatabaseMigratorTests : GRDBTestCase { do { let dbQueue = try makeDatabaseQueue() - try XCTAssertTrue(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "1")) - try XCTAssertTrue(migrator.hasUnappliedMigrations(in: dbQueue)) + try XCTAssertFalse(migrator.isMigrated(in: dbQueue, upTo: "1")) + try XCTAssertFalse(migrator.isMigrated(in: dbQueue)) try migrator.migrate(dbQueue, upTo: "1") - try XCTAssertFalse(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "1")) - try XCTAssertFalse(migrator.hasUnappliedMigrations(in: dbQueue)) + try XCTAssertTrue(migrator.isMigrated(in: dbQueue, upTo: "1")) + try XCTAssertTrue(migrator.isMigrated(in: dbQueue)) } // Two migrations @@ -372,17 +372,17 @@ class DatabaseMigratorTests : GRDBTestCase { do { let dbQueue = try makeDatabaseQueue() - try XCTAssertTrue(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "1")) - try XCTAssertTrue(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "2")) - try XCTAssertTrue(migrator.hasUnappliedMigrations(in: dbQueue)) + try XCTAssertFalse(migrator.isMigrated(in: dbQueue, upTo: "1")) + try XCTAssertFalse(migrator.isMigrated(in: dbQueue, upTo: "2")) + try XCTAssertFalse(migrator.isMigrated(in: dbQueue)) try migrator.migrate(dbQueue, upTo: "1") - try XCTAssertFalse(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "1")) - try XCTAssertTrue(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "2")) - try XCTAssertTrue(migrator.hasUnappliedMigrations(in: dbQueue)) + try XCTAssertTrue(migrator.isMigrated(in: dbQueue, upTo: "1")) + try XCTAssertFalse(migrator.isMigrated(in: dbQueue, upTo: "2")) + try XCTAssertFalse(migrator.isMigrated(in: dbQueue)) try migrator.migrate(dbQueue, upTo: "2") - try XCTAssertFalse(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "1")) - try XCTAssertFalse(migrator.hasUnappliedMigrations(in: dbQueue, upTo: "2")) - try XCTAssertFalse(migrator.hasUnappliedMigrations(in: dbQueue)) + try XCTAssertTrue(migrator.isMigrated(in: dbQueue, upTo: "1")) + try XCTAssertTrue(migrator.isMigrated(in: dbQueue, upTo: "2")) + try XCTAssertTrue(migrator.isMigrated(in: dbQueue)) } } From fa26faa6fd63d0f1572f4d20776e5862f667c6cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 28 Feb 2020 07:42:38 +0100 Subject: [PATCH 23/46] CHANGELOG --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 934602902..95482de1b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,7 +66,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ### New - [#706](https://github.com/groue/GRDB.swift/pull/706): Enhance SQLLiteral and SQL interpolation again -- [#710](https://github.com/groue/GRDB.swift/pull/710): Check if a DatabaseMigrator has unapplied migrations +- [#710](https://github.com/groue/GRDB.swift/pull/710): Check if all migrations have been applied ### Breaking Change From d35d6fc2f843d613ce83175d32f314839deee5b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 28 Feb 2020 14:27:52 +0100 Subject: [PATCH 24/46] Rename isMigrated(in:upTo:) to isMigrated(in:beyond:), introduce lastAppliedMigration(in:) --- GRDB/Migration/DatabaseMigrator.swift | 33 ++++++- README.md | 24 ++--- Tests/GRDBTests/DatabaseMigratorTests.swift | 103 ++++++++++++++++++-- 3 files changed, 136 insertions(+), 24 deletions(-) diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index ece0eaf79..8fba1f4a4 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -179,7 +179,7 @@ public struct DatabaseMigrator { /// - throws: An eventual database error. public func appliedMigrations(in reader: DatabaseReader) throws -> Set { return try reader.read { db in - return try appliedIdentifiers(db) + return try appliedIdentifiers(db).intersection(migrations.map { $0.identifier }) } } @@ -191,15 +191,16 @@ public struct DatabaseMigrator { guard let lastMigration = migrations.last else { return true } - return try isMigrated(in: reader, upTo: lastMigration.identifier) + return try isMigrated(in: reader, beyond: lastMigration.identifier) } - /// Returns true if all migrations up to the provided target are applied. + /// Returns true if all migrations up to the provided target are applied, + /// and maybe further. /// /// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool). /// - parameter targetIdentifier: The identifier of a registered migration. /// - throws: An eventual database error. - public func isMigrated(in reader: DatabaseReader, upTo targetIdentifier: String) throws -> Bool { + public func isMigrated(in reader: DatabaseReader, beyond targetIdentifier: String) throws -> Bool { return try reader.read { db in let appliedIdentifiers = try self.appliedIdentifiers(db) let unappliedMigrations = self.unappliedMigrations( @@ -209,6 +210,30 @@ public struct DatabaseMigrator { } } + /// Returns the identifier of the last applied migration. + /// + /// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool). + /// - throws: An eventual database error. + public func lastAppliedMigration(in reader: DatabaseReader) throws -> String? { + return try reader.read { db in + let appliedIdentifiers = try self.appliedIdentifiers(db) + if appliedIdentifiers.isEmpty { + return nil + } + let lastAppliedIdentifier = migrations + .last { appliedIdentifiers.contains($0.identifier) }! + .identifier + let unappliedMigrations = self.unappliedMigrations( + upTo: lastAppliedIdentifier, + appliedIdentifiers: appliedIdentifiers) + if unappliedMigrations.isEmpty { + return lastAppliedIdentifier + } else { + return nil + } + } + } + // MARK: - Non public private mutating func registerMigration(_ migration: Migration) { diff --git a/README.md b/README.md index 215759224..d74b4eb8d 100644 --- a/README.md +++ b/README.md @@ -4931,35 +4931,35 @@ You migrate the database up to the latest version with the `migrate(_:)` method: try migrator.migrate(dbQueue) // or migrator.migrate(dbPool) ``` -To migrate a database up to a specific version, use `migrate(_:upTo:)`: +Migrate a database up to a specific version: ```swift try migrator.migrate(dbQueue, upTo: "v2") -``` -Migrations can only run forward: - -```swift +// Migrations can only run forward: try migrator.migrate(dbQueue, upTo: "v2") try migrator.migrate(dbQueue, upTo: "v1") -// fatal error: database is already migrated beyond migration "v1" +// ^ fatal error: database is already migrated beyond migration "v1" ``` -Check if migrations have been applied: +Check if consecutive migrations have been applied: ```swift if try migrator.isMigrated(in: dbQueue) { - // All migrations have been applied + // All migrations have been applied, up to the last one. } -if try migrator.isMigrated(in: dbQueue, upTo: "v2") { - // All migrations have been applied until "v2" +if try migrator.isMigrated(in: dbQueue, beyond: "v2") { + // All migrations have been applied up to "v2", and maybe further. +} +if try migrator.lastAppliedMigration(in: dbQueue) == "v2" { + // All migrations have been applied up to "v2", and no further. } ``` -Check if a specific migration has been applied: +Check which migrations have been applied: ```swift -let appliedMigrations = try migrator.appliedMigrations(in: dbQueue) +let appliedMigrations = try migrator.appliedMigrations(in: dbQueue) // Set if appliedMigrations.contains("v2") { // "v2" migration has been applied } diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index 6a7480419..9c57b3a24 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -357,10 +357,10 @@ class DatabaseMigratorTests : GRDBTestCase { do { let dbQueue = try makeDatabaseQueue() - try XCTAssertFalse(migrator.isMigrated(in: dbQueue, upTo: "1")) + try XCTAssertFalse(migrator.isMigrated(in: dbQueue, beyond: "1")) try XCTAssertFalse(migrator.isMigrated(in: dbQueue)) try migrator.migrate(dbQueue, upTo: "1") - try XCTAssertTrue(migrator.isMigrated(in: dbQueue, upTo: "1")) + try XCTAssertTrue(migrator.isMigrated(in: dbQueue, beyond: "1")) try XCTAssertTrue(migrator.isMigrated(in: dbQueue)) } @@ -372,20 +372,107 @@ class DatabaseMigratorTests : GRDBTestCase { do { let dbQueue = try makeDatabaseQueue() - try XCTAssertFalse(migrator.isMigrated(in: dbQueue, upTo: "1")) - try XCTAssertFalse(migrator.isMigrated(in: dbQueue, upTo: "2")) + try XCTAssertFalse(migrator.isMigrated(in: dbQueue, beyond: "1")) + try XCTAssertFalse(migrator.isMigrated(in: dbQueue, beyond: "2")) try XCTAssertFalse(migrator.isMigrated(in: dbQueue)) try migrator.migrate(dbQueue, upTo: "1") - try XCTAssertTrue(migrator.isMigrated(in: dbQueue, upTo: "1")) - try XCTAssertFalse(migrator.isMigrated(in: dbQueue, upTo: "2")) + try XCTAssertTrue(migrator.isMigrated(in: dbQueue, beyond: "1")) + try XCTAssertFalse(migrator.isMigrated(in: dbQueue, beyond: "2")) try XCTAssertFalse(migrator.isMigrated(in: dbQueue)) try migrator.migrate(dbQueue, upTo: "2") - try XCTAssertTrue(migrator.isMigrated(in: dbQueue, upTo: "1")) - try XCTAssertTrue(migrator.isMigrated(in: dbQueue, upTo: "2")) + try XCTAssertTrue(migrator.isMigrated(in: dbQueue, beyond: "1")) + try XCTAssertTrue(migrator.isMigrated(in: dbQueue, beyond: "2")) try XCTAssertTrue(migrator.isMigrated(in: dbQueue)) } } + func testLastAppliedMigration() throws { + var migrator = DatabaseMigrator() + + // No migration + do { + let dbQueue = try makeDatabaseQueue() + try XCTAssertNil(migrator.lastAppliedMigration(in: dbQueue)) + } + + // One migration + + migrator.registerMigration("1") { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + t.column("score", .integer) + } + } + + do { + let dbQueue = try makeDatabaseQueue() + try XCTAssertNil(migrator.lastAppliedMigration(in: dbQueue)) + try migrator.migrate(dbQueue, upTo: "1") + try XCTAssertEqual(migrator.lastAppliedMigration(in: dbQueue), "1") + } + + // Two migrations + + migrator.registerMigration("2") { db in + try db.execute(sql: "INSERT INTO player (id, name, score) VALUES (NULL, 'Arthur', 1000)") + } + + do { + let dbQueue = try makeDatabaseQueue() + try XCTAssertNil(migrator.lastAppliedMigration(in: dbQueue)) + try migrator.migrate(dbQueue, upTo: "1") + try XCTAssertEqual(migrator.lastAppliedMigration(in: dbQueue), "1") + try migrator.migrate(dbQueue, upTo: "2") + try XCTAssertEqual(migrator.lastAppliedMigration(in: dbQueue), "2") + } + } + + func testMergedMigrators() throws { + // Migrate a database + var oldMigrator = DatabaseMigrator() + oldMigrator.registerMigration("1", migrate: { _ in }) + oldMigrator.registerMigration("3", migrate: { _ in }) + + let dbQueue = try makeDatabaseQueue() + try oldMigrator.migrate(dbQueue) + + try XCTAssertEqual(oldMigrator.appliedMigrations(in: dbQueue), ["1", "3"]) + try XCTAssertTrue(oldMigrator.isMigrated(in: dbQueue)) + try XCTAssertTrue(oldMigrator.isMigrated(in: dbQueue, beyond: "1")) + try XCTAssertTrue(oldMigrator.isMigrated(in: dbQueue, beyond: "3")) + try XCTAssertEqual(oldMigrator.lastAppliedMigration(in: dbQueue), "3") + + // A source code merge inserts a migration between "1" and "3" + var newMigrator = DatabaseMigrator() + newMigrator.registerMigration("1", migrate: { _ in }) + newMigrator.registerMigration("2", migrate: { _ in }) + newMigrator.registerMigration("3", migrate: { _ in }) + + try XCTAssertEqual(newMigrator.appliedMigrations(in: dbQueue), ["1", "3"]) + try XCTAssertFalse(newMigrator.isMigrated(in: dbQueue)) + try XCTAssertTrue(newMigrator.isMigrated(in: dbQueue, beyond: "1")) + try XCTAssertFalse(newMigrator.isMigrated(in: dbQueue, beyond: "2")) + try XCTAssertFalse(newMigrator.isMigrated(in: dbQueue, beyond: "3")) + try XCTAssertNil(newMigrator.lastAppliedMigration(in: dbQueue)) + + // The new source code migrates the database + try newMigrator.migrate(dbQueue) + + try XCTAssertEqual(oldMigrator.appliedMigrations(in: dbQueue), ["1", "3"]) + try XCTAssertTrue(oldMigrator.isMigrated(in: dbQueue)) + try XCTAssertTrue(oldMigrator.isMigrated(in: dbQueue, beyond: "1")) + try XCTAssertTrue(oldMigrator.isMigrated(in: dbQueue, beyond: "3")) + try XCTAssertEqual(oldMigrator.lastAppliedMigration(in: dbQueue), "3") + + try XCTAssertEqual(newMigrator.appliedMigrations(in: dbQueue), ["1", "2", "3"]) + try XCTAssertTrue(newMigrator.isMigrated(in: dbQueue)) + try XCTAssertTrue(newMigrator.isMigrated(in: dbQueue, beyond: "1")) + try XCTAssertTrue(newMigrator.isMigrated(in: dbQueue, beyond: "2")) + try XCTAssertTrue(newMigrator.isMigrated(in: dbQueue, beyond: "3")) + try XCTAssertEqual(newMigrator.lastAppliedMigration(in: dbQueue), "3") + } + func testEraseDatabaseOnSchemaChange() throws { // 1st version of the migrator var migrator1 = DatabaseMigrator() From 32675b38f1120b6c23f9ccf1a47d4e45fdb570de Mon Sep 17 00:00:00 2001 From: Pakkito Date: Fri, 28 Feb 2020 17:00:09 +0100 Subject: [PATCH 25/46] Automatically setup memory management when UIKit is available Signed-off-by: Pakkito --- .../GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift | 4 ---- GRDB/Core/DatabasePool.swift | 17 +++++++++-------- GRDB/Core/DatabaseQueue.swift | 16 +++++++++------- README.md | 7 +------ 4 files changed, 19 insertions(+), 25 deletions(-) diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift index 672c383c0..3df9947f3 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift @@ -18,9 +18,5 @@ class AppDelegate: UIResponder, UIApplicationDelegate { .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) .appendingPathComponent("db.sqlite") dbQueue = try AppDatabase.openDatabase(atPath: databaseURL.path) - - // Be a nice iOS citizen, and don't consume too much memory - // See https://github.com/groue/GRDB.swift/blob/master/README.md#memory-management - dbQueue.setupMemoryManagement(in: application) } } diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 50653f20f..210345431 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -24,10 +24,6 @@ public final class DatabasePool: DatabaseWriter { var databaseSnapshotCount = LockedBox(value: 0) - #if os(iOS) - private weak var application: UIApplication? - #endif - // MARK: - Database Information /// The path to the database. @@ -138,6 +134,12 @@ public final class DatabasePool: DatabaseWriter { } setupSuspension() + + // Be a nice iOS citizen, and don't consume too much memory + // See https://github.com/groue/GRDB.swift/#memory-management + #if canImport(UIKit) + setupMemoryManagement() + #endif } deinit { @@ -206,7 +208,7 @@ extension DatabasePool { } - #if os(iOS) + #if canImport(UIKit) /// Listens to UIApplicationDidEnterBackgroundNotification and /// UIApplicationDidReceiveMemoryWarningNotification in order to release /// as much memory as possible. @@ -214,8 +216,7 @@ extension DatabasePool { /// - param application: The UIApplication that will start a background /// task to let the database pool release its memory when the application /// enters background. - public func setupMemoryManagement(in application: UIApplication) { - self.application = application + private func setupMemoryManagement() { let center = NotificationCenter.default center.addObserver( self, @@ -231,7 +232,7 @@ extension DatabasePool { @objc private func applicationDidEnterBackground(_ notification: NSNotification) { - guard let application = application else { + guard let application = notification.object as? UIApplication else { return } diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 99c3928a8..446c3785d 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -7,9 +7,6 @@ import UIKit /// A DatabaseQueue serializes access to an SQLite database. public final class DatabaseQueue: DatabaseWriter { private var writer: SerializedDatabase - #if os(iOS) - private weak var application: UIApplication? - #endif // MARK: - Configuration @@ -43,6 +40,12 @@ public final class DatabaseQueue: DatabaseWriter { defaultLabel: "GRDB.DatabaseQueue") setupSuspension() + + // Be a nice iOS citizen, and don't consume too much memory + // See https://github.com/groue/GRDB.swift/#memory-management + #if canImport(UIKit) + setupMemoryManagement() + #endif } /// Opens an in-memory SQLite database. @@ -83,7 +86,7 @@ extension DatabaseQueue { writer.sync { $0.releaseMemory() } } - #if os(iOS) + #if canImport(UIKit) /// Listens to UIApplicationDidEnterBackgroundNotification and /// UIApplicationDidReceiveMemoryWarningNotification in order to release /// as much memory as possible. @@ -91,8 +94,7 @@ extension DatabaseQueue { /// - param application: The UIApplication that will start a background /// task to let the database queue release its memory when the application /// enters background. - public func setupMemoryManagement(in application: UIApplication) { - self.application = application + private func setupMemoryManagement() { let center = NotificationCenter.default center.addObserver( self, @@ -108,7 +110,7 @@ extension DatabaseQueue { @objc private func applicationDidEnterBackground(_ notification: NSNotification) { - guard let application = application else { + guard let application = notification.object as? UIApplication else { return } diff --git a/README.md b/README.md index 768b36ece..4206346f6 100644 --- a/README.md +++ b/README.md @@ -7147,12 +7147,7 @@ This method blocks the current thread until all current database accesses are co **The iOS operating system likes applications that do not consume much memory.** -[Database queues](#database-queues) and [pools](#database-pools) can call the `releaseMemory` method for you, when application receives memory warnings, and when application enters background: call the `setupMemoryManagement` method after creating the queue or pool instance: - -``` -let dbQueue = try DatabaseQueue(...) -dbQueue.setupMemoryManagement(in: UIApplication.shared) -``` +[Database queues](#database-queues) and [pools](#database-pools) automatically calls the `releaseMemory` method for you, when application receives memory warnings, and when application enters background. ## Data Protection From f07735f05f189c886f6e99ff8a66b2697170398c Mon Sep 17 00:00:00 2001 From: Pakkito Date: Fri, 28 Feb 2020 17:21:53 +0100 Subject: [PATCH 26/46] Add support for xcode 11.4 Signed-off-by: Pakkito --- Makefile | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 011848f91..7d30e94d3 100644 --- a/Makefile +++ b/Makefile @@ -49,7 +49,14 @@ endif TEST_ACTIONS = clean build build-for-testing test-without-building # When adding support for an Xcode version, look for available devices with `instruments -s devices` -ifeq ($(XCODEVERSION),11.3) +ifeq ($(XCODEVERSION),11.4) + MAX_SWIFT_VERSION = 5.2 + MIN_SWIFT_VERSION = 4.2 + MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 11,OS=13.4" + MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5,OS=10.3.1" + MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV 4K,OS=13.4" + MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=10.2" +else ifeq ($(XCODEVERSION),11.3) MAX_SWIFT_VERSION = 5.1 MIN_SWIFT_VERSION = 4.2 MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 11,OS=13.3" From eb98f508915c65dbe2bc9f0dececf205964d49a3 Mon Sep 17 00:00:00 2001 From: Pakkito Date: Fri, 28 Feb 2020 18:00:16 +0100 Subject: [PATCH 27/46] Avoid breaking changes - Deprecate setupMemoryManagement(application:) - UIApplication is not available on watchOS, so instead of checking against `#if canImport(UIKit)` we use `#if os(iOS)` Signed-off-by: Pakkito --- GRDB/Core/DatabasePool.swift | 17 ++++++++++------- GRDB/Core/DatabaseQueue.swift | 17 ++++++++++------- 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 210345431..477739919 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -137,13 +137,13 @@ public final class DatabasePool: DatabaseWriter { // Be a nice iOS citizen, and don't consume too much memory // See https://github.com/groue/GRDB.swift/#memory-management - #if canImport(UIKit) - setupMemoryManagement() + #if os(iOS) + setupAutomaticMemoryManagement() #endif } deinit { - // Undo job done in setupMemoryManagement() + // Undo job done in setupAutomaticMemoryManagement() // // https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error // Explicit unregistration is required before iOS 9 and OS X 10.11. @@ -196,8 +196,6 @@ extension DatabasePool { /// /// This method blocks the current thread until all database accesses /// are completed. - /// - /// See also setupMemoryManagement(application:) public func releaseMemory() { // Release writer memory writer.sync { $0.releaseMemory() } @@ -208,7 +206,12 @@ extension DatabasePool { } - #if canImport(UIKit) + #if os(iOS) + @available(*, deprecated, message: "Memory management is now enabled by default. This deprecated method does nothing.") + public func setupMemoryManagement(in application: UIApplication) { + // No op. + } + /// Listens to UIApplicationDidEnterBackgroundNotification and /// UIApplicationDidReceiveMemoryWarningNotification in order to release /// as much memory as possible. @@ -216,7 +219,7 @@ extension DatabasePool { /// - param application: The UIApplication that will start a background /// task to let the database pool release its memory when the application /// enters background. - private func setupMemoryManagement() { + private func setupAutomaticMemoryManagement() { let center = NotificationCenter.default center.addObserver( self, diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 446c3785d..77af619e7 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -43,8 +43,8 @@ public final class DatabaseQueue: DatabaseWriter { // Be a nice iOS citizen, and don't consume too much memory // See https://github.com/groue/GRDB.swift/#memory-management - #if canImport(UIKit) - setupMemoryManagement() + #if os(iOS) + setupAutomaticMemoryManagement() #endif } @@ -65,7 +65,7 @@ public final class DatabaseQueue: DatabaseWriter { } deinit { - // Undo job done in setupMemoryManagement() + // Undo job done in setupAutomaticMemoryManagement() // // https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error // Explicit unregistration is required before iOS 9 and OS X 10.11. @@ -80,13 +80,16 @@ extension DatabaseQueue { /// Free as much memory as possible. /// /// This method blocks the current thread until all database accesses are completed. - /// - /// See also setupMemoryManagement(application:) public func releaseMemory() { writer.sync { $0.releaseMemory() } } - #if canImport(UIKit) + #if os(iOS) + @available(*, deprecated, message: "Memory management is now enabled by default. This deprecated method does nothing.") + public func setupMemoryManagement(in application: UIApplication) { + // No op. + } + /// Listens to UIApplicationDidEnterBackgroundNotification and /// UIApplicationDidReceiveMemoryWarningNotification in order to release /// as much memory as possible. @@ -94,7 +97,7 @@ extension DatabaseQueue { /// - param application: The UIApplication that will start a background /// task to let the database queue release its memory when the application /// enters background. - private func setupMemoryManagement() { + private func setupAutomaticMemoryManagement() { let center = NotificationCenter.default center.addObserver( self, From 522639282deae880cff3a8a0fccaa08602afacce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Feb 2020 14:03:12 +0100 Subject: [PATCH 28/46] Update JSONSynchronization playground --- .../Contents.swift | 52 ++-- .../Sources/SortedDifference.swift | 245 ++++++++++++++++++ .../Sources/sortedMerge.swift | 88 ------- 3 files changed, 276 insertions(+), 109 deletions(-) create mode 100644 Documentation/Playgrounds/JSONSynchronization.playground/Sources/SortedDifference.swift delete mode 100644 Documentation/Playgrounds/JSONSynchronization.playground/Sources/sortedMerge.swift diff --git a/Documentation/Playgrounds/JSONSynchronization.playground/Contents.swift b/Documentation/Playgrounds/JSONSynchronization.playground/Contents.swift index 553c57dd8..979ebeb7b 100644 --- a/Documentation/Playgrounds/JSONSynchronization.playground/Contents.swift +++ b/Documentation/Playgrounds/JSONSynchronization.playground/Contents.swift @@ -35,7 +35,7 @@ try dbQueue.inDatabase { db in } -// Define the Player `Codable` that is a `FetchableRecord` and `MutablePersistableRecord`. +// Define the Player codable record type struct Player: Codable, FetchableRecord, MutablePersistableRecord { var id: Int64 var name: String @@ -54,40 +54,33 @@ struct Player: Codable, FetchableRecord, MutablePersistableRecord { } } -extension Player { - static func orderedById() -> QueryInterfaceRequest { - return order(Columns.id) - } -} - -// This is just the container of our incoming JSON -struct PlayersToSync: Codable { - let players: [Player] -} +// Make Player identifiable +extension Player: Identifiable { } // Synchronizes the players table with a JSON payload func synchronizePlayers(with jsonString: String, in db: Database) throws { + struct SyncData: Decodable { + let players: [Player] + } let jsonData = jsonString.data(using: .utf8)! - let dataToSync = try JSONDecoder().decode(PlayersToSync.self, from: jsonData) + let syncData = try JSONDecoder().decode(SyncData.self, from: jsonData) - // Sort new players to sync by id: - let playersToSync = dataToSync.players.sorted { $0.id < $1.id } + // Sort players to sync by id: + let playersToSync = syncData.players.sorted { $0.id < $1.id } // Sort database players by id: - let players = try Player.orderedById().fetchAll(db) + let players = try Player.orderByPrimaryKey().fetchAll(db) // Now that both lists are sorted by id, we can compare them with - // the sortedMerge() function (see https://gist.github.com/groue/7e8510849ded36f7d770). + // SortedDifference (see https://github.com/groue/SortedDifference). // // We'll delete, insert or update players, depending on their presence // in either lists. - for mergeStep in sortedMerge( + for change in SortedDifference( left: players, // Database players - right: playersToSync, // PlayersToSync players (Decoded) - leftKey: { $0.id }, // The id of a database player - rightKey: { $0.id }) // The id of a PlayersToSync player + right: playersToSync) // PlayersToSync players (Decoded) { - switch mergeStep { + switch change { case .left(let player): // Delete database player without matching JSON player: try player.delete(db) @@ -140,3 +133,20 @@ do { try synchronizePlayers(with: jsonString2, in: db) } } + +do { + let jsonString3 = """ + { + "players": [ + { "id": 2, "name": "Barbara", "score": 3000}, + { "id": 3, "name": "Craig", "score": 500}, + { "id": 4, "name": "Daniel", "score": 1500}, + ] + } + """ + print("---\nImport \(jsonString3)") + try dbQueue.inDatabase { db in + // SELECT * FROM player ORDER BY id + try synchronizePlayers(with: jsonString3, in: db) + } +} diff --git a/Documentation/Playgrounds/JSONSynchronization.playground/Sources/SortedDifference.swift b/Documentation/Playgrounds/JSONSynchronization.playground/Sources/SortedDifference.swift new file mode 100644 index 000000000..78303105e --- /dev/null +++ b/Documentation/Playgrounds/JSONSynchronization.playground/Sources/SortedDifference.swift @@ -0,0 +1,245 @@ +// Copyright (C) 2019 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. + +/// Given two sequences (left and right), this sequence tells whether elements +/// are only found on the left, on the right, or on both sides. +public struct SortedDifference: Sequence where + LeftSequence: Sequence, + RightSequence: Sequence, + ID: Comparable +{ + private let left: LeftSequence + private let right: RightSequence + private let lID: (LeftSequence.Element) -> ID + private let rID: (RightSequence.Element) -> ID + + /// Given two sequences (left and right), returns a sequence which tells + /// whether elements are only found on the left, on the right, or on + /// both sides. + /// + /// Both input sequences do not have to share the same element type, but + /// their elements must share a common comparable id. + /// + /// For example: + /// + /// // Prints: + /// // - common(Left(id: 1), Right(id: 1)) + /// // - left(Left(id: 2)) + /// struct Left { var id: Int } + /// struct Right { var id: Int } + /// for change in SortedDifference( + /// left: [Left(id: 1), Left(id: 2)], + /// identifiedBy: { $0.id }, + /// right: [Right(id: 1)], + /// identifiedBy: { $0.id }) + /// { + /// print(change) + /// } + /// + /// - precondition: Both input sequences must be sorted by id. + /// - precondition: Ids must be unique in each sequences. + /// - parameters: + /// - left: The left sequence. + /// - right: The right sequence. + /// - leftID: A function that returns the id of a left element. + /// - rightID: A function that returns the id of a right element. + public init( + left: LeftSequence, + identifiedBy leftID: @escaping (LeftSequence.Element) -> ID, + right: RightSequence, + identifiedBy rightID: @escaping (RightSequence.Element) -> ID) + { + self.left = left + self.right = right + self.lID = leftID + self.rID = rightID + } + + public func makeIterator() -> Iterator { + Iterator( + lIterator: left.makeIterator(), + rIterator: right.makeIterator(), + lID: lID, + rID: rID) + } + + public struct Iterator: IteratorProtocol { + private var lIterator: LeftSequence.Iterator + private var rIterator: RightSequence.Iterator + private var lOpt: LeftSequence.Element? + private var rOpt: RightSequence.Element? + private let lID: (LeftSequence.Element) -> ID + private let rID: (RightSequence.Element) -> ID + + init( + lIterator: LeftSequence.Iterator, + rIterator: RightSequence.Iterator, + lID: @escaping (LeftSequence.Element) -> ID, + rID: @escaping (RightSequence.Element) -> ID) + { + self.lIterator = lIterator + self.rIterator = rIterator + self.lID = lID + self.rID = rID + self.lOpt = self.lIterator.next() + self.rOpt = self.rIterator.next() + } + + public mutating func next() -> SortedDifferenceChange? { + switch (lOpt, rOpt) { + case let (lElem?, rElem?): + let (lID, rID) = (self.lID(lElem), self.rID(rElem)) + if lID > rID { + rOpt = rIterator.next() + return .right(rElem) + } else if lID == rID { + (lOpt, rOpt) = (lIterator.next(), rIterator.next()) + return .common(lElem, rElem) + } else { + lOpt = lIterator.next() + return .left(lElem) + } + case let (nil, rElem?): + rOpt = rIterator.next() + return .right(rElem) + case let (lElem?, nil): + lOpt = lIterator.next() + return .left(lElem) + case (nil, nil): + return nil + } + } + } +} + +@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) +extension SortedDifference where + LeftSequence.Element: Identifiable, + RightSequence.Element: Identifiable, + LeftSequence.Element.ID == ID, + RightSequence.Element.ID == ID +{ + /// Given two sequences (left and right), returns a sequence which tells + /// whether elements are only found on the left, on the right, or on + /// both sides. + /// + /// Both input sequences do not have to share the same element type, but + /// their elements must share a common comparable id. + /// + /// For example: + /// + /// // Prints: + /// // - common(Left(id: 1), Right(id: 1)) + /// // - left(Left(id: 2)) + /// struct Left: Identifiable { var id: Int } + /// struct Right: Identifiable { var id: Int } + /// for change in SortedDifference( + /// left: [Left(id: 1), Left(id: 2)], + /// right: [Right(id: 1)]) + /// { + /// print(change) + /// } + /// + /// - precondition: Both input sequences must be sorted by id. + /// - precondition: Ids must be unique in each sequences. + /// - parameters: + /// - left: The left sequence. + /// - right: The right sequence. + public init(left: LeftSequence, right: RightSequence) { + self.init( + left: left, + identifiedBy: { $0.id }, + right: right, + identifiedBy: { $0.id }) + } +} + +extension SortedDifference where + LeftSequence.Element: Comparable, + RightSequence.Element == LeftSequence.Element, + LeftSequence.Element == ID +{ + /// Given two sequences (left and right), this sequence tells whether + /// elements are only found on the left, on the right, or on both sides. + /// + /// For example: + /// + /// // Prints: + /// // - common(1, 1) + /// // - left(2) + /// for change in SortedDifference(left: [1, 2], right: [1]) { + /// print(change) + /// } + /// + /// - precondition: Both input sequences must be sorted. + /// - precondition: Both input sequences must contain unique elements. + /// - parameters: + /// - left: The left sequence. + /// - right: The right sequence. + public init(left: LeftSequence, right: RightSequence) { + self.init( + left: left, + identifiedBy: { $0 }, + right: right, + identifiedBy: { $0 }) + } +} + +/// An element of the SortedDifference sequence. +public enum SortedDifferenceChange { + /// An element only found in the left sequence + case left(Left) + /// An element only found in the right sequence + case right(Right) + /// Left and right elements share a common id + case common(Left, Right) +} + +extension SortedDifferenceChange: CustomStringConvertible { + public var description: String { + switch self { + case let .left(lhs): + return "left(\(String(describing: lhs)))" + case let .right(rhs): + return "right(\(String(describing: rhs)))" + case let .common(lhs, rhs): + return "common(\(String(describing: lhs)), \(String(describing: rhs)))" + } + } +} + +extension SortedDifferenceChange: CustomDebugStringConvertible { + public var debugDescription: String { + switch self { + case let .left(lhs): + return "left(\(String(reflecting: lhs)))" + case let .right(rhs): + return "right(\(String(reflecting: rhs)))" + case let .common(lhs, rhs): + return "common(\(String(reflecting: lhs)), \(String(reflecting: rhs)))" + } + } +} + +extension SortedDifferenceChange: Equatable where + Left: Equatable, + Right: Equatable +{ } diff --git a/Documentation/Playgrounds/JSONSynchronization.playground/Sources/sortedMerge.swift b/Documentation/Playgrounds/JSONSynchronization.playground/Sources/sortedMerge.swift deleted file mode 100644 index 3ba6899f7..000000000 --- a/Documentation/Playgrounds/JSONSynchronization.playground/Sources/sortedMerge.swift +++ /dev/null @@ -1,88 +0,0 @@ -/// Given two sorted sequences (left and right), this function emits "merge steps" -/// which tell whether elements are only found on the left, on the right, or on -/// both sides. -/// -/// Both sequences do not have to share the same element type. Yet elements must -/// share a common comparable *key*. -/// -/// Both sequences must be sorted by this key. -/// -/// Keys must be unique in both sequences. -/// -/// The example below compare two sequences sorted by integer representation, -/// and prints: -/// -/// - Left: 1 -/// - Common: 2, 2 -/// - Common: 3, 3 -/// - Right: 4 -/// -/// for mergeStep in sortedMerge( -/// left: [1,2,3], -/// right: ["2", "3", "4"], -/// leftKey: { $0 }, -/// rightKey: { Int($0)! }) -/// { -/// switch mergeStep { -/// case .left(let left): -/// print("- Left: \(left)") -/// case .right(let right): -/// print("- Right: \(right)") -/// case .common(let left, let right): -/// print("- Common: \(left), \(right)") -/// } -/// } -/// -/// - parameters: -/// - left: The left sequence. -/// - right: The right sequence. -/// - leftKey: A function that returns the key of a left element. -/// - rightKey: A function that returns the key of a right element. -/// - returns: A sequence of MergeStep -public func sortedMerge( - left lSeq: LeftSequence, - right rSeq: RightSequence, - leftKey: @escaping (LeftSequence.Element) -> Key, - rightKey: @escaping (RightSequence.Element) -> Key) -> AnySequence> -{ - return AnySequence { () -> AnyIterator> in - var (lGen, rGen) = (lSeq.makeIterator(), rSeq.makeIterator()) - var (lOpt, rOpt) = (lGen.next(), rGen.next()) - return AnyIterator { - switch (lOpt, rOpt) { - case (let lElem?, let rElem?): - let (lKey, rKey) = (leftKey(lElem), rightKey(rElem)) - if lKey > rKey { - rOpt = rGen.next() - return .right(rElem) - } else if lKey == rKey { - (lOpt, rOpt) = (lGen.next(), rGen.next()) - return .common(lElem, rElem) - } else { - lOpt = lGen.next() - return .left(lElem) - } - case (nil, let rElem?): - rOpt = rGen.next() - return .right(rElem) - case (let lElem?, nil): - lOpt = lGen.next() - return .left(lElem) - case (nil, nil): - return nil - } - } - } -} - -/** - Support for sortedMerge() - */ -public enum MergeStep { - /// An element only found in the left sequence: - case left(LeftElement) - /// An element only found in the right sequence: - case right(RightElement) - /// Left and right elements share a common key: - case common(LeftElement, RightElement) -} From a7d02b90a5659cc84c8ff9efa87951bafbc82841 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Feb 2020 14:09:29 +0100 Subject: [PATCH 29/46] Update license year --- Documentation/AssociationsBasics.md | 2 +- .../Sources/SortedDifference.swift | 2 +- GRDB/Utils/Inflections+English.swift | 2 +- LICENSE | 2 +- Support/Info.plist | 2 +- Tests/CustomSQLite/CustomSQLite/Info.plist | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 5f28de852..f95ce9c3b 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -2380,7 +2380,7 @@ This documentation owns a lot to the [Active Record Associations](http://guides. **GRDB** -Copyright (C) 2019 Gwendal Roué +Copyright (C) 2015-2020 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: diff --git a/Documentation/Playgrounds/JSONSynchronization.playground/Sources/SortedDifference.swift b/Documentation/Playgrounds/JSONSynchronization.playground/Sources/SortedDifference.swift index 78303105e..144b4cb64 100644 --- a/Documentation/Playgrounds/JSONSynchronization.playground/Sources/SortedDifference.swift +++ b/Documentation/Playgrounds/JSONSynchronization.playground/Sources/SortedDifference.swift @@ -1,4 +1,4 @@ -// Copyright (C) 2019 Gwendal Roué +// Copyright (C) 2020 Gwendal Roué // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the diff --git a/GRDB/Utils/Inflections+English.swift b/GRDB/Utils/Inflections+English.swift index 1d570786d..815d659db 100644 --- a/GRDB/Utils/Inflections+English.swift +++ b/GRDB/Utils/Inflections+English.swift @@ -1,4 +1,4 @@ -// Copyright (C) 2019 Gwendal Roué +// Copyright (C) 2015-2020 Gwendal Roué // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the diff --git a/LICENSE b/LICENSE index bd480b04b..8318870b1 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (C) 2019 Gwendal Roué +Copyright (C) 2015-2020 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: diff --git a/Support/Info.plist b/Support/Info.plist index 6557e2d90..89d702b82 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -21,7 +21,7 @@ CFBundleVersion $(CURRENT_PROJECT_VERSION) NSHumanReadableCopyright - Copyright © 2015-2019 Gwendal Roué. + Copyright © 2015-2020 Gwendal Roué. NSPrincipalClass diff --git a/Tests/CustomSQLite/CustomSQLite/Info.plist b/Tests/CustomSQLite/CustomSQLite/Info.plist index 6f85d07ad..efe118221 100644 --- a/Tests/CustomSQLite/CustomSQLite/Info.plist +++ b/Tests/CustomSQLite/CustomSQLite/Info.plist @@ -23,7 +23,7 @@ LSMinimumSystemVersion $(MACOSX_DEPLOYMENT_TARGET) NSHumanReadableCopyright - Copyright © 2019 Gwendal Roué. All rights reserved. + Copyright © 2015-2020 Gwendal Roué. All rights reserved. NSMainStoryboardFile Main NSPrincipalClass From 9ed8cb3eff624b1c50b0562cc16b52b26977dc57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Feb 2020 14:30:05 +0100 Subject: [PATCH 30/46] Fix Swiftlint warnings --- GRDB/Core/DatabasePool.swift | 1 + GRDB/Core/DatabaseQueue.swift | 1 + 2 files changed, 2 insertions(+) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 477739919..f4aa43b34 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -207,6 +207,7 @@ extension DatabasePool { #if os(iOS) + // swiftlint:disable:next line_length @available(*, deprecated, message: "Memory management is now enabled by default. This deprecated method does nothing.") public func setupMemoryManagement(in application: UIApplication) { // No op. diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 77af619e7..12dd4a1d9 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -85,6 +85,7 @@ extension DatabaseQueue { } #if os(iOS) + // swiftlint:disable:next line_length @available(*, deprecated, message: "Memory management is now enabled by default. This deprecated method does nothing.") public func setupMemoryManagement(in application: UIApplication) { // No op. From 7b29156664a6c9c6d04f093393dd1ce8efd0ec4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Feb 2020 14:33:02 +0100 Subject: [PATCH 31/46] Fix typo and improve wording --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4206346f6..b32c4cb0f 100644 --- a/README.md +++ b/README.md @@ -7147,7 +7147,7 @@ This method blocks the current thread until all current database accesses are co **The iOS operating system likes applications that do not consume much memory.** -[Database queues](#database-queues) and [pools](#database-pools) automatically calls the `releaseMemory` method for you, when application receives memory warnings, and when application enters background. +[Database queues](#database-queues) and [pools](#database-pools) automatically call the `releaseMemory` method when the application receives a memory warning, and when the application enters background. ## Data Protection From c534193f5c3f036e45750e74b272e5000b1b03c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Feb 2020 14:36:07 +0100 Subject: [PATCH 32/46] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 672ce1c4f..47ab87c43 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,6 +66,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ### New - [#706](https://github.com/groue/GRDB.swift/pull/706): Enhance SQLLiteral and SQL interpolation again +- [#712](https://github.com/groue/GRDB.swift/pull/712) by [@pakko972](https://github.com/pakko972): Automatic iOS memory management ### Breaking Change From c2c587752cc65b231b27e206b844754942e4bf37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Feb 2020 14:41:46 +0100 Subject: [PATCH 33/46] Disable flaky testBusyModeTimeoutTooShort It just ruins Travis builds :-( --- .../DatabaseConfigurationTests.swift | 97 ++++++++++--------- 1 file changed, 49 insertions(+), 48 deletions(-) diff --git a/Tests/GRDBTests/DatabaseConfigurationTests.swift b/Tests/GRDBTests/DatabaseConfigurationTests.swift index 38fcd0c4d..896d81323 100644 --- a/Tests/GRDBTests/DatabaseConfigurationTests.swift +++ b/Tests/GRDBTests/DatabaseConfigurationTests.swift @@ -208,54 +208,55 @@ class DatabaseConfigurationTests: GRDBTestCase { _ = group.wait(timeout: .distantFuture) } - func testBusyModeTimeoutTooShort() throws { - let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite") - #if GRDBCIPHER_USE_ENCRYPTION - // Work around SQLCipher bug when two connections are open to the - // same empty database: make sure the database is not empty before - // running this test - try dbQueue1.inDatabase { db in - try db.execute(sql: "CREATE TABLE SQLCipherWorkAround (foo INTEGER)") - } - #endif - - var configuration2 = dbQueue1.configuration - configuration2.busyMode = .timeout(0.1) - let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite", configuration: configuration2) - - let s1 = DispatchSemaphore(value: 0) - let s2 = DispatchSemaphore(value: 0) - let queue = DispatchQueue.global(priority: .default) - let group = DispatchGroup() - - queue.async(group: group) { - do { - try dbQueue1.inTransaction(.exclusive) { db in - s2.signal() - queue.asyncAfter(deadline: .now() + 1) { - s1.signal() - } - _ = s1.wait(timeout: .distantFuture) - return .commit - } - } catch { - XCTFail("\(error)") - } - } - - queue.async(group: group) { - do { - _ = s2.wait(timeout: .distantFuture) - try dbQueue2.inTransaction(.exclusive) { db in return .commit } - XCTFail("Expected error") - } catch let error as DatabaseError where error.resultCode == .SQLITE_BUSY { - } catch { - XCTFail("\(error)") - } - } - - _ = group.wait(timeout: .distantFuture) - } + // TODO: fix flaky test +// func testBusyModeTimeoutTooShort() throws { +// let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite") +// #if GRDBCIPHER_USE_ENCRYPTION +// // Work around SQLCipher bug when two connections are open to the +// // same empty database: make sure the database is not empty before +// // running this test +// try dbQueue1.inDatabase { db in +// try db.execute(sql: "CREATE TABLE SQLCipherWorkAround (foo INTEGER)") +// } +// #endif +// +// var configuration2 = dbQueue1.configuration +// configuration2.busyMode = .timeout(0.1) +// let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite", configuration: configuration2) +// +// let s1 = DispatchSemaphore(value: 0) +// let s2 = DispatchSemaphore(value: 0) +// let queue = DispatchQueue.global(priority: .default) +// let group = DispatchGroup() +// +// queue.async(group: group) { +// do { +// try dbQueue1.inTransaction(.exclusive) { db in +// s2.signal() +// queue.asyncAfter(deadline: .now() + 1) { +// s1.signal() +// } +// _ = s1.wait(timeout: .distantFuture) +// return .commit +// } +// } catch { +// XCTFail("\(error)") +// } +// } +// +// queue.async(group: group) { +// do { +// _ = s2.wait(timeout: .distantFuture) +// try dbQueue2.inTransaction(.exclusive) { db in return .commit } +// XCTFail("Expected error") +// } catch let error as DatabaseError where error.resultCode == .SQLITE_BUSY { +// } catch { +// XCTFail("\(error)") +// } +// } +// +// _ = group.wait(timeout: .distantFuture) +// } // TODO: fix flaky test. It fails on Xcode 10.0, tvOS 10.0 // func testBusyModeTimeoutTooLong() throws { From b71de1559aa517f1c2c466d722b38283cf293d19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Feb 2020 14:43:17 +0100 Subject: [PATCH 34/46] Disable flaky testCachedStatementsAreNotShared See https://github.com/groue/GRDB.swift/issues/679 --- .../DatabasePoolSchemaCacheTests.swift | 77 ++++++++++--------- 1 file changed, 39 insertions(+), 38 deletions(-) diff --git a/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift b/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift index b02a5b789..4f3e588fc 100644 --- a/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift +++ b/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift @@ -83,44 +83,45 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase { } } } - - func testCachedStatementsAreNotShared() throws { - // This is a regression test. - // - // If cached statements were shared between reader connections, this - // test would crash with fatal error: Database was not used on the - // correct thread. - let dbPool = try makeDatabasePool() - try dbPool.write { db in - try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") - try db.execute(sql: "INSERT INTO items (id) VALUES (1)") - } - - // Block 1 Block 2 - // SELECT 1 FROM items WHERE id = 1 - // > - let s1 = DispatchSemaphore(value: 0) - // SELECT 1 FROM items WHERE id = 1 - - let block1 = { () in - try! dbPool.read { db in - let stmt = try! db.cachedSelectStatement(sql: "SELECT * FROM items") - XCTAssertEqual(try Int.fetchOne(stmt)!, 1) - s1.signal() - } - } - let block2 = { () in - try! dbPool.read { db in - _ = s1.wait(timeout: .distantFuture) - let stmt = try! db.cachedSelectStatement(sql: "SELECT * FROM items") - XCTAssertEqual(try Int.fetchOne(stmt)!, 1) - } - } - let blocks = [block1, block2] - DispatchQueue.concurrentPerform(iterations: blocks.count) { index in - blocks[index]() - } - } + + // TODO: fix flaky test +// func testCachedStatementsAreNotShared() throws { +// // This is a regression test. +// // +// // If cached statements were shared between reader connections, this +// // test would crash with fatal error: Database was not used on the +// // correct thread. +// let dbPool = try makeDatabasePool() +// try dbPool.write { db in +// try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") +// try db.execute(sql: "INSERT INTO items (id) VALUES (1)") +// } +// +// // Block 1 Block 2 +// // SELECT 1 FROM items WHERE id = 1 +// // > +// let s1 = DispatchSemaphore(value: 0) +// // SELECT 1 FROM items WHERE id = 1 +// +// let block1 = { () in +// try! dbPool.read { db in +// let stmt = try! db.cachedSelectStatement(sql: "SELECT * FROM items") +// XCTAssertEqual(try Int.fetchOne(stmt)!, 1) +// s1.signal() +// } +// } +// let block2 = { () in +// try! dbPool.read { db in +// _ = s1.wait(timeout: .distantFuture) +// let stmt = try! db.cachedSelectStatement(sql: "SELECT * FROM items") +// XCTAssertEqual(try Int.fetchOne(stmt)!, 1) +// } +// } +// let blocks = [block1, block2] +// DispatchQueue.concurrentPerform(iterations: blocks.count) { index in +// blocks[index]() +// } +// } func testCacheSnapshotIsolation() throws { // This test checks that the schema cache follows snapshot isolation. From e62df26a53d2b61ceca7ca9838a050d59b066631 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Feb 2020 14:44:23 +0100 Subject: [PATCH 35/46] Disable flaky testDatabasePoolReleaseMemoryClosesReaderConnections See https://github.com/groue/GRDB.swift/issues/489 --- .../DatabasePoolReleaseMemoryTests.swift | 153 +++++++++--------- 1 file changed, 77 insertions(+), 76 deletions(-) diff --git a/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift b/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift index 374686e88..90810391d 100644 --- a/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift +++ b/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift @@ -45,82 +45,83 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase { XCTAssertEqual(openConnectionCount, 0) } - func testDatabasePoolReleaseMemoryClosesReaderConnections() throws { - let countQueue = DispatchQueue(label: "GRDB") - var openConnectionCount = 0 - var totalOpenConnectionCount = 0 - - dbConfiguration.SQLiteConnectionDidOpen = { - countQueue.sync { - totalOpenConnectionCount += 1 - openConnectionCount += 1 - } - } - - dbConfiguration.SQLiteConnectionDidClose = { - countQueue.sync { - openConnectionCount -= 1 - } - } - - let dbPool = try makeDatabasePool() - try dbPool.write { db in - try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") - for _ in 0..<2 { - try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)") - } - } - - // Block 1 Block 2 Block3 - // SELECT * FROM items - // step - // > - let s1 = DispatchSemaphore(value: 0) - // SELECT * FROM items - // step - // > - let s2 = DispatchSemaphore(value: 0) - // step step - // > - let s3 = DispatchSemaphore(value: 0) - // end end releaseMemory - - let block1 = { () in - try! dbPool.read { db in - let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items") - XCTAssertTrue(try cursor.next() != nil) - s1.signal() - _ = s2.wait(timeout: .distantFuture) - XCTAssertTrue(try cursor.next() != nil) - s3.signal() - XCTAssertTrue(try cursor.next() == nil) - } - } - let block2 = { () in - _ = s1.wait(timeout: .distantFuture) - try! dbPool.read { db in - let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items") - XCTAssertTrue(try cursor.next() != nil) - s2.signal() - XCTAssertTrue(try cursor.next() != nil) - XCTAssertTrue(try cursor.next() == nil) - } - } - let block3 = { () in - _ = s3.wait(timeout: .distantFuture) - dbPool.releaseMemory() - } - let blocks = [block1, block2, block3] - DispatchQueue.concurrentPerform(iterations: blocks.count) { index in // FIXME: this crashes sometimes - blocks[index]() - } - - // Two readers, one writer - XCTAssertEqual(totalOpenConnectionCount, 3) - - // Writer is still open - XCTAssertEqual(openConnectionCount, 1) - } + // TODO: fix flaky test +// func testDatabasePoolReleaseMemoryClosesReaderConnections() throws { +// let countQueue = DispatchQueue(label: "GRDB") +// var openConnectionCount = 0 +// var totalOpenConnectionCount = 0 +// +// dbConfiguration.SQLiteConnectionDidOpen = { +// countQueue.sync { +// totalOpenConnectionCount += 1 +// openConnectionCount += 1 +// } +// } +// +// dbConfiguration.SQLiteConnectionDidClose = { +// countQueue.sync { +// openConnectionCount -= 1 +// } +// } +// +// let dbPool = try makeDatabasePool() +// try dbPool.write { db in +// try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") +// for _ in 0..<2 { +// try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)") +// } +// } +// +// // Block 1 Block 2 Block3 +// // SELECT * FROM items +// // step +// // > +// let s1 = DispatchSemaphore(value: 0) +// // SELECT * FROM items +// // step +// // > +// let s2 = DispatchSemaphore(value: 0) +// // step step +// // > +// let s3 = DispatchSemaphore(value: 0) +// // end end releaseMemory +// +// let block1 = { () in +// try! dbPool.read { db in +// let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items") +// XCTAssertTrue(try cursor.next() != nil) +// s1.signal() +// _ = s2.wait(timeout: .distantFuture) +// XCTAssertTrue(try cursor.next() != nil) +// s3.signal() +// XCTAssertTrue(try cursor.next() == nil) +// } +// } +// let block2 = { () in +// _ = s1.wait(timeout: .distantFuture) +// try! dbPool.read { db in +// let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items") +// XCTAssertTrue(try cursor.next() != nil) +// s2.signal() +// XCTAssertTrue(try cursor.next() != nil) +// XCTAssertTrue(try cursor.next() == nil) +// } +// } +// let block3 = { () in +// _ = s3.wait(timeout: .distantFuture) +// dbPool.releaseMemory() +// } +// let blocks = [block1, block2, block3] +// DispatchQueue.concurrentPerform(iterations: blocks.count) { index in // FIXME: this crashes sometimes +// blocks[index]() +// } +// +// // Two readers, one writer +// XCTAssertEqual(totalOpenConnectionCount, 3) +// +// // Writer is still open +// XCTAssertEqual(openConnectionCount, 1) +// } func testBlocksRetainConnection() throws { let countQueue = DispatchQueue(label: "GRDB") From 7af846c87f4bb4073979143f7734cbde4f5578f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Feb 2020 15:06:45 +0100 Subject: [PATCH 36/46] Rename new DatabaseMigrator methods --- Documentation/AppGroupContainers.md | 2 +- GRDB/Migration/DatabaseMigrator.swift | 12 ++-- README.md | 6 +- Tests/GRDBTests/DatabaseMigratorTests.swift | 80 ++++++++++----------- 4 files changed, 51 insertions(+), 49 deletions(-) diff --git a/Documentation/AppGroupContainers.md b/Documentation/AppGroupContainers.md index e08e7877d..1ca3683a1 100644 --- a/Documentation/AppGroupContainers.md +++ b/Documentation/AppGroupContainers.md @@ -88,7 +88,7 @@ Since several processes may open the database at the same time, protect the crea // Check here if the database schema is correct, for example // with a DatabaseMigrator. - if try migrator.isMigrated(in: dbPool) { + if try migrator.hasCompletedMigrations(in: dbPool) { return dbPool } else { return nil diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 8fba1f4a4..d7f870296 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -187,11 +187,11 @@ public struct DatabaseMigrator { /// /// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool). /// - throws: An eventual database error. - public func isMigrated(in reader: DatabaseReader) throws -> Bool { + public func hasCompletedMigrations(in reader: DatabaseReader) throws -> Bool { guard let lastMigration = migrations.last else { return true } - return try isMigrated(in: reader, beyond: lastMigration.identifier) + return try hasCompletedMigrations(in: reader, through: lastMigration.identifier) } /// Returns true if all migrations up to the provided target are applied, @@ -200,7 +200,7 @@ public struct DatabaseMigrator { /// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool). /// - parameter targetIdentifier: The identifier of a registered migration. /// - throws: An eventual database error. - public func isMigrated(in reader: DatabaseReader, beyond targetIdentifier: String) throws -> Bool { + public func hasCompletedMigrations(in reader: DatabaseReader, through targetIdentifier: String) throws -> Bool { return try reader.read { db in let appliedIdentifiers = try self.appliedIdentifiers(db) let unappliedMigrations = self.unappliedMigrations( @@ -210,11 +210,13 @@ public struct DatabaseMigrator { } } - /// Returns the identifier of the last applied migration. + /// Returns the identifier of the last migration for which all predecessors + /// have been applied. /// /// - parameter reader: A DatabaseReader (DatabaseQueue or DatabasePool). + /// - returns: An eventual migration identifier. /// - throws: An eventual database error. - public func lastAppliedMigration(in reader: DatabaseReader) throws -> String? { + public func lastCompletedMigration(in reader: DatabaseReader) throws -> String? { return try reader.read { db in let appliedIdentifiers = try self.appliedIdentifiers(db) if appliedIdentifiers.isEmpty { diff --git a/README.md b/README.md index d5fc0c5a8..1e633eb4d 100644 --- a/README.md +++ b/README.md @@ -4945,13 +4945,13 @@ try migrator.migrate(dbQueue, upTo: "v1") Check if consecutive migrations have been applied: ```swift -if try migrator.isMigrated(in: dbQueue) { +if try migrator.hasCompletedMigrations(in: dbQueue) { // All migrations have been applied, up to the last one. } -if try migrator.isMigrated(in: dbQueue, beyond: "v2") { +if try migrator.hasCompletedMigrations(in: dbQueue, through: "v2") { // All migrations have been applied up to "v2", and maybe further. } -if try migrator.lastAppliedMigration(in: dbQueue) == "v2" { +if try migrator.lastCompletedMigration(in: dbQueue) == "v2" { // All migrations have been applied up to "v2", and no further. } ``` diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index 9c57b3a24..729377b05 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -336,13 +336,13 @@ class DatabaseMigratorTests : GRDBTestCase { } } - func testIsMigrated() throws { + func testHasCompletedMigrations() throws { var migrator = DatabaseMigrator() // No migration do { let dbQueue = try makeDatabaseQueue() - try XCTAssertTrue(migrator.isMigrated(in: dbQueue)) + try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue)) } // One migration @@ -357,11 +357,11 @@ class DatabaseMigratorTests : GRDBTestCase { do { let dbQueue = try makeDatabaseQueue() - try XCTAssertFalse(migrator.isMigrated(in: dbQueue, beyond: "1")) - try XCTAssertFalse(migrator.isMigrated(in: dbQueue)) + try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue, through: "1")) + try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue)) try migrator.migrate(dbQueue, upTo: "1") - try XCTAssertTrue(migrator.isMigrated(in: dbQueue, beyond: "1")) - try XCTAssertTrue(migrator.isMigrated(in: dbQueue)) + try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue, through: "1")) + try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue)) } // Two migrations @@ -372,27 +372,27 @@ class DatabaseMigratorTests : GRDBTestCase { do { let dbQueue = try makeDatabaseQueue() - try XCTAssertFalse(migrator.isMigrated(in: dbQueue, beyond: "1")) - try XCTAssertFalse(migrator.isMigrated(in: dbQueue, beyond: "2")) - try XCTAssertFalse(migrator.isMigrated(in: dbQueue)) + try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue, through: "1")) + try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue, through: "2")) + try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue)) try migrator.migrate(dbQueue, upTo: "1") - try XCTAssertTrue(migrator.isMigrated(in: dbQueue, beyond: "1")) - try XCTAssertFalse(migrator.isMigrated(in: dbQueue, beyond: "2")) - try XCTAssertFalse(migrator.isMigrated(in: dbQueue)) + try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue, through: "1")) + try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue, through: "2")) + try XCTAssertFalse(migrator.hasCompletedMigrations(in: dbQueue)) try migrator.migrate(dbQueue, upTo: "2") - try XCTAssertTrue(migrator.isMigrated(in: dbQueue, beyond: "1")) - try XCTAssertTrue(migrator.isMigrated(in: dbQueue, beyond: "2")) - try XCTAssertTrue(migrator.isMigrated(in: dbQueue)) + try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue, through: "1")) + try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue, through: "2")) + try XCTAssertTrue(migrator.hasCompletedMigrations(in: dbQueue)) } } - func testLastAppliedMigration() throws { + func testLastCompletedMigration() throws { var migrator = DatabaseMigrator() // No migration do { let dbQueue = try makeDatabaseQueue() - try XCTAssertNil(migrator.lastAppliedMigration(in: dbQueue)) + try XCTAssertNil(migrator.lastCompletedMigration(in: dbQueue)) } // One migration @@ -407,9 +407,9 @@ class DatabaseMigratorTests : GRDBTestCase { do { let dbQueue = try makeDatabaseQueue() - try XCTAssertNil(migrator.lastAppliedMigration(in: dbQueue)) + try XCTAssertNil(migrator.lastCompletedMigration(in: dbQueue)) try migrator.migrate(dbQueue, upTo: "1") - try XCTAssertEqual(migrator.lastAppliedMigration(in: dbQueue), "1") + try XCTAssertEqual(migrator.lastCompletedMigration(in: dbQueue), "1") } // Two migrations @@ -420,11 +420,11 @@ class DatabaseMigratorTests : GRDBTestCase { do { let dbQueue = try makeDatabaseQueue() - try XCTAssertNil(migrator.lastAppliedMigration(in: dbQueue)) + try XCTAssertNil(migrator.lastCompletedMigration(in: dbQueue)) try migrator.migrate(dbQueue, upTo: "1") - try XCTAssertEqual(migrator.lastAppliedMigration(in: dbQueue), "1") + try XCTAssertEqual(migrator.lastCompletedMigration(in: dbQueue), "1") try migrator.migrate(dbQueue, upTo: "2") - try XCTAssertEqual(migrator.lastAppliedMigration(in: dbQueue), "2") + try XCTAssertEqual(migrator.lastCompletedMigration(in: dbQueue), "2") } } @@ -438,10 +438,10 @@ class DatabaseMigratorTests : GRDBTestCase { try oldMigrator.migrate(dbQueue) try XCTAssertEqual(oldMigrator.appliedMigrations(in: dbQueue), ["1", "3"]) - try XCTAssertTrue(oldMigrator.isMigrated(in: dbQueue)) - try XCTAssertTrue(oldMigrator.isMigrated(in: dbQueue, beyond: "1")) - try XCTAssertTrue(oldMigrator.isMigrated(in: dbQueue, beyond: "3")) - try XCTAssertEqual(oldMigrator.lastAppliedMigration(in: dbQueue), "3") + try XCTAssertTrue(oldMigrator.hasCompletedMigrations(in: dbQueue)) + try XCTAssertTrue(oldMigrator.hasCompletedMigrations(in: dbQueue, through: "1")) + try XCTAssertTrue(oldMigrator.hasCompletedMigrations(in: dbQueue, through: "3")) + try XCTAssertEqual(oldMigrator.lastCompletedMigration(in: dbQueue), "3") // A source code merge inserts a migration between "1" and "3" var newMigrator = DatabaseMigrator() @@ -450,27 +450,27 @@ class DatabaseMigratorTests : GRDBTestCase { newMigrator.registerMigration("3", migrate: { _ in }) try XCTAssertEqual(newMigrator.appliedMigrations(in: dbQueue), ["1", "3"]) - try XCTAssertFalse(newMigrator.isMigrated(in: dbQueue)) - try XCTAssertTrue(newMigrator.isMigrated(in: dbQueue, beyond: "1")) - try XCTAssertFalse(newMigrator.isMigrated(in: dbQueue, beyond: "2")) - try XCTAssertFalse(newMigrator.isMigrated(in: dbQueue, beyond: "3")) - try XCTAssertNil(newMigrator.lastAppliedMigration(in: dbQueue)) + try XCTAssertFalse(newMigrator.hasCompletedMigrations(in: dbQueue)) + try XCTAssertTrue(newMigrator.hasCompletedMigrations(in: dbQueue, through: "1")) + try XCTAssertFalse(newMigrator.hasCompletedMigrations(in: dbQueue, through: "2")) + try XCTAssertFalse(newMigrator.hasCompletedMigrations(in: dbQueue, through: "3")) + try XCTAssertNil(newMigrator.lastCompletedMigration(in: dbQueue)) // The new source code migrates the database try newMigrator.migrate(dbQueue) try XCTAssertEqual(oldMigrator.appliedMigrations(in: dbQueue), ["1", "3"]) - try XCTAssertTrue(oldMigrator.isMigrated(in: dbQueue)) - try XCTAssertTrue(oldMigrator.isMigrated(in: dbQueue, beyond: "1")) - try XCTAssertTrue(oldMigrator.isMigrated(in: dbQueue, beyond: "3")) - try XCTAssertEqual(oldMigrator.lastAppliedMigration(in: dbQueue), "3") + try XCTAssertTrue(oldMigrator.hasCompletedMigrations(in: dbQueue)) + try XCTAssertTrue(oldMigrator.hasCompletedMigrations(in: dbQueue, through: "1")) + try XCTAssertTrue(oldMigrator.hasCompletedMigrations(in: dbQueue, through: "3")) + try XCTAssertEqual(oldMigrator.lastCompletedMigration(in: dbQueue), "3") try XCTAssertEqual(newMigrator.appliedMigrations(in: dbQueue), ["1", "2", "3"]) - try XCTAssertTrue(newMigrator.isMigrated(in: dbQueue)) - try XCTAssertTrue(newMigrator.isMigrated(in: dbQueue, beyond: "1")) - try XCTAssertTrue(newMigrator.isMigrated(in: dbQueue, beyond: "2")) - try XCTAssertTrue(newMigrator.isMigrated(in: dbQueue, beyond: "3")) - try XCTAssertEqual(newMigrator.lastAppliedMigration(in: dbQueue), "3") + try XCTAssertTrue(newMigrator.hasCompletedMigrations(in: dbQueue)) + try XCTAssertTrue(newMigrator.hasCompletedMigrations(in: dbQueue, through: "1")) + try XCTAssertTrue(newMigrator.hasCompletedMigrations(in: dbQueue, through: "2")) + try XCTAssertTrue(newMigrator.hasCompletedMigrations(in: dbQueue, through: "3")) + try XCTAssertEqual(newMigrator.lastCompletedMigration(in: dbQueue), "3") } func testEraseDatabaseOnSchemaChange() throws { From 11f88075450552f392c255368a37eb31a466e979 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Feb 2020 16:01:45 +0100 Subject: [PATCH 37/46] Make barrierWriteWithoutTransaction a requirement of DatabaseWriter --- GRDB/Core/DatabaseQueue.swift | 14 ++++++++++++++ GRDB/Core/DatabaseWriter.swift | 16 ++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 12dd4a1d9..e00ae5ed5 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -379,6 +379,20 @@ extension DatabaseQueue { return try writer.sync(updates) } + /// Synchronously executes database updates in a protected dispatch queue, + /// outside of any transaction, and returns the result. + /// + /// Eventual concurrent database accesses are postponed until the updates + /// are completed. + /// + /// This method is *not* reentrant. + /// + /// - parameter updates: The updates to the database. + /// - throws: The error thrown by the updates. + public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { + return try writer.sync(updates) + } + /// Synchronously executes database updates in a protected dispatch queue, /// outside of any transaction, and returns the result. /// diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 9d39cd503..5d2851ff5 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -53,6 +53,17 @@ public protocol DatabaseWriter: DatabaseReader { /// - throws: The error thrown by the updates. func writeWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T + /// Synchronously executes database updates in a protected dispatch queue, + /// outside of any transaction, and returns the result. + /// + /// No concurrent write or read happens during the execution of the updates. + /// + /// This method is *not* reentrant. + /// + /// - parameter updates: The updates to the database. + /// - throws: The error thrown by the updates. + func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T + #if compiler(>=5.0) /// Asynchronously executes database updates in a protected dispatch queue, /// wrapped inside a transaction. @@ -652,6 +663,11 @@ public final class AnyDatabaseWriter: DatabaseWriter { return try base.writeWithoutTransaction(updates) } + /// :nodoc: + public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { + return try base.barrierWriteWithoutTransaction(updates) + } + #if compiler(>=5.0) /// :nodoc: public func asyncWrite( From ce0df653f46db6e50d02640b54aeb0234d213abd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Feb 2020 16:11:15 +0100 Subject: [PATCH 38/46] Expose Database.erase() --- GRDB/Core/Database.swift | 43 +++++++++++++++++-- GRDB/Core/DatabaseReader.swift | 22 ++++++---- GRDB/Core/DatabaseWriter.swift | 35 +-------------- Tests/GRDBTests/DatabasePoolBackupTests.swift | 26 +++++------ 4 files changed, 68 insertions(+), 58 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index bbe0bf3c2..0e6d18ef5 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1080,16 +1080,53 @@ public final class Database { publicStatementCache.clear() } + // MARK: - Erasing + + func erase() throws { + #if SQLITE_HAS_CODEC + // SQLCipher does not support the backup API: + // https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631 + // So we'll drop all database objects one after the other. + + // Prevent foreign keys from messing with drop table statements + let foreignKeysEnabled = try Bool.fetchOne(self, sql: "PRAGMA foreign_keys")! + if foreignKeysEnabled { + try execute(sql: "PRAGMA foreign_keys = OFF") + } + + try throwingFirstError( + execute: { + // Remove all database objects, one after the other + try inTransaction { + let sql = "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'" + while let row = try Row.fetchOne(self, sql: sql) { + let type: String = row["type"] + let name: String = row["name"] + try execute(sql: "DROP \(type) \(name.quotedDatabaseIdentifier)") + } + return .commit + } + }, + finally: { + // Restore foreign keys if needed + if foreignKeysEnabled { + try execute(sql: "PRAGMA foreign_keys = ON") + } + }) + #else + try DatabaseQueue().backup(to: self) + #endif + } + // MARK: - Backup - static func backup( - from dbFrom: Database, + func backup( to dbDest: Database, afterBackupInit: (() -> Void)? = nil, afterBackupStep: (() -> Void)? = nil) throws { - guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", dbFrom.sqliteConnection, "main") else { + guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", sqliteConnection, "main") else { throw DatabaseError(resultCode: dbDest.lastErrorCode, message: dbDest.lastErrorMessage) } guard Int(bitPattern: backup) != Int(SQLITE_ERROR) else { diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index e1564e258..4908ebf82 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -278,18 +278,22 @@ extension DatabaseReader { /// the backup. Those writes may, or may not, be reflected in the backup, /// but they won't trigger any error. public func backup(to writer: DatabaseWriter) throws { - try backup(to: writer, afterBackupInit: nil, afterBackupStep: nil) + try writer.writeWithoutTransaction { dbDest in + try backup(to: dbDest) + } } - func backup(to writer: DatabaseWriter, afterBackupInit: (() -> Void)?, afterBackupStep: (() -> Void)?) throws { + func backup( + to dbDest: Database, + afterBackupInit: (() -> Void)? = nil, + afterBackupStep: (() -> Void)? = nil) + throws + { try read { dbFrom in - try writer.writeWithoutTransaction { dbDest in - try Database.backup( - from: dbFrom, - to: dbDest, - afterBackupInit: afterBackupInit, - afterBackupStep: afterBackupStep) - } + try dbFrom.backup( + to: dbDest, + afterBackupInit: afterBackupInit, + afterBackupStep: afterBackupStep) } } } diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 5d2851ff5..d9263928e 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -291,40 +291,7 @@ extension DatabaseWriter { /// - precondition: database is not accessed concurrently during the /// execution of this method. public func erase() throws { - #if SQLITE_HAS_CODEC - // SQLCipher does not support the backup API: - // https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631 - // So we'll drop all database objects one after the other. - try writeWithoutTransaction { db in - // Prevent foreign keys from messing with drop table statements - let foreignKeysEnabled = try Bool.fetchOne(db, sql: "PRAGMA foreign_keys")! - if foreignKeysEnabled { - try db.execute(sql: "PRAGMA foreign_keys = OFF") - } - - try throwingFirstError( - execute: { - // Remove all database objects, one after the other - try db.inTransaction { - let sql = "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'" - while let row = try Row.fetchOne(db, sql: sql) { - let type: String = row["type"] - let name: String = row["name"] - try db.execute(sql: "DROP \(type) \(name.quotedDatabaseIdentifier)") - } - return .commit - } - }, - finally: { - // Restore foreign keys if needed - if foreignKeysEnabled { - try db.execute(sql: "PRAGMA foreign_keys = ON") - } - }) - } - #else - try DatabaseQueue().backup(to: self) - #endif + try writeWithoutTransaction { try $0.erase() } } // MARK: - Claiming Disk Space diff --git a/Tests/GRDBTests/DatabasePoolBackupTests.swift b/Tests/GRDBTests/DatabasePoolBackupTests.swift index 790836fc9..29acdc2e4 100644 --- a/Tests/GRDBTests/DatabasePoolBackupTests.swift +++ b/Tests/GRDBTests/DatabasePoolBackupTests.swift @@ -35,7 +35,7 @@ class DatabasePoolBackupTests: GRDBTestCase { } } - // TODO: this test is fragile: understand if somethig is wrong, or not: + // TODO: fix flaky test // @available(OSX 10.10, *) // func testConcurrentWriteDuringBackup() throws { // let source = try makeDatabasePool(filename: "source.sqlite") @@ -58,17 +58,19 @@ class DatabasePoolBackupTests: GRDBTestCase { // } // } // -// try source.backup( -// to: destination, -// afterBackupInit: { -// s1.signal() -// _ = s2.wait(timeout: .distantFuture) -// }, -// afterBackupStep: { -// try! source.write { db in -// try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)") -// } -// }) +// try destination.writeWithoutTransaction { dbDestination in +// try source.backup( +// to: dbDestination, +// afterBackupInit: { +// s1.signal() +// _ = s2.wait(timeout: .distantFuture) +// }, +// afterBackupStep: { +// try! source.write { db in +// try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)") +// } +// }) +// } // // try source.read { db in // XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 3) From e1b14d4ee50953888d57ae3b815d75058ca50dd4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Feb 2020 17:26:59 +0100 Subject: [PATCH 39/46] DatabaseMigrator uses barrierWriteWithoutTransaction This prevents concurrent reads from reading right in between two migration transactions --- GRDB/Migration/DatabaseMigrator.swift | 64 +++++++++++++-------------- 1 file changed, 32 insertions(+), 32 deletions(-) diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 46532fdda..d80c1a065 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -136,38 +136,40 @@ public struct DatabaseMigrator { /// - targetIdentifier: The identifier of a registered migration. /// - throws: An eventual error thrown by the registered migration blocks. public func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) throws { - if eraseDatabaseOnSchemaChange { - // Create a temporary witness database, on disk, just in case - // migrations would involve a lot of data. - let witness = try DatabaseQueue(path: "", configuration: writer.configuration) - - // Erase database if we detect a change in the current schema. - let (currentIdentifier, currentSchema) = try writer.writeWithoutTransaction { db -> (String?, SchemaInfo) in - try setupMigrations(db) - let identifiers = try appliedIdentifiers(db) - let currentIdentifier = migrations - .reversed() - .first { identifiers.contains($0.identifier) }? - .identifier - return try (currentIdentifier, db.schema()) - } - - if let currentIdentifier = currentIdentifier { - let witnessSchema: SchemaInfo = try witness.writeWithoutTransaction { db in - try setupMigrations(db) - try runMigrations(db, upTo: currentIdentifier) - return try db.schema() + try writer.barrierWriteWithoutTransaction { db in + if eraseDatabaseOnSchemaChange { + // Fetch information about current database state + var info: (lastAppliedIdentifier: String, schema: SchemaInfo)? + try db.inTransaction(.deferred) { + let identifiers = try appliedIdentifiers(db) + if let lastAppliedIdentifier = migrations + .last(where: { identifiers.contains($0.identifier) })? + .identifier + { + info = try (lastAppliedIdentifier: lastAppliedIdentifier, schema: db.schema()) + } + return .commit } - if currentSchema != witnessSchema { - try writer.erase() + if let info = info { + // Create a temporary witness database (on disk, just in case + // migrations would involve a lot of data). + let witness = try DatabaseQueue(path: "", configuration: writer.configuration) + + // Grab schema of migrated witness database + let witnessSchema: SchemaInfo = try witness.writeWithoutTransaction { db in + try runMigrations(db, upTo: info.lastAppliedIdentifier) + return try db.schema() + } + + // Erase database if we detect a schema change + if info.schema != witnessSchema { + try db.erase() + } } } - } - - // Migrate to target schema - try writer.writeWithoutTransaction { db in - try setupMigrations(db) + + // Migrate to target schema try runMigrations(db, upTo: targetIdentifier) } } @@ -189,10 +191,6 @@ public struct DatabaseMigrator { migrations.append(migration) } - private func setupMigrations(_ db: Database) throws { - try db.execute(sql: "CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)") - } - private func appliedIdentifiers(_ db: Database) throws -> Set { let tableExists = try Bool.fetchOne(db, sql: """ SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type='table' AND name='grdb_migrations') @@ -204,6 +202,8 @@ public struct DatabaseMigrator { } private func runMigrations(_ db: Database, upTo targetIdentifier: String) throws { + try db.execute(sql: "CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)") + var prefixMigrations: [Migration] = [] for migration in migrations { prefixMigrations.append(migration) From 50cd4418d21a8555fed08eae35387efe9b5f1719 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Feb 2020 17:32:15 +0100 Subject: [PATCH 40/46] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 47ab87c43..ad38c97fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -67,6 +67,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [#706](https://github.com/groue/GRDB.swift/pull/706): Enhance SQLLiteral and SQL interpolation again - [#712](https://github.com/groue/GRDB.swift/pull/712) by [@pakko972](https://github.com/pakko972): Automatic iOS memory management +- [#713](https://github.com/groue/GRDB.swift/pull/713): Enhance DatabaseMigrator isolation ### Breaking Change From 0e43f1b95a4eb3832898d9aed85f97310adf7c6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Mar 2020 08:58:50 +0100 Subject: [PATCH 41/46] appliedIdentifiers always filters out unknown migrations --- GRDB/Migration/DatabaseMigrator.swift | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index d7f870296..25e106e81 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -178,9 +178,7 @@ public struct DatabaseMigrator { /// - parameter targetIdentifier: The identifier of a registered migration. /// - throws: An eventual database error. public func appliedMigrations(in reader: DatabaseReader) throws -> Set { - return try reader.read { db in - return try appliedIdentifiers(db).intersection(migrations.map { $0.identifier }) - } + return try reader.read(appliedIdentifiers) } /// Returns true if all migrations are applied. @@ -257,6 +255,7 @@ public struct DatabaseMigrator { return [] } return try Set(String.fetchAll(db, sql: "SELECT identifier FROM grdb_migrations")) + .intersection(migrations.map { $0.identifier }) } /// Returns unapplied migration identifier, From ea421865aa491b78e87a05c1c7e65243c595ab4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Mar 2020 11:34:58 +0100 Subject: [PATCH 42/46] Improve barrierWriteWithoutTransaction documentation --- GRDB/Core/DatabasePool.swift | 9 ++++++--- GRDB/Core/DatabaseWriter.swift | 4 +++- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index f4aa43b34..511f812b7 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -731,9 +731,12 @@ extension DatabasePool: DatabaseReader { return try writer.sync(updates) } - /// A barrier write ensures that no database access is executed until all - /// previous accesses have completed, and the specified updates have been - /// executed. + /// Synchronously executes database updates in a protected dispatch queue, + /// outside of any transaction, and returns the result. + /// + /// Updates are guaranteed an exclusive access to the database. They wait + /// until all pending writes and reads are completed. They postpone all + /// other writes and reads until they are completed. /// /// This method is *not* reentrant. /// diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index d9263928e..d3ea94ec7 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -56,7 +56,9 @@ public protocol DatabaseWriter: DatabaseReader { /// Synchronously executes database updates in a protected dispatch queue, /// outside of any transaction, and returns the result. /// - /// No concurrent write or read happens during the execution of the updates. + /// Updates are guaranteed an exclusive access to the database. They wait + /// until all pending writes and reads are completed. They postpone all + /// other writes and reads until they are completed. /// /// This method is *not* reentrant. /// From 7c684d06c142ade6abb48b5e300fe50d70b49287 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Feb 2020 17:53:49 +0100 Subject: [PATCH 43/46] Simplify schema cache management We don't need EmptyDatabaseSchemaCache. It does not help unsafe reads to work better if concurrent writes modify the schema anyway. --- GRDB/Core/Database+Schema.swift | 7 --- GRDB/Core/DatabasePool.swift | 44 +++++++++---------- GRDB/Core/DatabaseQueue.swift | 4 +- GRDB/Core/DatabaseSchemaCache.swift | 43 +----------------- GRDB/Core/DatabaseSnapshot.swift | 2 +- .../DatabasePoolSchemaCacheTests.swift | 10 ++--- 6 files changed, 29 insertions(+), 81 deletions(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 6b69b7737..2b770dc67 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -10,13 +10,6 @@ extension Database { // MARK: - Database Schema - func withSchemaCache(_ schemaCache: DatabaseSchemaCache, _ block: () throws -> T) rethrows -> T { - var oldCache = self.schemaCache - defer { self.schemaCache = oldCache } - self.schemaCache = schemaCache - return try block() - } - /// Clears the database schema cache. /// /// You may need to clear the cache manually if the database schema is diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 511f812b7..991e2f111 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -54,7 +54,7 @@ public final class DatabasePool: DatabaseWriter { writer = try SerializedDatabase( path: path, configuration: configuration, - schemaCache: SimpleDatabaseSchemaCache(), + schemaCache: DatabaseSchemaCache(), defaultLabel: "GRDB.DatabasePool", purpose: "writer") @@ -97,7 +97,7 @@ public final class DatabasePool: DatabaseWriter { let reader = try SerializedDatabase( path: path, configuration: self.readerConfiguration, - schemaCache: SimpleDatabaseSchemaCache(), + schemaCache: DatabaseSchemaCache(), defaultLabel: "GRDB.DatabasePool", purpose: "reader.\(readerCount)") reader.sync { self.setupDatabase($0) } @@ -372,9 +372,8 @@ extension DatabasePool: DatabaseReader { // See DatabasePoolTests.testReadMethodIsolationOfBlock(). try db.inTransaction(.deferred) { // Reset the schema cache before running user code in snapshot isolation - result = try db.withSchemaCache(SimpleDatabaseSchemaCache()) { - try block(db) - } + db.clearSchemaCache() + result = try block(db) return .commit } return result! @@ -420,9 +419,8 @@ extension DatabasePool: DatabaseReader { try db.beginTransaction(.deferred) // Reset the schema cache before running user code in snapshot isolation - db.withSchemaCache(SimpleDatabaseSchemaCache()) { - block(.success(db)) - } + db.clearSchemaCache() + block(.success(db)) } catch { block(.failure(error)) } @@ -464,10 +462,9 @@ extension DatabasePool: DatabaseReader { GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.") return try readerPool.get { reader in try reader.sync { db in - // No schema cache when snapshot isolation is not established - return try db.withSchemaCache(EmptyDatabaseSchemaCache()) { - try block(db) - } + // Reset the schema cache + db.clearSchemaCache() + return try block(db) } } } @@ -505,10 +502,9 @@ extension DatabasePool: DatabaseReader { } else { return try readerPool.get { reader in try reader.sync { db in - // No schema cache when snapshot isolation is not established - return try db.withSchemaCache(EmptyDatabaseSchemaCache()) { - try block(db) - } + // Reset the schema cache + db.clearSchemaCache() + return try block(db) } } } @@ -560,11 +556,12 @@ extension DatabasePool: DatabaseReader { // Release the writer queue isolationSemaphore.signal() - // Reset the schema cache before running user code in snapshot isolation - db.schemaCache = SimpleDatabaseSchemaCache() - // Fetch and release the future - futureResult = DatabaseResult { try block(db) } + futureResult = DatabaseResult { + // Reset the schema cache before running user code in snapshot isolation + db.clearSchemaCache() + return try block(db) + } futureSemaphore.signal() } } catch { @@ -664,10 +661,9 @@ extension DatabasePool: DatabaseReader { isolationSemaphore.signal() // Reset the schema cache before running user code in snapshot isolation - db.withSchemaCache(SimpleDatabaseSchemaCache()) { - // Fetch and release the future - block(.success(db)) - } + db.clearSchemaCache() + + block(.success(db)) } } catch { isolationSemaphore.signal() diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index e00ae5ed5..0c8e82819 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -36,7 +36,7 @@ public final class DatabaseQueue: DatabaseWriter { writer = try SerializedDatabase( path: path, configuration: configuration, - schemaCache: SimpleDatabaseSchemaCache(), + schemaCache: DatabaseSchemaCache(), defaultLabel: "GRDB.DatabaseQueue") setupSuspension() @@ -60,7 +60,7 @@ public final class DatabaseQueue: DatabaseWriter { writer = try! SerializedDatabase( path: ":memory:", configuration: configuration, - schemaCache: SimpleDatabaseSchemaCache(), + schemaCache: DatabaseSchemaCache(), defaultLabel: "GRDB.DatabaseQueue") } diff --git a/GRDB/Core/DatabaseSchemaCache.swift b/GRDB/Core/DatabaseSchemaCache.swift index 4f29cef90..dd7916ec7 100644 --- a/GRDB/Core/DatabaseSchemaCache.swift +++ b/GRDB/Core/DatabaseSchemaCache.swift @@ -1,24 +1,5 @@ -/// The protocol for database schema cache. -protocol DatabaseSchemaCache { - mutating func clear() - - var schemaInfo: SchemaInfo? { get set } - - func primaryKey(_ table: String) -> PrimaryKeyInfo? - mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String) - - func columns(in table: String) -> [ColumnInfo]? - mutating func set(columns: [ColumnInfo], forTable table: String) - - func indexes(on table: String) -> [IndexInfo]? - mutating func set(indexes: [IndexInfo], forTable table: String) - - func foreignKeys(on table: String) -> [ForeignKeyInfo]? - mutating func set(foreignKeys: [ForeignKeyInfo], forTable table: String) -} - /// A thread-unsafe database schema cache -struct SimpleDatabaseSchemaCache: DatabaseSchemaCache { +struct DatabaseSchemaCache { var schemaInfo: SchemaInfo? private var primaryKeys: [String: PrimaryKeyInfo] = [:] private var columns: [String: [ColumnInfo]] = [:] @@ -65,25 +46,3 @@ struct SimpleDatabaseSchemaCache: DatabaseSchemaCache { self.foreignKeys[table] = foreignKeys } } - -/// An always empty database schema cache -struct EmptyDatabaseSchemaCache: DatabaseSchemaCache { - func clear() { } - - var schemaInfo: SchemaInfo? { - get { return nil } - set { } - } - - func primaryKey(_ table: String) -> PrimaryKeyInfo? { return nil } - func set(primaryKey: PrimaryKeyInfo, forTable table: String) { } - - func columns(in table: String) -> [ColumnInfo]? { return nil } - func set(columns: [ColumnInfo], forTable table: String) { } - - func indexes(on table: String) -> [IndexInfo]? { return nil } - func set(indexes: [IndexInfo], forTable table: String) { } - - func foreignKeys(on table: String) -> [ForeignKeyInfo]? { return nil } - func set(foreignKeys: [ForeignKeyInfo], forTable table: String) { } -} diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index df92854f9..d5427ed6c 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -22,7 +22,7 @@ public class DatabaseSnapshot: DatabaseReader { serializedDatabase = try SerializedDatabase( path: path, configuration: configuration, - schemaCache: SimpleDatabaseSchemaCache(), + schemaCache: DatabaseSchemaCache(), defaultLabel: defaultLabel, purpose: purpose) diff --git a/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift b/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift index 4f3e588fc..69d1ff40b 100644 --- a/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift +++ b/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift @@ -187,7 +187,7 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase { } } - func testUnsafeReaderHasNoDatabaseCache() throws { + func testUnsafeReaderHasDatabaseCache() throws { let dbPool = try makeDatabasePool() try dbPool.write { db in @@ -206,10 +206,10 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase { _ = try db.columns(in: "items") _ = try db.indexes(on: "items") - // Assert that a reader cache is still empty - XCTAssertTrue(db.schemaCache.primaryKey("items") == nil) - XCTAssertTrue(db.schemaCache.columns(in: "items") == nil) - XCTAssertTrue(db.schemaCache.indexes(on: "items") == nil) + // Assert that a reader cache is warmed + XCTAssertFalse(db.schemaCache.primaryKey("items") == nil) + XCTAssertFalse(db.schemaCache.columns(in: "items") == nil) + XCTAssertFalse(db.schemaCache.indexes(on: "items") == nil) } } } From 48097ba7e797a48623d15f9c9d803327725a3bed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Mar 2020 18:42:05 +0100 Subject: [PATCH 44/46] Update thank you notice --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1e633eb4d..e04df33ab 100644 --- a/README.md +++ b/README.md @@ -8196,7 +8196,7 @@ Sample Code **Thanks** - [Pierlis](http://pierlis.com), where we write great software. -- [@alextrob](https://github.com/alextrob), [@bellebethcooper](https://github.com/bellebethcooper), [@bfad](https://github.com/bfad), [@cfilipov](https://github.com/cfilipov), [@charlesmchen-signal](https://github.com/charlesmchen-signal), [@Chiliec](https://github.com/Chiliec), [@chrisballinger](https://github.com/chrisballinger), [@darrenclark](https://github.com/darrenclark), [@davidkraus](https://github.com/davidkraus), [@fpillet](http://github.com/fpillet), [@gjeck](https://github.com/gjeck), [@gusrota](https://github.com/gusrota), [@hartbit](https://github.com/hartbit), [@kdubb](https://github.com/kdubb), [@kluufger](https://github.com/kluufger), [@KyleLeneau](https://github.com/KyleLeneau), [@Marus](https://github.com/Marus), [@MaxDesiatov](https://github.com/MaxDesiatov), [@michaelkirk-signal](https://github.com/michaelkirk-signal), [@pakko972](https://github.com/pakko972), [@peter-ss](https://github.com/peter-ss), [@pierlo](https://github.com/pierlo), [@pocketpixels](https://github.com/pocketpixels), [@robcas3](https://github.com/robcas3), [@runhum](https://github.com/runhum), [@schveiguy](https://github.com/schveiguy), [@SD10](https://github.com/SD10), [@sobri909](https://github.com/sobri909), [@sroddy](https://github.com/sroddy), [@swiftlyfalling](https://github.com/swiftlyfalling), [@Timac](https://github.com/Timac), [@valexa](https://github.com/valexa), and [@zmeyc](https://github.com/zmeyc) for their contributions, help, and feedback on GRDB. +- [@alextrob](https://github.com/alextrob), [@bellebethcooper](https://github.com/bellebethcooper), [@bfad](https://github.com/bfad), [@cfilipov](https://github.com/cfilipov), [@charlesmchen-signal](https://github.com/charlesmchen-signal), [@Chiliec](https://github.com/Chiliec), [@chrisballinger](https://github.com/chrisballinger), [@darrenclark](https://github.com/darrenclark), [@davidkraus](https://github.com/davidkraus), [@fpillet](http://github.com/fpillet), [@gjeck](https://github.com/gjeck), [@gusrota](https://github.com/gusrota), [@haikusw](https://github.com/haikusw), [@hartbit](https://github.com/hartbit), [@kdubb](https://github.com/kdubb), [@kluufger](https://github.com/kluufger), [@KyleLeneau](https://github.com/KyleLeneau), [@Marus](https://github.com/Marus), [@MaxDesiatov](https://github.com/MaxDesiatov), [@michaelkirk-signal](https://github.com/michaelkirk-signal), [@pakko972](https://github.com/pakko972), [@peter-ss](https://github.com/peter-ss), [@pierlo](https://github.com/pierlo), [@pocketpixels](https://github.com/pocketpixels), [@robcas3](https://github.com/robcas3), [@runhum](https://github.com/runhum), [@schveiguy](https://github.com/schveiguy), [@SD10](https://github.com/SD10), [@sobri909](https://github.com/sobri909), [@sroddy](https://github.com/sroddy), [@swiftlyfalling](https://github.com/swiftlyfalling), [@Timac](https://github.com/Timac), [@valexa](https://github.com/valexa), and [@zmeyc](https://github.com/zmeyc) for their contributions, help, and feedback on GRDB. - [@aymerick](https://github.com/aymerick) and [@kali](https://github.com/kali) because SQL. - [ccgus/fmdb](https://github.com/ccgus/fmdb) for its excellency. From fa7ae31894d7676d66c2ac28106a490decbded66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 2 Mar 2020 07:53:25 +0100 Subject: [PATCH 45/46] TODO --- TODO.md | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/TODO.md b/TODO.md index fcb1f5900..e41d29cfa 100644 --- a/TODO.md +++ b/TODO.md @@ -8,11 +8,6 @@ - [ ] Test NOT TESTED methods - [ ] Cancellation of a started ValueObservation. Context: https://github.com/groue/GRDB.swift/issues/601#issuecomment-524733140 - [ ] Remove submodules -- [ ] DatabaseMigrator.unappliedMigrations(in:upTo:), DatabaseMigrator.needsMigrate(in:). Update App Group sample code, so that read-only apps check the schema. -- [ ] DatabaseMigrator should always use dbWriter.writeBarrierWithoutTransaction -- [ ] Remove EmptyDatabaseSchemaCache, it is useless -- [ ] DatabasePool.databaseSchemaIsLocked = true (should forbid schema changes, and never reset dbPool readers' caches). Or can we invalidate reader's cache automatically from the writer connection? -- [ ] Database.clearSchemaCache() is fine, but what about dbPool readers? Can we invalidate the cache for a whole pool? ## Documentation @@ -43,6 +38,8 @@ - [ ] FTS: prefix queries - [ ] A way to stop a ValueObservation observer without waiting for deinit - [ ] More schema alterations +- [ ] DatabasePool.databaseSchemaIsLocked = true (should forbid schema changes, and never reset dbPool readers' caches). Or can we invalidate reader's cache automatically from the writer connection? +- [ ] Database.clearSchemaCache() is fine, but what about dbPool readers? Can we invalidate the cache for a whole pool? ## Unsure if necessary From 5a7c6fb33f75be0ecad83241ed63a8a2b0a394d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 2 Mar 2020 07:59:48 +0100 Subject: [PATCH 46/46] v4.11.0 --- CHANGELOG.md | 9 +++++++++ GRDB.swift.podspec | 2 +- Makefile | 6 +++--- README.md | 42 +++++++++++++++++++++--------------------- Support/Info.plist | 2 +- 5 files changed, 35 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c25fa255f..1bf95822e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,11 +6,14 @@ All notable changes to this project will be documented in this file. GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library. + #### 4.x Releases +- `4.11.x` Releases - [4.11.0](#4110) - `4.10.x` Releases - [4.10.0](#4100) - `4.9.x` Releases - [4.9.0](#490) - `4.8.x` Releases - [4.8.0](#480) | [4.8.1](#481) @@ -61,7 +64,13 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [0.110.0](#01100), ... + + +## 4.11.0 + +Released March 2, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v4.10.0...v4.11.0) ### New diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 1b0ce9495..cef26d10a 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '4.10.0' + s.version = '4.11.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' diff --git a/Makefile b/Makefile index 7d30e94d3..b47878ecf 100644 --- a/Makefile +++ b/Makefile @@ -466,10 +466,10 @@ ifdef JAZZY --author 'Gwendal Roué' \ --author_url https://github.com/groue \ --github_url https://github.com/groue/GRDB.swift \ - --github-file-prefix https://github.com/groue/GRDB.swift/tree/v4.10.0 \ - --module-version 4.10.0 \ + --github-file-prefix https://github.com/groue/GRDB.swift/tree/v4.11.0 \ + --module-version 4.11.0 \ --module GRDB \ - --root-url http://groue.github.io/GRDB.swift/docs/4.10/ \ + --root-url http://groue.github.io/GRDB.swift/docs/4.11/ \ --output Documentation/Reference \ --podspec GRDB.swift.podspec else diff --git a/README.md b/README.md index e04df33ab..54957d9c3 100644 --- a/README.md +++ b/README.md @@ -12,14 +12,14 @@ --- -**Latest release**: February 23, 2020 • version 4.10.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 3 to GRDB 4](Documentation/GRDB3MigrationGuide.md) +**Latest release**: March 2, 2020 • version 4.11.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 3 to GRDB 4](Documentation/GRDB3MigrationGuide.md) **Requirements**: iOS 9.0+ / macOS 10.9+ / tvOS 9.0+ / watchOS 2.0+ • Swift 4.2+ / Xcode 10.0+ | Swift version | GRDB version | | ------------- | ----------------------------------------------------------- | -| **Swift 5** | **v4.10.0** | -| **Swift 4.2** | **v4.10.0** | +| **Swift 5** | **v4.11.0** | +| **Swift 4.2** | **v4.11.0** | | Swift 4.1 | [v3.7.0](https://github.com/groue/GRDB.swift/tree/v3.7.0) | | Swift 4 | [v2.10.0](https://github.com/groue/GRDB.swift/tree/v2.10.0) | | Swift 3.2 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) | @@ -263,7 +263,7 @@ Documentation #### Reference -- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/4.10/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) +- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/4.11/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) #### Getting Started @@ -478,7 +478,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/4.10/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/4.11/Structs/Configuration.html) for more details. ## Database Pools @@ -559,7 +559,7 @@ let dbPool = try DatabasePool( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/4.10/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/4.11/Structs/Configuration.html) for more details. Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information. @@ -619,7 +619,7 @@ try dbQueue.write { db in } ``` -The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.10/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. +The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.11/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. In Swift 5, you can embed query arguments right into your SQL queries, with the `literal` argument label, as in the example below. See [SQL Interpolation] for more details. @@ -820,7 +820,7 @@ Both arrays and cursors can iterate over database results. How do you choose one - **Cursors are granted with direct access to SQLite,** unlike arrays that have to take the time to copy database values. If you look after extra performance, you may prefer cursors over arrays. -- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/4.10/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: +- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/4.11/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: ```swift // Prints all Github links @@ -902,7 +902,7 @@ let rows = try Row.fetchAll(db, arguments: ["name": "Arthur"]) ``` -See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.10/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. +See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.11/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care: @@ -1185,7 +1185,7 @@ GRDB ships with built-in support for the following value types: - Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol. -Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/4.10/Structs/StatementArguments.html): +Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/4.11/Structs/StatementArguments.html): ```swift let url: URL = ... @@ -1592,7 +1592,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction } ``` -Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/4.10/Structs/Configuration.html) configuration flag: +Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/4.11/Structs/Configuration.html) configuration flag: ```swift // fatal error: A transaction has been left opened at the end of a database access @@ -1706,7 +1706,7 @@ try dbQueue.write { db in } ``` -The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.10/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). +The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.11/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). ```swift updateStatement.arguments = ["name": "Arthur", "score": 1000] @@ -1965,7 +1965,7 @@ row["consumed"] // "Hello" row["produced"] // nil ``` -Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/4.10/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters, described below. +Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/4.11/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters, described below. To see how row adapters can be used, see [Joined Queries Support](#joined-queries-support). @@ -2427,7 +2427,7 @@ try Place.fetchAll(db, sql: "SELECT ...", arguments:...) // [Place] try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place? ``` -See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.10/Structs/StatementArguments.html) for more information about the query arguments. +See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.11/Structs/StatementArguments.html) for more information about the query arguments. > :point_up: **Note**: for performance reasons, the same row argument to `init(row:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`. @@ -2808,7 +2808,7 @@ protocol EncodableRecord { } ``` -See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/4.10/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.10/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.10/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. +See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/4.11/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.11/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.11/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. > :point_up: **Note**: there is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs, and uuid strings). @@ -4197,7 +4197,7 @@ Player // SELECT * FROM player ``` -Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/4.10/Structs/StatementArguments.html): +Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/4.11/Structs/StatementArguments.html): ```swift // SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate) @@ -4812,7 +4812,7 @@ let request = Player.all() **To build custom requests**, you can use one of the built-in requests, derive requests from other requests, or create your own request type that adopts the [FetchRequest](#fetchrequest-protocol) protocol. -- [SQLRequest](http://groue.github.io/GRDB.swift/docs/4.10/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example: +- [SQLRequest](http://groue.github.io/GRDB.swift/docs/4.11/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example: ```swift extension Player { @@ -4856,7 +4856,7 @@ let request = Player.all() - The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method. -- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/4.10/Structs/AnyFetchRequest.html): a [type-erased](http://chris.eidhof.nl/post/type-erasers-in-swift/) request. +- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/4.11/Structs/AnyFetchRequest.html): a [type-erased](http://chris.eidhof.nl/post/type-erasers-in-swift/) request. ### Fetching From Custom Requests @@ -6403,7 +6403,7 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan ### DatabaseRegion -**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/4.10/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**. +**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/4.11/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**. A request knows which database modifications can impact its results. It can communicate this information to [transaction observers](#transactionobserver-protocol) by the way of a DatabaseRegion. @@ -6413,7 +6413,7 @@ DatabaseRegion fuels, for example, [ValueObservation and DatabaseRegionObservati For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table. -For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/4.10/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). +For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/4.11/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). #### The DatabaseRegionConvertible Protocol @@ -7512,7 +7512,7 @@ try snapshot2.read { db in ### DatabaseWriter and DatabaseReader Protocols -Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/4.10/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/4.10/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only. +Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/4.11/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/4.11/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only. These protocols provide a unified API that let you write generic code that targets all concurrency modes. They fuel, for example: diff --git a/Support/Info.plist b/Support/Info.plist index 89d702b82..739e62260 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 4.10.0 + 4.11.0 CFBundleSignature ???? CFBundleVersion