From e1ee2afba12ffc873665f102fb86f4ee12037616 Mon Sep 17 00:00:00 2001 From: bellebethcooper Date: Wed, 26 Jun 2019 17:24:26 +1000 Subject: [PATCH 01/91] Minor typo fix --- GRDB/Record/FetchableRecord.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 34653de2a..b72a6240d 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -440,7 +440,7 @@ public final class RecordCursor : Cursor { public enum DatabaseDateDecodingStrategy { /// The strategy that uses formatting from the Date structure. /// - /// It decodes numeric values as a nunber of seconds since Epoch + /// It decodes numeric values as a number of seconds since Epoch /// (midnight UTC on January 1st, 1970). /// /// It decodes strings in the following formats, assuming UTC time zone. From 1d47fb16be19155816368cb3c2de91d9ba7a94cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 26 Jun 2019 09:34:50 +0200 Subject: [PATCH 02/91] TODO: predicates --- TODO.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/TODO.md b/TODO.md index 60b4a6b87..e2c97bdc6 100644 --- a/TODO.md +++ b/TODO.md @@ -54,6 +54,8 @@ players.update(...) // Runs the expected UPDATE statement ``` +- [ ] Predicates, so that a filter can be evaluated both on the database, and on a record instance + Swift 4.2 - [ ] https://github.com/apple/swift-evolution/blob/master/proposals/0208-package-manager-system-library-targets.md From ff2f8bd88e8738734de388e1b409660b4c4fdd60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 28 Jun 2019 17:18:00 +0200 Subject: [PATCH 03/91] More TODO --- TODO.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/TODO.md b/TODO.md index e2c97bdc6..9d67288cf 100644 --- a/TODO.md +++ b/TODO.md @@ -55,6 +55,39 @@ ``` - [ ] Predicates, so that a filter can be evaluated both on the database, and on a record instance +- [ ] ValueObservation erasure + + ``` + // Do better than this + observation.mapReducer { _, reducer in AnyValueReducer(reducer) } + ``` +- [ ] Association: + + ```swift + let request = DeviceConfiguration.all() + .joining(optional: DeviceConfiguration.activeSubscription /* belongsTo */ + .including(all: Subscription.carCategoryRelationships)) /* hasMany */ + ``` + + The request above executes the two following SQL queries: + + ```sql + SELECT "deviceConfiguration".* + FROM "deviceConfiguration" + LEFT JOIN "subscription" ON "subscription"."uid" = "deviceConfiguration"."activeSubscriptionUID" + LIMIT 1 + + SELECT "subscriptionCarCategory".*, "subscription"."uid" AS "grdb_uid" + FROM "subscriptionCarCategory" + JOIN "subscription" ON ("subscription"."uid" = "subscriptionCarCategory"."subscriptionUID") AND ("subscription"."uid" = 2) + ``` + + - Problem 1: In the first query, the left join has no purpose. + - Problem 2: Do we generally support all queries like `joining(one.joining(one.joining(one.including(all))))` - series of nested joinings of to-one associations ending with an including(all:)? + +- [ ] ValueObservation.flatMap: + + Make it possible to build a single observation where some requests depend on the result of other requests. As long as we can't express this in a single observation, we fail the "guaranteed consistency is possible" contract. Swift 4.2 From 036e236dc01d97e0167c90bd6960c249cab5beed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 28 Jun 2019 19:01:58 +0200 Subject: [PATCH 04/91] Failing test for #561 --- .../DatabasePoolCollationTests.swift | 48 ++++++++++++++----- 1 file changed, 37 insertions(+), 11 deletions(-) diff --git a/Tests/GRDBTests/DatabasePoolCollationTests.swift b/Tests/GRDBTests/DatabasePoolCollationTests.swift index 5a53822b5..ce0551253 100644 --- a/Tests/GRDBTests/DatabasePoolCollationTests.swift +++ b/Tests/GRDBTests/DatabasePoolCollationTests.swift @@ -15,24 +15,50 @@ class DatabasePoolCollationTests: GRDBTestCase { } dbPool.add(collation: collation1) - try dbPool.write { db in - try db.execute(sql: "CREATE TABLE items (text TEXT COLLATE collation1)") - try db.execute(sql: "INSERT INTO items (text) VALUES ('a')") - try db.execute(sql: "INSERT INTO items (text) VALUES ('b')") - try db.execute(sql: "INSERT INTO items (text) VALUES ('c')") - } - try dbPool.read { db in - XCTAssertEqual(try String.fetchAll(db, sql: "SELECT text FROM items ORDER BY text"), ["a", "b", "c"]) - XCTAssertEqual(try String.fetchAll(db, sql: "SELECT text FROM items ORDER BY text COLLATE collation1"), ["a", "b", "c"]) - } - let collation2 = DatabaseCollation("collation2") { (string1, string2) in return (string1 == string2) ? .orderedSame : ((string1 < string2) ? .orderedDescending : .orderedAscending) } dbPool.add(collation: collation2) + try dbPool.write { db in + // Both collations are available in writer + try db.execute(sql: """ + CREATE TABLE items (text TEXT COLLATE collation2); + INSERT INTO items (text) VALUES ('a'); + INSERT INTO items (text) VALUES ('b'); + INSERT INTO items (text) VALUES ('c'); + """) + XCTAssertEqual(try String.fetchAll(db, sql: "SELECT text FROM items ORDER BY text"), ["c", "b", "a"]) + XCTAssertEqual(try String.fetchAll(db, sql: "SELECT text FROM items ORDER BY text COLLATE collation1"), ["a", "b", "c"]) + } + try dbPool.read { db in + // Both collations are available in reader + XCTAssertEqual(try String.fetchAll(db, sql: "SELECT text FROM items ORDER BY text"), ["c", "b", "a"]) + XCTAssertEqual(try String.fetchAll(db, sql: "SELECT text FROM items ORDER BY text COLLATE collation1"), ["a", "b", "c"]) XCTAssertEqual(try String.fetchAll(db, sql: "SELECT text FROM items ORDER BY text COLLATE collation2"), ["c", "b", "a"]) } + + dbPool.remove(collation: collation1) + + do { + // collation1 is no longer available in writer + try dbPool.write { db in + _ = try String.fetchAll(db, sql: "SELECT text FROM items ORDER BY text COLLATE collation1") + } + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ERROR) + XCTAssert(error.message!.contains("collation1")) + } + + do { + // collation1 is no longer available in reader + try dbPool.read { db in + _ = try String.fetchAll(db, sql: "SELECT text FROM items ORDER BY text COLLATE collation1") + } + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ERROR) + XCTAssert(error.message!.contains("collation1")) + } } } From 7802eb356d8c3607eda3106c34f3240663cfc860 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 28 Jun 2019 19:02:21 +0200 Subject: [PATCH 05/91] Fix failing test for #561 --- GRDB/Core/DatabaseCollation.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/Core/DatabaseCollation.swift b/GRDB/Core/DatabaseCollation.swift index 530992caa..d94780412 100644 --- a/GRDB/Core/DatabaseCollation.swift +++ b/GRDB/Core/DatabaseCollation.swift @@ -50,6 +50,6 @@ extension DatabaseCollation: Hashable { /// :nodoc: public static func == (lhs: DatabaseCollation, rhs: DatabaseCollation) -> Bool { // See https://www.sqlite.org/c3ref/create_collation.html - return sqlite3_stricmp(lhs.name, lhs.name) == 0 + return sqlite3_stricmp(lhs.name, rhs.name) == 0 } } From fbc50dd2d18915986135045189e41e8c6ec97e45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 28 Jun 2019 19:06:11 +0200 Subject: [PATCH 06/91] CHANGELOG --- CHANGELOG.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 05df3dc0e..bc267f775 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,9 +5,9 @@ All notable changes to this project will be documented in this file. GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: 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 @@ -51,9 +51,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: - [0.110.0](#01100), ... - + +- [#562](https://github.com/groue/GRDB.swift/pull/537): Fix crash when using more than one DatabaseCollation + ## 4.1.1 From 498c65a64c9af1ae77c54be5d4a7fcd2b896d742 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 28 Jun 2019 19:06:49 +0200 Subject: [PATCH 07/91] CHANGELOG --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bc267f775..6e6b4e37d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,7 +54,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: ## Next Release -- [#562](https://github.com/groue/GRDB.swift/pull/537): Fix crash when using more than one DatabaseCollation +- [#562](https://github.com/groue/GRDB.swift/pull/562): Fix crash when using more than one DatabaseCollation ## 4.1.1 From 9946880c5e790d5877fc2821f18dc76c0ed1d535 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Jun 2019 14:12:46 +0200 Subject: [PATCH 08/91] Add tests for including(optional: hasOne.including(all: hasMany)) --- .../AssociationPrefetchingSQLTests.swift | 110 ++++++++++++++++++ 1 file changed, 110 insertions(+) diff --git a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift index 9238115a7..5c7aae764 100644 --- a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift @@ -1028,4 +1028,114 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { } } } + + func testIncludingOptionalHasOneIncludingAllHasMany() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + // Plain request + do { + let request = A + .including(optional: A + .hasOne(C.self) + .including(all: C + .hasMany(D.self) + .orderByPrimaryKey()) + ) + .orderByPrimaryKey() + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + XCTAssertEqual(selectQueries, [ + """ + SELECT "a".*, "c".* \ + FROM "a" \ + LEFT JOIN "c" ON "c"."colc2" = "a"."cola1" \ + ORDER BY "a"."cola1" + """, + """ + SELECT "d".*, "c"."colc2" AS "grdb_colc2" \ + FROM "d" \ + JOIN "c" ON ("c"."colc1" = "d"."cold2") AND ("c"."colc2" IN (1, 2, 3)) \ + ORDER BY "d"."cold1" + """]) + } + + // Request with filters + do { + let request = A + .including(optional: A + .hasOne(C.self) + .filter(Column("colc1") == 9) + .including(all: C + .hasMany(D.self) + .filter(Column("cold1") == 11) + .orderByPrimaryKey() + .forKey("ds1")) + .including(all: C + .hasMany(D.self) + .filter(Column("cold1") != 11) + .orderByPrimaryKey() + .forKey("ds2")) + .forKey("c1")) + .including(optional: A + .hasOne(C.self) + .filter(Column("colc1") != 9) + .including(all: C + .hasMany(D.self) + .filter(Column("cold1") == 11) + .orderByPrimaryKey() + .forKey("ds1")) + .including(all: C + .hasMany(D.self) + .filter(Column("cold1") != 11) + .orderByPrimaryKey() + .forKey("ds2")) + .forKey("c2")) + .orderByPrimaryKey() + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + XCTAssertEqual(selectQueries, [ + """ + SELECT "a".*, "c1".*, "c2".* \ + FROM "a" \ + LEFT JOIN "c" "c1" ON ("c1"."colc2" = "a"."cola1") AND ("c1"."colc1" = 9) \ + LEFT JOIN "c" "c2" ON ("c2"."colc2" = "a"."cola1") AND ("c2"."colc1" <> 9) \ + ORDER BY "a"."cola1" + """, + """ + SELECT "d".*, "c"."colc2" AS "grdb_colc2" \ + FROM "d" \ + JOIN "c" ON ("c"."colc1" = "d"."cold2") AND ("c"."colc1" = 9) AND ("c"."colc2" IN (1, 2, 3)) \ + WHERE "d"."cold1" = 11 \ + ORDER BY "d"."cold1" + """, + """ + SELECT "d".*, "c"."colc2" AS "grdb_colc2" \ + FROM "d" \ + JOIN "c" ON ("c"."colc1" = "d"."cold2") AND ("c"."colc1" = 9) AND ("c"."colc2" IN (1, 2, 3)) \ + WHERE "d"."cold1" <> 11 \ + ORDER BY "d"."cold1" + """, + """ + SELECT "d".*, "c"."colc2" AS "grdb_colc2" \ + FROM "d" \ + JOIN "c" ON ("c"."colc1" = "d"."cold2") AND ("c"."colc1" <> 9) AND ("c"."colc2" IN (1, 2, 3)) \ + WHERE "d"."cold1" = 11 \ + ORDER BY "d"."cold1" + """, + """ + SELECT "d".*, "c"."colc2" AS "grdb_colc2" \ + FROM "d" \ + JOIN "c" ON ("c"."colc1" = "d"."cold2") AND ("c"."colc1" <> 9) AND ("c"."colc2" IN (1, 2, 3)) \ + WHERE "d"."cold1" <> 11 \ + ORDER BY "d"."cold1" + """]) + } + } + } } From 3e4c6fd102cd0b26fa1acc7e4d892068dc96899a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Jun 2019 14:40:08 +0200 Subject: [PATCH 09/91] Add more eager loading SQL tests (and spot a possible optimization) --- ...ciationPrefetchingCodableRecordTests.swift | 71 +++- ...ationPrefetchingFetchableRecordTests.swift | 80 +++- ...sociationPrefetchingObservationTests.swift | 22 +- .../AssociationPrefetchingRowTests.swift | 73 +++- .../AssociationPrefetchingSQLTests.swift | 389 +++++++++++++++++- 5 files changed, 628 insertions(+), 7 deletions(-) diff --git a/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift b/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift index a8a2f85f3..5d8c9ad14 100644 --- a/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift @@ -20,7 +20,7 @@ private struct C: TableRecord, FetchableRecord, Decodable, Equatable { } private struct D: TableRecord, FetchableRecord, Decodable, Equatable { var cold1: Int64 - var cold2: Int64 + var cold2: Int64? var cold3: String } @@ -61,6 +61,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); + INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); """, arguments: [ 1, "a1", @@ -77,6 +78,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { 11, 8, "d2", 12, 8, "d3", 13, 9, "d4", + 14, nil, "d5", ]) } } @@ -791,7 +793,6 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { } } - // TODO: make a variant with joining(optional:) func testIncludingOptionalBelongsToIncludingAllHasMany() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in @@ -1014,6 +1015,72 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { } } + func testJoiningOptionalHasOneThroughIncludingAllHasMany() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + // Plain request + do { + let request = D + .joining(optional: D + .hasOne(A.self, through: D.belongsTo(C.self), using: C.belongsTo(A.self)) + .including(all: A + .hasMany(B.self) + .orderByPrimaryKey())) + .orderByPrimaryKey() + + // Record (flat) + do { + struct Record: FetchableRecord, Decodable, Equatable { + var d: D + var bs: [B] // not optional + } + + // Record.fetchAll + do { + let records = try Record.fetchAll(db, request) + XCTAssertEqual(records, [ + Record( + d: D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]), + bs: [ + B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), + B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), + ]), + Record( + d: D(row: ["cold1": 11, "cold2": 8, "cold3": "d2"]), + bs: [ + B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), + ]), + Record( + d: D(row: ["cold1": 12, "cold2": 8, "cold3": "d3"]), + bs: [ + B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), + ]), + Record( + d: D(row: ["cold1": 13, "cold2": 9, "cold3": "d4"]), + bs: [ + B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), + ]), + Record( + d: D(row: ["cold1": 14, "cold2": nil, "cold3": "d5"]), + bs: []), + ]) + } + + // Record.fetchOne + do { + let record = try Record.fetchOne(db, request)! + XCTAssertEqual(record, Record( + d: D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]), + bs: [ + B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), + B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), + ])) + } + } + } + } + } + func testSelfJoin() throws { struct Employee: TableRecord, FetchableRecord, Decodable, Hashable { static let subordinates = hasMany(Employee.self, key: "subordinates") diff --git a/Tests/GRDBTests/AssociationPrefetchingFetchableRecordTests.swift b/Tests/GRDBTests/AssociationPrefetchingFetchableRecordTests.swift index e7cd853b1..1b99ee0a3 100644 --- a/Tests/GRDBTests/AssociationPrefetchingFetchableRecordTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingFetchableRecordTests.swift @@ -36,7 +36,7 @@ private struct C: TableRecord, FetchableRecord, Equatable { } private struct D: TableRecord, FetchableRecord, Equatable { var cold1: Int64 - var cold2: Int64 + var cold2: Int64? var cold3: String init(row: Row) { @@ -83,6 +83,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); + INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); """, arguments: [ 1, "a1", @@ -99,6 +100,7 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { 11, 8, "d2", 12, 8, "d3", 13, 9, "d4", + 14, nil, "d5", ]) } } @@ -973,7 +975,6 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { } } - // TODO: make a variant with joining(optional:) func testIncludingOptionalBelongsToIncludingAllHasMany() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in @@ -1243,4 +1244,79 @@ class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { } } } + + func testJoiningOptionalHasOneThroughIncludingAllHasMany() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + // Plain request + do { + let request = D + .joining(optional: D + .hasOne(A.self, through: D.belongsTo(C.self), using: C.belongsTo(A.self)) + .including(all: A + .hasMany(B.self) + .orderByPrimaryKey())) + .orderByPrimaryKey() + + // Record (flat) + do { + struct Record: FetchableRecord, Equatable { + var d: D + var bs: [B] // not optional + + init(d: D, bs: [B]) { + self.d = d + self.bs = bs + } + + init(row: Row) { + self.init(d: D(row: row), bs: row["bs"]) + } + } + + // Record.fetchAll + do { + let records = try Record.fetchAll(db, request) + XCTAssertEqual(records, [ + Record( + d: D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]), + bs: [ + B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), + B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), + ]), + Record( + d: D(row: ["cold1": 11, "cold2": 8, "cold3": "d2"]), + bs: [ + B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), + ]), + Record( + d: D(row: ["cold1": 12, "cold2": 8, "cold3": "d3"]), + bs: [ + B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), + ]), + Record( + d: D(row: ["cold1": 13, "cold2": 9, "cold3": "d4"]), + bs: [ + B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), + ]), + Record( + d: D(row: ["cold1": 14, "cold2": nil, "cold3": "d5"]), + bs: []), + ]) + } + + // Record.fetchOne + do { + let record = try Record.fetchOne(db, request)! + XCTAssertEqual(record, Record( + d: D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]), + bs: [ + B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), + B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), + ])) + } + } + } + } + } } diff --git a/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift b/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift index fc37d82c3..35c8de862 100644 --- a/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift @@ -236,7 +236,6 @@ class AssociationPrefetchingObservationTests: GRDBTestCase { } } - // TODO: make a variant with joining(optional:) func testIncludingOptionalBelongsToIncludingAllHasMany() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in @@ -287,4 +286,25 @@ class AssociationPrefetchingObservationTests: GRDBTestCase { } } } + + func testJoiningOptionalHasOneThroughIncludingAllHasMany() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + // Plain request + do { + let request = D + .joining(optional: D + .hasOne(A.self, through: D.belongsTo(C.self), using: C.belongsTo(A.self)) + .including(all: A + .hasMany(B.self) + .orderByPrimaryKey())) + .orderByPrimaryKey() + + try XCTAssert([ + "a(*),b(colb1,colb2,colb3),c(colc1,colc2),d(cold1,cold2,cold3)", // iOS 12 + "a(cola1),b(colb1,colb2,colb3),c(colc1,colc2),d(cold1,cold2,cold3)", // iOS 9 + ].contains(request.databaseRegion(db).description)) + } + } + } } diff --git a/Tests/GRDBTests/AssociationPrefetchingRowTests.swift b/Tests/GRDBTests/AssociationPrefetchingRowTests.swift index 8413ce108..f3af02c95 100644 --- a/Tests/GRDBTests/AssociationPrefetchingRowTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingRowTests.swift @@ -47,6 +47,7 @@ class AssociationPrefetchingRowTests: GRDBTestCase { INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); + INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?); """, arguments: [ 1, "a1", @@ -63,6 +64,7 @@ class AssociationPrefetchingRowTests: GRDBTestCase { 11, 8, "d2", 12, 8, "d3", 13, 9, "d4", + 14, nil, "d5", ]) } } @@ -779,7 +781,6 @@ class AssociationPrefetchingRowTests: GRDBTestCase { } } - // TODO: make a variant with joining(optional:) func testIncludingOptionalBelongsToIncludingAllHasMany() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in @@ -991,6 +992,76 @@ class AssociationPrefetchingRowTests: GRDBTestCase { } } + func testJoiningOptionalHasOneThroughIncludingAllHasMany() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + // Plain request + do { + let request = D + .joining(optional: D + .hasOne(A.self, through: D.belongsTo(C.self), using: C.belongsTo(A.self)) + .including(all: A + .hasMany(B.self) + .orderByPrimaryKey())) + .orderByPrimaryKey() + + // Row.fetchAll + do { + let rows = try Row.fetchAll(db, request) + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].description, "[cold1:10 cold2:7 cold3:\"d1\"]") + XCTAssertEqual(rows[0].debugDescription, """ + ▿ [cold1:10 cold2:7 cold3:"d1"] + + bs: 2 rows + """) + + XCTAssertEqual(rows[0].unscoped, ["cold1": 10, "cold2": 7, "cold3": "d1"]) + XCTAssertEqual(rows[0].prefetchedRows.keys, ["bs"]) + XCTAssertEqual(rows[0].prefetchedRows["bs"]!.count, 2) + XCTAssertEqual(rows[0].prefetchedRows["bs"]![0], ["colb1": 4, "colb2": 1, "colb3": "b1", "grdb_colc1": 7]) + XCTAssertEqual(rows[0].prefetchedRows["bs"]![1], ["colb1": 5, "colb2": 1, "colb3": "b2", "grdb_colc1": 7]) + XCTAssertEqual(rows[0].scopes.count, 0) + + XCTAssertEqual(rows[1].unscoped, ["cold1": 11, "cold2": 8, "cold3": "d2"]) + XCTAssertEqual(rows[1].prefetchedRows.keys, ["bs"]) + XCTAssertEqual(rows[1].prefetchedRows["bs"]!.count, 1) + XCTAssertEqual(rows[1].prefetchedRows["bs"]![0], ["colb1": 6, "colb2": 2, "colb3": "b3", "grdb_colc1": 8]) + XCTAssertEqual(rows[1].scopes.count, 0) + + XCTAssertEqual(rows[2].unscoped, ["cold1": 12, "cold2": 8, "cold3": "d3"]) + XCTAssertEqual(rows[2].prefetchedRows.keys, ["bs"]) + XCTAssertEqual(rows[2].prefetchedRows["bs"]!.count, 1) + XCTAssertEqual(rows[2].prefetchedRows["bs"]![0], ["colb1": 6, "colb2": 2, "colb3": "b3", "grdb_colc1": 8]) + XCTAssertEqual(rows[2].scopes.count, 0) + + XCTAssertEqual(rows[3].unscoped, ["cold1": 13, "cold2": 9, "cold3": "d4"]) + XCTAssertEqual(rows[3].prefetchedRows.keys, ["bs"]) + XCTAssertEqual(rows[3].prefetchedRows["bs"]!.count, 1) + XCTAssertEqual(rows[3].prefetchedRows["bs"]![0], ["colb1": 6, "colb2": 2, "colb3": "b3", "grdb_colc1": 9]) + XCTAssertEqual(rows[3].scopes.count, 0) + + XCTAssertEqual(rows[4].unscoped, ["cold1": 14, "cold2": nil, "cold3": "d5"]) + XCTAssertEqual(rows[4].prefetchedRows.keys, ["bs"]) + XCTAssertEqual(rows[4].prefetchedRows["bs"]!.count, 0) + XCTAssertEqual(rows[4].scopes.count, 0) + } + + // Row.fetchOne + do { + let row = try Row.fetchOne(db, request)! + + XCTAssertEqual(row.unscoped, ["cold1": 10, "cold2": 7, "cold3": "d1"]) + XCTAssertEqual(row.prefetchedRows.keys, ["bs"]) + XCTAssertEqual(row.prefetchedRows["bs"]!.count, 2) + XCTAssertEqual(row.prefetchedRows["bs"]![0], ["colb1": 4, "colb2": 1, "colb3": "b1", "grdb_colc1": 7]) + XCTAssertEqual(row.prefetchedRows["bs"]![1], ["colb1": 5, "colb2": 1, "colb3": "b2", "grdb_colc1": 7]) + XCTAssertEqual(row.scopes.count, 0) + } + } + } + } + func testEquatable() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in diff --git a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift index 5c7aae764..600696418 100644 --- a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift @@ -12,6 +12,12 @@ private struct D: TableRecord { } class AssociationPrefetchingSQLTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { + // A.hasMany(B) + // A.hasMany(C) + // B.belongsTo(A) + // C.belongsTo(A) + // C.hasMany(D) + // D.belongsTo(C) try dbWriter.write { db in try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("cola1") @@ -918,7 +924,6 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { } } - // TODO: make a variant with joining(optional:) func testIncludingOptionalBelongsToIncludingAllHasMany() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in @@ -1138,4 +1143,386 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { } } } + + func testIncludingOptionalBelongsToIncludingOptionalBelongsToIncludingAllHasMany() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + // Plain request + do { + let request = D + .including(optional: D + .belongsTo(C.self) + .including(optional: C + .belongsTo(A.self) + .including(all: A + .hasMany(B.self) + .orderByPrimaryKey()))) + .orderByPrimaryKey() + .filter(Column("cold2") != 8) + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + XCTAssertEqual(selectQueries, [ + """ + SELECT "d".*, "c".*, "a".* \ + FROM "d" \ + LEFT JOIN "c" ON "c"."colc1" = "d"."cold2" \ + LEFT JOIN "a" ON "a"."cola1" = "c"."colc2" \ + WHERE "d"."cold2" <> 8 \ + ORDER BY "d"."cold1" + """, + """ + SELECT "b".*, "c"."colc1" AS "grdb_colc1" \ + FROM "b" \ + JOIN "a" ON "a"."cola1" = "b"."colb2" \ + JOIN "c" ON ("c"."colc2" = "a"."cola1") AND ("c"."colc1" IN (7, 9)) \ + ORDER BY "b"."colb1" + """]) + } + } + } + + func testIncludingOptionalHasOneThroughIncludingAllHasMany() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + // Plain request + do { + let request = D + .including(optional: D + .hasOne(A.self, through: D.belongsTo(C.self), using: C.belongsTo(A.self)) + .including(all: A + .hasMany(B.self) + .orderByPrimaryKey())) + .orderByPrimaryKey() + .filter(Column("cold2") != 8) + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + XCTAssertEqual(selectQueries, [ + """ + SELECT "d".*, "a".* \ + FROM "d" \ + LEFT JOIN "c" ON "c"."colc1" = "d"."cold2" \ + LEFT JOIN "a" ON "a"."cola1" = "c"."colc2" \ + WHERE "d"."cold2" <> 8 \ + ORDER BY "d"."cold1" + """, + """ + SELECT "b".*, "c"."colc1" AS "grdb_colc1" \ + FROM "b" \ + JOIN "a" ON "a"."cola1" = "b"."colb2" \ + JOIN "c" ON ("c"."colc2" = "a"."cola1") AND ("c"."colc1" IN (7, 9)) \ + ORDER BY "b"."colb1" + """]) + } + } + } + + func testJoiningOptionalBelongsToIncludingAllHasMany() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + // Plain request + do { + let request = B + .joining(optional: B + .belongsTo(A.self) + .including(all: A + .hasMany(C.self) + .orderByPrimaryKey()) + ) + .orderByPrimaryKey() + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + #warning("TODO: remove the harmless but useless LEFT JOIN in the first query") + XCTAssertEqual(selectQueries, [ + """ + SELECT "b".* \ + FROM "b" \ + LEFT JOIN "a" ON "a"."cola1" = "b"."colb2" \ + ORDER BY "b"."colb1" + """, + """ + SELECT "c".*, "a"."cola1" AS "grdb_cola1" \ + FROM "c" \ + JOIN "a" ON ("a"."cola1" = "c"."colc2") AND ("a"."cola1" IN (1, 2)) \ + ORDER BY "c"."colc1" + """]) + } + + // Request with filters + do { + let request = B + .joining(optional: B + .belongsTo(A.self) + .filter(Column("cola2") == "a1") + .including(all: A + .hasMany(C.self) + .filter(Column("colc1") == 9) + .orderByPrimaryKey() + .forKey("cs1")) + .including(all: A + .hasMany(C.self) + .filter(Column("colc1") != 9) + .orderByPrimaryKey() + .forKey("cs2")) + .forKey("a1")) + .joining(optional: B + .belongsTo(A.self) + .filter(Column("cola2") == "a2") + .including(all: A + .hasMany(C.self) + .filter(Column("colc1") == 9) + .orderByPrimaryKey() + .forKey("cs1")) + .including(all: A + .hasMany(C.self) + .filter(Column("colc1") != 9) + .orderByPrimaryKey() + .forKey("cs2")) + .forKey("a2")) + .orderByPrimaryKey() + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + #warning("TODO: remove the harmless but useless LEFT JOIN in the first query") + XCTAssertEqual(selectQueries, [ + """ + SELECT "b".* \ + FROM "b" \ + LEFT JOIN "a" "a1" ON ("a1"."cola1" = "b"."colb2") AND ("a1"."cola2" = 'a1') \ + LEFT JOIN "a" "a2" ON ("a2"."cola1" = "b"."colb2") AND ("a2"."cola2" = 'a2') \ + ORDER BY "b"."colb1" + """, + """ + SELECT "c".*, "a"."cola1" AS "grdb_cola1" \ + FROM "c" \ + JOIN "a" ON ("a"."cola1" = "c"."colc2") AND ("a"."cola2" = 'a1') AND ("a"."cola1" IN (1, 2)) \ + WHERE "c"."colc1" = 9 \ + ORDER BY "c"."colc1" + """, + """ + SELECT "c".*, "a"."cola1" AS "grdb_cola1" \ + FROM "c" \ + JOIN "a" ON ("a"."cola1" = "c"."colc2") AND ("a"."cola2" = 'a1') AND ("a"."cola1" IN (1, 2)) \ + WHERE "c"."colc1" <> 9 \ + ORDER BY "c"."colc1" + """, + """ + SELECT "c".*, "a"."cola1" AS "grdb_cola1" \ + FROM "c" \ + JOIN "a" ON ("a"."cola1" = "c"."colc2") AND ("a"."cola2" = 'a2') AND ("a"."cola1" IN (1, 2)) \ + WHERE "c"."colc1" = 9 \ + ORDER BY "c"."colc1" + """, + """ + SELECT "c".*, "a"."cola1" AS "grdb_cola1" \ + FROM "c" \ + JOIN "a" ON ("a"."cola1" = "c"."colc2") AND ("a"."cola2" = 'a2') AND ("a"."cola1" IN (1, 2)) \ + WHERE "c"."colc1" <> 9 \ + ORDER BY "c"."colc1" + """]) + } + } + } + + func testJoiningOptionalHasOneIncludingAllHasMany() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + // Plain request + do { + let request = A + .joining(optional: A + .hasOne(C.self) + .including(all: C + .hasMany(D.self) + .orderByPrimaryKey()) + ) + .orderByPrimaryKey() + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + #warning("TODO: remove the harmless but useless LEFT JOIN in the first query") + XCTAssertEqual(selectQueries, [ + """ + SELECT "a".* \ + FROM "a" \ + LEFT JOIN "c" ON "c"."colc2" = "a"."cola1" \ + ORDER BY "a"."cola1" + """, + """ + SELECT "d".*, "c"."colc2" AS "grdb_colc2" \ + FROM "d" \ + JOIN "c" ON ("c"."colc1" = "d"."cold2") AND ("c"."colc2" IN (1, 2, 3)) \ + ORDER BY "d"."cold1" + """]) + } + + // Request with filters + do { + let request = A + .joining(optional: A + .hasOne(C.self) + .filter(Column("colc1") == 9) + .including(all: C + .hasMany(D.self) + .filter(Column("cold1") == 11) + .orderByPrimaryKey() + .forKey("ds1")) + .including(all: C + .hasMany(D.self) + .filter(Column("cold1") != 11) + .orderByPrimaryKey() + .forKey("ds2")) + .forKey("c1")) + .joining(optional: A + .hasOne(C.self) + .filter(Column("colc1") != 9) + .including(all: C + .hasMany(D.self) + .filter(Column("cold1") == 11) + .orderByPrimaryKey() + .forKey("ds1")) + .including(all: C + .hasMany(D.self) + .filter(Column("cold1") != 11) + .orderByPrimaryKey() + .forKey("ds2")) + .forKey("c2")) + .orderByPrimaryKey() + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + #warning("TODO: remove the harmless but useless LEFT JOIN in the first query") + XCTAssertEqual(selectQueries, [ + """ + SELECT "a".* \ + FROM "a" \ + LEFT JOIN "c" "c1" ON ("c1"."colc2" = "a"."cola1") AND ("c1"."colc1" = 9) \ + LEFT JOIN "c" "c2" ON ("c2"."colc2" = "a"."cola1") AND ("c2"."colc1" <> 9) \ + ORDER BY "a"."cola1" + """, + """ + SELECT "d".*, "c"."colc2" AS "grdb_colc2" \ + FROM "d" \ + JOIN "c" ON ("c"."colc1" = "d"."cold2") AND ("c"."colc1" = 9) AND ("c"."colc2" IN (1, 2, 3)) \ + WHERE "d"."cold1" = 11 \ + ORDER BY "d"."cold1" + """, + """ + SELECT "d".*, "c"."colc2" AS "grdb_colc2" \ + FROM "d" \ + JOIN "c" ON ("c"."colc1" = "d"."cold2") AND ("c"."colc1" = 9) AND ("c"."colc2" IN (1, 2, 3)) \ + WHERE "d"."cold1" <> 11 \ + ORDER BY "d"."cold1" + """, + """ + SELECT "d".*, "c"."colc2" AS "grdb_colc2" \ + FROM "d" \ + JOIN "c" ON ("c"."colc1" = "d"."cold2") AND ("c"."colc1" <> 9) AND ("c"."colc2" IN (1, 2, 3)) \ + WHERE "d"."cold1" = 11 \ + ORDER BY "d"."cold1" + """, + """ + SELECT "d".*, "c"."colc2" AS "grdb_colc2" \ + FROM "d" \ + JOIN "c" ON ("c"."colc1" = "d"."cold2") AND ("c"."colc1" <> 9) AND ("c"."colc2" IN (1, 2, 3)) \ + WHERE "d"."cold1" <> 11 \ + ORDER BY "d"."cold1" + """]) + } + } + } + + func testJoiningOptionalBelongsToJoiningOptionalBelongsToIncludingAllHasMany() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + // Plain request + do { + let request = D + .joining(optional: D + .belongsTo(C.self) + .joining(optional: C + .belongsTo(A.self) + .including(all: A + .hasMany(B.self) + .orderByPrimaryKey()))) + .orderByPrimaryKey() + .filter(Column("cold2") != 8) + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + #warning("TODO: remove the harmless but useless LEFT JOIN in the first query") + XCTAssertEqual(selectQueries, [ + """ + SELECT "d".* \ + FROM "d" \ + LEFT JOIN "c" ON "c"."colc1" = "d"."cold2" \ + LEFT JOIN "a" ON "a"."cola1" = "c"."colc2" \ + WHERE "d"."cold2" <> 8 \ + ORDER BY "d"."cold1" + """, + """ + SELECT "b".*, "c"."colc1" AS "grdb_colc1" \ + FROM "b" \ + JOIN "a" ON "a"."cola1" = "b"."colb2" \ + JOIN "c" ON ("c"."colc2" = "a"."cola1") AND ("c"."colc1" IN (7, 9)) \ + ORDER BY "b"."colb1" + """]) + } + } + } + + func testJoiningOptionalHasOneThroughIncludingAllHasMany() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + // Plain request + do { + let request = D + .joining(optional: D + .hasOne(A.self, through: D.belongsTo(C.self), using: C.belongsTo(A.self)) + .including(all: A + .hasMany(B.self) + .orderByPrimaryKey())) + .orderByPrimaryKey() + .filter(Column("cold2") != 8) + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + #warning("TODO: remove the harmless but useless LEFT JOIN in the first query") + XCTAssertEqual(selectQueries, [ + """ + SELECT "d".* \ + FROM "d" \ + LEFT JOIN "c" ON "c"."colc1" = "d"."cold2" \ + LEFT JOIN "a" ON "a"."cola1" = "c"."colc2" \ + WHERE "d"."cold2" <> 8 \ + ORDER BY "d"."cold1" + """, + """ + SELECT "b".*, "c"."colc1" AS "grdb_colc1" \ + FROM "b" \ + JOIN "a" ON "a"."cola1" = "b"."colb2" \ + JOIN "c" ON ("c"."colc2" = "a"."cola1") AND ("c"."colc1" IN (7, 9)) \ + ORDER BY "b"."colb1" + """]) + } + } + } } From 2b401fe74505cec8e8c82af0c9d4833669aed42d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 29 Jun 2019 15:32:13 +0200 Subject: [PATCH 10/91] We don't really care about useless LEFT JOINs --- .../AssociationPrefetchingSQLTests.swift | 24 ++++++++++++++----- 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift index 600696418..a10f90cd1 100644 --- a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift @@ -1240,7 +1240,9 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter { $0.contains("SELECT") } - #warning("TODO: remove the harmless but useless LEFT JOIN in the first query") + // LEFT JOIN in the first query are useless but harmless. + // And SQLite may well optimize them out. + // So don't bother removing them. XCTAssertEqual(selectQueries, [ """ SELECT "b".* \ @@ -1293,7 +1295,9 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter { $0.contains("SELECT") } - #warning("TODO: remove the harmless but useless LEFT JOIN in the first query") + // LEFT JOIN in the first query are useless but harmless. + // And SQLite may well optimize them out. + // So don't bother removing them. XCTAssertEqual(selectQueries, [ """ SELECT "b".* \ @@ -1352,7 +1356,9 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter { $0.contains("SELECT") } - #warning("TODO: remove the harmless but useless LEFT JOIN in the first query") + // LEFT JOIN in the first query are useless but harmless. + // And SQLite may well optimize them out. + // So don't bother removing them. XCTAssertEqual(selectQueries, [ """ SELECT "a".* \ @@ -1405,7 +1411,9 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter { $0.contains("SELECT") } - #warning("TODO: remove the harmless but useless LEFT JOIN in the first query") + // LEFT JOIN in the first query are useless but harmless. + // And SQLite may well optimize them out. + // So don't bother removing them. XCTAssertEqual(selectQueries, [ """ SELECT "a".* \ @@ -1466,7 +1474,9 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter { $0.contains("SELECT") } - #warning("TODO: remove the harmless but useless LEFT JOIN in the first query") + // LEFT JOIN in the first query are useless but harmless. + // And SQLite may well optimize them out. + // So don't bother removing them. XCTAssertEqual(selectQueries, [ """ SELECT "d".* \ @@ -1505,7 +1515,9 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter { $0.contains("SELECT") } - #warning("TODO: remove the harmless but useless LEFT JOIN in the first query") + // LEFT JOIN in the first query are useless but harmless. + // And SQLite may well optimize them out. + // So don't bother removing them. XCTAssertEqual(selectQueries, [ """ SELECT "d".* \ From b3215cc471aed7369e440c593c89415e9c5aa529 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 30 Jun 2019 13:43:12 +0200 Subject: [PATCH 11/91] Less TODO --- TODO.md | 28 ++++------------------------ 1 file changed, 4 insertions(+), 24 deletions(-) diff --git a/TODO.md b/TODO.md index 9d67288cf..b49c5103b 100644 --- a/TODO.md +++ b/TODO.md @@ -54,36 +54,16 @@ players.update(...) // Runs the expected UPDATE statement ``` -- [ ] Predicates, so that a filter can be evaluated both on the database, and on a record instance +- [ ] Predicates, so that a filter can be evaluated both on the database, and on a record instance. + + After investigation, we can't do it reliably without knowing the collation used by a column. And SQLite does not provide this information elsewhere than in the full CREATE TABLE statement stored in sqlite_master. + - [ ] ValueObservation erasure ``` // Do better than this observation.mapReducer { _, reducer in AnyValueReducer(reducer) } ``` -- [ ] Association: - - ```swift - let request = DeviceConfiguration.all() - .joining(optional: DeviceConfiguration.activeSubscription /* belongsTo */ - .including(all: Subscription.carCategoryRelationships)) /* hasMany */ - ``` - - The request above executes the two following SQL queries: - - ```sql - SELECT "deviceConfiguration".* - FROM "deviceConfiguration" - LEFT JOIN "subscription" ON "subscription"."uid" = "deviceConfiguration"."activeSubscriptionUID" - LIMIT 1 - - SELECT "subscriptionCarCategory".*, "subscription"."uid" AS "grdb_uid" - FROM "subscriptionCarCategory" - JOIN "subscription" ON ("subscription"."uid" = "subscriptionCarCategory"."subscriptionUID") AND ("subscription"."uid" = 2) - ``` - - - Problem 1: In the first query, the left join has no purpose. - - Problem 2: Do we generally support all queries like `joining(one.joining(one.joining(one.including(all))))` - series of nested joinings of to-one associations ending with an including(all:)? - [ ] ValueObservation.flatMap: From df6bb8761c9533d48ca5311c5f155778ce2c9ccc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 30 Jun 2019 19:00:20 +0200 Subject: [PATCH 12/91] Swiftlint + whitespace --- .swiftlint.yml | 57 ++ GRDB.xcodeproj/project.pbxproj | 41 ++ GRDB/Core/Configuration.swift | 14 +- GRDB/Core/Cursor.swift | 43 +- GRDB/Core/Database+Schema.swift | 58 +- GRDB/Core/Database+Statements.swift | 14 +- GRDB/Core/Database.swift | 183 ++--- GRDB/Core/DatabaseCollation.swift | 18 +- GRDB/Core/DatabaseError.swift | 38 +- GRDB/Core/DatabaseFunction.swift | 34 +- GRDB/Core/DatabasePool.swift | 74 +- GRDB/Core/DatabaseQueue.swift | 36 +- GRDB/Core/DatabaseReader.swift | 18 +- GRDB/Core/DatabaseRegion.swift | 30 +- GRDB/Core/DatabaseRegionObservation.swift | 10 +- GRDB/Core/DatabaseSnapshot.swift | 2 +- GRDB/Core/DatabaseValue.swift | 48 +- GRDB/Core/DatabaseValueConversion.swift | 86 ++- GRDB/Core/DatabaseValueConvertible.swift | 96 ++- GRDB/Core/DatabaseWriter.swift | 43 +- GRDB/Core/FetchRequest.swift | 10 +- GRDB/Core/Row.swift | 140 ++-- GRDB/Core/RowAdapter.swift | 35 +- GRDB/Core/SQLInterpolation.swift | 8 +- GRDB/Core/SQLLiteral.swift | 9 +- GRDB/Core/SQLRequest.swift | 28 +- GRDB/Core/SchedulingWatchdog.swift | 7 +- GRDB/Core/SerializedDatabase.swift | 28 +- GRDB/Core/Statement.swift | 87 ++- GRDB/Core/StatementAuthorizer.swift | 27 +- GRDB/Core/StatementColumnConvertible.swift | 111 ++- GRDB/Core/Support/CoreGraphics/CGFloat.swift | 4 +- GRDB/Core/Support/Foundation/Data.swift | 8 +- .../Foundation/DatabaseDateComponents.swift | 22 +- ...alueConvertible+ReferenceConvertible.swift | 12 +- GRDB/Core/Support/Foundation/Date.swift | 14 +- GRDB/Core/Support/Foundation/NSData.swift | 2 +- GRDB/Core/Support/Foundation/NSNull.swift | 2 +- GRDB/Core/Support/Foundation/NSNumber.swift | 18 +- GRDB/Core/Support/Foundation/NSString.swift | 2 +- .../Support/Foundation/SQLiteDateParser.swift | 1 + GRDB/Core/Support/Foundation/URL.swift | 4 +- GRDB/Core/Support/Foundation/UUID.swift | 6 +- .../DatabaseValueConvertible+Decodable.swift | 10 +- .../DatabaseValueConvertible+Encodable.swift | 17 +- .../StandardLibrary/StandardLibrary.swift | 97 +-- GRDB/Core/TransactionObserver.swift | 635 ++++++++++-------- GRDB/FTS/FTS3.swift | 7 +- GRDB/FTS/FTS3Pattern.swift | 2 +- GRDB/FTS/FTS3TokenizerDescriptor.swift | 45 +- GRDB/FTS/FTS4.swift | 21 +- GRDB/FTS/FTS5.swift | 41 +- GRDB/FTS/FTS5CustomTokenizer.swift | 51 +- GRDB/FTS/FTS5Pattern.swift | 38 +- GRDB/FTS/FTS5Tokenizer.swift | 95 ++- GRDB/FTS/FTS5TokenizerDescriptor.swift | 38 +- GRDB/FTS/FTS5WrapperTokenizer.swift | 141 ++-- GRDB/Fixit/GRDB-4.0.swift | 162 ++++- GRDB/Migration/DatabaseMigrator.swift | 122 ++-- GRDB/Migration/Migration.swift | 37 +- GRDB/QueryInterface/FTS5+QueryInterface.swift | 78 +-- .../Request/Association/Association.swift | 8 +- .../Association/AssociationAggregate.swift | 266 ++++++-- .../QueryInterfaceRequest+Association.swift | 2 +- .../Request/QueryInterfaceRequest.swift | 28 +- .../Request/RequestProtocols.swift | 18 +- .../SQL/SQLCollatedExpression.swift | 2 +- GRDB/QueryInterface/SQL/SQLCollection.swift | 8 +- GRDB/QueryInterface/SQL/SQLExpressible.swift | 2 +- .../SQL/SQLExpression+QueryInterface.swift | 118 ++-- GRDB/QueryInterface/SQL/SQLExpression.swift | 16 +- .../SQL/SQLForeignKeyRequest.swift | 2 +- GRDB/QueryInterface/SQL/SQLFunctions.swift | 4 +- GRDB/QueryInterface/SQL/SQLOperators.swift | 4 +- GRDB/QueryInterface/SQL/SQLOrdering.swift | 2 +- GRDB/QueryInterface/SQL/SQLQuery.swift | 2 +- GRDB/QueryInterface/SQL/SQLRelation.swift | 20 +- .../SQL/SQLSelectable+QueryInterface.swift | 14 +- GRDB/QueryInterface/SQL/SQLSelectable.swift | 17 +- ...QLSpecificExpressible+QueryInterface.swift | 1 - .../SQLGeneration/SQLGenerationContext.swift | 6 +- .../SQLGeneration/SQLQueryGenerator.swift | 44 +- .../SQLInterpolation+QueryInterface.swift | 6 +- .../Schema/TableDefinition.swift | 269 ++++++-- .../Schema/VirtualTableModule.swift | 8 +- .../TableRecord+Association.swift | 30 +- .../TableRecord+QueryInterfaceRequest.swift | 53 +- GRDB/Record/EncodableRecord+Encodable.swift | 53 +- GRDB/Record/EncodableRecord.swift | 3 +- GRDB/Record/FetchableRecord+Decodable.swift | 73 +- GRDB/Record/FetchableRecord+TableRecord.swift | 28 +- GRDB/Record/FetchableRecord.swift | 55 +- GRDB/Record/FetchedRecordsController.swift | 223 +++--- GRDB/Record/PersistableRecord.swift | 66 +- GRDB/Record/Record.swift | 22 +- GRDB/Utils/Inflections+English.swift | 1 + GRDB/Utils/Inflections.swift | 35 +- GRDB/Utils/OrderedDictionary.swift | 18 +- GRDB/Utils/Pool.swift | 6 +- GRDB/Utils/Utils.swift | 14 +- ...Observation+DatabaseValueConvertible.swift | 13 +- .../ValueObservation+FetchableRecord.swift | 8 +- .../ValueObservation+Row.swift | 2 +- GRDB/ValueObservation/ValueObservation.swift | 2 +- GRDB/ValueObservation/ValueObserver.swift | 4 +- .../ValueReducer/Combine.swift | 15 +- .../ValueReducer/RemoveDuplicates.swift | 3 +- GRDBCustom.xcodeproj/project.pbxproj | 40 +- ...atabaseValueConvertibleEscapingTests.swift | 26 +- Tests/GRDBTests/GRDBTestCase.swift | 4 +- 110 files changed, 3257 insertions(+), 1572 deletions(-) create mode 100644 .swiftlint.yml diff --git a/.swiftlint.yml b/.swiftlint.yml new file mode 100644 index 000000000..eca723179 --- /dev/null +++ b/.swiftlint.yml @@ -0,0 +1,57 @@ +included: + - GRDB + +disabled_rules: + - cyclomatic_complexity + - file_length + - force_cast + - force_try + - function_body_length + - function_parameter_count + - identifier_name + - is_disjoint + - large_tuple + - nesting + - opening_brace + - redundant_optional_initialization + - syntactic_sugar + - todo + - trailing_comma + - trailing_whitespace + - type_body_length + - type_name + - unused_setter_value + +opt_in_rules: + - anyobject_protocol + - array_init + - attributes + - closure_spacing + - collection_alignment + - contains_over_first_not_nil + - convenience_type + - empty_count + - empty_string + - explicit_init + - fatal_error_message + - first_where + - joined_default_parameter + - last_where + - legacy_multiple + - legacy_random + - modifier_order + - no_extension_access_modifier + - overridden_super_call + - pattern_matching_keywords + - prohibited_super_call + - reduce_into + - redundant_type_annotation + - sorted_first_last + - toggle_bool + - unused_import + - unused_private_declaration + - yoda_condition + +vertical_whitespace: + max_empty_lines: 2 + diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 2e51e1755..f31dcb2ba 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -2313,6 +2313,7 @@ 56E5D7C61B4D3FED00430942 /* Frameworks */, 56E5D7C71B4D3FED00430942 /* Headers */, 56E5D7C81B4D3FED00430942 /* Resources */, + 56EB54FA22C9115E00850069 /* Swiftlint */, ); buildRules = ( ); @@ -2367,6 +2368,7 @@ DC3773EF19C8CBB3004FCF85 /* Frameworks */, DC3773F019C8CBB3004FCF85 /* Headers */, DC3773F119C8CBB3004FCF85 /* Resources */, + 56EB54F322C8ED5100850069 /* Swiftlint */, ); buildRules = ( ); @@ -2559,6 +2561,45 @@ }; /* End PBXResourcesBuildPhase section */ +/* Begin PBXShellScriptBuildPhase section */ + 56EB54F322C8ED5100850069 /* Swiftlint */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + name = Swiftlint; + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n"; + }; + 56EB54FA22C9115E00850069 /* Swiftlint */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + name = Swiftlint; + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n"; + }; +/* End PBXShellScriptBuildPhase section */ + /* Begin PBXSourcesBuildPhase section */ 560C97D41C0E22D300BF8471 /* Sources */ = { isa = PBXSourcesBuildPhase; diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 0cb8a17e5..1194e9a11 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -1,11 +1,11 @@ import Foundation import Dispatch #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// Configuration for a DatabaseQueue or DatabasePool. @@ -85,7 +85,7 @@ public struct Configuration { public var passphrase: String? #endif - + /// If set, allows custom configuration to be run every time /// a new connection is opened. /// @@ -181,9 +181,9 @@ public struct Configuration { // MARK: - Not Public var threadingMode: Database.ThreadingMode = .`default` - var SQLiteConnectionDidOpen: (() -> ())? - var SQLiteConnectionWillClose: ((SQLiteConnection) -> ())? - var SQLiteConnectionDidClose: (() -> ())? + var SQLiteConnectionDidOpen: (() -> Void)? + var SQLiteConnectionWillClose: ((SQLiteConnection) -> Void)? + var SQLiteConnectionDidClose: (() -> Void)? var SQLiteOpenFlags: Int32 { let readWriteFlags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE) return threadingMode.SQLiteOpenFlags | readWriteFlags diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index 51ef3b303..95705d5a2 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -29,7 +29,10 @@ extension Sequence { /// Returns a cursor over the concatenated results of mapping transform /// over self. - public func flatMap(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor, SegmentOfResult>> { + public func flatMap( + _ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) + -> FlattenCursor, SegmentOfResult>> + { return AnyCursor(self).flatMap(transform) } } @@ -76,7 +79,7 @@ extension Set { /// `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, /// `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, /// `suffix`. -public protocol Cursor : class { +public protocol Cursor: AnyObject { /// The type of element traversed by the cursor. associatedtype Element @@ -141,7 +144,9 @@ extension Cursor { /// Returns a cursor over the concatenated non-nil results of mapping /// transform over this cursor. - public func compactMap(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor>, ElementOfResult> { + public func compactMap(_ transform: @escaping (Element) throws -> ElementOfResult?) + -> MapCursor>, ElementOfResult> + { return map(transform).filter { $0 != nil }.map { $0! } } @@ -190,7 +195,7 @@ extension Cursor { public func dropFirst() -> DropFirstCursor { return dropFirst(1) } - + /// Returns an array containing all but the given number of final /// elements. /// @@ -243,13 +248,19 @@ extension Cursor { /// Returns a cursor over the concatenated results of mapping transform /// over self. - public func flatMap(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor>> { + public func flatMap(_ transform: @escaping (Element) throws -> SegmentOfResult) + -> FlattenCursor>> + where SegmentOfResult: Sequence + { return flatMap { try AnyCursor(transform($0)) } } /// Returns a cursor over the concatenated results of mapping transform /// over self. - public func flatMap(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor> { + public func flatMap(_ transform: @escaping (Element) throws -> SegmentOfResult) + -> FlattenCursor> + where SegmentOfResult: Cursor + { return map(transform).joined() } @@ -503,7 +514,7 @@ extension Cursor where Element: StringProtocol { /// This cursor forwards its next() method to an arbitrary underlying cursor /// having the same Element type, hiding the specifics of the underlying /// cursor. -public final class AnyCursor : Cursor { +public final class AnyCursor: Cursor { private let element: () throws -> Element? /// Creates a cursor that wraps a base cursor but whose type depends only on @@ -539,11 +550,11 @@ public final class AnyCursor : Cursor { } /// :nodoc: -public final class DropFirstCursor : Cursor { +public final class DropFirstCursor: Cursor { private let base: Base private let limit: Int private var dropped: Int = 0 - + init(_ base: Base, limit: Int) { GRDBPrecondition(limit >= 0, "Can't drop a negative number of elements from a cursor") self.base = base @@ -566,7 +577,7 @@ public final class DropFirstCursor : Cursor { /// consecutive elements of some base cursor that satisfy a given predicate. /// /// :nodoc: -public final class DropWhileCursor : Cursor { +public final class DropWhileCursor: Cursor { private let base: Base private let predicate: (Base.Element) throws -> Bool private var predicateHasFailed = false @@ -605,7 +616,7 @@ public final class DropWhileCursor : Cursor { /// // Prints: "1: bar" /// /// :nodoc: -public final class EnumeratedCursor : Cursor { +public final class EnumeratedCursor: Cursor { private let base: Base private var index: Int @@ -628,7 +639,7 @@ public final class EnumeratedCursor : Cursor { /// also satisfy a given predicate. /// /// :nodoc: -public final class FilterCursor : Cursor { +public final class FilterCursor: Cursor { private let base: Base private let isIncluded: (Base.Element) throws -> Bool @@ -656,7 +667,7 @@ public final class FilterCursor : Cursor { /// See Cursor.joined(), Cursor.flatMap(_:), Sequence.flatMap(_:) /// /// :nodoc: -public final class FlattenCursor : Cursor where Base.Element: Cursor { +public final class FlattenCursor: Cursor where Base.Element: Cursor { private let base: Base private var inner: Base.Element? @@ -686,7 +697,7 @@ public final class FlattenCursor : Cursor where Base.Element: Curs /// See Cursor.map(_:) /// /// :nodoc: -public final class MapCursor : Cursor { +public final class MapCursor: Cursor { private let base: Base private let transform: (Base.Element) throws -> Element @@ -708,7 +719,7 @@ public final class MapCursor : Cursor { /// `Base` cursor. /// /// :nodoc: -public final class PrefixCursor : Cursor { +public final class PrefixCursor: Cursor { private let base: Base private let maxLength: Int private var taken = 0 @@ -735,7 +746,7 @@ public final class PrefixCursor : Cursor { /// some base cursor that satisfy a given predicate. /// /// :nodoc: -public final class PrefixWhileCursor : Cursor { +public final class PrefixWhileCursor: Cursor { private let base: Base private let predicate: (Base.Element) throws -> Bool private var predicateHasFailed = false diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 0155a214e..71e0b773a 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -1,15 +1,15 @@ #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif extension Database { - + // MARK: - Database Schema - + /// Clears the database schema cache. /// /// You may need to clear the cache manually if the database schema is @@ -71,7 +71,7 @@ extension Database { .names(ofType: type) .contains { $0.lowercased() == name } } - + /// The primary key for table named `tableName`. /// /// All tables have a primary key, even when it is not explicit. When a @@ -203,7 +203,12 @@ extension Database { /// True if a sequence of columns uniquely identifies a row, that is to say /// if the columns are the primary key, or if there is a unique index on them. - public func table(_ tableName: String, hasUniqueKey columns: T) throws -> Bool where T.Iterator.Element == String { + public func table( + _ tableName: String, + hasUniqueKey columns: T) + throws -> Bool + where T.Iterator.Element == String + { return try columnsForUniqueKey(Array(columns), in: tableName) != nil } @@ -213,7 +218,9 @@ extension Database { return foreignKeys } - var rawForeignKeys: [(destinationTable: String, mapping: [(origin: String, destination: String?, seq: Int)])] = [] + var rawForeignKeys: [( + destinationTable: String, + mapping: [(origin: String, destination: String?, seq: Int)])] = [] var previousId: Int? = nil for row in try Row.fetchAll(self, sql: "PRAGMA foreign_key_list(\(tableName.quotedDatabaseIdentifier))") { // row = [id:0 seq:0 table:"parents" from:"parentId" to:"id" on_update:"..." on_delete:"..." match:"..."] @@ -224,9 +231,13 @@ extension Database { let destination: String? = row[4] if previousId == id { - rawForeignKeys[rawForeignKeys.count - 1].mapping.append((origin: origin, destination: destination, seq: seq)) + rawForeignKeys[rawForeignKeys.count - 1] + .mapping + .append((origin: origin, destination: destination, seq: seq)) } else { - rawForeignKeys.append((destinationTable: table, mapping: [(origin: origin, destination: destination, seq: seq)])) + rawForeignKeys.append(( + destinationTable: table, + mapping: [(origin: origin, destination: destination, seq: seq)])) previousId = id } } @@ -281,7 +292,7 @@ extension Database { } extension Database { - + /// The columns in the table named `tableName` /// /// - throws: A DatabaseError if table does not exist. @@ -313,7 +324,7 @@ extension Database { // 0 | id | INTEGER | 0 | NULL | 1 | // 1 | name | TEXT | 0 | NULL | 0 | // 2 | score | INTEGER | 0 | NULL | 0 | - + if sqlite3_libversion_number() < 3008005 { // Work around a bug in SQLite where PRAGMA table_info would // return a result even after the table was deleted. @@ -324,7 +335,7 @@ extension Database { let columns = try ColumnInfo .fetchAll(self, sql: "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))") .sorted(by: { $0.cid < $1.cid }) - guard columns.count > 0 else { + if columns.isEmpty { throw DatabaseError(message: "no such table: \(tableName)") } @@ -335,14 +346,25 @@ extension Database { /// If there exists a unique key on columns, return the columns /// ordered as the matching index (or primay key). Case of returned columns /// is not guaranteed. - func columnsForUniqueKey(_ columns: T, in tableName: String) throws -> [String]? where T.Iterator.Element == String { - let primaryKey = try self.primaryKey(tableName) // first, so that we fail early and consistently should the table not exist + func columnsForUniqueKey( + _ columns: T, + in tableName: String) + throws -> [String]? + where T.Iterator.Element == String + { + // Check primaryKey first, so that we fail early if the table does not exist + let primaryKey = try self.primaryKey(tableName) let lowercasedColumns = Set(columns.map { $0.lowercased() }) if Set(primaryKey.columns.map { $0.lowercased() }) == lowercasedColumns { return primaryKey.columns } - if let index = try indexes(on: tableName).first(where: { index in index.isUnique && Set(index.columns.map { $0.lowercased() }) == lowercasedColumns }) { - // There is an explicit unique index on the columns + + // Is there is an explicit unique index on the columns? + let indexes = try self.indexes(on: tableName) + let matchingIndex = indexes.first { index in + index.isUnique && Set(index.columns.map { $0.lowercased() }) == lowercasedColumns + } + if let index = matchingIndex { return index.columns } return nil @@ -366,7 +388,7 @@ extension Database { /// 2 score INTEGER 0 NULL 0 /// /// See `Database.columns(in:)` and https://www.sqlite.org/pragma.html#pragma_table_info -public struct ColumnInfo : FetchableRecord { +public struct ColumnInfo: FetchableRecord { let cid: Int /// The column name diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 1553dbf62..8b39b5643 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -1,10 +1,10 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif extension Database { @@ -213,13 +213,15 @@ extension Database { // Check that all arguments were consumed: it is a programmer error to // provide arguments that do not match the statement. if arguments.values.isEmpty == false { - throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)") + throw DatabaseError( + resultCode: .SQLITE_MISUSE, + message: "wrong number of statement arguments: \(initialValuesCount)") } } } extension Database { - + func updateStatementWillExecute(_ statement: UpdateStatement) { observationBroker.updateStatementWillExecute(statement) } @@ -294,7 +296,7 @@ struct StatementCache { selectStatements[sql] = statement return statement } - + mutating func updateStatement(_ sql: String) throws -> UpdateStatement { if let statement = updateStatements[sql] { return statement diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index ee308af24..0194390e7 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1,10 +1,10 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// A raw SQLite connection, suitable for the SQLite C API. @@ -36,7 +36,7 @@ public final class Database { public let sqliteConnection: SQLiteConnection // MARK: - Configuration - + /// The error logging function. /// /// Quoting https://www.sqlite.org/errlog.html: @@ -137,11 +137,14 @@ public final class Database { sqlite3_set_authorizer(sqliteConnection, nil, nil) case (nil, .some): let dbPointer = Unmanaged.passUnretained(self).toOpaque() - sqlite3_set_authorizer(sqliteConnection, { (dbPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in - guard let dbPointer = dbPointer else { return SQLITE_OK } - let db = Unmanaged.fromOpaque(dbPointer).takeUnretainedValue() - return db.authorizer!.authorize(actionCode, cString1, cString2, cString3, cString4) - }, dbPointer) + sqlite3_set_authorizer( + sqliteConnection, + { (dbPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in + guard let dbPointer = dbPointer else { return SQLITE_OK } + let db = Unmanaged.fromOpaque(dbPointer).takeUnretainedValue() + return db.authorizer!.authorize(actionCode, cString1, cString2, cString3, cString4) + }, + dbPointer) default: break } @@ -164,9 +167,9 @@ public final class Database { private var collations = Set() private var _readOnlyDepth = 0 // Modify with beginReadOnly/endReadOnly private var isClosed: Bool = false - + // MARK: - Initializer - + init(path: String, configuration: Configuration, schemaCache: DatabaseSchemaCache) throws { self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags) self.configuration = configuration @@ -179,7 +182,7 @@ public final class Database { } extension Database { - + // MARK: - Database Opening private static func openConnection(path: String, flags: Int32) throws -> SQLiteConnection { @@ -207,7 +210,7 @@ extension Database { } extension Database { - + // MARK: - Database Setup /// This method must be called after database initialization @@ -220,14 +223,14 @@ extension Database { setupDefaultCollations() observationBroker.installCommitAndRollbackHooks() try activateExtendedCodes() - + #if SQLITE_HAS_CODEC try validateSQLCipher() if let passphrase = configuration.passphrase { try setCipherPassphrase(passphrase) } #endif - + // Last step before we can start accessing the database. // This is the opportunity to run SQLCipher configuration // pragmas such as cipher_page_size, for example. @@ -240,24 +243,34 @@ extension Database { guard configuration.trace != nil else { return } - // sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0 http://www.sqlite.org/changes.html#version_3_14 - // It is available from iOS 10.0 and OS X 10.12 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + // sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0 + // http://www.sqlite.org/changes.html#version_3_14 + // It is available from iOS 10.0 and OS X 10.12 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) #if GRDBCUSTOMSQLITE || GRDBCIPHER - let dbPointer = Unmanaged.passUnretained(self).toOpaque() - sqlite3_trace_v2(sqliteConnection, UInt32(SQLITE_TRACE_STMT), { (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in - return Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql) - }, dbPointer) + let dbPointer = Unmanaged.passUnretained(self).toOpaque() + sqlite3_trace_v2( + sqliteConnection, + UInt32(SQLITE_TRACE_STMT), + { (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in + Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql) + }, + dbPointer) #elseif os(Linux) - setupTrace_v1() + setupTrace_v1() #else - if #available(iOS 10.0, OSX 10.12, watchOS 3.0, *) { - let dbPointer = Unmanaged.passUnretained(self).toOpaque() - sqlite3_trace_v2(sqliteConnection, UInt32(SQLITE_TRACE_STMT), { (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in - return Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql) - }, dbPointer) - } else { - setupTrace_v1() - } + if #available(iOS 10.0, OSX 10.12, watchOS 3.0, *) { + let dbPointer = Unmanaged.passUnretained(self).toOpaque() + sqlite3_trace_v2( + sqliteConnection, + UInt32(SQLITE_TRACE_STMT), + { (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in + Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql) + }, + dbPointer) + } else { + setupTrace_v1() + } #endif } @@ -391,7 +404,7 @@ extension Database { } extension Database { - + // MARK: - Database Closing /// This method must be called before database deallocation @@ -409,18 +422,19 @@ extension Database { private static func closeConnection(_ sqliteConnection: SQLiteConnection) { // sqlite3_close_v2 was added in SQLite 3.7.14 http://www.sqlite.org/changes.html#version_3_7_14 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + // It is available from iOS 8.2 and OS X 10.10 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) #if GRDBCUSTOMSQLITE || GRDBCIPHER - closeConnection_v2(sqliteConnection, sqlite3_close_v2) + closeConnection_v2(sqliteConnection, sqlite3_close_v2) #else - if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) { - closeConnection_v2(sqliteConnection, sqlite3_close_v2) - } else { - closeConnection_v1(sqliteConnection) - } + if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) { + closeConnection_v2(sqliteConnection, sqlite3_close_v2) + } else { + closeConnection_v1(sqliteConnection) + } #endif } - + private static func closeConnection_v1(_ sqliteConnection: SQLiteConnection) { // https://www.sqlite.org/c3ref/close.html // > If the database connection is associated with unfinalized prepared @@ -466,7 +480,7 @@ extension Database { } extension Database { - + // MARK: - Functions /// Add or redefine an SQL function. @@ -492,7 +506,7 @@ extension Database { } extension Database { - + // MARK: - Collations /// Add or redefine a collation. @@ -539,7 +553,8 @@ extension Database { _readOnlyDepth += 1 if _readOnlyDepth == 1 && configuration.readonly == false { // PRAGMA query_only was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + // It is available from iOS 8.2 and OS X 10.10 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) try internalCachedUpdateStatement(sql: "PRAGMA query_only = 1").execute() } } @@ -548,7 +563,8 @@ extension Database { _readOnlyDepth -= 1 if _readOnlyDepth == 0 && configuration.readonly == false { // PRAGMA query_only was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + // It is available from iOS 8.2 and OS X 10.10 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) try internalCachedUpdateStatement(sql: "PRAGMA query_only = 0").execute() } } @@ -583,7 +599,7 @@ extension Database { } extension Database { - + // MARK: - Transactions & Savepoint /// Executes a block inside a database transaction. @@ -640,7 +656,7 @@ extension Database { } } } - + if let firstError = firstError { throw firstError } @@ -674,7 +690,7 @@ extension Database { if !isInsideTransaction && configuration.defaultTransactionKind != .deferred { return try inTransaction(configuration.defaultTransactionKind, block) } - + // If the savepoint is top-level, we'll use ROLLBACK TRANSACTION in // order to perform the special error handling of rollbacks (see // the rollback method). @@ -849,7 +865,7 @@ extension Database { } extension Database { - + // MARK: - Memory Management func releaseMemory() { @@ -864,7 +880,13 @@ extension Database { // MARK: - Backup - static func backup(from dbFrom: Database, to dbDest: Database, afterBackupInit: (() -> ())? = nil, afterBackupStep: (() -> ())? = nil) throws { + static func backup( + from dbFrom: Database, + to dbDest: Database, + afterBackupInit: (() -> Void)? = nil, + afterBackupStep: (() -> Void)? = nil) + throws + { guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", dbFrom.sqliteConnection, "main") else { throw DatabaseError(resultCode: dbDest.lastErrorCode, message: dbDest.lastErrorMessage) } @@ -904,35 +926,36 @@ extension Database { } #if SQLITE_HAS_CODEC - extension Database { - - // MARK: - Encryption - - func change(passphrase: String) throws { - // FIXME: sqlite3_rekey is discouraged. - // - // https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320 - // - // > We (Zetetic) have been discouraging the use of sqlite3_rekey in - // > favor of attaching a new database with the desired encryption - // > options and using sqlcipher_export() to migrate the contents and - // > schema of the original db into the new one: - // > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/ - let data = passphrase.data(using: .utf8)! - #if swift(>=5.0) - let code = data.withUnsafeBytes { - sqlite3_rekey(sqliteConnection, $0.baseAddress, Int32($0.count)) - } - #else - let code = data.withUnsafeBytes { - sqlite3_rekey(sqliteConnection, $0, Int32(data.count)) - } - #endif - guard code == SQLITE_OK else { - throw DatabaseError(resultCode: code, message: lastErrorMessage) - } +extension Database { + + // MARK: - Encryption + + func change(passphrase: String) throws { + // FIXME: sqlite3_rekey is discouraged. + // + // https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320 + // + // > We (Zetetic) have been discouraging the use of sqlite3_rekey in + // > favor of attaching a new database with the desired encryption + // > options and using sqlcipher_export() to migrate the contents and + // > schema of the original db into the new one: + // > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/ + // swiftlint:disable:previous line_length + let data = passphrase.data(using: .utf8)! + #if swift(>=5.0) + let code = data.withUnsafeBytes { + sqlite3_rekey(sqliteConnection, $0.baseAddress, Int32($0.count)) + } + #else + let code = data.withUnsafeBytes { + sqlite3_rekey(sqliteConnection, $0, Int32(data.count)) + } + #endif + guard code == SQLITE_OK else { + throw DatabaseError(resultCode: code, message: lastErrorMessage) } } +} #endif extension Database { @@ -991,7 +1014,7 @@ extension Database { /// A built-in SQLite collation. /// /// See https://www.sqlite.org/datatype3.html#collation - public struct CollationName : RawRepresentable, Hashable { + public struct CollationName: RawRepresentable, Hashable { /// :nodoc: public let rawValue: String @@ -1022,7 +1045,7 @@ extension Database { /// } /// /// See https://www.sqlite.org/datatype3.html - public struct ColumnType : RawRepresentable, Hashable { + public struct ColumnType: RawRepresentable, Hashable { /// :nodoc: public let rawValue: String @@ -1063,7 +1086,7 @@ extension Database { /// An SQLite conflict resolution. /// /// See https://www.sqlite.org/lang_conflict.html. - public enum ConflictResolution : String { + public enum ConflictResolution: String { case rollback = "ROLLBACK" case abort = "ABORT" case fail = "FAIL" @@ -1074,7 +1097,7 @@ extension Database { /// A foreign key action. /// /// See https://www.sqlite.org/foreignkeys.html - public enum ForeignKeyAction : String { + public enum ForeignKeyAction: String { case cascade = "CASCADE" case restrict = "RESTRICT" case setNull = "SET NULL" @@ -1091,7 +1114,7 @@ extension Database { } /// An SQLite transaction kind. See https://www.sqlite.org/lang_transaction.html - public enum TransactionKind : String { + public enum TransactionKind: String { case deferred = "DEFERRED" case immediate = "IMMEDIATE" case exclusive = "EXCLUSIVE" diff --git a/GRDB/Core/DatabaseCollation.swift b/GRDB/Core/DatabaseCollation.swift index d94780412..0b182fd94 100644 --- a/GRDB/Core/DatabaseCollation.swift +++ b/GRDB/Core/DatabaseCollation.swift @@ -1,10 +1,10 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// A Collation is a string comparison function used by SQLite. @@ -27,8 +27,16 @@ public final class DatabaseCollation { self.name = name self.function = { (length1, buffer1, length2, buffer2) in // Buffers are not C strings: they do not end with \0. - let string1 = String(bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped), length: Int(length1), encoding: .utf8, freeWhenDone: false)! - let string2 = String(bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped), length: Int(length2), encoding: .utf8, freeWhenDone: false)! + let string1 = String( + bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped), + length: Int(length1), + encoding: .utf8, + freeWhenDone: false)! + let string2 = String( + bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped), + length: Int(length2), + encoding: .utf8, + freeWhenDone: false)! return function(string1, string2) } } diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index 2ed6eab62..308f2d28b 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -1,13 +1,13 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif -public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible { +public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible { public let rawValue: Int32 public init(rawValue: Int32) { @@ -48,6 +48,7 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible // Primary Result codes // https://www.sqlite.org/rescode.html#primary_result_code_list + // swiftlint:disable operator_usage_whitespace public static let SQLITE_OK = ResultCode(rawValue: 0) // Successful result public static let SQLITE_ERROR = ResultCode(rawValue: 1) // SQL error or missing database public static let SQLITE_INTERNAL = ResultCode(rawValue: 2) // Internal logic error in SQLite @@ -79,10 +80,12 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible public static let SQLITE_WARNING = ResultCode(rawValue: 28) // Warnings from sqlite3_log() public static let SQLITE_ROW = ResultCode(rawValue: 100) // sqlite3_step() has another row ready public static let SQLITE_DONE = ResultCode(rawValue: 101) // sqlite3_step() has finished executing + // swiftlint:enable operator_usage_whitespace // Extended Result Code // https://www.sqlite.org/rescode.html#extended_result_code_list + // swiftlint:disable operator_usage_whitespace public static let SQLITE_IOERR_READ = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (1<<8))) public static let SQLITE_IOERR_SHORT_READ = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (2<<8))) public static let SQLITE_IOERR_WRITE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (3<<8))) @@ -139,21 +142,23 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible public static let SQLITE_WARNING_AUTOINDEX = ResultCode(rawValue: (SQLITE_WARNING.rawValue | (1<<8))) public static let SQLITE_AUTH_USER = ResultCode(rawValue: (SQLITE_AUTH.rawValue | (1<<8))) public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8))) + // swiftlint:enable operator_usage_whitespace } // CustomStringConvertible extension ResultCode { var errorString: String? { // sqlite3_errstr was added in SQLite 3.7.15 http://www.sqlite.org/changes.html#version_3_7_15 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + // It is available from iOS 8.2 and OS X 10.10 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) #if GRDBCUSTOMSQLITE || GRDBCIPHER - return String(cString: sqlite3_errstr(rawValue)) + return String(cString: sqlite3_errstr(rawValue)) #else - if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) { - return String(cString: sqlite3_errstr(rawValue)) - } else { - return nil - } + if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) { + return String(cString: sqlite3_errstr(rawValue)) + } else { + return nil + } #endif } @@ -168,7 +173,7 @@ extension ResultCode { } /// DatabaseError wraps an SQLite error. -public struct DatabaseError : Error, CustomStringConvertible, CustomNSError { +public struct DatabaseError: Error, CustomStringConvertible, CustomNSError { /// The SQLite error code (see /// https://www.sqlite.org/rescode.html#primary_result_code_list). @@ -207,7 +212,12 @@ public struct DatabaseError : Error, CustomStringConvertible, CustomNSError { public let sql: String? /// Creates a Database Error - public init(resultCode: ResultCode = .SQLITE_ERROR, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) { + public init( + resultCode: ResultCode = .SQLITE_ERROR, + message: String? = nil, + sql: String? = nil, + arguments: StatementArguments? = nil) + { self.extendedResultCode = resultCode self.message = message ?? resultCode.errorString self.sql = sql @@ -264,7 +274,7 @@ extension DatabaseError { /// NSError bridging: the user-info dictionary. /// :nodoc: - public var errorUserInfo: [String : Any] { + public var errorUserInfo: [String: Any] { return [NSLocalizedDescriptionKey: description] } } diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index 0a9f4e036..6827ca0ae 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -1,9 +1,9 @@ #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// An SQL function or aggregate. @@ -44,7 +44,12 @@ public final class DatabaseFunction: Hashable { /// as Int, String, NSDate, etc. The array is guaranteed to have /// exactly *argumentCount* elements, provided *argumentCount* is /// not nil. - public init(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?) { + public init( + _ name: String, + argumentCount: Int32? = nil, + pure: Bool = false, + function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?) + { self.identity = Identity(name: name, nArg: argumentCount ?? -1) self.pure = pure self.kind = .function{ (argc, argv) in @@ -94,10 +99,15 @@ public final class DatabaseFunction: Hashable { /// an array of DatabaseValue arguments. The array is guaranteed to /// have exactly *argumentCount* elements, provided *argumentCount* is /// not nil. - public init(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, aggregate: Aggregate.Type) { + public init( + _ name: String, + argumentCount: Int32? = nil, + pure: Bool = false, + aggregate: Aggregate.Type) + { self.identity = Identity(name: name, nArg: argumentCount ?? -1) self.pure = pure - self.kind = .aggregate { return Aggregate() } + self.kind = .aggregate { Aggregate() } } /// Calls sqlite3_create_function_v2 @@ -197,7 +207,9 @@ public final class DatabaseFunction: Hashable { var xFunc: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer?) -> Void)? { guard case .function = self else { return nil } return { (sqliteContext, argc, argv) in - let definition = Unmanaged.fromOpaque(sqlite3_user_data(sqliteContext)).takeUnretainedValue() + let definition = Unmanaged + .fromOpaque(sqlite3_user_data(sqliteContext)) + .takeUnretainedValue() do { try DatabaseFunction.report( result: definition.compute(argc, argv), @@ -262,11 +274,15 @@ public final class DatabaseFunction: Hashable { private static func unmanagedAggregateContext(_ sqliteContext: OpaquePointer?) -> Unmanaged { // The current aggregate buffer let stride = MemoryLayout>.stride - let aggregateContextBufferP = UnsafeMutableRawBufferPointer(start: sqlite3_aggregate_context(sqliteContext, Int32(stride))!, count: stride) + let aggregateContextBufferP = UnsafeMutableRawBufferPointer( + start: sqlite3_aggregate_context(sqliteContext, Int32(stride))!, + count: stride) if aggregateContextBufferP.contains(where: { $0 != 0 }) { // TODO: This testt looks weird. Review. // Buffer contains non-null pointer: load aggregate context - let aggregateContextP = aggregateContextBufferP.baseAddress!.assumingMemoryBound(to: Unmanaged.self) + let aggregateContextP = aggregateContextBufferP + .baseAddress! + .assumingMemoryBound(to: Unmanaged.self) return aggregateContextP.pointee } else { // Buffer contains null pointer: create aggregate context... diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 5d9eb114d..2fd86c81e 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -1,14 +1,14 @@ import Foundation import Dispatch #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif #if os(iOS) - import UIKit +import UIKit #endif /// A DatabasePool grants concurrent accesses to an SQLite database. @@ -79,7 +79,10 @@ public final class DatabasePool: DatabaseWriter { // opens a pool to an existing non-WAL database, and // attempts to read from it. // See https://github.com/groue/GRDB.swift/issues/102 - try db.execute(sql: "CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY); DROP TABLE grdb_issue_102;") + try db.execute(sql: """ + CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY); + DROP TABLE grdb_issue_102; + """) } } } @@ -87,8 +90,13 @@ public final class DatabasePool: DatabaseWriter { // Readers readerConfig = configuration readerConfig.readonly = true - readerConfig.defaultTransactionKind = .deferred // Make it the default for readers. Other transaction kinds are forbidden by SQLite in read-only connections. - readerConfig.allowsUnsafeTransactions = false // Because there's no guarantee that one can get the same reader in order to close its opened transaction. + // Readers use deferred transactions by default. + // Other transaction kinds are forbidden by SQLite in read-only connections. + readerConfig.defaultTransactionKind = .deferred + // Readers can't allow dangling transactions because there's no + // guarantee that one can get the same reader later in order to close + // an opened transaction. + readerConfig.allowsUnsafeTransactions = false var readerCount = 0 readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: { [unowned self] in readerCount += 1 // protected by pool's ReadWriteBox (undocumented behavior and protection) @@ -134,9 +142,9 @@ public final class DatabasePool: DatabaseWriter { } extension DatabasePool { - + // MARK: - WAL Checkpoints - + /// Runs a WAL checkpoint /// /// See https://www.sqlite.org/wal.html and @@ -158,9 +166,9 @@ extension DatabasePool { } extension DatabasePool { - + // MARK: - Memory management - + /// Free as much memory as possible. /// /// This method blocks the current thread until all database accesses are completed. @@ -195,7 +203,8 @@ extension DatabasePool { object: nil) } - @objc private func applicationDidEnterBackground(_ notification: NSNotification) { + @objc + private func applicationDidEnterBackground(_ notification: NSNotification) { guard let application = application else { return } @@ -213,7 +222,8 @@ extension DatabasePool { } } - @objc private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) { + @objc + private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) { DispatchQueue.global().async { self.releaseMemory() } @@ -222,24 +232,24 @@ extension DatabasePool { } #if SQLITE_HAS_CODEC - extension DatabasePool { - - // MARK: - Encryption - - /// Changes the passphrase of an encrypted database - public func change(passphrase: String) throws { - try readerPool.clear(andThen: { - try writer.sync { try $0.change(passphrase: passphrase) } - readerConfig.passphrase = passphrase - }) - } +extension DatabasePool { + + // MARK: - Encryption + + /// Changes the passphrase of an encrypted database + public func change(passphrase: String) throws { + try readerPool.clear(andThen: { + try writer.sync { try $0.change(passphrase: passphrase) } + readerConfig.passphrase = passphrase + }) } +} #endif -extension DatabasePool : DatabaseReader { +extension DatabasePool: DatabaseReader { // MARK: - Reading from Database - + /// Synchronously executes a read-only block in a protected dispatch queue, /// and returns its result. The block is wrapped in a deferred transaction. /// @@ -493,7 +503,7 @@ extension DatabasePool : DatabaseReader { asyncConcurrentRead(block) } #endif - + #if compiler(>=5.0) /// Asynchronously executes a read-only block in a protected dispatch queue. /// @@ -649,7 +659,11 @@ extension DatabasePool : DatabaseReader { /// - updates: The updates to the database. /// - throws: The error thrown by the updates, or by the /// wrapping transaction. - public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ updates: (Database) throws -> Database.TransactionCompletion) throws { + public func writeInTransaction( + _ kind: Database.TransactionKind? = nil, + _ updates: (Database) throws -> Database.TransactionCompletion) + throws + { try writer.sync { db in try db.inTransaction(kind) { try updates(db) @@ -811,7 +825,9 @@ extension DatabasePool { // Sanity check if writer.onValidQueue { writer.execute { db in - GRDBPrecondition(!db.isInsideTransaction, "makeSnapshot() must not be called from inside a transaction.") + GRDBPrecondition( + !db.isInsideTransaction, + "makeSnapshot() must not be called from inside a transaction.") } } diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index a4286bc20..791a2f132 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -71,9 +71,9 @@ public final class DatabaseQueue: DatabaseWriter { } extension DatabaseQueue { - + // MARK: - Memory management - + /// Free as much memory as possible. /// /// This method blocks the current thread until all database accesses are completed. @@ -106,7 +106,8 @@ extension DatabaseQueue { object: nil) } - @objc private func applicationDidEnterBackground(_ notification: NSNotification) { + @objc + private func applicationDidEnterBackground(_ notification: NSNotification) { guard let application = application else { return } @@ -124,7 +125,8 @@ extension DatabaseQueue { } } - @objc private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) { + @objc + private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) { DispatchQueue.global().async { self.releaseMemory() } @@ -133,15 +135,15 @@ extension DatabaseQueue { } #if SQLITE_HAS_CODEC - extension DatabaseQueue { - - // MARK: - Encryption - - /// Changes the passphrase of an encrypted database - public func change(passphrase: String) throws { - try writer.sync { try $0.change(passphrase: passphrase) } - } +extension DatabaseQueue { + + // MARK: - Encryption + + /// Changes the passphrase of an encrypted database + public func change(passphrase: String) throws { + try writer.sync { try $0.change(passphrase: passphrase) } } +} #endif extension DatabaseQueue { @@ -202,7 +204,7 @@ extension DatabaseQueue { } } #endif - + /// Synchronously executes a block in a protected dispatch queue, and /// returns its result. /// @@ -302,7 +304,11 @@ extension DatabaseQueue { /// - updates: The updates to the database. /// - throws: The error thrown by the updates, or by the /// wrapping transaction. - public func inTransaction(_ kind: Database.TransactionKind? = nil, _ updates: (Database) throws -> Database.TransactionCompletion) throws { + public func inTransaction( + _ kind: Database.TransactionKind? = nil, + _ updates: (Database) throws -> Database.TransactionCompletion) + throws + { try writer.sync { db in try db.inTransaction(kind) { try updates(db) @@ -323,7 +329,7 @@ extension DatabaseQueue { public func writeWithoutTransaction(_ 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/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index f9a9fd664..ffad142a8 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -1,9 +1,9 @@ #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// The protocol for all types that can fetch values from a database. @@ -21,7 +21,7 @@ /// connection to the database. Should you have to cope with external /// connections, protect yourself with transactions, and be ready to setup a /// [busy handler](https://www.sqlite.org/c3ref/busy_handler.html). -public protocol DatabaseReader : class { +public protocol DatabaseReader: AnyObject { /// The database configuration var configuration: Configuration { get } @@ -220,10 +220,14 @@ extension DatabaseReader { try backup(to: writer, afterBackupInit: nil, afterBackupStep: nil) } - func backup(to writer: DatabaseWriter, afterBackupInit: (() -> ())?, afterBackupStep: (() -> ())?) throws { + func backup(to writer: DatabaseWriter, afterBackupInit: (() -> Void)?, afterBackupStep: (() -> Void)?) throws { try read { dbFrom in try writer.writeWithoutTransaction { dbDest in - try Database.backup(from: dbFrom, to: dbDest, afterBackupInit: afterBackupInit, afterBackupStep: afterBackupStep) + try Database.backup( + from: dbFrom, + to: dbDest, + afterBackupInit: afterBackupInit, + afterBackupStep: afterBackupStep) } } } @@ -233,7 +237,7 @@ extension DatabaseReader { /// /// Instances of AnyDatabaseReader forward their methods to an arbitrary /// underlying database reader. -public final class AnyDatabaseReader : DatabaseReader { +public final class AnyDatabaseReader: DatabaseReader { private let base: DatabaseReader /// Creates a database reader that wraps a base database reader. diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 7df10aa59..c754ca697 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -31,6 +31,7 @@ /// let region = try request.databaseRegion(db) public struct DatabaseRegion: CustomStringConvertible, Equatable { private let tableRegions: [String: TableRegion]? + private init(tableRegions: [String: TableRegion]?) { self.tableRegions = tableRegions } @@ -125,9 +126,9 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable { switch (tableRegion, otherTableRegion) { case (nil, nil): preconditionFailure() - case (nil, let tableRegion?), (let tableRegion?, nil): + case let (nil, tableRegion?), let (tableRegion?, nil): tableRegionUnion = tableRegion - case (let tableRegion?, let otherTableRegion?): + case let (tableRegion?, otherTableRegion?): tableRegionUnion = tableRegion.union(otherTableRegion) } tableRegionsUnion[table] = tableRegionUnion @@ -184,7 +185,10 @@ extension DatabaseRegion { // Slow path when several tables are observed. guard let tableRegion = tableRegions[event.tableName] else { // Shouldn't happen if the precondition is met. - fatalError("precondition failure: event was not filtered out in observes(eventsOfKind:) by region.isModified(byEventsOfKind:)") + fatalError(""" + precondition failure: event was not filtered out in observes(eventsOfKind:) \ + by region.isModified(byEventsOfKind:) + """) } return tableRegion.contains(rowID: event.rowID) } @@ -198,16 +202,14 @@ extension DatabaseRegion { switch (lhs.tableRegions, rhs.tableRegions) { case (nil, nil): return true - case (let ltableRegions?, let rtableRegions?): + case let (ltableRegions?, rtableRegions?): let ltableNames = Set(ltableRegions.keys) let rtableNames = Set(rtableRegions.keys) guard ltableNames == rtableNames else { return false } - for tableName in ltableNames { - if ltableRegions[tableName]! != rtableRegions[tableName]! { - return false - } + for tableName in ltableNames where ltableRegions[tableName]! != rtableRegions[tableName]! { + return false } return true default: @@ -257,17 +259,17 @@ private struct TableRegion: Equatable { func intersection(_ other: TableRegion) -> TableRegion { let columnsIntersection: Set? switch (self.columns, other.columns) { - case (nil, let columns), (let columns, nil): + case let (nil, columns), let (columns, nil): columnsIntersection = columns - case (let columns?, let other?): + case let (columns?, other?): columnsIntersection = columns.intersection(other) } let rowIdsIntersection: Set? switch (self.rowIds, other.rowIds) { - case (nil, let rowIds), (let rowIds, nil): + case let (nil, rowIds), let (rowIds, nil): rowIdsIntersection = rowIds - case (let rowIds?, let other?): + case let (rowIds?, other?): rowIdsIntersection = rowIds.intersection(other) } @@ -279,7 +281,7 @@ private struct TableRegion: Equatable { switch (self.columns, other.columns) { case (nil, _), (_, nil): columnsUnion = nil - case (let columns?, let other?): + case let (columns?, other?): columnsUnion = columns.union(other) } @@ -287,7 +289,7 @@ private struct TableRegion: Equatable { switch (self.rowIds, other.rowIds) { case (nil, _), (_, nil): rowIdsUnion = nil - case (let rowIds?, let other?): + case let (rowIds?, other?): rowIdsUnion = rowIds.union(other) } diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index a55fd2b3f..847525b53 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -18,7 +18,7 @@ public struct DatabaseRegionObservation { /// A closure that is evaluated when the observation starts, and returns /// the observed database region. var observedRegion: (Database) throws -> DatabaseRegion - + // Not public because we foster DatabaseRegionConvertible. init(tracking region: @escaping (Database) throws -> DatabaseRegion) { self.observedRegion = { db in @@ -87,7 +87,11 @@ extension DatabaseRegionObservation { /// - parameter onChange: A closure that is provided a database connection /// with write access each time the observed region has been modified. /// - returns: a TransactionObserver - public func start(in dbWriter: DatabaseWriter, onChange: @escaping (Database) -> Void) throws -> TransactionObserver { + public func start( + in dbWriter: DatabaseWriter, + onChange: @escaping (Database) -> Void) + throws -> TransactionObserver + { // Use unsafeReentrantWrite so that observation can start from any // dispatch queue. return try dbWriter.unsafeReentrantWrite { db -> TransactionObserver in @@ -123,7 +127,7 @@ private class DatabaseRegionObserver: TransactionObserver { func databaseDidCommit(_ db: Database) { guard isChanged else { return } isChanged = false - + onChange(db) } diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 6cef0ca48..094423cf2 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -6,7 +6,7 @@ import Dispatch /// See DatabasePool.makeSnapshot() /// /// For more information, read about "snapshot isolation" at https://sqlite.org/isolation.html -public class DatabaseSnapshot : DatabaseReader { +public class DatabaseSnapshot: DatabaseReader { private var serializedDatabase: SerializedDatabase /// The database configuration diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index b4b84dfc2..aee43d0f6 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -1,10 +1,10 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif // MARK: - DatabaseValue @@ -20,7 +20,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon public static let null = DatabaseValue(storage: .null) /// An SQLite storage (NULL, INTEGER, REAL, TEXT, BLOB). - public enum Storage : Equatable { + public enum Storage: Equatable { /// The NULL storage class. case null @@ -60,10 +60,10 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon public static func == (_ lhs: Storage, _ rhs: Storage) -> Bool { switch (lhs, rhs) { case (.null, .null): return true - case (.int64(let lhs), .int64(let rhs)): return lhs == rhs - case (.double(let lhs), .double(let rhs)): return lhs == rhs - case (.string(let lhs), .string(let rhs)): return lhs == rhs - case (.blob(let lhs), .blob(let rhs)): return lhs == rhs + case let (.int64(lhs), .int64(rhs)): return lhs == rhs + case let (.double(lhs), .double(rhs)): return lhs == rhs + case let (.string(lhs), .string(rhs)): return lhs == rhs + case let (.blob(lhs), .blob(rhs)): return lhs == rhs default: return false } } @@ -120,7 +120,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon fatalError("Unexpected SQLite value type: \(type)") } } - + /// Returns a DatabaseValue initialized from a raw SQLite statement pointer. init(sqliteStatement: SQLiteStatement, index: Int32) { switch sqlite3_column_type(sqliteStatement, index) { @@ -187,17 +187,17 @@ extension DatabaseValue { switch (lhs.storage, rhs.storage) { case (.null, .null): return true - case (.int64(let lhs), .int64(let rhs)): + case let (.int64(lhs), .int64(rhs)): return lhs == rhs - case (.double(let lhs), .double(let rhs)): + case let (.double(lhs), .double(rhs)): return lhs == rhs - case (.int64(let lhs), .double(let rhs)): + case let (.int64(lhs), .double(rhs)): return Int64(exactly: rhs) == lhs - case (.double(let lhs), .int64(let rhs)): + case let (.double(lhs), .int64(rhs)): return rhs == Int64(exactly: lhs) - case (.string(let lhs), .string(let rhs)): + case let (.string(lhs), .string(rhs)): return lhs == rhs - case (.blob(let lhs), .blob(let rhs)): + case let (.blob(lhs), .blob(rhs)): return lhs == rhs default: return false @@ -266,8 +266,10 @@ extension DatabaseValue { case .blob: // We can't assume all blobs are true, and return false: // - // SELECT NOT X'31' -- 0 (because X'31' is turned into the string '1', then into integer 1, which is negated into 0) - // SELECT NOT X'30' -- 1 (because X'30' is turned into the string '0', then into integer 0, which is negated into 1) + // SELECT NOT X'31' -- 0 (because X'31' is turned into the string '1', + // then into integer 1, which is negated into 0) + // SELECT NOT X'30' -- 1 (because X'30' is turned into the string '0', + // then into integer 0, which is negated into 1) return SQLExpressionNot(self) } } @@ -309,17 +311,17 @@ extension DatabaseValue { /// easier testing. func < (lhs: DatabaseValue, rhs: DatabaseValue) -> Bool { switch (lhs.storage, rhs.storage) { - case (.int64(let lhs), .int64(let rhs)): + case let (.int64(lhs), .int64(rhs)): return lhs < rhs - case (.double(let lhs), .double(let rhs)): + case let (.double(lhs), .double(rhs)): return lhs < rhs - case (.int64(let lhs), .double(let rhs)): + case let (.int64(lhs), .double(rhs)): return Double(lhs) < rhs - case (.double(let lhs), .int64(let rhs)): + case let (.double(lhs), .int64(rhs)): return lhs < Double(rhs) - case (.string(let lhs), .string(let rhs)): + case let (.string(lhs), .string(rhs)): return lhs.utf8.lexicographicallyPrecedes(rhs.utf8) - case (.blob(let lhs), .blob(let rhs)): + case let (.blob(lhs), .blob(rhs)): return lhs.lexicographicallyPrecedes(rhs, by: <) case (.blob, _): return false diff --git a/GRDB/Core/DatabaseValueConversion.swift b/GRDB/Core/DatabaseValueConversion.swift index a752e34e5..ca59df531 100644 --- a/GRDB/Core/DatabaseValueConversion.swift +++ b/GRDB/Core/DatabaseValueConversion.swift @@ -1,9 +1,9 @@ #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif // MARK: - Conversion Context and Errors @@ -14,6 +14,7 @@ struct ValueConversionContext { case columnIndex(Int) case columnName(String) } + var row: Row? var sql: String? var arguments: StatementArguments? @@ -89,7 +90,12 @@ extension ValueConversionContext { /// The canonical conversion error message /// /// - parameter dbValue: nil means "missing column" -func conversionErrorMessage(to: T.Type, from dbValue: DatabaseValue?, conversionContext: ValueConversionContext?) -> String { +func conversionErrorMessage( + to: T.Type, + from dbValue: DatabaseValue?, + conversionContext: ValueConversionContext?) + -> String +{ var message: String var extras: [String] = [] @@ -128,12 +134,33 @@ func conversionErrorMessage(to: T.Type, from dbValue: DatabaseValue?, convers /// The canonical conversion fatal error /// /// - parameter dbValue: nil means "missing column", for consistency with (row["missing"] as DatabaseValue? == nil) -func fatalConversionError(to: T.Type, from dbValue: DatabaseValue?, conversionContext: ValueConversionContext?, file: StaticString = #file, line: UInt = #line) -> Never { - fatalError(conversionErrorMessage(to: T.self, from: dbValue, conversionContext: conversionContext), file: file, line: line) +func fatalConversionError( + to: T.Type, + from dbValue: DatabaseValue?, + conversionContext: ValueConversionContext?, + file: StaticString = #file, + line: UInt = #line) + -> Never +{ + fatalError( + conversionErrorMessage( + to: T.self, + from: dbValue, + conversionContext: conversionContext), + file: file, + line: line) } @usableFromInline -func fatalConversionError(to: T.Type, from dbValue: DatabaseValue?, in row: Row, atColumn columnName: String, file: StaticString = #file, line: UInt = #line) -> Never { +func fatalConversionError( + to: T.Type, + from dbValue: DatabaseValue?, + in row: Row, + atColumn columnName: String, + file: StaticString = #file, + line: UInt = #line) + -> Never +{ fatalConversionError( to: T.self, from: dbValue, @@ -141,7 +168,14 @@ func fatalConversionError(to: T.Type, from dbValue: DatabaseValue?, in row: R } @usableFromInline -func fatalConversionError(to: T.Type, sqliteStatement: SQLiteStatement, index: Int32, file: StaticString = #file, line: UInt = #line) -> Never { +func fatalConversionError( + to: T.Type, + sqliteStatement: SQLiteStatement, + index: Int32, + file: StaticString = #file, + line: UInt = #line) + -> Never +{ let row = Row(sqliteStatement: sqliteStatement) fatalConversionError( to: T.self, @@ -150,7 +184,15 @@ func fatalConversionError(to: T.Type, sqliteStatement: SQLiteStatement, index } @usableFromInline -func fatalConversionError(to: T.Type, from dbValue: DatabaseValue?, sqliteStatement: SQLiteStatement, index: Int32, file: StaticString = #file, line: UInt = #line) -> Never { +func fatalConversionError( + to: T.Type, + from dbValue: DatabaseValue?, + sqliteStatement: SQLiteStatement, + index: Int32, + file: StaticString = #file, + line: UInt = #line) + -> Never +{ let row = Row(sqliteStatement: sqliteStatement) fatalConversionError( to: T.self, @@ -172,7 +214,11 @@ extension DatabaseValueConvertible { } } - static func decode(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Self { + static func decode( + from dbValue: DatabaseValue, + conversionContext: @autoclosure () -> ValueConversionContext?) + -> Self + { if let value = fromDatabaseValue(dbValue) { return value } else { @@ -198,8 +244,12 @@ extension DatabaseValueConvertible { fatalConversionError(to: Self.self, from: dbValue, sqliteStatement: sqliteStatement, index: index) } } - - static func decodeIfPresent(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Self? { + + static func decodeIfPresent( + from dbValue: DatabaseValue, + conversionContext: @autoclosure () -> ValueConversionContext?) + -> Self? + { // Use fromDatabaseValue before checking for null: this allows DatabaseValue to convert NULL to .null. if let value = fromDatabaseValue(dbValue) { return value @@ -258,12 +308,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { // Support for @inlinable decoding extension Row { @usableFromInline - func fastDecode(_ type: Value.Type, atUncheckedIndex index: Int) -> Value { + func fastDecode( + _ type: Value.Type, + atUncheckedIndex index: Int) + -> Value + { return impl.fastDecode(type, atUncheckedIndex: index) } @usableFromInline - func fastDecodeIfPresent(_ type: Value.Type, atUncheckedIndex index: Int) -> Value? { + func fastDecodeIfPresent( + _ type: Value.Type, + atUncheckedIndex index: Int) + -> Value? + { return impl.fastDecodeIfPresent(type, atUncheckedIndex: index) } } diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 30cc1753f..936b1da73 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -1,9 +1,9 @@ #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif // MARK: - DatabaseValueConvertible @@ -24,7 +24,7 @@ /// try String.fetchOne(statement, arguments:...) // String? /// /// DatabaseValueConvertible is adopted by Bool, Int, String, etc. -public protocol DatabaseValueConvertible : SQLExpressible { +public protocol DatabaseValueConvertible: SQLExpressible { /// Returns a value that can be stored in the database. var databaseValue: DatabaseValue { get } @@ -49,7 +49,7 @@ extension DatabaseValueConvertible { /// print(url) /// } /// } -public final class DatabaseValueCursor : Cursor { +public final class DatabaseValueCursor: Cursor { @usableFromInline let _statement: SelectStatement @usableFromInline let _sqliteStatement: SQLiteStatement @usableFromInline let _columnIndex: Int32 @@ -102,12 +102,12 @@ public final class DatabaseValueCursor : Cursor /// print(url) /// } /// } -public final class NullableDatabaseValueCursor : Cursor { +public final class NullableDatabaseValueCursor: Cursor { @usableFromInline let _statement: SelectStatement @usableFromInline let _sqliteStatement: SQLiteStatement @usableFromInline let _columnIndex: Int32 @usableFromInline var _done = false - + init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { _statement = statement _sqliteStatement = statement.sqliteStatement @@ -182,7 +182,12 @@ extension DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor { + public static func fetchCursor( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> DatabaseValueCursor + { return try DatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) } @@ -197,7 +202,12 @@ extension DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: An array. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { + public static func fetchAll( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Self] + { return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } @@ -215,7 +225,12 @@ extension DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { + public static func fetchOne( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> Self? + { // fetchOne returns nil if there is no row, or if there is a row with a null value let cursor = try NullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) return try cursor.next() ?? nil @@ -223,7 +238,7 @@ extension DatabaseValueConvertible { } extension DatabaseValueConvertible { - + // MARK: Fetching From SQL /// Returns a cursor over values fetched from an SQL query. @@ -245,7 +260,13 @@ extension DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DatabaseValueCursor { + public static func fetchCursor( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> DatabaseValueCursor + { return try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -260,7 +281,13 @@ extension DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: An array. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self] { + public static func fetchAll( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> [Self] + { return try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -278,7 +305,13 @@ extension DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self? { + public static func fetchOne( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> Self? + { return try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } } @@ -430,7 +463,12 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor { + public static func fetchCursor( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> NullableDatabaseValueCursor + { return try NullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) } @@ -445,7 +483,12 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: An array of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] { + public static func fetchAll( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Wrapped?] + { return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } } @@ -473,7 +516,13 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor { + public static func fetchCursor( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> NullableDatabaseValueCursor + { return try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -488,7 +537,13 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// - adapter: Optional RowAdapter /// - returns: An array of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Wrapped?] { + public static func fetchAll( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> [Wrapped?] + { return try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } } @@ -515,7 +570,9 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// - request: A FetchRequest. /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: R) throws -> NullableDatabaseValueCursor { + public static func fetchCursor(_ db: Database, _ request: R) + throws -> NullableDatabaseValueCursor + { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchCursor(request.statement, adapter: request.adapter) } @@ -572,4 +629,3 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: return try Optional.fetchAll(db, self) } } - diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 1dbc6c740..20da6b446 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -15,10 +15,10 @@ import Dispatch /// connection to the database. Should you have to cope with external /// connections, protect yourself with transactions, and be ready to setup a /// [busy handler](https://www.sqlite.org/c3ref/busy_handler.html). -public protocol DatabaseWriter : DatabaseReader { +public protocol DatabaseWriter: DatabaseReader { // MARK: - Writing in Database - + /// Synchronously executes database updates in a protected dispatch queue, /// wrapped inside a transaction, and returns the result. /// @@ -76,16 +76,18 @@ public protocol DatabaseWriter : DatabaseReader { /// - parameter completion: A closure that is called with the eventual /// transaction error. /// - throws: The error thrown by the updates, or by the wrapping transaction. - func asyncWrite(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result) -> Void) + func asyncWrite( + _ updates: @escaping (Database) throws -> T, + completion: @escaping (Database, Result) -> Void) #endif - + /// Asynchronously executes database updates in a protected dispatch queue, /// outside of any transaction. /// /// Eventual concurrent reads may see partial updates unless you wrap them /// in a transaction. func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) - + /// Synchronously executes database updates in a protected dispatch queue, /// outside of any transaction, and returns the result. /// @@ -98,7 +100,7 @@ public protocol DatabaseWriter : DatabaseReader { /// This method is reentrant. It should be avoided because it fosters /// dangerous concurrency practices. func unsafeReentrantWrite(_ updates: (Database) throws -> T) rethrows -> T - + // MARK: - Reading from Database /// Concurrently executes a read-only block in a protected dispatch queue. @@ -175,7 +177,7 @@ public protocol DatabaseWriter : DatabaseReader { } extension DatabaseWriter { - + /// Synchronously executes database updates in a protected dispatch queue, /// wrapped inside a transaction, and returns the result. /// @@ -228,7 +230,10 @@ extension DatabaseWriter { /// - parameter completion: A closure that is called with the eventual /// transaction error. /// - throws: The error thrown by the updates, or by the wrapping transaction. - public func asyncWrite(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result) -> Void) { + public func asyncWrite( + _ updates: @escaping (Database) throws -> T, + completion: @escaping (Database, Result) -> Void) + { asyncWriteWithoutTransaction { db in do { var result: T? @@ -255,7 +260,10 @@ extension DatabaseWriter { /// - parameter extent: The duration of the observation. The default is /// the observer lifetime (observation lasts until observer /// is deallocated). - public func add(transactionObserver: TransactionObserver, extent: Database.TransactionObservationExtent = .observerLifetime) { + public func add( + transactionObserver: TransactionObserver, + extent: Database.TransactionObservationExtent = .observerLifetime) + { writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) } } @@ -273,7 +281,8 @@ extension DatabaseWriter { /// 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 + // 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 @@ -285,7 +294,8 @@ extension DatabaseWriter { // Remove all database objects, one after the other do { try db.inTransaction { - while let row = try Row.fetchOne(db, sql: "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'") { + 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)") @@ -545,7 +555,7 @@ public class DatabaseFuture { /// /// Instances of AnyDatabaseWriter forward their methods to an arbitrary /// underlying database writer. -public final class AnyDatabaseWriter : DatabaseWriter { +public final class AnyDatabaseWriter: DatabaseWriter { private let base: DatabaseWriter /// Creates a database writer that wraps a base database writer. @@ -608,7 +618,10 @@ public final class AnyDatabaseWriter : DatabaseWriter { #if compiler(>=5.0) /// :nodoc: - public func asyncWrite(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result) -> Void) { + public func asyncWrite( + _ updates: @escaping (Database) throws -> T, + completion: @escaping (Database, Result) -> Void) + { base.asyncWrite(updates, completion: completion) } #endif @@ -617,12 +630,12 @@ public final class AnyDatabaseWriter : DatabaseWriter { public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { base.asyncWriteWithoutTransaction(updates) } - + /// :nodoc: public func unsafeReentrantWrite(_ updates: (Database) throws -> T) rethrows -> T { return try base.unsafeReentrantWrite(updates) } - + // MARK: - Functions /// :nodoc: diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index d0abb0e6a..02a7925d2 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -23,7 +23,7 @@ public struct PreparedRequest { { self.init(statement: statement, adapter: adapter, supplementaryFetch: nil) } - + init( statement: SelectStatement, adapter: RowAdapter?, @@ -62,7 +62,7 @@ public protocol FetchRequest: DatabaseRegionConvertible { /// prepared statement. /// - returns: A prepared statement and an eventual row adapter. func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) - + /// Returns a PreparedRequest that is ready to be executed. /// /// - parameter db: A database connection. @@ -86,7 +86,7 @@ public protocol FetchRequest: DatabaseRegionConvertible { } extension FetchRequest { - + /// Returns an adapted request. public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest { return AdaptedFetchRequest(self, adapter) @@ -134,7 +134,7 @@ extension FetchRequest { // MARK: - AdaptedFetchRequest /// An adapted request. -public struct AdaptedFetchRequest : FetchRequest { +public struct AdaptedFetchRequest: FetchRequest { public typealias RowDecoder = Base.RowDecoder private let base: Base @@ -175,7 +175,7 @@ public struct AdaptedFetchRequest : FetchRequest { /// /// An AnyFetchRequest forwards its operations to an underlying request, /// hiding its specifics. -public struct AnyFetchRequest : FetchRequest { +public struct AnyFetchRequest: FetchRequest { public typealias RowDecoder = T private let _preparedRequest: (Database, _ singleResult: Bool) throws -> PreparedRequest diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 28734b9e9..14e900892 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -1,14 +1,17 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// A database row. -public final class Row : Equatable, Hashable, RandomAccessCollection, ExpressibleByDictionaryLiteral, CustomStringConvertible, CustomDebugStringConvertible { +public final class Row: Equatable, Hashable, RandomAccessCollection, + ExpressibleByDictionaryLiteral, CustomStringConvertible, + CustomDebugStringConvertible +{ // It is not a violation of the Demeter law when another type uses this // property, which is exposed for optimizations. let impl: RowImpl @@ -45,7 +48,7 @@ public final class Row : Equatable, Hashable, RandomAccessCollection, Expressibl /// let bookRows = row.prefetchedRows["books"] /// print(bookRows[0]) /// // Prints [id:42 title:"Moby-Dick"] - public internal(set) var prefetchedRows: PrefetchedRowsView = PrefetchedRowsView() + public internal(set) var prefetchedRows = PrefetchedRowsView() // MARK: - Building rows @@ -126,8 +129,13 @@ public final class Row : Equatable, Hashable, RandomAccessCollection, Expressibl /// The row is implemented on top of StatementCopyRowImpl, which *copies* /// the values from the SQLite statement so that further iteration of the /// statement does not modify the row. - convenience init(copiedFromSQLiteStatement sqliteStatement: SQLiteStatement, statementRef: Unmanaged) { - self.init(impl: StatementCopyRowImpl(sqliteStatement: sqliteStatement, columnNames: statementRef.takeUnretainedValue().columnNames)) + convenience init( + copiedFromSQLiteStatement sqliteStatement: SQLiteStatement, + statementRef: Unmanaged) + { + self.init(impl: StatementCopyRowImpl( + sqliteStatement: sqliteStatement, + columnNames: statementRef.takeUnretainedValue().columnNames)) } init(impl: RowImpl) { @@ -139,7 +147,7 @@ public final class Row : Equatable, Hashable, RandomAccessCollection, Expressibl } extension Row { - + // MARK: - Columns /// The names of columns in the row. @@ -416,7 +424,12 @@ extension Row { /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions /// (see https://www.sqlite.org/datatype3.html). @inlinable - public subscript(_ column: Column) -> Value? { + public subscript(_ column: Column) + -> Value? + where + Value: DatabaseValueConvertible & StatementColumnConvertible, + Column: ColumnExpression + { return self[column.name] } @@ -448,7 +461,10 @@ extension Row { /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions /// (see https://www.sqlite.org/datatype3.html). @inlinable - public subscript(_ column: Column) -> Value { + public subscript(_ column: Column) + -> Value + where Value: DatabaseValueConvertible & StatementColumnConvertible, Column: ColumnExpression + { return self[column.name] } @@ -565,7 +581,7 @@ extension Row { } return Record(row: scopedRow) } - + /// Returns the eventual record associated with the given scope. /// /// For example: @@ -761,7 +777,7 @@ extension Row { /// try dbQueue.read { db in /// let rows: RowCursor = try Row.fetchCursor(db, sql: "SELECT * FROM player") /// } -public final class RowCursor : Cursor { +public final class RowCursor: Cursor { public let statement: SelectStatement @usableFromInline let _sqliteStatement: SQLiteStatement @usableFromInline let _row: Row // Reused for performance @@ -833,7 +849,12 @@ extension Row { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor { + public static func fetchCursor( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> RowCursor + { return try RowCursor(statement: statement, arguments: arguments, adapter: adapter) } @@ -848,7 +869,12 @@ extension Row { /// - adapter: Optional RowAdapter /// - returns: An array of rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row] { + public static func fetchAll( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Row] + { // The cursor reuses a single mutable row. Return immutable copies. return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter).map { $0.copy() }) } @@ -864,7 +890,12 @@ extension Row { /// - adapter: Optional RowAdapter /// - returns: An optional row. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? { + public static func fetchOne( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> Row? + { let cursor = try fetchCursor(statement, arguments: arguments, adapter: adapter) // Keep cursor alive until we can copy the fetched row return try withExtendedLifetime(cursor) { @@ -905,7 +936,13 @@ extension Row { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RowCursor { + public static func fetchCursor( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> RowCursor + { return try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -924,7 +961,13 @@ extension Row { /// - adapter: Optional RowAdapter /// - returns: An array of rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Row] { + public static func fetchAll( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> [Row] + { return try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -943,7 +986,13 @@ extension Row { /// - adapter: Optional RowAdapter /// - returns: An optional row. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Row? { + public static func fetchOne( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> Row? + { return try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } } @@ -1079,7 +1128,7 @@ extension FetchRequest where RowDecoder == Row { return try Row.fetchOne(db, self) } } - + // ExpressibleByDictionaryLiteral extension Row { @@ -1198,7 +1247,7 @@ extension Row { if level == 0 && self == self.unadapted && prefetchedRows.prefetches.isEmpty { return description } - let prefix = repeatElement(" ", count: level + 1).joined(separator: "") + let prefix = repeatElement(" ", count: level + 1).joined() var str = "" if level == 0 { str = "▿ " + description @@ -1234,7 +1283,7 @@ extension Row { // MARK: - RowIndex /// Indexes to (ColumnName, DatabaseValue) pairs in a database row. -public struct RowIndex : Comparable, Strideable { +public struct RowIndex: Comparable, Strideable { let index: Int init(_ index: Int) { self.index = index } } @@ -1386,7 +1435,7 @@ extension Row { } return names } - + /// Returns the row associated with the given scope. /// /// For example: @@ -1461,7 +1510,7 @@ extension Row { public var isEmpty: Bool { return prefetches.isEmpty } - + /// The keys for available prefetched rows /// /// For example: @@ -1483,7 +1532,7 @@ extension Row { } return result } - + /// Returns the prefetched rows associated with the given key. /// /// For example: @@ -1538,13 +1587,20 @@ extension OrderedDictionary where Key == String, Value == Row.Prefetch { protocol RowImpl { var count: Int { get } var isFetched: Bool { get } + func scopes(prefetchedRows: Row.PrefetchedRowsView) -> Row.ScopesView func columnName(atUncheckedIndex index: Int) -> String - func hasNull(atUncheckedIndex index:Int) -> Bool + func hasNull(atUncheckedIndex index: Int) -> Bool func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue - func fastDecode(_ type: Value.Type, atUncheckedIndex index: Int) -> Value - func fastDecodeIfPresent(_ type: Value.Type, atUncheckedIndex index: Int) -> Value? - func dataNoCopy(atUncheckedIndex index:Int) -> Data? + func fastDecode( + _ type: Value.Type, + atUncheckedIndex index: Int) + -> Value + func fastDecodeIfPresent( + _ type: Value.Type, + atUncheckedIndex index: Int) + -> Value? + func dataNoCopy(atUncheckedIndex index: Int) -> Data? /// Returns the index of the leftmost column that matches *name* (case-insensitive) func index(ofColumn name: String) -> Int? @@ -1558,7 +1614,7 @@ protocol RowImpl { extension RowImpl { func copiedRow(_ row: Row) -> Row { // unless customized, assume unsafe and unadapted row - return Row(impl: ArrayRowImpl(columns: row.map { $0 })) + return Row(impl: ArrayRowImpl(columns: Array(row))) } func unscopedRow(_ row: Row) -> Row { @@ -1576,7 +1632,7 @@ extension RowImpl { return Row.ScopesView() } - func hasNull(atUncheckedIndex index:Int) -> Bool { + func hasNull(atUncheckedIndex index: Int) -> Bool { // unless customized, use slow check (see StatementRowImpl and AdaptedRowImpl for customization) return databaseValue(atUncheckedIndex: index).isNull } @@ -1601,7 +1657,7 @@ extension RowImpl { conversionContext: ValueConversionContext(Row(impl: self)).atColumn(index)) } - func dataNoCopy(atUncheckedIndex index:Int) -> Data? { + func dataNoCopy(atUncheckedIndex index: Int) -> Data? { // unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization) return Data.decodeIfPresent( from: databaseValue(atUncheckedIndex: index), @@ -1611,7 +1667,7 @@ extension RowImpl { // TODO: merge with StatementCopyRowImpl eventually? /// See Row.init(dictionary:) -private struct ArrayRowImpl : RowImpl { +private struct ArrayRowImpl: RowImpl { let columns: [(String, DatabaseValue)] init(columns: [(String, DatabaseValue)]) { @@ -1647,13 +1703,16 @@ private struct ArrayRowImpl : RowImpl { // TODO: merge with ArrayRowImpl eventually? /// See Row.init(copiedFromStatementRef:sqliteStatement:) -private struct StatementCopyRowImpl : RowImpl { +private struct StatementCopyRowImpl: RowImpl { let dbValues: ContiguousArray let columnNames: [String] init(sqliteStatement: SQLiteStatement, columnNames: [String]) { let sqliteStatement = sqliteStatement - self.dbValues = ContiguousArray((0.. let sqliteStatement: SQLiteStatement let lowercaseColumnIndexes: [String: Int] @@ -1694,7 +1753,8 @@ private struct StatementRowImpl : RowImpl { self.statementRef = statementRef self.sqliteStatement = sqliteStatement // Optimize row[columnName] - let lowercaseColumnNames = (0.. Bool { + func hasNull(atUncheckedIndex index: Int) -> Bool { // Avoid extracting values, because this modifies the SQLite statement. return sqlite3_column_type(sqliteStatement, Int32(index)) == SQLITE_NULL } - func dataNoCopy(atUncheckedIndex index:Int) -> Data? { + func dataNoCopy(atUncheckedIndex index: Int) -> Data? { guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else { return nil } @@ -1761,7 +1821,7 @@ private struct StatementRowImpl : RowImpl { } // This one is not optimized at all, since it is only used in fatal conversion errors, so far -private struct SQLiteStatementRowImpl : RowImpl { +private struct SQLiteStatementRowImpl: RowImpl { let sqliteStatement: SQLiteStatement var count: Int { return Int(sqlite3_column_count(sqliteStatement)) } var isFetched: Bool { return true } @@ -1784,7 +1844,7 @@ private struct SQLiteStatementRowImpl : RowImpl { } /// See Row.init() -private struct EmptyRowImpl : RowImpl { +private struct EmptyRowImpl: RowImpl { var count: Int { return 0 } diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index b9ab95c8c..87662cd31 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -100,7 +100,7 @@ public struct LayoutedColumnMapping { /// LayoutedColumnMapping adopts LayoutedRowAdapter /// /// :nodoc: -extension LayoutedColumnMapping : LayoutedRowAdapter { +extension LayoutedColumnMapping: LayoutedRowAdapter { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Returns self. @@ -117,7 +117,7 @@ extension LayoutedColumnMapping : LayoutedRowAdapter { } /// :nodoc: -extension LayoutedColumnMapping : RowLayout { +extension LayoutedColumnMapping: RowLayout { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Returns the index of the leftmost column named `name`, in a @@ -171,7 +171,7 @@ public protocol RowLayout { func layoutIndex(ofColumn name: String) -> Int? } -extension SelectStatement : RowLayout { +extension SelectStatement: RowLayout { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public var layoutColumns: [(Int, String)] { @@ -270,7 +270,7 @@ public struct EmptyRowAdapter: RowAdapter { /// /// // [foo:"bar"] /// try Row.fetchOne(db, sql: sql, adapter: adapter) -public struct ColumnMapping : RowAdapter { +public struct ColumnMapping: RowAdapter { /// A dictionary from mapped column names to column names in a base row. let mapping: [String: String] @@ -287,7 +287,12 @@ public struct ColumnMapping : RowAdapter { .map { (mappedColumn, baseColumn) -> (Int, String) in guard let index = layout.layoutIndex(ofColumn: baseColumn) else { let columnNames = layout.layoutColumns.map { $0.1 } - throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Mapping references missing column \(baseColumn). Valid column names are: \(columnNames.joined(separator: ", ")).") + throw DatabaseError( + resultCode: .SQLITE_MISUSE, + message: """ + Mapping references missing column \(baseColumn). \ + Valid column names are: \(columnNames.joined(separator: ", ")). + """) } let baseIndex = layout.layoutColumns[index].0 return (baseIndex, mappedColumn) @@ -304,7 +309,7 @@ public struct ColumnMapping : RowAdapter { /// /// // [baz:3] /// try Row.fetchOne(db, sql: sql, adapter: adapter) -public struct SuffixRowAdapter : RowAdapter { +public struct SuffixRowAdapter: RowAdapter { /// The suffix index let index: Int @@ -331,7 +336,7 @@ public struct SuffixRowAdapter : RowAdapter { /// /// // [bar:2 baz:3] /// try Row.fetchOne(db, sql: sql, adapter: adapter) -public struct RangeRowAdapter : RowAdapter { +public struct RangeRowAdapter: RowAdapter { /// The range let range: CountableRange @@ -376,7 +381,7 @@ public struct RangeRowAdapter : RowAdapter { /// if let barRow = row.scopes["bar"] { /// barRow["value"] // "bar" /// } -public struct ScopeAdapter : RowAdapter { +public struct ScopeAdapter: RowAdapter { /// The base adapter let base: RowAdapter @@ -439,15 +444,15 @@ public struct ScopeAdapter : RowAdapter { } /// The LayoutedRowAdapter for ScopeAdapter -struct LayoutedScopeAdapter : LayoutedRowAdapter { +struct LayoutedScopeAdapter: LayoutedRowAdapter { let mapping: LayoutedColumnMapping let scopes: [String: LayoutedRowAdapter] } -struct ChainedAdapter : RowAdapter { +struct ChainedAdapter: RowAdapter { let first: RowAdapter let second: RowAdapter - + func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { return try second.layoutedAdapter(from: first.layoutedAdapter(from: layout).mapping) } @@ -458,7 +463,7 @@ extension Row { convenience init(base: Row, adapter: LayoutedRowAdapter) { self.init(impl: AdaptedRowImpl(base: base, adapter: adapter)) } - + /// Returns self if adapter is nil func adapted(with adapter: RowAdapter?, layout: RowLayout) throws -> Row { guard let adapter = adapter else { @@ -468,7 +473,7 @@ extension Row { } } -struct AdaptedRowImpl : RowImpl { +struct AdaptedRowImpl: RowImpl { let base: Row let adapter: LayoutedRowAdapter let mapping: LayoutedColumnMapping @@ -517,7 +522,7 @@ struct AdaptedRowImpl : RowImpl { return Value.fastDecodeIfPresent(from: base, atUncheckedIndex: mappedIndex) } - func dataNoCopy(atUncheckedIndex index:Int) -> Data? { + func dataNoCopy(atUncheckedIndex index: Int) -> Data? { let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index) return base.impl.dataNoCopy(atUncheckedIndex: mappedIndex) } @@ -533,7 +538,7 @@ struct AdaptedRowImpl : RowImpl { func copiedRow(_ row: Row) -> Row { return Row(base: base.copy(), adapter: adapter) } - + func unscopedRow(_ row: Row) -> Row { assert(adapter.mapping.scopes.isEmpty) return Row(base: base, adapter: adapter.mapping) diff --git a/GRDB/Core/SQLInterpolation.swift b/GRDB/Core/SQLInterpolation.swift index 49bc2b3b0..9253c01d8 100644 --- a/GRDB/Core/SQLInterpolation.swift +++ b/GRDB/Core/SQLInterpolation.swift @@ -7,23 +7,23 @@ public struct SQLInterpolation: StringInterpolationProtocol { get { return context.arguments! } set { context.arguments = newValue } } - + public init(literalCapacity: Int, interpolationCount: Int) { sql = "" sql.reserveCapacity(literalCapacity + interpolationCount) } - + /// "SELECT * FROM player" public mutating func appendLiteral(_ sql: String) { self.sql += sql } - + /// "SELECT * FROM \(sql: "player")" public mutating func appendInterpolation(sql: String, arguments: StatementArguments = StatementArguments()) { self.sql += sql self.arguments += arguments } - + /// "SELECT * FROM player WHERE \(literal: condition)" public mutating func appendInterpolation(literal sqlLiteral: SQLLiteral) { sql += sqlLiteral.sql diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index e95e58b88..161cc24f3 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -1,4 +1,5 @@ -/// SQLLiteral is a type which support [SQL Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md). +/// SQLLiteral is a type which support [SQL +/// Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md). /// /// For example: /// @@ -9,8 +10,8 @@ /// try db.execute(literal: query) /// } public struct SQLLiteral { - private(set) public var sql: String - private(set) public var arguments: StatementArguments + public private(set) var sql: String + public private(set) var arguments: StatementArguments /// Creates an SQLLiteral from a plain SQL string, and eventual arguments. /// @@ -63,7 +64,7 @@ extension SQLLiteral { public mutating func append(literal sqlLiteral: SQLLiteral) { self += sqlLiteral } - + /// Appends a plain SQL string to the receiver, and eventual arguments. /// /// let name = "O'Brien" diff --git a/GRDB/Core/SQLRequest.swift b/GRDB/Core/SQLRequest.swift index 60ccd4360..5dd439fb0 100644 --- a/GRDB/Core/SQLRequest.swift +++ b/GRDB/Core/SQLRequest.swift @@ -1,5 +1,5 @@ /// A FetchRequest built from raw SQL. -public struct SQLRequest : FetchRequest { +public struct SQLRequest: FetchRequest { /// There are two statement caches: one "public" for statements generated by /// the user, and one "internal" for the statements generated by GRDB. Those /// are separated so that GRDB has no opportunity to inadvertently modify @@ -30,10 +30,10 @@ public struct SQLRequest : FetchRequest { /// The request adapter public var adapter: RowAdapter? - + private var sqlLiteral: SQLLiteral private let cache: Cache? - + /// Creates a request from an SQL string, optional arguments, and /// optional row adapter. /// @@ -51,8 +51,16 @@ public struct SQLRequest : FetchRequest { /// - cached: Defaults to false. If true, the request reuses a cached /// prepared statement. /// - returns: A SQLRequest - public init(sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil, cached: Bool = false) { - self.init(literal: SQLLiteral(sql: sql, arguments: arguments), adapter: adapter, fromCache: cached ? .public : nil) + public init( + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil, + cached: Bool = false) + { + self.init( + literal: SQLLiteral(sql: sql, arguments: arguments), + adapter: adapter, + fromCache: cached ? .public : nil) } /// Creates a request from an SQLLiteral, and optional row adapter. @@ -80,7 +88,7 @@ public struct SQLRequest : FetchRequest { public init(literal sqlLiteral: SQLLiteral, adapter: RowAdapter? = nil, cached: Bool = false) { self.init(literal: sqlLiteral, adapter: adapter, fromCache: cached ? .public : nil) } - + /// Creates an SQL request from any other fetch request. /// /// - parameters: @@ -89,7 +97,13 @@ public struct SQLRequest : FetchRequest { /// - cached: Defaults to false. If true, the request reuses a cached /// prepared statement. /// - returns: An SQLRequest - public init(_ db: Database, request: Request, cached: Bool = false) throws where Request.RowDecoder == RowDecoder { + public init( + _ db: Database, + request: Request, + cached: Bool = false) + throws + where Request: FetchRequest, Request.RowDecoder == RowDecoder + { let request = try request.makePreparedRequest(db, forSingleResult: false) self.init( literal: SQLLiteral(sql: request.statement.sql, arguments: request.statement.arguments), diff --git a/GRDB/Core/SchedulingWatchdog.swift b/GRDB/Core/SchedulingWatchdog.swift index 93318631b..087926c45 100644 --- a/GRDB/Core/SchedulingWatchdog.swift +++ b/GRDB/Core/SchedulingWatchdog.swift @@ -43,7 +43,12 @@ final class SchedulingWatchdog { return try body() } - static func preconditionValidQueue(_ db: Database, _ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) { + static func preconditionValidQueue( + _ db: Database, + _ message: @autoclosure() -> String = "Database was not used on the correct thread.", + file: StaticString = #file, + line: UInt = #line) + { GRDBPrecondition(current?.allows(db) ?? false, message(), file: file, line: line) } diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index 7fabe2ee2..c08b1445a 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -16,7 +16,14 @@ final class SerializedDatabase { /// The dispatch queue private let queue: DispatchQueue - init(path: String, configuration: Configuration = Configuration(), schemaCache: DatabaseSchemaCache, defaultLabel: String, purpose: String? = nil) throws { + init( + path: String, + configuration: Configuration = Configuration(), + schemaCache: DatabaseSchemaCache, + defaultLabel: String, + purpose: String? = nil) + throws + { // According to https://www.sqlite.org/threadsafe.html // // > SQLite support three different threading modes: @@ -193,12 +200,25 @@ final class SerializedDatabase { } /// Fatal error if current dispatch queue is not valid. - func preconditionValidQueue(_ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) { + func preconditionValidQueue( + _ message: @autoclosure() -> String = "Database was not used on the correct thread.", + file: StaticString = #file, + line: UInt = #line) + { SchedulingWatchdog.preconditionValidQueue(db, message(), file: file, line: line) } /// Fatal error if a transaction has been left opened. - private func preconditionNoUnsafeTransactionLeft(_ db: Database, _ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access", file: StaticString = #file, line: UInt = #line) { - GRDBPrecondition(configuration.allowsUnsafeTransactions || !db.isInsideTransaction, message(), file: file, line: line) + private func preconditionNoUnsafeTransactionLeft( + _ db: Database, + _ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access", + file: StaticString = #file, + line: UInt = #line) + { + GRDBPrecondition( + configuration.allowsUnsafeTransactions || !db.isInsideTransaction, + message(), + file: file, + line: line) } } diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 73a76d472..b3a4a9949 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -1,10 +1,10 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// A raw SQLite statement, suitable for the SQLite C API. @@ -56,18 +56,25 @@ public class Statement { var sqliteStatement: SQLiteStatement? = nil // sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20 #if GRDBCUSTOMSQLITE || GRDBCIPHER - let code = sqlite3_prepare_v3(database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), &sqliteStatement, statementEnd) + let code = sqlite3_prepare_v3( + database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), + &sqliteStatement, statementEnd) #else let code: Int32 if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) { - code = sqlite3_prepare_v3(database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), &sqliteStatement, statementEnd) + code = sqlite3_prepare_v3( + database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), + &sqliteStatement, statementEnd) } else { code = sqlite3_prepare_v2(database.sqliteConnection, statementStart, -1, &sqliteStatement, statementEnd) } #endif guard code == SQLITE_OK else { - throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: String(cString: statementStart)) + throw DatabaseError( + resultCode: code, + message: database.lastErrorMessage, + sql: String(cString: statementStart)) } guard let statement = sqliteStatement else { @@ -102,7 +109,7 @@ public class Statement { // Returns ["id", nil", "name"] for "INSERT INTO table VALUES (:id, ?, :name)" fileprivate lazy var sqliteArgumentNames: [String?] = { - return (0.. ?", arguments: [1000]) /// .fetchAll(db) -public struct StatementArguments: CustomStringConvertible, Equatable, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral { +public struct StatementArguments: CustomStringConvertible, Equatable, + ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral +{ private(set) var values: [DatabaseValue] = [] private(set) var namedValues: [String: DatabaseValue] = [:] @@ -667,7 +686,9 @@ public struct StatementArguments: CustomStringConvertible, Equatable, Expressibl /// /// - parameter sequence: A sequence of (key, value) pairs /// - returns: A StatementArguments. - public init(_ sequence: Sequence) where Sequence.Element == (String, DatabaseValueConvertible?) { + public init(_ sequence: Sequence) + where Sequence: Swift.Sequence, Sequence.Element == (String, DatabaseValueConvertible?) + { namedValues = Dictionary(uniqueKeysWithValues: sequence.map { ($0.0, $0.1?.databaseValue ?? .null) }) } @@ -843,33 +864,51 @@ public struct StatementArguments: CustomStringConvertible, Equatable, Expressibl /// append(contentsOf:) method. public static func += (lhs: inout StatementArguments, rhs: StatementArguments) { let replacedValues = lhs.append(contentsOf: rhs) - GRDBPrecondition(replacedValues.isEmpty, "already defined statement argument: \(replacedValues.keys.joined(separator: ", "))") + GRDBPrecondition( + replacedValues.isEmpty, + "already defined statement argument: \(replacedValues.keys.joined(separator: ", "))") } // MARK: Not Public - mutating func extractBindings(forStatement statement: Statement, allowingRemainingValues: Bool) throws -> [DatabaseValue] { + mutating func extractBindings( + forStatement statement: Statement, + allowingRemainingValues: Bool) + throws -> [DatabaseValue] + { let initialValuesCount = values.count let bindings = try statement.sqliteArgumentNames.map { argumentName -> DatabaseValue in if let argumentName = argumentName { if let dbValue = namedValues[argumentName] { return dbValue } else if values.isEmpty { - throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "missing statement argument: \(argumentName)", sql: statement.sql, arguments: nil) + throw DatabaseError( + resultCode: .SQLITE_MISUSE, + message: "missing statement argument: \(argumentName)", + sql: statement.sql, + arguments: nil) } else { return values.removeFirst() } } else { if values.isEmpty { - throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)", sql: statement.sql, arguments: nil) + throw DatabaseError( + resultCode: .SQLITE_MISUSE, + message: "wrong number of statement arguments: \(initialValuesCount)", + sql: statement.sql, + arguments: nil) } else { return values.removeFirst() } } } if !allowingRemainingValues && !values.isEmpty { - throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)", sql: statement.sql, arguments: nil) + throw DatabaseError( + resultCode: .SQLITE_MISUSE, + message: "wrong number of statement arguments: \(initialValuesCount)", + sql: statement.sql, + arguments: nil) } return bindings } @@ -907,7 +946,7 @@ extension StatementArguments { public var description: String { let valuesDescriptions = values.map { $0.description } let namedValuesDescriptions = namedValues.map { (key, value) -> String in - return "\(String(reflecting: key)): \(value)" + "\(String(reflecting: key)): \(value)" } return "[" + (namedValuesDescriptions + valuesDescriptions).joined(separator: ", ") + "]" } diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index e94bfa4a5..679a54a3d 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -1,16 +1,16 @@ #if os(Linux) - import Glibc +import Glibc #endif #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// A protocol around sqlite3_set_authorizer -protocol StatementAuthorizer : class { +protocol StatementAuthorizer: AnyObject { func authorize( _ actionCode: Int32, _ cString1: UnsafePointer?, @@ -21,7 +21,7 @@ protocol StatementAuthorizer : class { } /// A class that gathers information about one statement during its compilation. -final class StatementCompilationAuthorizer : StatementAuthorizer { +final class StatementCompilationAuthorizer: StatementAuthorizer { /// What this statements reads var databaseRegion = DatabaseRegion() @@ -47,7 +47,11 @@ final class StatementCompilationAuthorizer : StatementAuthorizer { _ cString4: UnsafePointer?) -> Int32 { - // print("StatementCompilationAuthorizer: \(actionCode) \([cString1, cString2, cString3, cString4].flatMap { $0.map({ String(cString: $0) }) })") + // print(""" + // StatementCompilationAuthorizer: \ + // \(actionCode) \ + // \([cString1, cString2, cString3, cString4].compactMap { $0.map({ String(cString: $0) }) }) + // """) switch actionCode { case SQLITE_DROP_TABLE, SQLITE_DROP_VTABLE, SQLITE_DROP_TEMP_TABLE, @@ -168,7 +172,7 @@ final class StatementCompilationAuthorizer : StatementAuthorizer { // /// Warning: to perform well, this authorizer must be used during statement /// execution, not during statement compilation. -final class TruncateOptimizationBlocker : StatementAuthorizer { +final class TruncateOptimizationBlocker: StatementAuthorizer { func authorize( _ actionCode: Int32, _ cString1: UnsafePointer?, @@ -177,8 +181,11 @@ final class TruncateOptimizationBlocker : StatementAuthorizer { _ cString4: UnsafePointer?) -> Int32 { - // print("TruncateOptimizationBlocker: \(actionCode) \([cString1, cString2, cString3, cString4].flatMap { $0.map({ String(cString: $0) }) })") + // print(""" + // TruncateOptimizationBlocker: \ + // \(actionCode) \ + // \([cString1, cString2, cString3, cString4].compactMap { $0.map({ String(cString: $0) }) }) + // """) return (actionCode == SQLITE_DELETE) ? SQLITE_IGNORE : SQLITE_OK } } - diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 2ae6f87ba..734acdb3f 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -1,9 +1,9 @@ #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// The StatementColumnConvertible protocol grants access to the low-level C @@ -109,17 +109,20 @@ public final class FastDatabaseValueCursor = try Optional.fetchCursor(db, sql: "SELECT email FROM player") +/// let emails: FastNullableDatabaseValueCursor = +/// try Optional.fetchCursor(db, sql: "SELECT email FROM player") /// while let email = emails.next() { // String? /// print(email ?? "") /// } /// } -public final class FastNullableDatabaseValueCursor : Cursor { +public final class FastNullableDatabaseValueCursor: Cursor + where Value: DatabaseValueConvertible & StatementColumnConvertible +{ @usableFromInline let _statement: SelectStatement @usableFromInline let _columnIndex: Int32 @usableFromInline let _sqliteStatement: SQLiteStatement @usableFromInline var _done = false - + init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { _statement = statement _sqliteStatement = statement.sqliteStatement @@ -187,7 +190,12 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor { + public static func fetchCursor( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> FastDatabaseValueCursor + { return try FastDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) } @@ -202,7 +210,12 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - adapter: Optional RowAdapter /// - returns: An array of values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { + public static func fetchAll( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Self] + { return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } @@ -217,15 +230,23 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - adapter: Optional RowAdapter /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { + public static func fetchOne( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> Self? + { // fetchOne returns nil if there is no row, or if there is a row with a null value - let cursor = try FastNullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) + let cursor = try FastNullableDatabaseValueCursor( + statement: statement, + arguments: arguments, + adapter: adapter) return try cursor.next() ?? nil } } extension DatabaseValueConvertible where Self: StatementColumnConvertible { - + // MARK: Fetching From SQL /// Returns a cursor over values fetched from an SQL query. @@ -247,7 +268,13 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor { + public static func fetchCursor( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> FastDatabaseValueCursor + { return try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -262,7 +289,13 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - adapter: Optional RowAdapter /// - returns: An array of values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self] { + public static func fetchAll( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> [Self] + { return try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -277,7 +310,13 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - adapter: Optional RowAdapter /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self? { + public static func fetchOne( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> Self? + { return try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } } @@ -304,7 +343,9 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - request: A FetchRequest. /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: R) throws -> FastDatabaseValueCursor { + public static func fetchCursor(_ db: Database, _ request: R) + throws -> FastDatabaseValueCursor + { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchCursor(request.statement, adapter: request.adapter) } @@ -426,7 +467,12 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor { + public static func fetchCursor( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> FastNullableDatabaseValueCursor + { return try FastNullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) } @@ -441,7 +487,12 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// - adapter: Optional RowAdapter /// - returns: An array of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] { + public static func fetchAll( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Wrapped?] + { return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } } @@ -469,7 +520,13 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor { + public static func fetchCursor( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> FastNullableDatabaseValueCursor + { return try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -484,7 +541,13 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// - adapter: Optional RowAdapter /// - returns: An array of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Wrapped?] { + public static func fetchAll( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> [Wrapped?] + { return try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } } @@ -511,7 +574,9 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// - request: A FetchRequest. /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: R) throws -> FastNullableDatabaseValueCursor { + public static func fetchCursor(_ db: Database, _ request: R) + throws -> FastNullableDatabaseValueCursor + { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchCursor(request.statement, adapter: request.adapter) } @@ -532,7 +597,11 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv } } -extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible { +extension FetchRequest + where + RowDecoder: _OptionalProtocol, + RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible +{ // MARK: Fetching Optional values diff --git a/GRDB/Core/Support/CoreGraphics/CGFloat.swift b/GRDB/Core/Support/CoreGraphics/CGFloat.swift index 444dc0c40..a7f7c6bc4 100644 --- a/GRDB/Core/Support/CoreGraphics/CGFloat.swift +++ b/GRDB/Core/Support/CoreGraphics/CGFloat.swift @@ -2,8 +2,8 @@ import CoreGraphics /// CGFloat adopts DatabaseValueConvertible -extension CGFloat : DatabaseValueConvertible { - +extension CGFloat: DatabaseValueConvertible { + /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { return Double(self).databaseValue diff --git a/GRDB/Core/Support/Foundation/Data.swift b/GRDB/Core/Support/Foundation/Data.swift index 8c4202bdc..281fdd920 100644 --- a/GRDB/Core/Support/Foundation/Data.swift +++ b/GRDB/Core/Support/Foundation/Data.swift @@ -1,14 +1,14 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// Data is convertible to and from DatabaseValue. -extension Data : DatabaseValueConvertible, StatementColumnConvertible { +extension Data: DatabaseValueConvertible, StatementColumnConvertible { @inlinable public init(sqliteStatement: SQLiteStatement, index: Int32) { if let bytes = sqlite3_column_blob(sqliteStatement, index) { diff --git a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift index f84be4909..0057f4a6f 100644 --- a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift +++ b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift @@ -1,17 +1,17 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// DatabaseDateComponents reads and stores DateComponents in the database. -public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumnConvertible { - +public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnConvertible { + /// The available formats for reading and storing date components. - public enum Format : String { + public enum Format: String { /// The format "yyyy-MM-dd". case YMD = "yyyy-MM-dd" @@ -81,8 +81,10 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn fatalConversionError(to: DatabaseDateComponents.self, sqliteStatement: sqliteStatement, index: index) } let length = Int(sqlite3_column_bytes(sqliteStatement, index)) // avoid an strlen - let optionalComponents = cString.withMemoryRebound(to: Int8.self, capacity: length + 1 /* trailing \0 */) { cString in - SQLiteDateParser().components(cString: cString, length: length) + let optionalComponents = cString.withMemoryRebound( + to: Int8.self, + capacity: length + 1 /* trailing \0 */) { cString in + SQLiteDateParser().components(cString: cString, length: length) } guard let components = optionalComponents else { fatalConversionError(to: DatabaseDateComponents.self, sqliteStatement: sqliteStatement, index: index) @@ -122,7 +124,9 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn let minute = dateComponents.minute ?? 0 let second = dateComponents.second ?? 0 let nanosecond = dateComponents.nanosecond ?? 0 - timeString = String(format: "%02d:%02d:%02d.%03d", hour, minute, second, Int(round(Double(nanosecond) / 1_000_000.0))) + timeString = String( + format: "%02d:%02d:%02d.%03d", + hour, minute, second, Int(round(Double(nanosecond) / 1_000_000.0))) default: timeString = nil } diff --git a/GRDB/Core/Support/Foundation/DatabaseValueConvertible+ReferenceConvertible.swift b/GRDB/Core/Support/Foundation/DatabaseValueConvertible+ReferenceConvertible.swift index d5fedd5ad..4a3e3c53b 100644 --- a/GRDB/Core/Support/Foundation/DatabaseValueConvertible+ReferenceConvertible.swift +++ b/GRDB/Core/Support/Foundation/DatabaseValueConvertible+ReferenceConvertible.swift @@ -26,14 +26,22 @@ extension DatabaseValueConvertible where Self: ReferenceConvertible, Self.Refere } } -extension DatabaseValueConvertible where Self: Decodable & ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible { +extension DatabaseValueConvertible + where + Self: Decodable & ReferenceConvertible, + Self.ReferenceType: DatabaseValueConvertible +{ public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? { // Preserve custom database decoding return ReferenceType.fromDatabaseValue(databaseValue).flatMap { cast($0) } } } -extension DatabaseValueConvertible where Self: Encodable & ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible { +extension DatabaseValueConvertible + where + Self: Encodable & ReferenceConvertible, + Self.ReferenceType: DatabaseValueConvertible +{ public var databaseValue: DatabaseValue { // Preserve custom database encoding return (self as! ReferenceType).databaseValue diff --git a/GRDB/Core/Support/Foundation/Date.swift b/GRDB/Core/Support/Foundation/Date.swift index 4742c84ed..c51b103fd 100644 --- a/GRDB/Core/Support/Foundation/Date.swift +++ b/GRDB/Core/Support/Foundation/Date.swift @@ -1,16 +1,16 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif #if !os(Linux) /// NSDate is stored in the database using the format /// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone. -extension NSDate : DatabaseValueConvertible { +extension NSDate: DatabaseValueConvertible { /// Returns a database value that contains the date encoded as /// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone. public var databaseValue: DatabaseValue { @@ -38,7 +38,7 @@ extension NSDate : DatabaseValueConvertible { /// Date is stored in the database using the format /// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone. -extension Date : DatabaseValueConvertible { +extension Date: DatabaseValueConvertible { /// Returns a database value that contains the date encoded as /// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone. public var databaseValue: DatabaseValue { @@ -149,7 +149,7 @@ private let storageDateFormatter: DateFormatter = { formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0) return formatter - }() +}() // The NSCalendar for stored dates. private let UTCCalendar: Calendar = { @@ -157,4 +157,4 @@ private let UTCCalendar: Calendar = { calendar.locale = Locale(identifier: "en_US_POSIX") calendar.timeZone = TimeZone(secondsFromGMT: 0)! return calendar - }() +}() diff --git a/GRDB/Core/Support/Foundation/NSData.swift b/GRDB/Core/Support/Foundation/NSData.swift index 8bd9d2ecf..5a29bc4a4 100644 --- a/GRDB/Core/Support/Foundation/NSData.swift +++ b/GRDB/Core/Support/Foundation/NSData.swift @@ -2,7 +2,7 @@ import Foundation /// NSData is convertible to and from DatabaseValue. -extension NSData : DatabaseValueConvertible { +extension NSData: DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { diff --git a/GRDB/Core/Support/Foundation/NSNull.swift b/GRDB/Core/Support/Foundation/NSNull.swift index e954befe4..af531bab5 100644 --- a/GRDB/Core/Support/Foundation/NSNull.swift +++ b/GRDB/Core/Support/Foundation/NSNull.swift @@ -1,7 +1,7 @@ import Foundation /// NSNull adopts DatabaseValueConvertible -extension NSNull : DatabaseValueConvertible { +extension NSNull: DatabaseValueConvertible { /// Returns DatabaseValue.null. public var databaseValue: DatabaseValue { diff --git a/GRDB/Core/Support/Foundation/NSNumber.swift b/GRDB/Core/Support/Foundation/NSNumber.swift index 2caf60868..7c33a68fb 100644 --- a/GRDB/Core/Support/Foundation/NSNumber.swift +++ b/GRDB/Core/Support/Foundation/NSNumber.swift @@ -1,10 +1,16 @@ #if !os(Linux) import Foundation -private let integerRoundingBehavior = NSDecimalNumberHandler(roundingMode: .plain, scale: 0, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false) +private let integerRoundingBehavior = NSDecimalNumberHandler( + roundingMode: .plain, + scale: 0, + raiseOnExactness: false, + raiseOnOverflow: false, + raiseOnUnderflow: false, + raiseOnDivideByZero: false) /// NSNumber adopts DatabaseValueConvertible -extension NSNumber : DatabaseValueConvertible { +extension NSNumber: DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { @@ -34,13 +40,17 @@ extension NSNumber : DatabaseValueConvertible { return Int64(intValue).databaseValue case "L": let uint = uintValue - GRDBPrecondition(UInt64(uint) <= UInt64(Int64.max), "could not convert \(uint) to an Int64 that can be stored in the database") + GRDBPrecondition( + UInt64(uint) <= UInt64(Int64.max), + "could not convert \(uint) to an Int64 that can be stored in the database") return Int64(uint).databaseValue case "q": return Int64(int64Value).databaseValue case "Q": let uint64 = uint64Value - GRDBPrecondition(uint64 <= UInt64(Int64.max), "could not convert \(uint64) to an Int64 that can be stored in the database") + GRDBPrecondition( + uint64 <= UInt64(Int64.max), + "could not convert \(uint64) to an Int64 that can be stored in the database") return Int64(uint64).databaseValue case "f": return Double(floatValue).databaseValue diff --git a/GRDB/Core/Support/Foundation/NSString.swift b/GRDB/Core/Support/Foundation/NSString.swift index d5455bed4..ba9941012 100644 --- a/GRDB/Core/Support/Foundation/NSString.swift +++ b/GRDB/Core/Support/Foundation/NSString.swift @@ -2,7 +2,7 @@ import Foundation /// NSString adopts DatabaseValueConvertible -extension NSString : DatabaseValueConvertible { +extension NSString: DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index cd42663c0..b6630fe39 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -58,6 +58,7 @@ class SQLiteDateParser { withUnsafeMutablePointer(to: &parserComponents.minute) { minuteP in withUnsafeMutablePointer(to: &parserComponents.second) { secondP in parserComponents.nanosecond.withUnsafeMutableBufferPointer { nanosecondBuffer in + // swiftlint:disable:next line_length withVaList([yearP, monthP, dayP, hourP, minuteP, secondP, nanosecondBuffer.baseAddress!]) { pointer in vsscanf(cString, "%4d-%2d-%2d%*1[ T]%2d:%2d:%2d.%9s", pointer) } diff --git a/GRDB/Core/Support/Foundation/URL.swift b/GRDB/Core/Support/Foundation/URL.swift index 4cc95b1b4..6990562e1 100644 --- a/GRDB/Core/Support/Foundation/URL.swift +++ b/GRDB/Core/Support/Foundation/URL.swift @@ -2,7 +2,7 @@ import Foundation #if !os(Linux) /// NSURL stores its absoluteString in the database. -extension NSURL : DatabaseValueConvertible { +extension NSURL: DatabaseValueConvertible { /// Returns a value that can be stored in the database. /// (the URL's absoluteString). @@ -21,4 +21,4 @@ extension NSURL : DatabaseValueConvertible { #endif /// URL stores its absoluteString in the database. -extension URL : DatabaseValueConvertible { } +extension URL: DatabaseValueConvertible { } diff --git a/GRDB/Core/Support/Foundation/UUID.swift b/GRDB/Core/Support/Foundation/UUID.swift index 8ed8d68b0..92447987c 100644 --- a/GRDB/Core/Support/Foundation/UUID.swift +++ b/GRDB/Core/Support/Foundation/UUID.swift @@ -1,10 +1,10 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif #if !os(Linux) diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift index f04cfd071..b37fb8d80 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift @@ -13,7 +13,8 @@ private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer { /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. - /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. + /// - throws: `DecodingError.typeMismatch` if the encountered encoded value + /// cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. func decode(_ type: Bool.Type) throws -> Bool { if let result = Bool.fromDatabaseValue(dbValue) { @@ -131,9 +132,10 @@ private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer { /// /// - parameter type: The type to decode as. /// - returns: A value of the requested type. - /// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type. + /// - throws: `DecodingError.typeMismatch` if the encountered encoded value + /// cannot be converted to the requested type. /// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null. - func decode(_ type: T.Type) throws -> T where T : Decodable { + func decode(_ type: T.Type) throws -> T where T: Decodable { if let type = T.self as? DatabaseValueConvertible.Type { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows custom database decoding, such as decoding Date from @@ -159,7 +161,7 @@ private struct DatabaseValueDecoder: Decoder { // Decoder let codingPath: [CodingKey] - var userInfo: [CodingUserInfoKey : Any] { return [:] } + var userInfo: [CodingUserInfoKey: Any] { return [:] } func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer { throw DecodingError.typeMismatch( diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift index 8aa705b32..bd37c0bde 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift @@ -1,4 +1,4 @@ -private struct DatabaseValueEncodingContainer : SingleValueEncodingContainer { +private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer { let encode: (DatabaseValue) -> Void var codingPath: [CodingKey] { return [] } @@ -34,7 +34,7 @@ private struct DatabaseValueEncodingContainer : SingleValueEncodingContainer { /// - parameter value: The value to encode. /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. /// - precondition: May not be called after a previous `self.encode(_:)` call. - mutating func encode(_ value: T) throws where T : Encodable { + mutating func encode(_ value: T) throws where T: Encodable { if let dbValueConvertible = value as? DatabaseValueConvertible { // Prefer DatabaseValueConvertible encoding over Decodable. // This allows us to encode Date as String, for example. @@ -45,7 +45,7 @@ private struct DatabaseValueEncodingContainer : SingleValueEncodingContainer { } } -private struct DatabaseValueEncoder : Encoder { +private struct DatabaseValueEncoder: Encoder { let encode: (DatabaseValue) -> Void /// The path of coding keys taken to get to this point in encoding. @@ -53,7 +53,7 @@ private struct DatabaseValueEncoder : Encoder { var codingPath: [CodingKey] { return [] } /// Any contextual information set by the user for encoding. - var userInfo: [CodingUserInfoKey : Any] = [:] + var userInfo: [CodingUserInfoKey: Any] = [:] init(encode: @escaping (DatabaseValue) -> Void) { self.encode = encode @@ -64,7 +64,8 @@ private struct DatabaseValueEncoder : Encoder { /// - parameter type: The key type to use for the container. /// - returns: A new keyed encoding container. /// - precondition: May not be called after a prior `self.unkeyedContainer()` call. - /// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call. + /// - precondition: May not be called after a value has been encoded through + /// a previous `self.singleValueContainer()` call. func container(keyedBy type: Key.Type) -> KeyedEncodingContainer { fatalError("keyed encoding is not supported") } @@ -73,7 +74,8 @@ private struct DatabaseValueEncoder : Encoder { /// /// - returns: A new empty unkeyed container. /// - precondition: May not be called after a prior `self.container(keyedBy:)` call. - /// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call. + /// - precondition: May not be called after a value has been encoded through + /// a previous `self.singleValueContainer()` call. func unkeyedContainer() -> UnkeyedEncodingContainer { fatalError("unkeyed encoding is not supported") } @@ -83,7 +85,8 @@ private struct DatabaseValueEncoder : Encoder { /// - returns: A new empty single value container. /// - precondition: May not be called after a prior `self.container(keyedBy:)` call. /// - precondition: May not be called after a prior `self.unkeyedContainer()` call. - /// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call. + /// - precondition: May not be called after a value has been encoded through + /// a previous `self.singleValueContainer()` call. func singleValueContainer() -> SingleValueEncodingContainer { return DatabaseValueEncodingContainer(encode: encode) } diff --git a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift index 099b742fe..0914b0dcf 100644 --- a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift +++ b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift @@ -1,9 +1,9 @@ #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif // MARK: - Value Types @@ -500,11 +500,12 @@ extension DatabaseFunction { /// let nameColumn = Column("name") /// let request = Player.select(nameColumn.capitalized) /// let names = try String.fetchAll(dbQueue, request) // [String] - public static let capitalize = DatabaseFunction("swiftCapitalizedString", argumentCount: 1, pure: true) { dbValues in - guard let string = String.fromDatabaseValue(dbValues[0]) else { - return nil - } - return string.capitalized + public static let capitalize = + DatabaseFunction("swiftCapitalizedString", argumentCount: 1, pure: true) { dbValues in + guard let string = String.fromDatabaseValue(dbValues[0]) else { + return nil + } + return string.capitalized } /// An SQL function that returns the Swift built-in lowercased @@ -519,11 +520,12 @@ extension DatabaseFunction { /// let nameColumn = Column("name") /// let request = Player.select(nameColumn.lowercased()) /// let names = try String.fetchAll(dbQueue, request) // [String] - public static let lowercase = DatabaseFunction("swiftLowercaseString", argumentCount: 1, pure: true) { dbValues in - guard let string = String.fromDatabaseValue(dbValues[0]) else { - return nil - } - return string.lowercased() + public static let lowercase = + DatabaseFunction("swiftLowercaseString", argumentCount: 1, pure: true) { dbValues in + guard let string = String.fromDatabaseValue(dbValues[0]) else { + return nil + } + return string.lowercased() } /// An SQL function that returns the Swift built-in uppercased @@ -538,11 +540,12 @@ extension DatabaseFunction { /// let nameColumn = Column("name") /// let request = Player.select(nameColumn.uppercased()) /// let names = try String.fetchAll(dbQueue, request) // [String] - public static let uppercase = DatabaseFunction("swiftUppercaseString", argumentCount: 1, pure: true) { dbValues in - guard let string = String.fromDatabaseValue(dbValues[0]) else { - return nil - } - return string.uppercased() + public static let uppercase = + DatabaseFunction("swiftUppercaseString", argumentCount: 1, pure: true) { dbValues in + guard let string = String.fromDatabaseValue(dbValues[0]) else { + return nil + } + return string.uppercased() } } @@ -560,11 +563,12 @@ extension DatabaseFunction { /// let request = Player.select(nameColumn.localizedCapitalized) /// let names = try String.fetchAll(dbQueue, request) // [String] @available(iOS 9.0, OSX 10.11, watchOS 3.0, *) - public static let localizedCapitalize = DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { dbValues in - guard let string = String.fromDatabaseValue(dbValues[0]) else { - return nil - } - return string.localizedCapitalized + public static let localizedCapitalize = + DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { dbValues in + guard let string = String.fromDatabaseValue(dbValues[0]) else { + return nil + } + return string.localizedCapitalized } /// An SQL function that returns the Swift built-in @@ -580,11 +584,12 @@ extension DatabaseFunction { /// let request = Player.select(nameColumn.localizedLowercased) /// let names = try String.fetchAll(dbQueue, request) // [String] @available(iOS 9.0, OSX 10.11, watchOS 3.0, *) - public static let localizedLowercase = DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { dbValues in - guard let string = String.fromDatabaseValue(dbValues[0]) else { - return nil - } - return string.localizedLowercase + public static let localizedLowercase = + DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { dbValues in + guard let string = String.fromDatabaseValue(dbValues[0]) else { + return nil + } + return string.localizedLowercase } /// An SQL function that returns the Swift built-in @@ -600,11 +605,12 @@ extension DatabaseFunction { /// let request = Player.select(nameColumn.localizedUppercased) /// let names = try String.fetchAll(dbQueue, request) // [String] @available(iOS 9.0, OSX 10.11, watchOS 3.0, *) - public static let localizedUppercase = DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { dbValues in - guard let string = String.fromDatabaseValue(dbValues[0]) else { - return nil - } - return string.localizedUppercase + public static let localizedUppercase = + DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { dbValues in + guard let string = String.fromDatabaseValue(dbValues[0]) else { + return nil + } + return string.localizedUppercase } } @@ -637,8 +643,9 @@ extension DatabaseCollation { /// name TEXT COLLATE \(collationName) /// ) /// """) - public static let unicodeCompare = DatabaseCollation("swiftCompare") { (lhs, rhs) in - return (lhs < rhs) ? .orderedAscending : ((lhs == rhs) ? .orderedSame : .orderedDescending) + public static let unicodeCompare = + DatabaseCollation("swiftCompare") { (lhs, rhs) in + (lhs < rhs) ? .orderedAscending : ((lhs == rhs) ? .orderedSame : .orderedDescending) } /// A collation, or SQL string comparison function, that compares strings @@ -655,8 +662,9 @@ extension DatabaseCollation { /// name TEXT COLLATE \(collationName) /// ) /// """) - public static let caseInsensitiveCompare = DatabaseCollation("swiftCaseInsensitiveCompare") { (lhs, rhs) in - return lhs.caseInsensitiveCompare(rhs) + public static let caseInsensitiveCompare = + DatabaseCollation("swiftCaseInsensitiveCompare") { (lhs, rhs) in + lhs.caseInsensitiveCompare(rhs) } /// A collation, or SQL string comparison function, that compares strings @@ -673,8 +681,9 @@ extension DatabaseCollation { /// name TEXT COLLATE \(collationName) /// ) /// """) - public static let localizedCaseInsensitiveCompare = DatabaseCollation("swiftLocalizedCaseInsensitiveCompare") { (lhs, rhs) in - return lhs.localizedCaseInsensitiveCompare(rhs) + public static let localizedCaseInsensitiveCompare = + DatabaseCollation("swiftLocalizedCaseInsensitiveCompare") { (lhs, rhs) in + return lhs.localizedCaseInsensitiveCompare(rhs) } /// A collation, or SQL string comparison function, that compares strings @@ -691,8 +700,9 @@ extension DatabaseCollation { /// name TEXT COLLATE \(collationName) /// ) /// """) - public static let localizedCompare = DatabaseCollation("swiftLocalizedCompare") { (lhs, rhs) in - return lhs.localizedCompare(rhs) + public static let localizedCompare = + DatabaseCollation("swiftLocalizedCompare") { (lhs, rhs) in + lhs.localizedCompare(rhs) } /// A collation, or SQL string comparison function, that compares strings @@ -709,7 +719,8 @@ extension DatabaseCollation { /// name TEXT COLLATE \(collationName) /// ) /// """) - public static let localizedStandardCompare = DatabaseCollation("swiftLocalizedStandardCompare") { (lhs, rhs) in - return lhs.localizedStandardCompare(rhs) + public static let localizedStandardCompare = + DatabaseCollation("swiftLocalizedStandardCompare") { (lhs, rhs) in + lhs.localizedStandardCompare(rhs) } } diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 096a246e8..c86139207 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -1,13 +1,13 @@ #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif extension Database { - + // MARK: - Database Observation /// Add a transaction observer, so that it gets notified of @@ -17,7 +17,10 @@ extension Database { /// - parameter extent: The duration of the observation. The default is /// the observer lifetime (observation lasts until observer /// is deallocated). - public func add(transactionObserver: TransactionObserver, extent: TransactionObservationExtent = .observerLifetime) { + public func add( + transactionObserver: TransactionObserver, + extent: TransactionObservationExtent = .observerLifetime) + { SchedulingWatchdog.preconditionValidQueue(self) observationBroker.add(transactionObserver: transactionObserver, extent: extent) } @@ -42,11 +45,11 @@ extension Database { /// /// If the transaction is committed, the closure is executed in a protected /// dispatch queue, serialized will all database updates. - public func afterNextTransactionCommit(_ closure: @escaping (Database) -> ()) { - class CommitHandler : TransactionObserver { - let closure: (Database) -> () + public func afterNextTransactionCommit(_ closure: @escaping (Database) -> Void) { + class CommitHandler: TransactionObserver { + let closure: (Database) -> Void - init(_ closure: @escaping (Database) -> ()) { + init(_ closure: @escaping (Database) -> Void) { self.closure = closure } @@ -195,7 +198,7 @@ class DatabaseObservationBroker { } func disableUntilNextTransaction(transactionObserver: TransactionObserver) { - if let observation = transactionObservations.first(where: { $0.isWrapping(transactionObserver)}) { + if let observation = transactionObservations.first(where: { $0.isWrapping(transactionObserver) }) { observation.isDisabled = true statementObservations.removeFirst { $0.0 === observation } } @@ -293,7 +296,7 @@ class DatabaseObservationBroker { statementObservations = [] database.authorizer = nil SchedulingWatchdog.current!.databaseObservationBroker = nil - + // Reset transactionState before databaseDidRollback eventually // executes other statements. let transactionState = self.transactionState @@ -318,7 +321,7 @@ class DatabaseObservationBroker { statementObservations = [] database.authorizer = nil SchedulingWatchdog.current!.databaseObservationBroker = nil - + // Has statement any effect on transaction/savepoints? if let transactionEffect = statement.transactionEffect { switch transactionEffect { @@ -379,7 +382,7 @@ class DatabaseObservationBroker { } } -#if SQLITE_ENABLE_PREUPDATE_HOOK + #if SQLITE_ENABLE_PREUPDATE_HOOK // Called from sqlite3_preupdate_hook private func databaseWillChange(with event: DatabasePreUpdateEvent) { if savepointStack.isEmpty { @@ -392,7 +395,7 @@ class DatabaseObservationBroker { savepointStack.eventsBuffer.append((event: event.copy(), statementObservations: statementObservations)) } } -#endif + #endif // Called from sqlite3_update_hook private func databaseDidChange(with event: DatabaseEvent) { @@ -597,17 +600,23 @@ class DatabaseObservationBroker { private func installUpdateHook() { let brokerPointer = Unmanaged.passUnretained(self).toOpaque() - sqlite3_update_hook(database.sqliteConnection, { (brokerPointer, updateKind, databaseNameCString, tableNameCString, rowID) in - let broker = Unmanaged.fromOpaque(brokerPointer!).takeUnretainedValue() - broker.databaseDidChange(with: DatabaseEvent( - kind: DatabaseEvent.Kind(rawValue: updateKind)!, - rowID: rowID, - databaseNameCString: databaseNameCString, - tableNameCString: tableNameCString)) - }, brokerPointer) + sqlite3_update_hook( + database.sqliteConnection, + { (brokerPointer, updateKind, databaseNameCString, tableNameCString, rowID) in + let broker = Unmanaged.fromOpaque(brokerPointer!).takeUnretainedValue() + broker.databaseDidChange(with: DatabaseEvent( + kind: DatabaseEvent.Kind(rawValue: updateKind)!, + rowID: rowID, + databaseNameCString: databaseNameCString, + tableNameCString: tableNameCString)) + }, + brokerPointer) #if SQLITE_ENABLE_PREUPDATE_HOOK - sqlite3_preupdate_hook(database.sqliteConnection, { (brokerPointer, databaseConnection, updateKind, databaseNameCString, tableNameCString, initialRowID, finalRowID) in + sqlite3_preupdate_hook( + database.sqliteConnection, + // swiftlint:disable:next line_length + { (brokerPointer, databaseConnection, updateKind, databaseNameCString, tableNameCString, initialRowID, finalRowID) in let broker = Unmanaged.fromOpaque(brokerPointer!).takeUnretainedValue() broker.databaseWillChange(with: DatabasePreUpdateEvent( connection: databaseConnection!, @@ -616,14 +625,15 @@ class DatabaseObservationBroker { finalRowID: finalRowID, databaseNameCString: databaseNameCString, tableNameCString: tableNameCString)) - }, brokerPointer) + }, + brokerPointer) #endif } private func uninstallUpdateHook() { sqlite3_update_hook(database.sqliteConnection, nil, nil) #if SQLITE_ENABLE_PREUPDATE_HOOK - sqlite3_preupdate_hook(database.sqliteConnection, nil, nil) + sqlite3_preupdate_hook(database.sqliteConnection, nil, nil) #endif } @@ -642,7 +652,7 @@ class DatabaseObservationBroker { /// or rollbacked on a database. /// /// Adopting types must be a class. -public protocol TransactionObserver : class { +public protocol TransactionObserver: AnyObject { /// Filters database changes that should be notified the the /// databaseDidChange(with:) method. @@ -713,7 +723,8 @@ public protocol TransactionObserver : class { /// /// As of OSX 10.11.5, and iOS 9.3.2, the built-in SQLite library /// does not have this enabled, so you'll need to compile your own - /// copy using GRDBCustomSQLite. See https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md + /// copy using GRDBCustomSQLite. + /// See https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md /// /// The databaseDidChangeWithEvent callback is always available, /// and may provide most/all of what you need. @@ -726,13 +737,13 @@ extension TransactionObserver { /// Default implementation does nothing public func databaseWillCommit() throws { } - + #if SQLITE_ENABLE_PREUPDATE_HOOK /// Default implementation does nothing public func databaseWillChange(with event: DatabasePreUpdateEvent) { } #endif - + /// After this method has been called, the `databaseDidChange(with:)` /// method won't be called until the next transaction. /// @@ -756,7 +767,10 @@ extension TransactionObserver { /// - precondition: This method must be called from `databaseDidChange(with:)`. public func stopObservingDatabaseChangesUntilNextTransaction() { guard let broker = SchedulingWatchdog.current?.databaseObservationBroker else { - fatalError("stopObservingDatabaseChangesUntilNextTransaction must be called from the databaseDidChange method") + fatalError(""" + stopObservingDatabaseChangesUntilNextTransaction must be called \ + from the databaseDidChange method + """) } broker.disableUntilNextTransaction(transactionObserver: self) } @@ -801,23 +815,23 @@ final class TransactionObservation { if isDisabled { return false } return observer?.observes(eventsOfKind: eventKind) ?? false } - + #if SQLITE_ENABLE_PREUPDATE_HOOK func databaseWillChange(with event: DatabasePreUpdateEvent) { if isDisabled { return } observer?.databaseWillChange(with: event) } #endif - + func databaseDidChange(with event: DatabaseEvent) { if isDisabled { return } observer?.databaseDidChange(with: event) } - + func databaseWillCommit() throws { try observer?.databaseWillCommit() } - + func databaseDidCommit(_ db: Database) { switch extent { case .observerLifetime, .databaseLifetime: @@ -867,11 +881,11 @@ public enum DatabaseEventKind { var modifiedRegion: DatabaseRegion { switch self { - case .delete(let tableName): + case let .delete(tableName): return DatabaseRegion(table: tableName) - case .insert(let tableName): + case let .insert(tableName): return DatabaseRegion(table: tableName) - case .update(let tableName, let updatedColumnNames): + case let .update(tableName, updatedColumnNames): return DatabaseRegion(table: tableName, columns: updatedColumnNames) } } @@ -881,9 +895,9 @@ extension DatabaseEventKind { /// The impacted database table public var tableName: String { switch self { - case .insert(tableName: let tableName): return tableName - case .delete(tableName: let tableName): return tableName - case .update(tableName: let tableName, columnNames: _): return tableName + case let .insert(tableName: tableName): return tableName + case let .delete(tableName: tableName): return tableName + case let .update(tableName: tableName, columnNames: _): return tableName } } } @@ -915,7 +929,7 @@ public struct DatabaseEvent { /// The database name public var databaseName: String { return impl.databaseName } - + /// The table name public var tableName: String { return impl.tableName } @@ -941,11 +955,16 @@ public struct DatabaseEvent { } init(kind: Kind, rowID: Int64, databaseNameCString: UnsafePointer?, tableNameCString: UnsafePointer?) { - self.init(kind: kind, rowID: rowID, impl: MetalDatabaseEventImpl(databaseNameCString: databaseNameCString, tableNameCString: tableNameCString)) + self.init( + kind: kind, + rowID: rowID, + impl: MetalDatabaseEventImpl( + databaseNameCString: databaseNameCString, + tableNameCString: tableNameCString)) } } -extension DatabaseEvent : DatabaseEventProtocol { +extension DatabaseEvent: DatabaseEventProtocol { func send(to observer: TransactionObservation) { observer.databaseDidChange(with: self) } @@ -970,19 +989,25 @@ private protocol DatabaseEventImpl { /// Optimization: MetalDatabaseEventImpl does not create Swift strings from raw /// SQLite char* until actually asked for databaseName or tableName. -private struct MetalDatabaseEventImpl : DatabaseEventImpl { +private struct MetalDatabaseEventImpl: DatabaseEventImpl { let databaseNameCString: UnsafePointer? let tableNameCString: UnsafePointer? - + var databaseName: String { return String(cString: databaseNameCString!) } var tableName: String { return String(cString: tableNameCString!) } + func copy(_ event: DatabaseEvent) -> DatabaseEvent { - return DatabaseEvent(kind: event.kind, rowID: event.rowID, impl: CopiedDatabaseEventImpl(databaseName: databaseName, tableName: tableName)) + return DatabaseEvent( + kind: event.kind, + rowID: event.rowID, + impl: CopiedDatabaseEventImpl( + databaseName: databaseName, + tableName: tableName)) } } /// Impl for DatabaseEvent that contains copies of event strings. -private struct CopiedDatabaseEventImpl : DatabaseEventImpl { +private struct CopiedDatabaseEventImpl: DatabaseEventImpl { let databaseName: String let tableName: String func copy(_ event: DatabaseEvent) -> DatabaseEvent { @@ -992,258 +1017,293 @@ private struct CopiedDatabaseEventImpl : DatabaseEventImpl { #if SQLITE_ENABLE_PREUPDATE_HOOK - public struct DatabasePreUpdateEvent { +public struct DatabasePreUpdateEvent { + + /// An event kind + public enum Kind: Int32 { + /// SQLITE_INSERT + case insert = 18 - /// An event kind - public enum Kind: Int32 { - /// SQLITE_INSERT - case insert = 18 - - /// SQLITE_DELETE - case delete = 9 - - /// SQLITE_UPDATE - case update = 23 - } + /// SQLITE_DELETE + case delete = 9 - /// The event kind - public let kind: Kind - - /// The database name - public var databaseName: String { return impl.databaseName } - - /// The table name - public var tableName: String { return impl.tableName } - - /// The number of columns in the row that is being inserted, updated, or deleted. - public var count: Int { return Int(impl.columnsCount) } - - /// The triggering depth of the row update - /// Returns: - /// 0 if the preupdate callback was invoked as a result of a direct insert, - // update, or delete operation; - /// 1 for inserts, updates, or deletes invoked by top-level triggers; - /// 2 for changes resulting from triggers called by top-level triggers; - /// ... and so forth - public var depth: CInt { return impl.depth } - - /// The initial rowID of the row being changed for .Update and .Delete changes, - /// and nil for .Insert changes. - public let initialRowID: Int64? - - /// The final rowID of the row being changed for .Update and .Insert changes, - /// and nil for .Delete changes. - public let finalRowID: Int64? - - /// The initial database values in the row. - /// - /// Values appear in the same order as the columns in the table. - /// - /// The result is nil if the event is an .Insert event. - public var initialDatabaseValues: [DatabaseValue]? { - guard (kind == .update || kind == .delete) else { return nil } - return impl.initialDatabaseValues - } - - /// Returns the initial `DatabaseValue` at given index. - /// - /// Indexes span from 0 for the leftmost column to (row.count - 1) for the - /// righmost column. - /// - /// The result is nil if the event is an .Insert event. - public func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { - GRDBPrecondition(index >= 0 && index < count, "row index out of range") - guard (kind == .update || kind == .delete) else { return nil } - return impl.initialDatabaseValue(atIndex: index) - } - - /// The final database values in the row. - /// - /// Values appear in the same order as the columns in the table. - /// - /// The result is nil if the event is a .Delete event. - public var finalDatabaseValues: [DatabaseValue]? { - guard (kind == .update || kind == .insert) else { return nil } - return impl.finalDatabaseValues - } - - /// Returns the final `DatabaseValue` at given index. - /// - /// Indexes span from 0 for the leftmost column to (row.count - 1) for the - /// righmost column. - /// - /// The result is nil if the event is a .Delete event. - public func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { - GRDBPrecondition(index >= 0 && index < count, "row index out of range") - guard (kind == .update || kind == .insert) else { return nil } - return impl.finalDatabaseValue(atIndex: index) - } - - /// Returns an event that can be stored: - /// - /// class MyObserver: TransactionObserver { - /// var events: [DatabasePreUpdateEvent] - /// func databaseWillChange(with event: DatabasePreUpdateEvent) { - /// events.append(event.copy()) - /// } - /// } - public func copy() -> DatabasePreUpdateEvent { - return impl.copy(self) - } - - fileprivate init(kind: Kind, initialRowID: Int64?, finalRowID: Int64?, impl: DatabasePreUpdateEventImpl) { - self.kind = kind - self.initialRowID = (kind == .update || kind == .delete ) ? initialRowID : nil - self.finalRowID = (kind == .update || kind == .insert ) ? finalRowID : nil - self.impl = impl - } - - init(connection: SQLiteConnection, kind: Kind, initialRowID: Int64, finalRowID: Int64, databaseNameCString: UnsafePointer?, tableNameCString: UnsafePointer?) { - self.init(kind: kind, - initialRowID: (kind == .update || kind == .delete ) ? finalRowID : nil, - finalRowID: (kind == .update || kind == .insert ) ? finalRowID : nil, - impl: MetalDatabasePreUpdateEventImpl(connection: connection, kind: kind, databaseNameCString: databaseNameCString, tableNameCString: tableNameCString)) - } - - private let impl: DatabasePreUpdateEventImpl + /// SQLITE_UPDATE + case update = 23 } - extension DatabasePreUpdateEvent : DatabaseEventProtocol { - func send(to observer: TransactionObservation) { - observer.databaseWillChange(with: self) - } - - func matchesKind(_ databaseEventKind: DatabaseEventKind) -> Bool { - switch (kind, databaseEventKind) { - case (.insert, .insert(let tableName)): return self.tableName == tableName - case (.delete, .delete(let tableName)): return self.tableName == tableName - case (.update, .update(let tableName, _)): return self.tableName == tableName - default: - return false - } - } + /// The event kind + public let kind: Kind + + /// The database name + public var databaseName: String { return impl.databaseName } + + /// The table name + public var tableName: String { return impl.tableName } + + /// The number of columns in the row that is being inserted, updated, or deleted. + public var count: Int { return Int(impl.columnsCount) } + + /// The triggering depth of the row update + /// Returns: + /// 0 if the preupdate callback was invoked as a result of a direct insert, + // update, or delete operation; + /// 1 for inserts, updates, or deletes invoked by top-level triggers; + /// 2 for changes resulting from triggers called by top-level triggers; + /// ... and so forth + public var depth: CInt { return impl.depth } + + /// The initial rowID of the row being changed for .Update and .Delete changes, + /// and nil for .Insert changes. + public let initialRowID: Int64? + + /// The final rowID of the row being changed for .Update and .Insert changes, + /// and nil for .Delete changes. + public let finalRowID: Int64? + + /// The initial database values in the row. + /// + /// Values appear in the same order as the columns in the table. + /// + /// The result is nil if the event is an .Insert event. + public var initialDatabaseValues: [DatabaseValue]? { + guard kind == .update || kind == .delete else { return nil } + return impl.initialDatabaseValues } - /// Protocol for internal implementation of DatabaseEvent - private protocol DatabasePreUpdateEventImpl { - var databaseName: String { get } - var tableName: String { get } - - var columnsCount: CInt { get } - var depth: CInt { get } - var initialDatabaseValues: [DatabaseValue]? { get } - var finalDatabaseValues: [DatabaseValue]? { get } - - func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? - func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? - - func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent + /// Returns the initial `DatabaseValue` at given index. + /// + /// Indexes span from 0 for the leftmost column to (row.count - 1) for the + /// righmost column. + /// + /// The result is nil if the event is an .Insert event. + public func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { + GRDBPrecondition(index >= 0 && index < count, "row index out of range") + guard kind == .update || kind == .delete else { return nil } + return impl.initialDatabaseValue(atIndex: index) } - /// Optimization: MetalDatabasePreUpdateEventImpl does not create Swift strings from raw - /// SQLite char* until actually asked for databaseName or tableName, - /// nor does it request other data via the sqlite3_preupdate_* APIs - /// until asked. - private struct MetalDatabasePreUpdateEventImpl : DatabasePreUpdateEventImpl { - let connection: SQLiteConnection - let kind: DatabasePreUpdateEvent.Kind - - let databaseNameCString: UnsafePointer? - let tableNameCString: UnsafePointer? - - var databaseName: String { return String(cString: databaseNameCString!) } - var tableName: String { return String(cString: tableNameCString!) } - - var columnsCount: CInt { return sqlite3_preupdate_count(connection) } - var depth: CInt { return sqlite3_preupdate_depth(connection) } - var initialDatabaseValues: [DatabaseValue]? { - guard (kind == .update || kind == .delete) else { return nil } - return preupdate_getValues_old(connection) - } - - var finalDatabaseValues: [DatabaseValue]? { - guard (kind == .update || kind == .insert) else { return nil } - return preupdate_getValues_new(connection) - } - - func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { - let columnCount = columnsCount - precondition(index >= 0 && index < Int(columnCount), "row index out of range") - return getValue(connection, column: CInt(index), sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in - return sqlite3_preupdate_old(connection, column, &value) - }) - } - - func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { - let columnCount = columnsCount - precondition(index >= 0 && index < Int(columnCount), "row index out of range") - return getValue(connection, column: CInt(index), sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in - return sqlite3_preupdate_new(connection, column, &value) - }) - } - - func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent { - return DatabasePreUpdateEvent(kind: event.kind, initialRowID: event.initialRowID, finalRowID: event.finalRowID, impl: CopiedDatabasePreUpdateEventImpl( - databaseName: databaseName, - tableName: tableName, - columnsCount: columnsCount, - depth: depth, - initialDatabaseValues: initialDatabaseValues, - finalDatabaseValues: finalDatabaseValues)) - } - - private func preupdate_getValues(_ connection: SQLiteConnection, sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt ) -> [DatabaseValue]? { - let columnCount = sqlite3_preupdate_count(connection) - guard columnCount > 0 else { return nil } - - var columnValues = [DatabaseValue]() - - for i in 0.. CInt ) -> DatabaseValue? { - var value : SQLiteValue? = nil - guard sqlite_func(connection, column, &value) == SQLITE_OK else { return nil } - if let value = value { - return DatabaseValue(sqliteValue: value) - } - return nil - } - - private func preupdate_getValues_old(_ connection: SQLiteConnection) -> [DatabaseValue]? { - return preupdate_getValues(connection, sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in - return sqlite3_preupdate_old(connection, column, &value) - }) - } - - private func preupdate_getValues_new(_ connection: SQLiteConnection) -> [DatabaseValue]? { - return preupdate_getValues(connection, sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in - return sqlite3_preupdate_new(connection, column, &value) - }) - } + /// The final database values in the row. + /// + /// Values appear in the same order as the columns in the table. + /// + /// The result is nil if the event is a .Delete event. + public var finalDatabaseValues: [DatabaseValue]? { + guard kind == .update || kind == .insert else { return nil } + return impl.finalDatabaseValues } - /// Impl for DatabasePreUpdateEvent that contains copies of all event data. - private struct CopiedDatabasePreUpdateEventImpl : DatabasePreUpdateEventImpl { - let databaseName: String - let tableName: String - let columnsCount: CInt - let depth: CInt - let initialDatabaseValues: [DatabaseValue]? - let finalDatabaseValues: [DatabaseValue]? - - func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { return initialDatabaseValues?[index] } - func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { return finalDatabaseValues?[index] } - - func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent { - return event + /// Returns the final `DatabaseValue` at given index. + /// + /// Indexes span from 0 for the leftmost column to (row.count - 1) for the + /// righmost column. + /// + /// The result is nil if the event is a .Delete event. + public func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { + GRDBPrecondition(index >= 0 && index < count, "row index out of range") + guard kind == .update || kind == .insert else { return nil } + return impl.finalDatabaseValue(atIndex: index) + } + + /// Returns an event that can be stored: + /// + /// class MyObserver: TransactionObserver { + /// var events: [DatabasePreUpdateEvent] + /// func databaseWillChange(with event: DatabasePreUpdateEvent) { + /// events.append(event.copy()) + /// } + /// } + public func copy() -> DatabasePreUpdateEvent { + return impl.copy(self) + } + + fileprivate init(kind: Kind, initialRowID: Int64?, finalRowID: Int64?, impl: DatabasePreUpdateEventImpl) { + self.kind = kind + self.initialRowID = (kind == .update || kind == .delete ) ? initialRowID : nil + self.finalRowID = (kind == .update || kind == .insert ) ? finalRowID : nil + self.impl = impl + } + + init( + connection: SQLiteConnection, + kind: Kind, + initialRowID: Int64, + finalRowID: Int64, + databaseNameCString: UnsafePointer?, + tableNameCString: UnsafePointer?) + { + self.init( + kind: kind, + initialRowID: (kind == .update || kind == .delete ) ? finalRowID : nil, + finalRowID: (kind == .update || kind == .insert ) ? finalRowID : nil, + impl: MetalDatabasePreUpdateEventImpl( + connection: connection, + kind: kind, + databaseNameCString: databaseNameCString, + tableNameCString: tableNameCString)) + } + + private let impl: DatabasePreUpdateEventImpl +} + +extension DatabasePreUpdateEvent: DatabaseEventProtocol { + func send(to observer: TransactionObservation) { + observer.databaseWillChange(with: self) + } + + func matchesKind(_ databaseEventKind: DatabaseEventKind) -> Bool { + switch (kind, databaseEventKind) { + case (.insert, .insert(let tableName)): return self.tableName == tableName + case (.delete, .delete(let tableName)): return self.tableName == tableName + case (.update, .update(let tableName, _)): return self.tableName == tableName + default: + return false } } +} + +/// Protocol for internal implementation of DatabaseEvent +private protocol DatabasePreUpdateEventImpl { + var databaseName: String { get } + var tableName: String { get } + + var columnsCount: CInt { get } + var depth: CInt { get } + var initialDatabaseValues: [DatabaseValue]? { get } + var finalDatabaseValues: [DatabaseValue]? { get } + + func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? + func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? + + func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent +} + +/// Optimization: MetalDatabasePreUpdateEventImpl does not create Swift strings from raw +/// SQLite char* until actually asked for databaseName or tableName, +/// nor does it request other data via the sqlite3_preupdate_* APIs +/// until asked. +private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { + let connection: SQLiteConnection + let kind: DatabasePreUpdateEvent.Kind + + let databaseNameCString: UnsafePointer? + let tableNameCString: UnsafePointer? + + var databaseName: String { return String(cString: databaseNameCString!) } + var tableName: String { return String(cString: tableNameCString!) } + + var columnsCount: CInt { return sqlite3_preupdate_count(connection) } + var depth: CInt { return sqlite3_preupdate_depth(connection) } + var initialDatabaseValues: [DatabaseValue]? { + guard kind == .update || kind == .delete else { return nil } + return preupdate_getValues_old(connection) + } + + var finalDatabaseValues: [DatabaseValue]? { + guard kind == .update || kind == .insert else { return nil } + return preupdate_getValues_new(connection) + } + + func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { + let columnCount = columnsCount + precondition(index >= 0 && index < Int(columnCount), "row index out of range") + return getValue( + connection, + column: CInt(index), + sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in + sqlite3_preupdate_old(connection, column, &value) + }) + } + + func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { + let columnCount = columnsCount + precondition(index >= 0 && index < Int(columnCount), "row index out of range") + return getValue( + connection, + column: CInt(index), + sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in + sqlite3_preupdate_new(connection, column, &value) + }) + } + + func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent { + return DatabasePreUpdateEvent( + kind: event.kind, + initialRowID: event.initialRowID, + finalRowID: event.finalRowID, + impl: CopiedDatabasePreUpdateEventImpl( + databaseName: databaseName, + tableName: tableName, + columnsCount: columnsCount, + depth: depth, + initialDatabaseValues: initialDatabaseValues, + finalDatabaseValues: finalDatabaseValues)) + } + + private func preupdate_getValues( + _ connection: SQLiteConnection, + sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt) + -> [DatabaseValue]? + { + let columnCount = sqlite3_preupdate_count(connection) + guard columnCount > 0 else { return nil } + + var columnValues = [DatabaseValue]() + + for i in 0.. CInt) + -> DatabaseValue? + { + var value: SQLiteValue? = nil + guard sqlite_func(connection, column, &value) == SQLITE_OK else { return nil } + if let value = value { + return DatabaseValue(sqliteValue: value) + } + return nil + } + + private func preupdate_getValues_old(_ connection: SQLiteConnection) -> [DatabaseValue]? { + return preupdate_getValues( + connection, + sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in + sqlite3_preupdate_old(connection, column, &value) + }) + } + + private func preupdate_getValues_new(_ connection: SQLiteConnection) -> [DatabaseValue]? { + return preupdate_getValues( + connection, + sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in + sqlite3_preupdate_new(connection, column, &value) + }) + } +} + +/// Impl for DatabasePreUpdateEvent that contains copies of all event data. +private struct CopiedDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { + let databaseName: String + let tableName: String + let columnsCount: CInt + let depth: CInt + let initialDatabaseValues: [DatabaseValue]? + let finalDatabaseValues: [DatabaseValue]? + + func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { return initialDatabaseValues?[index] } + func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { return finalDatabaseValues?[index] } + + func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent { + return event + } +} #endif @@ -1330,4 +1390,3 @@ class SavepointStack { } } } - diff --git a/GRDB/FTS/FTS3.swift b/GRDB/FTS/FTS3.swift index 4bf3abfca..f97d29479 100644 --- a/GRDB/FTS/FTS3.swift +++ b/GRDB/FTS/FTS3.swift @@ -4,7 +4,7 @@ /// try db.create(virtualTable: "document", using: FTS3()) { t in /// t.column("content") /// } -public struct FTS3 : VirtualTableModule { +public struct FTS3: VirtualTableModule { /// Options for Latin script characters. Matches the raw "remove_diacritics" /// tokenizer argument. /// @@ -55,7 +55,10 @@ public struct FTS3 : VirtualTableModule { if tokenizer.arguments.isEmpty { arguments.append("tokenize=\(tokenizer.name)") } else { - arguments.append("tokenize=\(tokenizer.name) " + tokenizer.arguments.map { "\"\($0)\"" as String }.joined(separator: " ")) + arguments.append("tokenize=\(tokenizer.name) ") + arguments.append(tokenizer.arguments + .map { "\"\($0)\"" as String } + .joined(separator: " ")) } } return arguments diff --git a/GRDB/FTS/FTS3Pattern.swift b/GRDB/FTS/FTS3Pattern.swift index 69c43d0e1..ffabbfb4b 100644 --- a/GRDB/FTS/FTS3Pattern.swift +++ b/GRDB/FTS/FTS3Pattern.swift @@ -115,7 +115,7 @@ public struct FTS3Pattern { #endif } -extension FTS3Pattern : DatabaseValueConvertible { +extension FTS3Pattern: DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { return rawPattern.databaseValue diff --git a/GRDB/FTS/FTS3TokenizerDescriptor.swift b/GRDB/FTS/FTS3TokenizerDescriptor.swift index 44f667d0f..8f4f6a401 100644 --- a/GRDB/FTS/FTS3TokenizerDescriptor.swift +++ b/GRDB/FTS/FTS3TokenizerDescriptor.swift @@ -48,7 +48,12 @@ public struct FTS3TokenizerDescriptor { /// these characters as token characters. /// /// See https://www.sqlite.org/fts3.html#tokenizer - public static func unicode61(diacritics: FTS3.Diacritics = .removeLegacy, separators: Set = [], tokenCharacters: Set = []) -> FTS3TokenizerDescriptor { + public static func unicode61( + diacritics: FTS3.Diacritics = .removeLegacy, + separators: Set = [], + tokenCharacters: Set = []) + -> FTS3TokenizerDescriptor + { return _unicode61(diacritics: diacritics, separators: separators, tokenCharacters: tokenCharacters) } #else @@ -68,14 +73,25 @@ public struct FTS3TokenizerDescriptor { /// /// See https://www.sqlite.org/fts3.html#tokenizer @available(OSX 10.10, *) - public static func unicode61(diacritics: FTS3.Diacritics = .removeLegacy, separators: Set = [], tokenCharacters: Set = []) -> FTS3TokenizerDescriptor { + public static func unicode61( + diacritics: FTS3.Diacritics = .removeLegacy, + separators: Set = [], + tokenCharacters: Set = []) + -> FTS3TokenizerDescriptor + { // query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + // It is available from iOS 8.2 and OS X 10.10 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) return _unicode61(diacritics: diacritics, separators: separators, tokenCharacters: tokenCharacters) } #endif - private static func _unicode61(diacritics: FTS3.Diacritics, separators: Set = [], tokenCharacters: Set = []) -> FTS3TokenizerDescriptor { + private static func _unicode61( + diacritics: FTS3.Diacritics, + separators: Set = [], + tokenCharacters: Set = []) + -> FTS3TokenizerDescriptor + { var arguments: [String] = [] switch diacritics { case .removeLegacy: @@ -88,12 +104,16 @@ public struct FTS3TokenizerDescriptor { #endif } if !separators.isEmpty { - // TODO: test "=" and "\"", "(" and ")" as separators, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:) - arguments.append("separators=" + separators.sorted().map { String($0) }.joined(separator: "")) + // TODO: test "=" and "\"", "(" and ")" as separators, with + // both FTS3Pattern(matchingAnyTokenIn:tokenizer:) + // and Database.create(virtualTable:using:) + arguments.append("separators=" + separators.sorted().map { String($0) }.joined()) } if !tokenCharacters.isEmpty { - // TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:) - arguments.append("tokenchars=" + tokenCharacters.sorted().map { String($0) }.joined(separator: "")) + // TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with + // both FTS3Pattern(matchingAnyTokenIn:tokenizer:) + // and Database.create(virtualTable:using:) + arguments.append("tokenchars=" + tokenCharacters.sorted().map { String($0) }.joined()) } return FTS3TokenizerDescriptor("unicode61", arguments: arguments) } @@ -108,13 +128,14 @@ public struct FTS3TokenizerDescriptor { return _tokenize(string) } #endif - + /// Returns an array of tokens found in the string argument. /// /// FTS3TokenizerDescriptor.simple.tokenize("foo bar") // ["foo", "bar"] private func _tokenize(_ string: String) -> [String] { // fts3tokenize was introduced in SQLite 3.7.17 https://www.sqlite.org/changes.html#version_3_7_17 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + // It is available from iOS 8.2 and OS X 10.10 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) return DatabaseQueue().inDatabase { db in var tokenizerChunks: [String] = [] tokenizerChunks.append(name) @@ -124,7 +145,9 @@ public struct FTS3TokenizerDescriptor { let tokenizerSQL = tokenizerChunks.joined(separator: ", ") // Assume fts3tokenize virtual table in an in-memory database always succeeds try! db.execute(sql: "CREATE VIRTUAL TABLE tokens USING fts3tokenize(\(tokenizerSQL))") - return try! String.fetchAll(db, sql: "SELECT token FROM tokens WHERE input = ? ORDER BY position", arguments: [string]) + return try! String.fetchAll(db, sql: """ + SELECT token FROM tokens WHERE input = ? ORDER BY position + """, arguments: [string]) } } } diff --git a/GRDB/FTS/FTS4.swift b/GRDB/FTS/FTS4.swift index 56dc6e0f8..7fcdec269 100644 --- a/GRDB/FTS/FTS4.swift +++ b/GRDB/FTS/FTS4.swift @@ -6,7 +6,7 @@ /// } /// /// See https://www.sqlite.org/fts3.html -public struct FTS4 : VirtualTableModule { +public struct FTS4: VirtualTableModule { /// Creates a FTS4 module suitable for the Database /// `create(virtualTable:using:)` method. @@ -53,7 +53,10 @@ public struct FTS4 : VirtualTableModule { if tokenizer.arguments.isEmpty { arguments.append("tokenize=\(tokenizer.name)") } else { - arguments.append("tokenize=\(tokenizer.name) " + tokenizer.arguments.map { "\"\($0)\"" as String }.joined(separator: " ")) + arguments.append("tokenize=\(tokenizer.name) ") + arguments.append(tokenizer.arguments + .map { "\"\($0)\"" as String } + .joined(separator: " ")) } } @@ -112,16 +115,16 @@ public struct FTS4 : VirtualTableModule { try db.execute(sql: """ CREATE TRIGGER \("__\(tableName)_bu".quotedDatabaseIdentifier) BEFORE UPDATE ON \(content) BEGIN - DELETE FROM \(ftsTable) WHERE docid=\(oldRowID); + DELETE FROM \(ftsTable) WHERE docid=\(oldRowID); END; CREATE TRIGGER \("__\(tableName)_bd".quotedDatabaseIdentifier) BEFORE DELETE ON \(content) BEGIN - DELETE FROM \(ftsTable) WHERE docid=\(oldRowID); + DELETE FROM \(ftsTable) WHERE docid=\(oldRowID); END; CREATE TRIGGER \("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN - INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns)); + INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns)); END; CREATE TRIGGER \("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN - INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns)); + INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns)); END; """) @@ -273,7 +276,8 @@ public final class FTS4ColumnDefinition { @discardableResult public func notIndexed() -> Self { // notindexed FTS4 option was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + // It is available from iOS 8.2 and OS X 10.10 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) self.isIndexed = false return self } @@ -292,7 +296,8 @@ public final class FTS4ColumnDefinition { @discardableResult public func notIndexed() -> Self { // notindexed FTS4 option was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + // It is available from iOS 8.2 and OS X 10.10 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) self.isIndexed = false return self } diff --git a/GRDB/FTS/FTS5.swift b/GRDB/FTS/FTS5.swift index d7346948f..652f991f1 100644 --- a/GRDB/FTS/FTS5.swift +++ b/GRDB/FTS/FTS5.swift @@ -1,10 +1,10 @@ #if SQLITE_ENABLE_FTS5 #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// FTS5 lets you define "fts5" virtual tables. @@ -15,7 +15,7 @@ /// } /// /// See https://www.sqlite.org/fts5.html -public struct FTS5 : VirtualTableModule { +public struct FTS5: VirtualTableModule { /// Options for Latin script characters. Matches the raw "remove_diacritics" /// tokenizer argument. /// @@ -34,7 +34,7 @@ public struct FTS5 : VirtualTableModule { case remove #endif } - + /// Creates a FTS5 module suitable for the Database /// `create(virtualTable:using:)` method. /// @@ -75,30 +75,41 @@ public struct FTS5 : VirtualTableModule { } if let tokenizer = definition.tokenizer { - arguments.append("tokenize=\(tokenizer.components.joined(separator: " ").sqlExpression.quotedSQL(wrappedInParenthesis: false))") + let tokenizerSQL = tokenizer + .components + .joined(separator: " ") + .sqlExpression + .quotedSQL() + arguments.append("tokenize=\(tokenizerSQL)") } switch definition.contentMode { - case .raw(let content, let contentRowID): + case let .raw(content, contentRowID): if let content = content { - let quotedContent = content.sqlExpression.quotedSQL(wrappedInParenthesis: false) + let quotedContent = content.sqlExpression.quotedSQL() arguments.append("content=\(quotedContent)") } if let contentRowID = contentRowID { - let quotedContentRowID = contentRowID.sqlExpression.quotedSQL(wrappedInParenthesis: false) + let quotedContentRowID = contentRowID.sqlExpression.quotedSQL() arguments.append("content_rowid=\(quotedContentRowID)") } - case .synchronized(let contentTable): - arguments.append("content=\(contentTable.sqlExpression.quotedSQL(wrappedInParenthesis: false))") + case let .synchronized(contentTable): + arguments.append("content=\(contentTable.sqlExpression.quotedSQL())") if let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn { - let quotedRowID = rowIDColumn.sqlExpression.quotedSQL(wrappedInParenthesis: false) + let quotedRowID = rowIDColumn.sqlExpression.quotedSQL() arguments.append("content_rowid=\(quotedRowID)") } } if let prefixes = definition.prefixes { - arguments.append("prefix=\(prefixes.sorted().map { "\($0)" }.joined(separator: " ").sqlExpression.quotedSQL(wrappedInParenthesis: false))") + let prefix = prefixes + .sorted() + .map { "\($0)" } + .joined(separator: " ") + .sqlExpression + .quotedSQL() + arguments.append("prefix=\(prefix)") } if let columnSize = definition.columnSize { @@ -190,7 +201,7 @@ public struct FTS5 : VirtualTableModule { } #if swift(>=5.0) return data.withUnsafeBytes { - $0.bindMemory(to: UnsafePointer.self).first! + $0.bindMemory(to: UnsafePointer.self).first! } #else return data.withUnsafeBytes { @@ -203,7 +214,9 @@ public struct FTS5 : VirtualTableModule { // https://forums.swift.org/t/c-interoperability-combinations-of-library-and-os-versions/14029/4 private static func api_v2( _ db: Database, + // swiftlint:disable:next line_length _ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer?, Int32, UInt32, UnsafeMutablePointer?, UnsafeMutablePointer?>?) -> Int32, + // swiftlint:disable:next line_length _ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, Int32, UnsafeMutableRawPointer?, UnsafePointer?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> Int32) -> UnsafePointer { diff --git a/GRDB/FTS/FTS5CustomTokenizer.swift b/GRDB/FTS/FTS5CustomTokenizer.swift index 9d3a54570..ebfc24d5c 100644 --- a/GRDB/FTS/FTS5CustomTokenizer.swift +++ b/GRDB/FTS/FTS5CustomTokenizer.swift @@ -1,14 +1,14 @@ #if SQLITE_ENABLE_FTS5 #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// The protocol for custom FTS5 tokenizers. -public protocol FTS5CustomTokenizer : FTS5Tokenizer { +public protocol FTS5CustomTokenizer: FTS5Tokenizer { /// The name of the tokenizer; should uniquely identify your custom /// tokenizer. static var name: String { get } @@ -41,7 +41,6 @@ extension FTS5CustomTokenizer { public static func tokenizerDescriptor(arguments: [String] = []) -> FTS5TokenizerDescriptor { return FTS5TokenizerDescriptor(components: [name] + arguments) } - } extension Database { @@ -52,7 +51,10 @@ extension Database { let db: Database let constructor: (Database, [String], UnsafeMutablePointer?) -> Int32 - init(db: Database, constructor: @escaping (Database, [String], UnsafeMutablePointer?) -> Int32) { + init( + db: Database, + constructor: @escaping (Database, [String], UnsafeMutablePointer?) -> Int32) + { self.db = db self.constructor = constructor } @@ -101,7 +103,13 @@ extension Database { Unmanaged.fromOpaque(constructorPointer).release() } - func xCreateTokenizer(constructorPointer: UnsafeMutableRawPointer?, azArg: UnsafeMutablePointer?>?, nArg: Int32, tokenizerHandle: UnsafeMutablePointer?) -> Int32 { + func xCreateTokenizer( + constructorPointer: UnsafeMutableRawPointer?, + azArg: UnsafeMutablePointer?>?, + nArg: Int32, + tokenizerHandle: UnsafeMutablePointer?) + -> Int32 + { guard let constructorPointer = constructorPointer else { return SQLITE_ERROR } @@ -122,20 +130,41 @@ extension Database { Unmanaged.fromOpaque(UnsafeMutableRawPointer(tokenizerPointer)).release() } - func xTokenize(tokenizerPointer: OpaquePointer?, context: UnsafeMutableRawPointer?, flags: Int32, pText: UnsafePointer?, nText: Int32, tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, Int32, UnsafePointer?, Int32, Int32, Int32) -> Int32)?) -> Int32 { + func xTokenize( + tokenizerPointer: OpaquePointer?, + context: UnsafeMutableRawPointer?, + flags: Int32, + pText: UnsafePointer?, + nText: Int32, + // swiftlint:disable:next line_length + tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, Int32, UnsafePointer?, Int32, Int32, Int32) -> Int32)?) + -> Int32 + { guard let tokenizerPointer = tokenizerPointer else { return SQLITE_ERROR } - let object = Unmanaged.fromOpaque(UnsafeMutableRawPointer(tokenizerPointer)).takeUnretainedValue() + let object = Unmanaged + .fromOpaque(UnsafeMutableRawPointer(tokenizerPointer)) + .takeUnretainedValue() guard let tokenizer = object as? FTS5Tokenizer else { return SQLITE_ERROR } - return tokenizer.tokenize(context: context, tokenization: FTS5Tokenization(rawValue: flags), pText: pText, nText: nText, tokenCallback: tokenCallback!) + return tokenizer.tokenize( + context: context, + tokenization: FTS5Tokenization(rawValue: flags), + pText: pText, + nText: nText, + tokenCallback: tokenCallback!) } var xTokenizer = fts5_tokenizer(xCreate: xCreateTokenizer, xDelete: xDeleteTokenizer, xTokenize: xTokenize) let code = withUnsafeMutablePointer(to: &xTokenizer) { xTokenizerPointer in - api.pointee.xCreateTokenizer(UnsafeMutablePointer(mutating: api), Tokenizer.name, constructorPointer, xTokenizerPointer, deleteConstructor) + api.pointee.xCreateTokenizer( + UnsafeMutablePointer(mutating: api), + Tokenizer.name, + constructorPointer, + xTokenizerPointer, + deleteConstructor) } guard code == SQLITE_OK else { // Assume a GRDB bug: there is no point throwing any error. diff --git a/GRDB/FTS/FTS5Pattern.swift b/GRDB/FTS/FTS5Pattern.swift index c67558f10..e70f480ca 100644 --- a/GRDB/FTS/FTS5Pattern.swift +++ b/GRDB/FTS/FTS5Pattern.swift @@ -13,7 +13,14 @@ public struct FTS5Pattern { /// /// - parameter string: The string to turn into an FTS5 pattern public init?(matchingAnyTokenIn string: String) { - guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil } + guard + let tokens = try? DatabaseQueue().inDatabase({ db in + try db + .makeTokenizer(.ascii()) + .nonSynonymTokens(in: string, for: .query) }) + else { + return nil + } guard !tokens.isEmpty else { return nil } try? self.init(rawPattern: tokens.joined(separator: " OR ")) } @@ -26,7 +33,14 @@ public struct FTS5Pattern { /// /// - parameter string: The string to turn into an FTS5 pattern public init?(matchingAllTokensIn string: String) { - guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil } + guard + let tokens = try? DatabaseQueue().inDatabase({ db in + try db + .makeTokenizer(.ascii()) + .nonSynonymTokens(in: string, for: .query) }) + else { + return nil + } guard !tokens.isEmpty else { return nil } try? self.init(rawPattern: tokens.joined(separator: " ")) } @@ -39,7 +53,14 @@ public struct FTS5Pattern { /// /// - parameter string: The string to turn into an FTS5 pattern public init?(matchingPhrase string: String) { - guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil } + guard + let tokens = try? DatabaseQueue().inDatabase({ db in + try db + .makeTokenizer(.ascii()) + .nonSynonymTokens(in: string, for: .query) }) + else { + return nil + } guard !tokens.isEmpty else { return nil } try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"") } @@ -52,7 +73,14 @@ public struct FTS5Pattern { /// /// - parameter string: The string to turn into an FTS5 pattern public init?(matchingPrefixPhrase string: String) { - guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil } + guard + let tokens = try? DatabaseQueue().inDatabase({ db in + try db + .makeTokenizer(.ascii()) + .nonSynonymTokens(in: string, for: .query) }) + else { + return nil + } guard !tokens.isEmpty else { return nil } try? self.init(rawPattern: "^\"" + tokens.joined(separator: " ") + "\"") } @@ -104,7 +132,7 @@ extension Database { } } -extension FTS5Pattern : DatabaseValueConvertible { +extension FTS5Pattern: DatabaseValueConvertible { /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { return rawPattern.databaseValue diff --git a/GRDB/FTS/FTS5Tokenizer.swift b/GRDB/FTS/FTS5Tokenizer.swift index d5dd44de2..5517fcb29 100644 --- a/GRDB/FTS/FTS5Tokenizer.swift +++ b/GRDB/FTS/FTS5Tokenizer.swift @@ -1,21 +1,28 @@ #if SQLITE_ENABLE_FTS5 #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// A low-level SQLite function that lets FTS5Tokenizer notify tokens. /// /// See FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:) -public typealias FTS5TokenCallback = @convention(c) (_ context: UnsafeMutableRawPointer?, _ flags: Int32, _ pToken: UnsafePointer?, _ nToken: Int32, _ iStart: Int32, _ iEnd: Int32) -> Int32 +public typealias FTS5TokenCallback = @convention(c) ( + _ context: UnsafeMutableRawPointer?, + _ flags: Int32, + _ pToken: UnsafePointer?, + _ nToken: Int32, + _ iStart: Int32, + _ iEnd: Int32) + -> Int32 /// The reason why FTS5 is requesting tokenization. /// /// See https://www.sqlite.org/fts5.html#custom_tokenizers -public struct FTS5Tokenization : OptionSet { +public struct FTS5Tokenization: OptionSet { public let rawValue: Int32 public init(rawValue: Int32) { @@ -36,7 +43,7 @@ public struct FTS5Tokenization : OptionSet { } /// The protocol for FTS5 tokenizers -public protocol FTS5Tokenizer : class { +public protocol FTS5Tokenizer: AnyObject { /// Tokenizes the text described by `pText` and `nText`, and /// notifies found tokens to the `tokenCallback` function. /// @@ -51,7 +58,13 @@ public protocol FTS5Tokenizer : class { /// - nText: The number of bytes in the tokenized text. /// - tokenCallback: The function to call for each found token. /// It matches the `xToken` callback at https://www.sqlite.org/fts5.html#custom_tokenizers - func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 + func tokenize( + context: UnsafeMutableRawPointer?, + tokenization: FTS5Tokenization, + pText: UnsafePointer?, + nText: Int32, + tokenCallback: @escaping FTS5TokenCallback) + -> Int32 } private class TokenizeContext { @@ -81,20 +94,34 @@ extension FTS5Tokenizer { var context = TokenizeContext() try withUnsafeMutablePointer(to: &context) { contextPointer in - let code = tokenize(context: UnsafeMutableRawPointer(contextPointer), tokenization: tokenization, pText: pText, nText: nText, tokenCallback: { (contextPointer, flags, pToken, nToken, iStart, iEnd) -> Int32 in - guard let contextPointer = contextPointer else { return SQLITE_ERROR } - - // Extract token - guard let token = pToken.flatMap({ String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0), count: Int(nToken), deallocator: .none), encoding: .utf8) }) else { + let code = tokenize( + context: UnsafeMutableRawPointer(contextPointer), + tokenization: tokenization, + pText: pText, + nText: nText, + tokenCallback: { (contextPointer, flags, pToken, nToken, _ /* iStart */, _ /* iEnd */) -> Int32 in + guard let contextPointer = contextPointer else { + return SQLITE_ERROR + } + + // Extract token + guard + let token = pToken.flatMap({ + String( + data: Data( + bytesNoCopy: UnsafeMutableRawPointer(mutating: $0), + count: Int(nToken), + deallocator: .none), + encoding: .utf8) }) + else { + return SQLITE_OK + } + + let context = contextPointer.assumingMemoryBound(to: TokenizeContext.self).pointee + context.tokens.append((token, FTS5TokenFlags(rawValue: flags))) return SQLITE_OK - } - - let context = contextPointer.assumingMemoryBound(to: TokenizeContext.self).pointee - context.tokens.append((token, FTS5TokenFlags(rawValue: flags))) - - return SQLITE_OK }) - if (code != SQLITE_OK) { + if code != SQLITE_OK { throw DatabaseError(resultCode: code) } } @@ -119,7 +146,7 @@ extension Database { /// Private type that makes a pre-registered FTS5 tokenizer available /// through the FTS5Tokenizer protocol. - private final class FTS5RegisteredTokenizer : FTS5Tokenizer { + private final class FTS5RegisteredTokenizer: FTS5Tokenizer { let xTokenizer: fts5_tokenizer let tokenizerPointer: OpaquePointer @@ -135,7 +162,13 @@ extension Database { if let argument = arguments.first { // Turn [String] into ContiguousArray> // (for an alternative implementation see https://oleb.net/blog/2016/10/swift-array-of-c-strings/) - func convertArguments(_ array: inout ContiguousArray>, _ car: String, _ cdr: [String], _ body: (ContiguousArray>) -> Result) -> Result { + func convertArguments( + _ array: inout ContiguousArray>, + _ car: String, + _ cdr: [String], + _ body: (ContiguousArray>) -> Result) + -> Result + { return car.withCString { cString in if let car = cdr.first { array.append(cString) @@ -148,7 +181,11 @@ extension Database { var cStrings = ContiguousArray>() code = convertArguments(&cStrings, argument, Array(arguments.suffix(from: 1))) { cStrings in cStrings.withUnsafeBufferPointer { azArg in - xCreate(contextPointer, UnsafeMutablePointer(OpaquePointer(azArg.baseAddress!)), Int32(cStrings.count), &tokenizerPointer) + xCreate( + contextPointer, + UnsafeMutablePointer(OpaquePointer(azArg.baseAddress!)), + Int32(cStrings.count), + &tokenizerPointer) } } } else { @@ -172,7 +209,14 @@ extension Database { } } - func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 { + func tokenize( + context: UnsafeMutableRawPointer?, + tokenization: FTS5Tokenization, + pText: UnsafePointer?, + nText: Int32, + tokenCallback: @escaping FTS5TokenCallback) + -> Int32 + { guard let xTokenize = xTokenizer.xTokenize else { return SQLITE_ERROR } @@ -216,7 +260,10 @@ extension Database { } let contextPointer = contextHandle.pointee - return try FTS5RegisteredTokenizer(xTokenizer: xTokenizerPointer.pointee, contextPointer: contextPointer, arguments: descriptor.arguments) + return try FTS5RegisteredTokenizer( + xTokenizer: xTokenizerPointer.pointee, + contextPointer: contextPointer, + arguments: descriptor.arguments) } } #endif diff --git a/GRDB/FTS/FTS5TokenizerDescriptor.swift b/GRDB/FTS/FTS5TokenizerDescriptor.swift index dab8ec8a4..7ef83c9ff 100644 --- a/GRDB/FTS/FTS5TokenizerDescriptor.swift +++ b/GRDB/FTS/FTS5TokenizerDescriptor.swift @@ -57,11 +57,20 @@ public struct FTS5TokenizerDescriptor { /// /// See https://www.sqlite.org/fts5.html#ascii_tokenizer public static func ascii(separators: Set = []) -> FTS5TokenizerDescriptor { + let components: [String] if separators.isEmpty { - return FTS5TokenizerDescriptor(components: ["ascii"]) + components = ["ascii"] } else { - return FTS5TokenizerDescriptor(components: ["ascii", "separators", separators.map { String($0) }.joined(separator: "").sqlExpression.quotedSQL(wrappedInParenthesis: false)]) + components = [ + "ascii", + "separators", + separators + .map { String($0) } + .joined() + .sqlExpression + .quotedSQL()] } + return FTS5TokenizerDescriptor(components: components) } /// The "porter" tokenizer @@ -98,7 +107,12 @@ public struct FTS5TokenizerDescriptor { /// consider these characters as token characters. /// /// See https://www.sqlite.org/fts5.html#unicode61_tokenizer - public static func unicode61(diacritics: FTS5.Diacritics = .removeLegacy, separators: Set = [], tokenCharacters: Set = []) -> FTS5TokenizerDescriptor { + public static func unicode61( + diacritics: FTS5.Diacritics = .removeLegacy, + separators: Set = [], + tokenCharacters: Set = []) + -> FTS5TokenizerDescriptor + { var components: [String] = ["unicode61"] switch diacritics { case .removeLegacy: @@ -111,26 +125,32 @@ public struct FTS5TokenizerDescriptor { #endif } if !separators.isEmpty { - // TODO: test "=" and "\"", "(" and ")" as separators, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:) + // TODO: test "=" and "\"", "(" and ")" as separators, with + // both FTS3Pattern(matchingAnyTokenIn:tokenizer:) + // and Database.create(virtualTable:using:) components.append(contentsOf: [ "separators", separators .sorted() .map { String($0) } - .joined(separator: "") + .joined() .sqlExpression - .quotedSQL(wrappedInParenthesis: false)]) + .quotedSQL() + ]) } if !tokenCharacters.isEmpty { - // TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:) + // TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with + // both FTS3Pattern(matchingAnyTokenIn:tokenizer:) + // and Database.create(virtualTable:using:) components.append(contentsOf: [ "tokenchars", tokenCharacters .sorted() .map { String($0) } - .joined(separator: "") + .joined() .sqlExpression - .quotedSQL(wrappedInParenthesis: false)]) + .quotedSQL() + ]) } return FTS5TokenizerDescriptor(components: components) } diff --git a/GRDB/FTS/FTS5WrapperTokenizer.swift b/GRDB/FTS/FTS5WrapperTokenizer.swift index a217176cb..bfa346335 100644 --- a/GRDB/FTS/FTS5WrapperTokenizer.swift +++ b/GRDB/FTS/FTS5WrapperTokenizer.swift @@ -1,16 +1,16 @@ #if SQLITE_ENABLE_FTS5 #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// Flags that tell SQLite how to register a token. /// /// See https://www.sqlite.org/fts5.html#custom_tokenizers -public struct FTS5TokenFlags : OptionSet { +public struct FTS5TokenFlags: OptionSet { public let rawValue: Int32 public init(rawValue: Int32) { @@ -24,7 +24,7 @@ public struct FTS5TokenFlags : OptionSet { /// A function that lets FTS5WrapperTokenizer notify tokens. /// /// See FTS5WrapperTokenizer.accept(token:flags:tokenCallback:) -public typealias FTS5WrapperTokenCallback = (_ token: String, _ flags: FTS5TokenFlags) throws -> () +public typealias FTS5WrapperTokenCallback = (_ token: String, _ flags: FTS5TokenFlags) throws -> Void /// The protocol for custom FTS5 tokenizers that wrap another tokenizer. /// @@ -44,11 +44,17 @@ public typealias FTS5WrapperTokenCallback = (_ token: String, _ flags: FTS5Token /// wrappedTokenizer = try db.makeTokenizer(.ascii()) /// } /// -/// func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws { +/// func accept( +/// token: String, +/// flags: FTS5TokenFlags, +/// for tokenization: FTS5Tokenization, +/// tokenCallback: FTS5WrapperTokenCallback) +/// throws +/// { /// try tokenCallback(token, flags) /// } /// } -public protocol FTS5WrapperTokenizer : FTS5CustomTokenizer { +public protocol FTS5WrapperTokenizer: FTS5CustomTokenizer { /// The wrapped tokenizer var wrappedTokenizer: FTS5Tokenizer { get } @@ -57,7 +63,13 @@ public protocol FTS5WrapperTokenizer : FTS5CustomTokenizer { /// /// For example: /// - /// func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws { + /// func accept( + /// token: String, + /// flags: FTS5TokenFlags, + /// for tokenization: FTS5Tokenization, + /// tokenCallback: FTS5WrapperTokenCallback) + /// throws + /// { /// // pass through: /// try tokenCallback(token, flags) /// } @@ -77,7 +89,12 @@ public protocol FTS5WrapperTokenizer : FTS5CustomTokenizer { /// - flags: Flags that tell SQLite how to register a token. /// - tokenization: The reason why FTS5 is requesting tokenization. /// - tokenCallback: The function to call for each customized token. - func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws + func accept( + token: String, + flags: FTS5TokenFlags, + for tokenization: FTS5Tokenization, + tokenCallback: FTS5WrapperTokenCallback) + throws } private struct FTS5WrapperContext { @@ -89,7 +106,14 @@ private struct FTS5WrapperContext { extension FTS5WrapperTokenizer { /// Default implementation - public func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 { + public func tokenize( + context: UnsafeMutableRawPointer?, + tokenization: FTS5Tokenization, + pText: UnsafePointer?, + nText: Int32, + tokenCallback: @escaping FTS5TokenCallback) + -> Int32 + { // `tokenCallback` is @convention(c). This requires a little setup // in order to transfer context. var customContext = FTS5WrapperContext( @@ -99,49 +123,62 @@ extension FTS5WrapperTokenizer { tokenCallback: tokenCallback) return withUnsafeMutablePointer(to: &customContext) { customContextPointer in // Invoke wrappedTokenizer - return wrappedTokenizer.tokenize(context: customContextPointer, tokenization: tokenization, pText: pText, nText: nText) { (customContextPointer, tokenFlags, pToken, nToken, iStart, iEnd) in - - // Extract token produced by wrapped tokenizer - guard let token = pToken.flatMap({ String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0), count: Int(nToken), deallocator: .none), encoding: .utf8) }) else { - return 0 // SQLITE_OK - } - - // Extract context - let customContext = customContextPointer!.assumingMemoryBound(to: FTS5WrapperContext.self).pointee - let tokenizer = customContext.tokenizer - let context = customContext.context - let tokenization = customContext.tokenization - let tokenCallback = customContext.tokenCallback - - // Process token produced by wrapped tokenizer - do { - try tokenizer.accept( - token: token, - flags: FTS5TokenFlags(rawValue: tokenFlags), - for: tokenization, - tokenCallback: { (token, flags) in - // Turn token into bytes - return try ContiguousArray(token.utf8).withUnsafeBufferPointer { buffer in - guard let addr = buffer.baseAddress else { - return - } - let pToken = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: Int8.self) - let nToken = Int32(buffer.count) - - // Inject token bytes into SQLite - let code = tokenCallback(context, flags.rawValue, pToken, nToken, iStart, iEnd) - guard code == SQLITE_OK else { - throw DatabaseError(resultCode: code, message: "token callback failed") - } - } - }) + return wrappedTokenizer.tokenize( + context: customContextPointer, + tokenization: tokenization, + pText: pText, + nText: nText) { (customContextPointer, tokenFlags, pToken, nToken, iStart, iEnd) in - return SQLITE_OK - } catch let error as DatabaseError { - return error.extendedResultCode.rawValue - } catch { - return SQLITE_ERROR - } + // Extract token produced by wrapped tokenizer + guard + let token = pToken.flatMap({ + String( + data: Data( + bytesNoCopy: UnsafeMutableRawPointer(mutating: $0), + count: Int(nToken), + deallocator: .none), + encoding: .utf8) }) + else { + return SQLITE_OK // 0 // SQLITE_OK + } + + // Extract context + let customContext = customContextPointer!.assumingMemoryBound(to: FTS5WrapperContext.self).pointee + let tokenizer = customContext.tokenizer + let context = customContext.context + let tokenization = customContext.tokenization + let tokenCallback = customContext.tokenCallback + + // Process token produced by wrapped tokenizer + do { + try tokenizer.accept( + token: token, + flags: FTS5TokenFlags(rawValue: tokenFlags), + for: tokenization, + tokenCallback: { (token, flags) in + // Turn token into bytes + return try ContiguousArray(token.utf8).withUnsafeBufferPointer { buffer in + guard let addr = buffer.baseAddress else { + return + } + let pToken = UnsafeMutableRawPointer(mutating: addr) + .assumingMemoryBound(to: Int8.self) + let nToken = Int32(buffer.count) + + // Inject token bytes into SQLite + let code = tokenCallback(context, flags.rawValue, pToken, nToken, iStart, iEnd) + guard code == SQLITE_OK else { + throw DatabaseError(resultCode: code, message: "token callback failed") + } + } + }) + + return SQLITE_OK + } catch let error as DatabaseError { + return error.extendedResultCode.rawValue + } catch { + return SQLITE_ERROR + } } } } diff --git a/GRDB/Fixit/GRDB-4.0.swift b/GRDB/Fixit/GRDB-4.0.swift index f468c0604..1c6c41220 100644 --- a/GRDB/Fixit/GRDB-4.0.swift +++ b/GRDB/Fixit/GRDB-4.0.swift @@ -4,7 +4,10 @@ import Dispatch extension Cursor { @available(*, unavailable, renamed: "compactMap") - public func flatMap(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor>, ElementOfResult> { preconditionFailure() } + public func flatMap( + _ transform: @escaping (Element) throws -> ElementOfResult?) + -> MapCursor>, ElementOfResult> + { preconditionFailure() } } extension DatabaseWriter { @@ -14,17 +17,26 @@ extension DatabaseWriter { extension ValueObservation { @available(*, unavailable, message: "Provide the reducer in a (Database) -> Reducer closure") - public static func tracking(_ regions: DatabaseRegionConvertible..., reducer: Reducer) -> ValueObservation { preconditionFailure() } + public static func tracking(_ regions: DatabaseRegionConvertible..., reducer: Reducer) + -> ValueObservation + { preconditionFailure() } @available(*, unavailable, message: "Use removeDuplicates() instead") - public static func tracking(_ regions: DatabaseRegionConvertible..., fetchDistinct fetch: @escaping (Database) throws -> Value) -> ValueObservation>> where Value: Equatable { preconditionFailure() } + public static func tracking( + _ regions: DatabaseRegionConvertible..., + fetchDistinct fetch: @escaping (Database) throws -> Value) + -> ValueObservation>> + where Value: Equatable + { preconditionFailure() } } @available(*, unavailable, renamed: "FastDatabaseValueCursor") -public typealias ColumnCursor = FastDatabaseValueCursor +public typealias ColumnCursor = FastDatabaseValueCursor + where Value: DatabaseValueConvertible & StatementColumnConvertible @available(*, unavailable, renamed: "FastNullableDatabaseValueCursor") -public typealias NullableColumnCursor = FastNullableDatabaseValueCursor +public typealias NullableColumnCursor = FastNullableDatabaseValueCursor + where Value: DatabaseValueConvertible & StatementColumnConvertible extension Database { @available(*, unavailable, renamed: "execute(sql:arguments:)") @@ -45,58 +57,141 @@ extension Database { extension DatabaseValueConvertible { @available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)") - public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor { preconditionFailure() } + public static func fetchCursor( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> DatabaseValueCursor + { preconditionFailure() } @available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)") - public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { preconditionFailure() } + public static func fetchAll( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Self] + { preconditionFailure() } @available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)") - public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { preconditionFailure() } + public static func fetchOne( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> Self? + { preconditionFailure() } } extension Optional where Wrapped: DatabaseValueConvertible { @available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)") - public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor { preconditionFailure() } + public static func fetchCursor( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> NullableDatabaseValueCursor + { preconditionFailure() } @available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)") - public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] { preconditionFailure() } + public static func fetchAll( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Wrapped?] + { preconditionFailure() } } extension Row { @available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)") - public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor { preconditionFailure() } + public static func fetchCursor( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> RowCursor + { preconditionFailure() } @available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)") - public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row] { preconditionFailure() } + public static func fetchAll( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Row] + { preconditionFailure() } @available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)") - public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? { preconditionFailure() } + public static func fetchOne( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> Row? + { preconditionFailure() } } extension DatabaseValueConvertible where Self: StatementColumnConvertible { @available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)") - public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor { preconditionFailure() } + public static func fetchCursor( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> FastDatabaseValueCursor + { preconditionFailure() } } extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible { @available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)") - public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor { preconditionFailure() } + public static func fetchCursor( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> FastNullableDatabaseValueCursor + { preconditionFailure() } } extension FetchableRecord { @available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)") - public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor { preconditionFailure() } + public static func fetchCursor( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> RecordCursor + { preconditionFailure() } @available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)") - public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { preconditionFailure() } + public static func fetchAll( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Self] + { preconditionFailure() } @available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)") - public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { preconditionFailure() } + public static func fetchOne( + _ db: Database, + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> Self? + { preconditionFailure() } } extension SQLRequest { @available(*, unavailable, renamed: "init(sql:arguments:adapter:cached:)") - public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false) { preconditionFailure() } + public init( + _ sql: String, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil, + cached: Bool = false) + { preconditionFailure() } } extension SQLExpressionLiteral { @@ -111,30 +206,49 @@ extension SQLExpression { extension FTS3TokenizerDescriptor { @available(*, unavailable, renamed: "unicode61(diacritics:separators:tokenCharacters:)") - public static func unicode61(removeDiacritics: Bool, separators: Set = [], tokenCharacters: Set = []) -> FTS3TokenizerDescriptor { preconditionFailure() } + public static func unicode61( + removeDiacritics: Bool, + separators: Set = [], + tokenCharacters: Set = []) + -> FTS3TokenizerDescriptor + { preconditionFailure() } } #if SQLITE_ENABLE_FTS5 extension FTS5TokenizerDescriptor { @available(*, unavailable, renamed: "unicode61(diacritics:separators:tokenCharacters:)") - public static func unicode61(removeDiacritics: Bool = true, separators: Set = [], tokenCharacters: Set = []) -> FTS5TokenizerDescriptor { preconditionFailure() } + public static func unicode61( + removeDiacritics: Bool = true, + separators: Set = [], + tokenCharacters: Set = []) + -> FTS5TokenizerDescriptor + { preconditionFailure() } } #endif extension DatabaseValue { @available(*, unavailable) - public func losslessConvert(sql: String? = nil, arguments: StatementArguments? = nil) -> T where T: DatabaseValueConvertible { preconditionFailure() } + public func losslessConvert(sql: String? = nil, arguments: StatementArguments? = nil) + -> T + where T: DatabaseValueConvertible + { preconditionFailure() } @available(*, unavailable) - public func losslessConvert(sql: String? = nil, arguments: StatementArguments? = nil) -> T? where T: DatabaseValueConvertible { preconditionFailure() } + public func losslessConvert(sql: String? = nil, arguments: StatementArguments? = nil) + -> T? + where T: DatabaseValueConvertible + { preconditionFailure() } } extension ValueScheduling { @available(*, unavailable, renamed: "async(onQueue:startImmediately:)") - public static func onQueue(_ queue: DispatchQueue, startImmediately: Bool) -> ValueScheduling { preconditionFailure() } + public static func onQueue(_ queue: DispatchQueue, startImmediately: Bool) + -> ValueScheduling + { preconditionFailure() } } extension ValueObservation { + // swiftlint:disable:next line_length @available(*, unavailable, message: "Observation extent is controlled by the lifetime of observers returned by the start() method.") public var extent: Database.TransactionObservationExtent { get { preconditionFailure() } diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index b8d18d176..70520ce1b 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -68,7 +68,7 @@ public struct DatabaseMigrator { /// for some downloaded data. public var eraseDatabaseOnSchemaChange = false private var migrations: [Migration] = [] - + /// A new migrator. public init() { } @@ -92,58 +92,64 @@ public struct DatabaseMigrator { } #if GRDBCUSTOMSQLITE || GRDBCIPHER - /// 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. - /// - /// :nodoc: - public mutating func registerMigrationWithDeferredForeignKeyCheck(_ identifier: String, migrate: @escaping (Database) throws -> Void) { - registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate)) - } + /// 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. + /// + /// :nodoc: + public mutating func registerMigrationWithDeferredForeignKeyCheck( + _ identifier: String, + migrate: @escaping (Database) throws -> Void) + { + registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, 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)) - } + @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 @@ -232,7 +238,9 @@ public struct DatabaseMigrator { // MARK: - Non public private mutating func registerMigration(_ migration: Migration) { - GRDBPrecondition(!migrations.map({ $0.identifier }).contains(migration.identifier), "already registered migration: \(String(reflecting: migration.identifier))") + GRDBPrecondition( + !migrations.map({ $0.identifier }).contains(migration.identifier), + "already registered migration: \(String(reflecting: migration.identifier))") migrations.append(migration) } @@ -254,13 +262,17 @@ public struct DatabaseMigrator { } // targetIdentifier must refer to a registered migration - GRDBPrecondition(prefixMigrations.last?.identifier == targetIdentifier, "undefined migration: \(String(reflecting: targetIdentifier))") + GRDBPrecondition( + prefixMigrations.last?.identifier == targetIdentifier, + "undefined migration: \(String(reflecting: targetIdentifier))") // Subsequent migration must not be applied 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))") + GRDBPrecondition( + !appliedIdentifiers.contains(nextIdentifier), + "database is already migrated beyond migration \(String(reflecting: targetIdentifier))") } for migration in prefixMigrations where !appliedIdentifiers.contains(migration.identifier) { diff --git a/GRDB/Migration/Migration.swift b/GRDB/Migration/Migration.swift index 17d60de28..ac17249da 100644 --- a/GRDB/Migration/Migration.swift +++ b/GRDB/Migration/Migration.swift @@ -5,26 +5,27 @@ struct Migration { 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 - } + 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 - } + 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 - } + @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 { diff --git a/GRDB/QueryInterface/FTS5+QueryInterface.swift b/GRDB/QueryInterface/FTS5+QueryInterface.swift index ab3bb55e0..b39ee6ca3 100644 --- a/GRDB/QueryInterface/FTS5+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS5+QueryInterface.swift @@ -1,44 +1,44 @@ #if SQLITE_ENABLE_FTS5 - extension QueryInterfaceRequest { - - // MARK: Full Text Search - - /// Creates a request with a full-text predicate added to the eventual - /// set of already applied predicates. - /// - /// // SELECT * FROM book WHERE book MATCH '...' - /// var request = Book.all() - /// request = request.matching(pattern) - /// - /// If the search pattern is nil, the request does not match any - /// database row. - /// - /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableRecord.databaseSelection` property, or - /// for individual requests with the `TableRecord.select` method. - public func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest { - guard let pattern = pattern else { - return none() - } - let alias = TableAlias() - let matchExpression = TableMatchExpression(alias: alias, pattern: pattern.databaseValue) - return self.aliased(alias).filter(matchExpression) - } - } +extension QueryInterfaceRequest { - extension TableRecord { - - // MARK: Full Text Search - - /// Returns a QueryInterfaceRequest with a matching predicate. - /// - /// // SELECT * FROM book WHERE book MATCH '...' - /// var request = Book.matching(pattern) - /// - /// If the search pattern is nil, the request does not match any - /// database row. - public static func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest { - return all().matching(pattern) + // MARK: Full Text Search + + /// Creates a request with a full-text predicate added to the eventual + /// set of already applied predicates. + /// + /// // SELECT * FROM book WHERE book MATCH '...' + /// var request = Book.all() + /// request = request.matching(pattern) + /// + /// If the search pattern is nil, the request does not match any + /// database row. + /// + /// The selection defaults to all columns. This default can be changed for + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. + public func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest { + guard let pattern = pattern else { + return none() } + let alias = TableAlias() + let matchExpression = TableMatchExpression(alias: alias, pattern: pattern.databaseValue) + return self.aliased(alias).filter(matchExpression) } +} + +extension TableRecord { + + // MARK: Full Text Search + + /// Returns a QueryInterfaceRequest with a matching predicate. + /// + /// // SELECT * FROM book WHERE book MATCH '...' + /// var request = Book.matching(pattern) + /// + /// If the search pattern is nil, the request does not match any + /// database row. + public static func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest { + return all().matching(pattern) + } +} #endif diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index 27cc272fd..8099053da 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -72,12 +72,12 @@ extension Association { extension Association { private func mapDestinationRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self { - return Self.init(sqlAssociation: sqlAssociation.mapDestinationRelation(transform)) + return .init(sqlAssociation: sqlAssociation.mapDestinationRelation(transform)) } } extension Association { - + /// The association key defines how rows fetched from this association /// should be consumed. /// @@ -306,7 +306,7 @@ public protocol AssociationToOne: Association { } extension AssociationToOne { public func forKey(_ key: String) -> Self { let associationKey = SQLAssociationKey.fixedSingular(key) - return Self.init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey)) + return .init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey)) } } @@ -320,7 +320,7 @@ public protocol AssociationToMany: Association { } extension AssociationToMany { public func forKey(_ key: String) -> Self { let associationKey = SQLAssociationKey.fixedPlural(key) - return Self.init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey)) + return .init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey)) } } diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index cf67dd5bb..ae808050a 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -1,5 +1,9 @@ import Foundation +public typealias AssociationAggregatePreparation = + (QueryInterfaceRequest) + -> (request: QueryInterfaceRequest, expression: SQLExpression) + /// An AssociationAggregate is able to compute aggregated values from a /// population of associated records. /// @@ -56,12 +60,12 @@ public struct AssociationAggregate { /// - We don't know yet if the aggregated value will be used in the /// SQL selection, or in the HAVING clause. /// - It helps implementing aggregate operators such as `&&`, `+`, etc. - let prepare: (QueryInterfaceRequest) -> (request: QueryInterfaceRequest, expression: SQLExpression) + let prepare: AssociationAggregatePreparation /// The SQL alias for the value of this aggregate. See aliased(_:). var alias: String? - init(_ prepare: @escaping (QueryInterfaceRequest) -> (request: QueryInterfaceRequest, expression: SQLExpression)) { + init(_ prepare: @escaping AssociationAggregatePreparation) { self.prepare = prepare } } @@ -121,7 +125,11 @@ public prefix func ! (aggregate: AssociationAggregate) - /// For example: /// /// Author.having(Author.books.isEmpty && Author.paintings.isEmpty) -public func && (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func && ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -131,7 +139,11 @@ public func && (lhs: AssociationAggregate, rhs: Associat // TODO: test /// :nodoc: -public func && (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func && ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression && rhs) @@ -140,7 +152,11 @@ public func && (lhs: AssociationAggregate, rhs: SQLExpre // TODO: test /// :nodoc: -public func && (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func && ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs && expression) @@ -153,7 +169,11 @@ public func && (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func || ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -163,7 +183,11 @@ public func || (lhs: AssociationAggregate, rhs: Associat // TODO: test /// :nodoc: -public func || (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func || ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression || rhs) @@ -172,7 +196,11 @@ public func || (lhs: AssociationAggregate, rhs: SQLExpre // TODO: test /// :nodoc: -public func || (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func || ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs || expression) @@ -186,7 +214,11 @@ public func || (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func == ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -199,7 +231,11 @@ public func == (lhs: AssociationAggregate, rhs: Associat /// For example: /// /// Author.having(Author.books.count == 3) -public func == (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func == ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression == rhs) @@ -211,7 +247,11 @@ public func == (lhs: AssociationAggregate, rhs: SQLExpre /// For example: /// /// Author.having(3 == Author.books.count) -public func == (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func == ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs == expression) @@ -247,7 +287,11 @@ public func == (lhs: Bool, rhs: AssociationAggregate) -> /// For example: /// /// Author.having(Author.books.count != Author.paintings.count) -public func != (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func != ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -260,7 +304,11 @@ public func != (lhs: AssociationAggregate, rhs: Associat /// For example: /// /// Author.having(Author.books.count != 3) -public func != (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func != ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression != rhs) @@ -272,7 +320,11 @@ public func != (lhs: AssociationAggregate, rhs: SQLExpre /// For example: /// /// Author.having(3 != Author.books.count) -public func != (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func != ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs != expression) @@ -308,7 +360,11 @@ public func != (lhs: Bool, rhs: AssociationAggregate) -> /// For example: /// /// Author.having(Author.books.count === Author.paintings.count) -public func === (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func === ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -321,7 +377,11 @@ public func === (lhs: AssociationAggregate, rhs: Associa /// For example: /// /// Author.having(Author.books.count === 3) -public func === (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func === ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression === rhs) @@ -333,7 +393,11 @@ public func === (lhs: AssociationAggregate, rhs: SQLExpr /// For example: /// /// Author.having(3 === Author.books.count) -public func === (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func === ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs === expression) @@ -345,7 +409,11 @@ public func === (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func !== ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -358,7 +426,11 @@ public func !== (lhs: AssociationAggregate, rhs: Associa /// For example: /// /// Author.having(Author.books.count !== 3) -public func !== (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func !== ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression !== rhs) @@ -370,7 +442,11 @@ public func !== (lhs: AssociationAggregate, rhs: SQLExpr /// For example: /// /// Author.having(3 !== Author.books.count) -public func !== (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func !== ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs !== expression) @@ -384,7 +460,11 @@ public func !== (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func <= ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -397,7 +477,11 @@ public func <= (lhs: AssociationAggregate, rhs: Associat /// For example: /// /// Author.having(Author.books.count <= 3) -public func <= (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func <= ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression <= rhs) @@ -409,7 +493,11 @@ public func <= (lhs: AssociationAggregate, rhs: SQLExpre /// For example: /// /// Author.having(3 <= Author.books.count) -public func <= (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func <= ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs <= expression) @@ -421,7 +509,11 @@ public func <= (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func < ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -434,7 +526,11 @@ public func < (lhs: AssociationAggregate, rhs: Associati /// For example: /// /// Author.having(Author.books.count < 3) -public func < (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func < ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression < rhs) @@ -446,7 +542,11 @@ public func < (lhs: AssociationAggregate, rhs: SQLExpres /// For example: /// /// Author.having(3 < Author.books.count) -public func < (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func < ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs < expression) @@ -458,7 +558,11 @@ public func < (lhs: SQLExpressible, rhs: AssociationAggregate Author.paintings.count) -public func > (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func > ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -471,7 +575,11 @@ public func > (lhs: AssociationAggregate, rhs: Associati /// For example: /// /// Author.having(Author.books.count > 3) -public func > (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func > ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression > rhs) @@ -483,7 +591,11 @@ public func > (lhs: AssociationAggregate, rhs: SQLExpres /// For example: /// /// Author.having(3 > Author.books.count) -public func > (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func > ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs > expression) @@ -495,7 +607,11 @@ public func > (lhs: SQLExpressible, rhs: AssociationAggregate= Author.paintings.count) -public func >= (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func >= ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -508,7 +624,11 @@ public func >= (lhs: AssociationAggregate, rhs: Associat /// For example: /// /// Author.having(Author.books.count >= 3) -public func >= (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func >= ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression >= rhs) @@ -520,7 +640,11 @@ public func >= (lhs: AssociationAggregate, rhs: SQLExpre /// For example: /// /// Author.having(3 >= Author.books.count) -public func >= (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func >= ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs >= expression) @@ -546,7 +670,11 @@ public prefix func - (aggregate: AssociationAggregate) - /// For example: /// /// Author.annotated(with: Author.books.count + Author.paintings.count) -public func + (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func + ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -559,7 +687,11 @@ public func + (lhs: AssociationAggregate, rhs: Associati /// For example: /// /// Author.annotated(with: Author.books.count + 1) -public func + (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func + ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression + rhs) @@ -571,7 +703,11 @@ public func + (lhs: AssociationAggregate, rhs: SQLExpres /// For example: /// /// Author.annotated(with: 1 + Author.books.count) -public func + (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func + ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs + expression) @@ -583,7 +719,11 @@ public func + (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func - ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -596,7 +736,11 @@ public func - (lhs: AssociationAggregate, rhs: Associati /// For example: /// /// Author.annotated(with: Author.books.count - 1) -public func - (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func - ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression - rhs) @@ -608,7 +752,11 @@ public func - (lhs: AssociationAggregate, rhs: SQLExpres /// For example: /// /// Author.annotated(with: 1 - Author.books.count) -public func - (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func - ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs - expression) @@ -620,7 +768,11 @@ public func - (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func * ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -633,7 +785,11 @@ public func * (lhs: AssociationAggregate, rhs: Associati /// For example: /// /// Author.annotated(with: Author.books.count * 2) -public func * (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func * ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression * rhs) @@ -645,7 +801,11 @@ public func * (lhs: AssociationAggregate, rhs: SQLExpres /// For example: /// /// Author.annotated(with: 2 * Author.books.count) -public func * (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func * ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs * expression) @@ -657,7 +817,11 @@ public func * (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { +public func / ( + lhs: AssociationAggregate, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) let (request, rExpression) = rhs.prepare(lRequest) @@ -670,7 +834,11 @@ public func / (lhs: AssociationAggregate, rhs: Associati /// For example: /// /// Author.annotated(with: Author.books.count / 2) -public func / (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func / ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression / rhs) @@ -682,7 +850,11 @@ public func / (lhs: AssociationAggregate, rhs: SQLExpres /// For example: /// /// Author.annotated(with: 2 / Author.books.count) -public func / (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { +public func / ( + lhs: SQLExpressible, + rhs: AssociationAggregate) + -> AssociationAggregate +{ return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) return (request: request, expression: lhs / expression) @@ -694,7 +866,11 @@ public func / (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { +public func ?? ( + lhs: AssociationAggregate, + rhs: SQLExpressible) + -> AssociationAggregate +{ var aggregate = AssociationAggregate { request in let (request, expression) = lhs.prepare(request) return (request: request, expression: expression ?? rhs) diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift index ccc080857..0d43f4f9e 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift @@ -20,7 +20,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { public func annotated(with aggregates: AssociationAggregate...) -> QueryInterfaceRequest { return annotated(with: aggregates) } - + /// Creates a request which appends *aggregates* to the current selection. /// /// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index fcf8db63d..a6e74d751 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -143,7 +143,9 @@ extension QueryInterfaceRequest: SelectionRequest { /// let request = Player.all().select([max(Column("score"))], as: Int.self) /// let maxScore: Int? = try request.fetchOne(db) /// } - public func select(_ selection: [SQLSelectable], as type: RowDecoder.Type) -> QueryInterfaceRequest { + public func select(_ selection: [SQLSelectable], as type: RowDecoder.Type) + -> QueryInterfaceRequest + { return mapQuery { $0.select(selection) }.asRequest(of: RowDecoder.self) } @@ -155,7 +157,9 @@ extension QueryInterfaceRequest: SelectionRequest { /// let request = Player.all().select(max(Column("score")), as: Int.self) /// let maxScore: Int? = try request.fetchOne(db) /// } - public func select(_ selection: SQLSelectable..., as type: RowDecoder.Type) -> QueryInterfaceRequest { + public func select(_ selection: SQLSelectable..., as type: RowDecoder.Type) + -> QueryInterfaceRequest + { return select(selection, as: type) } @@ -167,7 +171,12 @@ extension QueryInterfaceRequest: SelectionRequest { /// let request = Player.all().select(sql: "max(score)", as: Int.self) /// let maxScore: Int? = try request.fetchOne(db) /// } - public func select(sql: String, arguments: StatementArguments = StatementArguments(), as type: RowDecoder.Type) -> QueryInterfaceRequest { + public func select( + sql: String, + arguments: StatementArguments = StatementArguments(), + as type: RowDecoder.Type) + -> QueryInterfaceRequest + { return select(literal: SQLLiteral(sql: sql, arguments: arguments), as: type) } @@ -198,7 +207,11 @@ extension QueryInterfaceRequest: SelectionRequest { /// as: String.self) /// let name: String? = try request.fetchOne(db) /// } - public func select(literal sqlLiteral: SQLLiteral, as type: RowDecoder.Type) -> QueryInterfaceRequest { + public func select( + literal sqlLiteral: SQLLiteral, + as type: RowDecoder.Type) + -> QueryInterfaceRequest + { return select(SQLSelectionLiteral(literal: sqlLiteral), as: type) } @@ -225,7 +238,7 @@ extension QueryInterfaceRequest: SelectionRequest { extension QueryInterfaceRequest: FilteredRequest { // MARK: Request Derivation - + /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. /// @@ -235,7 +248,6 @@ extension QueryInterfaceRequest: FilteredRequest { public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { return mapQuery { $0.filter(predicate) } } - } extension QueryInterfaceRequest: OrderedRequest { @@ -328,7 +340,7 @@ extension QueryInterfaceRequest: JoinableRequest { extension QueryInterfaceRequest { // MARK: Request Derivation - + /// Creates a request which returns distinct rows. /// /// // SELECT DISTINCT * FROM player @@ -479,7 +491,7 @@ extension QueryInterfaceRequest where T: MutablePersistableRecord { // MARK: - Eager loading of hasMany associations /// Append rows from prefetched associations into the argument rows. -fileprivate func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [Row]) throws { +private func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [Row]) throws { guard let firstRow = rows.first else { // No rows -> no prefetch return diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index c8c467d4f..1a45b4cc1 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -176,7 +176,7 @@ extension FilteredRequest { // NOT TESTED return filter(SQLExpressionLiteral(literal: sqlLiteral)) } - + /// Creates a request that matches nothing. /// /// // SELECT * FROM player WHERE 0 @@ -230,7 +230,10 @@ extension TableRequest where Self: FilteredRequest { } /// Creates a request with the provided primary key *predicate*. - public func filter(keys: Sequence) -> Self where Sequence.Element: DatabaseValueConvertible { + public func filter(keys: Sequence) + -> Self + where Sequence.Element: DatabaseValueConvertible + { var request = self let keys = Array(keys) switch keys.count { @@ -241,7 +244,7 @@ extension TableRequest where Self: FilteredRequest { default: break } - + let databaseTableName = self.databaseTableName return request.filter { db in let primaryKey = try db.primaryKey(databaseTableName) @@ -286,7 +289,10 @@ extension TableRequest where Self: FilteredRequest { // ("foo", "bar") is not a unique key (primary key or columns of a // unique index) guard let columns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else { - fatalError("table \(databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))") + fatalError(""" + table \(databaseTableName) has no unique index on column(s) \ + \(key.keys.sorted().joined(separator: ", ")) + """) } let lowercaseColumns = columns.map { $0.lowercased() } @@ -365,13 +371,13 @@ extension AggregatingRequest { // NOT TESTED return group(SQLExpressionLiteral(literal: sqlLiteral)) } - + /// Creates a request with the provided *sql* added to the /// eventual set of already applied predicates. public func having(sql: String, arguments: StatementArguments = StatementArguments()) -> Self { return having(literal: SQLLiteral(sql: sql, arguments: arguments)) } - + /// Creates a request with the provided *sql* added to the /// eventual set of already applied predicates. public func having(literal sqlLiteral: SQLLiteral) -> Self { diff --git a/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift b/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift index 29582b5f2..f80d4de53 100644 --- a/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift @@ -51,7 +51,7 @@ public struct SQLCollatedExpression { } /// :nodoc: -extension SQLCollatedExpression : SQLOrderingTerm { +extension SQLCollatedExpression: SQLOrderingTerm { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: diff --git a/GRDB/QueryInterface/SQL/SQLCollection.swift b/GRDB/QueryInterface/SQL/SQLCollection.swift index a070b8e9c..2ebcd6045 100644 --- a/GRDB/QueryInterface/SQL/SQLCollection.swift +++ b/GRDB/QueryInterface/SQL/SQLCollection.swift @@ -37,15 +37,17 @@ extension SQLCollection { /// SQLExpressionsArray wraps an array of expressions /// /// SQLExpressionsArray([1, 2, 3]) -struct SQLExpressionsArray : SQLCollection { +struct SQLExpressionsArray: SQLCollection { let expressions: [SQLExpression] - init(_ expressions: S) where S.Iterator.Element : SQLExpressible { + init(_ expressions: S) where S.Iterator.Element: SQLExpressible { self.expressions = expressions.map { $0.sqlExpression } } func collectionSQL(_ context: inout SQLGenerationContext) -> String { - return (expressions.map { $0.expressionSQL(&context, wrappedInParenthesis: false) } as [String]).joined(separator: ", ") + return expressions + .map { $0.expressionSQL(&context, wrappedInParenthesis: false) } + .joined(separator: ", ") } func contains(_ value: SQLExpressible) -> SQLExpression { diff --git a/GRDB/QueryInterface/SQL/SQLExpressible.swift b/GRDB/QueryInterface/SQL/SQLExpressible.swift index 366864aee..a0bb76240 100644 --- a/GRDB/QueryInterface/SQL/SQLExpressible.swift +++ b/GRDB/QueryInterface/SQL/SQLExpressible.swift @@ -31,7 +31,7 @@ public protocol SQLExpressible { /// On the other side, Int adopts SQLExpressible (via DatabaseValueConvertible). /// /// :nodoc: -public protocol SQLSpecificExpressible : SQLExpressible { +public protocol SQLSpecificExpressible: SQLExpressible { // SQLExpressible can be adopted by Swift standard types, and user // types, through the DatabaseValueConvertible protocol which inherits // from SQLExpressible. diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift index b94bd973a..a1b8981e9 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -14,10 +14,10 @@ extension SQLExpression { /// The expression as a quoted SQL literal (not public in order to avoid abuses) /// - /// "foo'bar".databaseValue.quotedSQL(wrappedInParenthesis: true) // "'foo''bar'"" - func quotedSQL(wrappedInParenthesis: Bool) -> String { + /// "foo'bar".databaseValue.quotedSQL() // "'foo''bar'"" + func quotedSQL() -> String { var context = SQLGenerationContext.literalGenerationContext(withArguments: false) - return expressionSQL(&context, wrappedInParenthesis: wrappedInParenthesis) + return expressionSQL(&context, wrappedInParenthesis: false) } } @@ -33,7 +33,7 @@ extension SQLExpression { /// /// SQLExpressionLiteral(sql: "? + ?", arguments: [1, 2]) /// SQLExpressionLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]) -public struct SQLExpressionLiteral : SQLExpression { +public struct SQLExpressionLiteral: SQLExpression { private let sqlLiteral: SQLLiteral public var sql: String { return sqlLiteral.sql } public var arguments: StatementArguments { return sqlLiteral.arguments } @@ -93,7 +93,7 @@ public struct SQLExpressionLiteral : SQLExpression { /// SQLUnaryOperator is a SQLite unary operator. /// /// :nodoc: -public struct SQLUnaryOperator : Hashable { +public struct SQLUnaryOperator: Hashable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// The SQL operator @@ -121,7 +121,7 @@ public struct SQLUnaryOperator : Hashable { /// an operand expression. /// /// :nodoc: -public struct SQLExpressionUnary : SQLExpression { +public struct SQLExpressionUnary: SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// The unary operator @@ -167,7 +167,7 @@ public struct SQLExpressionUnary : SQLExpression { /// SQLBinaryOperator is a SQLite binary operator. /// /// :nodoc: -public struct SQLBinaryOperator : Hashable { +public struct SQLBinaryOperator: Hashable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// The SQL operator @@ -211,7 +211,7 @@ public struct SQLBinaryOperator : Hashable { /// SQLExpressionBinary(.multiply, Column("length"), Column("width")) /// /// :nodoc: -public struct SQLExpressionBinary : SQLExpression { +public struct SQLExpressionBinary: SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// The left operand @@ -247,22 +247,22 @@ public struct SQLExpressionBinary : SQLExpression { return "(\(expressionSQL(&context, wrappedInParenthesis: false)))" } return """ - \(lhs.expressionSQL(&context, wrappedInParenthesis: true)) \ - \(op.sql) \ - \(rhs.expressionSQL(&context, wrappedInParenthesis: true)) - """ + \(lhs.expressionSQL(&context, wrappedInParenthesis: true)) \ + \(op.sql) \ + \(rhs.expressionSQL(&context, wrappedInParenthesis: true)) + """ } - + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public var negated: SQLExpression { if let negatedOp = op.negated { - return SQLExpressionBinary(negatedOp, lhs, rhs) + return SQLExpressionBinary(negatedOp, lhs, rhs) } else { return SQLExpressionNot(self) } } - + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { @@ -272,7 +272,7 @@ public struct SQLExpressionBinary : SQLExpression { // MARK: - SQLExpressionAnd -struct SQLExpressionAnd : SQLExpression { +struct SQLExpressionAnd: SQLExpression { let expressions: [SQLExpression] init(_ expressions: [SQLExpression]) { @@ -312,7 +312,7 @@ struct SQLExpressionAnd : SQLExpression { // MARK: - SQLExpressionOr -struct SQLExpressionOr : SQLExpression { +struct SQLExpressionOr: SQLExpression { let expressions: [SQLExpression] init(_ expressions: [SQLExpression]) { @@ -388,10 +388,10 @@ struct SQLExpressionEqual: SQLExpression { return "(\(expressionSQL(&context, wrappedInParenthesis: false)))" } return """ - \(lhs.expressionSQL(&context, wrappedInParenthesis: true)) \ - \(op.rawValue) \ - \(rhs.expressionSQL(&context, wrappedInParenthesis: true)) - """ + \(lhs.expressionSQL(&context, wrappedInParenthesis: true)) \ + \(op.rawValue) \ + \(rhs.expressionSQL(&context, wrappedInParenthesis: true)) + """ } var negated: SQLExpression { @@ -422,9 +422,9 @@ struct SQLExpressionEqual: SQLExpression { } } switch (lhs, rhs) { - case (let column as ColumnExpression, let dbValue as DatabaseValue): + case let (column as ColumnExpression, dbValue as DatabaseValue): return matchedRowIds(column: column, dbValue: dbValue) - case (let dbValue as DatabaseValue, let column as ColumnExpression): + case let (dbValue as DatabaseValue, column as ColumnExpression): return matchedRowIds(column: column, dbValue: dbValue) default: return nil @@ -443,7 +443,7 @@ struct SQLExpressionEqual: SQLExpression { /// /// // id IN (1,2,3) /// SQLExpressionContains(Column("id"), SQLExpressionsArray([1,2,3])) -struct SQLExpressionContains : SQLExpression { +struct SQLExpressionContains: SQLExpression { let expression: SQLExpression let collection: SQLCollection let isNegated: Bool @@ -459,10 +459,10 @@ struct SQLExpressionContains : SQLExpression { return "(\(expressionSQL(&context, wrappedInParenthesis: false)))" } return """ - \(expression.expressionSQL(&context, wrappedInParenthesis: true)) \ - \(isNegated ? "NOT IN" : "IN") \ - (\(collection.collectionSQL(&context))) - """ + \(expression.expressionSQL(&context, wrappedInParenthesis: true)) \ + \(isNegated ? "NOT IN" : "IN") \ + (\(collection.collectionSQL(&context))) + """ } var negated: SQLExpression { @@ -509,7 +509,7 @@ struct SQLExpressionContains : SQLExpression { /// /// // id BETWEEN 1 AND 3 /// SQLExpressionBetween(Column("id"), 1.databaseValue, 3.databaseValue) -struct SQLExpressionBetween : SQLExpression { +struct SQLExpressionBetween: SQLExpression { let expression: SQLExpression let lowerBound: SQLExpression let upperBound: SQLExpression @@ -527,14 +527,14 @@ struct SQLExpressionBetween : SQLExpression { return "(\(expressionSQL(&context, wrappedInParenthesis: false)))" } return """ - \(expression.expressionSQL(&context, wrappedInParenthesis: true)) \ - \(isNegated ? "NOT BETWEEN" : "BETWEEN") \ - \(lowerBound.expressionSQL(&context, wrappedInParenthesis: true)) \ - AND \ - \(upperBound.expressionSQL(&context, wrappedInParenthesis: true)) - """ + \(expression.expressionSQL(&context, wrappedInParenthesis: true)) \ + \(isNegated ? "NOT BETWEEN" : "BETWEEN") \ + \(lowerBound.expressionSQL(&context, wrappedInParenthesis: true)) \ + AND \ + \(upperBound.expressionSQL(&context, wrappedInParenthesis: true)) + """ } - + var negated: SQLExpression { return SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated) } @@ -553,7 +553,7 @@ struct SQLExpressionBetween : SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// SQLFunctionName is an SQL function name. -public struct SQLFunctionName : Hashable { +public struct SQLFunctionName: Hashable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// The SQL function name @@ -581,7 +581,7 @@ public struct SQLFunctionName : Hashable { /// SQLExpressionFunction(.abs, [-1.databaseValue]) /// /// :nodoc: -public struct SQLExpressionFunction : SQLExpression { +public struct SQLExpressionFunction: SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// The function name @@ -616,11 +616,13 @@ public struct SQLExpressionFunction : SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String { - return """ - \(functionName.sql)(\ - \((arguments.map { $0.expressionSQL(&context, wrappedInParenthesis: false) } as [String]).joined(separator: ", "))\ - ) - """ + var sql = functionName.sql + sql += "(" + sql += arguments + .map { $0.expressionSQL(&context, wrappedInParenthesis: false) } + .joined(separator: ", ") + sql += ")" + return sql } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) @@ -636,7 +638,7 @@ public struct SQLExpressionFunction : SQLExpression { /// /// // COUNT(name) /// SQLExpressionCount(Column("name")) -struct SQLExpressionCount : SQLExpression { +struct SQLExpressionCount: SQLExpression { /// The counted value let counted: SQLSelectable @@ -659,7 +661,7 @@ struct SQLExpressionCount : SQLExpression { /// /// // COUNT(DISTINCT name) /// SQLExpressionCountDistinct(Column("name")) -struct SQLExpressionCountDistinct : SQLExpression { +struct SQLExpressionCountDistinct: SQLExpression { let counted: SQLExpression init(_ counted: SQLExpression) { @@ -680,7 +682,7 @@ struct SQLExpressionCountDistinct : SQLExpression { /// This one helps generating `COUNT(...) = 0` or `COUNT(...) > 0` while letting /// the user using the not `!` logical operator, or comparisons with booleans /// such as `== true` or `== false`. -struct SQLExpressionIsEmpty : SQLExpression { +struct SQLExpressionIsEmpty: SQLExpression { var countExpression: SQLExpression var isEmpty: Bool @@ -699,9 +701,9 @@ struct SQLExpressionIsEmpty : SQLExpression { return "(\(expressionSQL(&context, wrappedInParenthesis: false)))" } return """ - \(countExpression.expressionSQL(&context, wrappedInParenthesis: true)) \ - \(isEmpty ? "= 0" : "> 0") - """ + \(countExpression.expressionSQL(&context, wrappedInParenthesis: true)) \ + \(isEmpty ? "= 0" : "> 0") + """ } func qualifiedExpression(with alias: TableAlias) -> SQLExpression { @@ -720,10 +722,10 @@ struct TableMatchExpression: SQLExpression { return "(\(expressionSQL(&context, wrappedInParenthesis: false)))" } return """ - \(context.resolvedName(for: alias).quotedDatabaseIdentifier) \ - MATCH \ - \(pattern.expressionSQL(&context, wrappedInParenthesis: true)) - """ + \(context.resolvedName(for: alias).quotedDatabaseIdentifier) \ + MATCH \ + \(pattern.expressionSQL(&context, wrappedInParenthesis: true)) + """ } func qualifiedExpression(with alias: TableAlias) -> SQLExpression { @@ -739,7 +741,7 @@ struct TableMatchExpression: SQLExpression { /// /// // email = 'arthur@example.com' COLLATE NOCASE /// SQLExpressionCollate(Column("email") == "arthur@example.com", "NOCASE") -struct SQLExpressionCollate : SQLExpression { +struct SQLExpressionCollate: SQLExpression { let expression: SQLExpression let collationName: Database.CollationName @@ -754,10 +756,10 @@ struct SQLExpressionCollate : SQLExpression { } let sql = expression.expressionSQL(&context, wrappedInParenthesis: false) return """ - \(sql) \ - COLLATE \ - \(collationName.rawValue) - """ + \(sql) \ + COLLATE \ + \(collationName.rawValue) + """ } func qualifiedExpression(with alias: TableAlias) -> SQLExpression { diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index b2f5582ec..ac9fed167 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -5,20 +5,8 @@ /// SQLExpression is the protocol for types that represent an SQL expression, as /// described at https://www.sqlite.org/lang_expr.html /// -/// GRDB ships with a variety of types that already adopt this protocol, and -/// allow to represent many SQLite expressions: -/// -/// - Column -/// - DatabaseValue -/// - SQLExpressionLiteral -/// - SQLExpressionUnary -/// - SQLExpressionBinary -/// - SQLExpressionExists -/// - SQLExpressionFunction -/// - SQLExpressionCollate -/// /// :nodoc: -public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderingTerm { +public protocol SQLExpression: SQLSpecificExpressible, SQLSelectable, SQLOrderingTerm { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// @@ -131,7 +119,7 @@ extension SQLExpression { // MARK: - SQLExpressionNot -struct SQLExpressionNot : SQLExpression { +struct SQLExpressionNot: SQLExpression { let expression: SQLExpression init(_ expression: SQLExpression) { diff --git a/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift b/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift index 8514256da..18ffe5187 100644 --- a/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift +++ b/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift @@ -67,7 +67,7 @@ struct SQLForeignKeyRequest: Equatable { // No matching foreign key found: use the destination primary key if let originColumns = originColumns { let destinationColumns = try db.primaryKey(destinationTable).columns - if (originColumns.count == destinationColumns.count) { + if originColumns.count == destinationColumns.count { let mapping = zip(originColumns, destinationColumns).map { (origin: $0, destination: $1) } diff --git a/GRDB/QueryInterface/SQL/SQLFunctions.swift b/GRDB/QueryInterface/SQL/SQLFunctions.swift index 8645fc737..06bd1d4a8 100644 --- a/GRDB/QueryInterface/SQL/SQLFunctions.swift +++ b/GRDB/QueryInterface/SQL/SQLFunctions.swift @@ -158,7 +158,7 @@ extension SQLSpecificExpressible { public var capitalized: SQLExpression { return DatabaseFunction.capitalize.apply(sqlExpression) } - + /// Returns an SQL expression that applies the Swift's built-in /// lowercased String property. It is NULL for non-String arguments. /// @@ -168,7 +168,7 @@ extension SQLSpecificExpressible { public var lowercased: SQLExpression { return DatabaseFunction.lowercase.apply(sqlExpression) } - + /// Returns an SQL expression that applies the Swift's built-in /// uppercased String property. It is NULL for non-String arguments. /// diff --git a/GRDB/QueryInterface/SQL/SQLOperators.swift b/GRDB/QueryInterface/SQL/SQLOperators.swift index 8ff7c996f..ac0ee9c87 100644 --- a/GRDB/QueryInterface/SQL/SQLOperators.swift +++ b/GRDB/QueryInterface/SQL/SQLOperators.swift @@ -3,14 +3,14 @@ // Outputs "x = y" or "x IS NULL" private func isEqual(_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression { switch (lhs, rhs) { - case (let lhs, let rhs as DatabaseValue): + case let (lhs, rhs as DatabaseValue): switch rhs.storage { case .null: return SQLExpressionEqual(.is, lhs, rhs) default: return SQLExpressionEqual(.equal, lhs, rhs) } - case (let lhs as DatabaseValue, let rhs): + case let (lhs as DatabaseValue, rhs): switch lhs.storage { case .null: return SQLExpressionEqual(.is, rhs, lhs) diff --git a/GRDB/QueryInterface/SQL/SQLOrdering.swift b/GRDB/QueryInterface/SQL/SQLOrdering.swift index f0ba0a1bf..25be3e43e 100644 --- a/GRDB/QueryInterface/SQL/SQLOrdering.swift +++ b/GRDB/QueryInterface/SQL/SQLOrdering.swift @@ -23,7 +23,7 @@ public protocol SQLOrderingTerm { // MARK: - SQLOrdering -enum SQLOrdering : SQLOrderingTerm { +enum SQLOrdering: SQLOrderingTerm { case asc(SQLExpression) case desc(SQLExpression) diff --git a/GRDB/QueryInterface/SQL/SQLQuery.swift b/GRDB/QueryInterface/SQL/SQLQuery.swift index ad3e1b2fb..87e3825e5 100644 --- a/GRDB/QueryInterface/SQL/SQLQuery.swift +++ b/GRDB/QueryInterface/SQL/SQLQuery.swift @@ -11,7 +11,7 @@ struct SQLQuery { // `(a AND b AND c)` instead of `((a AND b) AND c)`. var havingExpressions: [SQLExpression] var limit: SQLLimit? - + init( relation: SQLRelation, isDistinct: Bool = false, diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index ec5123fa2..ec7f167eb 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -1,4 +1,5 @@ -/// A "relation", as defined by the [relational terminology](https://en.wikipedia.org/wiki/Relational_database#Terminology), +/// A "relation", as defined by the [relational +/// terminology](https://en.wikipedia.org/wiki/Relational_database#Terminology), /// is "a set of tuples sharing the same attributes; a set of columns and rows." /// /// SQLRelation is defined with a selection, a source table of query, and an @@ -200,7 +201,7 @@ extension SQLRelation { relation.selection.append(contentsOf: selection) return relation } - + func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> SQLRelation { var relation = self relation.filtersPromise = relation.filtersPromise.flatMap { filters in @@ -277,10 +278,10 @@ extension SQLRelation { /// as HasManyThrough, which have any number of pivot relations between the /// origin and the destination. func appendingChild(for association: SQLAssociation, kind: SQLRelation.Child.Kind) -> SQLRelation { + // Preserve association cardinality in intermediate steps of + // including(all:), and force desired cardinality otherwize let childCardinality = (kind == .allNotPrefetched) - // preserve association cardinality in intermediate steps of including(all:) ? association.destination.cardinality - // force desired cardinality otherwize : kind.cardinality let childKey = association.destination.key.name(for: childCardinality) let child = SQLRelation.Child( @@ -347,7 +348,10 @@ extension SQLRelation { if let existingChild = relation.children.removeValue(forKey: key) { guard let mergedChild = existingChild.merged(with: child) else { // can't merge - fatalError("The association key \"\(key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") + fatalError(""" + The association key \"\(key)\" is ambiguous. \ + Use the Association.forKey(_:) method is order to disambiguate. + """) } relation.children.appendValue(mergedChild, forKey: key) } else { @@ -387,7 +391,7 @@ enum SQLSource { func qualified(with alias: TableAlias) -> SQLSource { switch self { - case .table(let tableName, let sourceAlias): + case let .table(tableName, sourceAlias): if let sourceAlias = sourceAlias { alias.becomeProxy(of: sourceAlias) return self @@ -395,7 +399,7 @@ enum SQLSource { alias.setTableName(tableName) return .table(tableName: tableName, alias: alias) } - case .query(let query): + case let .query(query): return .query(query.qualified(with: alias)) } } @@ -774,7 +778,7 @@ extension SQLRelation.Child.Kind { // .including(all: associationToDestinationThroughPivot) // .including(all: associationToPivot) fatalError("Not implemented: merging a direct association and an indirect one with including(all:)") - + case (.allNotPrefetched, .allNotPrefetched): // Equivalent to Record.including(all: association) // diff --git a/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift index 08fbe4c48..311e87d16 100644 --- a/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift @@ -18,7 +18,7 @@ public struct AllColumns { public init() { } } -extension AllColumns : SQLSelectable { +extension AllColumns: SQLSelectable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func resultColumnSQL(_ context: inout SQLGenerationContext) -> String { @@ -69,7 +69,7 @@ struct QualifiedAllColumns { } } -extension QualifiedAllColumns : SQLSelectable { +extension QualifiedAllColumns: SQLSelectable { func resultColumnSQL(_ context: inout SQLGenerationContext) -> String { if let qualifier = context.qualifier(for: alias) { return qualifier.quotedDatabaseIdentifier + ".*" @@ -94,10 +94,10 @@ extension QualifiedAllColumns : SQLSelectable { // // So let's always return `*`, and fix this later. -// if context.qualifier(for: alias) != nil { -// // SELECT COUNT(t.*) is invalid SQL -// fatalError("Not implemented, or invalid query") -// } + // if context.qualifier(for: alias) != nil { + // // SELECT COUNT(t.*) is invalid SQL + // fatalError("Not implemented, or invalid query") + // } return "*" } @@ -118,7 +118,7 @@ extension QualifiedAllColumns : SQLSelectable { // MARK: - SQLAliasedExpression -struct SQLAliasedExpression : SQLSelectable { +struct SQLAliasedExpression: SQLSelectable { let expression: SQLExpression let name: String diff --git a/GRDB/QueryInterface/SQL/SQLSelectable.swift b/GRDB/QueryInterface/SQL/SQLSelectable.swift index cc492f4bb..a0497b7d1 100644 --- a/GRDB/QueryInterface/SQL/SQLSelectable.swift +++ b/GRDB/QueryInterface/SQL/SQLSelectable.swift @@ -25,7 +25,7 @@ public protocol SQLSelectable { // MARK: - SQLSelectionLiteral -struct SQLSelectionLiteral : SQLSelectable { +struct SQLSelectionLiteral: SQLSelectable { private let sqlLiteral: SQLLiteral init(literal sqlLiteral: SQLLiteral) { @@ -42,15 +42,24 @@ struct SQLSelectionLiteral : SQLSelectable { } func countedSQL(_ context: inout SQLGenerationContext) -> String { - fatalError("Selection literals can't be counted. To resolve this error, select one or several SQLExpressionLiteral instead.") + fatalError(""" + Selection literals can't be counted. \ + To resolve this error, select one or several SQLExpressionLiteral instead. + """) } func count(distinct: Bool) -> SQLCount? { - fatalError("Selection literals can't be counted. To resolve this error, select one or several SQLExpressionLiteral instead.") + fatalError(""" + Selection literals can't be counted. \ + To resolve this error, select one or several SQLExpressionLiteral instead. + """) } func columnCount(_ db: Database) throws -> Int { - fatalError("Selection literals don't known how many columns they contain. To resolve this error, select one or several SQLExpressionLiteral instead.") + fatalError(""" + Selection literals don't known how many columns they contain. \ + To resolve this error, select one or several SQLExpressionLiteral instead. + """) } func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { diff --git a/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift index 329f3b39e..3c9c39d56 100644 --- a/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift @@ -63,4 +63,3 @@ extension SQLSpecificExpressible { return SQLCollatedExpression(sqlExpression, collationName: Database.CollationName(collation.name)) } } - diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index 60d5f4a1b..525e32728 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -96,7 +96,6 @@ public struct SQLGenerationContext { /// /// A TableAlias identifies a table in a request. public class TableAlias: Hashable { - private var impl: Impl private enum Impl { /// A TableAlias is undefined when it is created by the GRDB user: /// @@ -144,6 +143,8 @@ public class TableAlias: Hashable { case proxy(TableAlias) } + private var impl: Impl + /// Resolve all proxies private var root: TableAlias { if case .proxy(let base) = impl { @@ -221,7 +222,8 @@ public class TableAlias: Hashable { let root = self.root let otherRoot = other.root switch (root.impl, otherRoot.impl) { - case let (.table(tableName: tableName, userName: userName), .table(tableName: otherTableName, userName: otherUserName)): + case let (.table(tableName: tableName, userName: userName), + .table(tableName: otherTableName, userName: otherUserName)): guard tableName == otherTableName else { // can't merge return nil diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 1ab3bf6c2..2d3c8d7b1 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -54,32 +54,43 @@ struct SQLQueryGenerator { GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") sql += " " + selection.map { $0.resultColumnSQL(&context) }.joined(separator: ", ") - sql += try " FROM " + relation.source.sql(db, &context) + sql += " FROM " + sql += try relation.source.sql(db, &context) for (_, join) in relation.joins { - sql += try " " + join.sql(db, &context, leftAlias: relation.alias) + sql += " " + sql += try join.sql(db, &context, leftAlias: relation.alias) } let filters = try relation.filtersPromise.resolve(db) if filters.isEmpty == false { - sql += " WHERE " + SQLExpressionAnd(filters).expressionSQL(&context, wrappedInParenthesis: false) + sql += " WHERE " + sql += SQLExpressionAnd(filters).expressionSQL(&context, wrappedInParenthesis: false) } if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty { - sql += " GROUP BY " + groupExpressions.map { $0.expressionSQL(&context, wrappedInParenthesis: false) }.joined(separator: ", ") + sql += " GROUP BY " + sql += groupExpressions + .map { $0.expressionSQL(&context, wrappedInParenthesis: false) } + .joined(separator: ", ") } if havingExpressions.isEmpty == false { - sql += " HAVING " + SQLExpressionAnd(havingExpressions).expressionSQL(&context, wrappedInParenthesis: false) + sql += " HAVING " + sql += SQLExpressionAnd(havingExpressions).expressionSQL(&context, wrappedInParenthesis: false) } let orderings = try relation.ordering.resolve(db) if !orderings.isEmpty { - sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") + sql += " ORDER BY " + sql += orderings + .map { $0.orderingTermSQL(&context) } + .joined(separator: ", ") } if let limit = limit { - sql += " LIMIT " + limit.sql + sql += " LIMIT " + sql += limit.sql } return sql @@ -409,23 +420,23 @@ private enum SQLQualifiedSource { init(_ source: SQLSource) { switch source { - case .table(let tableName, let alias): + case let .table(tableName, alias): let alias = alias ?? TableAlias(tableName: tableName) self = .table(tableName: tableName, alias: alias) - case .query(let query): + case let .query(query): self = .query(SQLQueryGenerator(query)) } } func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { switch self { - case .table(let tableName, let alias): + case let .table(tableName, alias): if let aliasName = context.aliasName(for: alias) { return "\(tableName.quotedDatabaseIdentifier) \(aliasName.quotedDatabaseIdentifier)" } else { return "\(tableName.quotedDatabaseIdentifier)" } - case .query(let query): + case let .query(query): return try "(\(query.sql(db, &context)))" } } @@ -437,15 +448,22 @@ private struct SQLQualifiedJoin { case leftJoin = "LEFT JOIN" case innerJoin = "JOIN" } + let kind: Kind let condition: SQLAssociationCondition let relation: SQLQualifiedRelation - func sql(_ db: Database,_ context: inout SQLGenerationContext, leftAlias: TableAlias) throws -> String { + func sql(_ db: Database, _ context: inout SQLGenerationContext, leftAlias: TableAlias) throws -> String { return try sql(db, &context, leftAlias: leftAlias, allowingInnerJoin: true) } - private func sql(_ db: Database,_ context: inout SQLGenerationContext, leftAlias: TableAlias, allowingInnerJoin allowsInnerJoin: Bool) throws -> String { + private func sql( + _ db: Database, + _ context: inout SQLGenerationContext, + leftAlias: TableAlias, + allowingInnerJoin allowsInnerJoin: Bool) + throws -> String + { var allowsInnerJoin = allowsInnerJoin var sql = "" diff --git a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift index 52f16831f..6d7d71382 100644 --- a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift @@ -44,7 +44,9 @@ extension SQLInterpolation { /// let request: SQLRequest = " /// SELECT \(CodingKey.name) FROM player /// """ - public mutating func appendInterpolation(_ codingKey: SQLExpressible & SQLSelectable & SQLOrderingTerm & CodingKey) { + public mutating func appendInterpolation( + _ codingKey: SQLExpressible & SQLSelectable & SQLOrderingTerm & CodingKey) + { sql += codingKey.sqlExpression.expressionSQL(&context, wrappedInParenthesis: false) } @@ -133,7 +135,7 @@ extension SQLInterpolation { public mutating func appendInterpolation(_ ordering: SQLOrderingTerm) { sql += ordering.orderingTermSQL(&context) } - + /// Appends the request SQL, wrapped in parentheses /// /// // SELECT name FROM player WHERE score = (SELECT MAX(score) FROM player) diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index 2c4c35c08..10a18d68b 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -25,8 +25,19 @@ extension Database { /// - withoutRowID: If true, uses WITHOUT ROWID optimization. /// - body: A closure that defines table columns and constraints. /// - throws: A DatabaseError whenever an SQLite error occurs. - public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, withoutRowID: Bool = false, body: (TableDefinition) -> Void) throws { - let definition = TableDefinition(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: withoutRowID) + public func create( + table name: String, + temporary: Bool = false, + ifNotExists: Bool = false, + withoutRowID: Bool = false, + body: (TableDefinition) -> Void) + throws + { + let definition = TableDefinition( + name: name, + temporary: temporary, + ifNotExists: ifNotExists, + withoutRowID: withoutRowID) body(definition) let sql = try definition.sql(self) try execute(sql: sql) @@ -55,10 +66,22 @@ extension Database { /// - body: A closure that defines table columns and constraints. /// - throws: A DatabaseError whenever an SQLite error occurs. @available(OSX 10.10, *) - public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, withoutRowID: Bool, body: (TableDefinition) -> Void) throws { + public func create( + table name: String, + temporary: Bool = false, + ifNotExists: Bool = false, + withoutRowID: Bool, + body: (TableDefinition) -> Void) + throws + { // WITHOUT ROWID was added in SQLite 3.8.2 http://www.sqlite.org/changes.html#version_3_8_2 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - let definition = TableDefinition(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: withoutRowID) + // It is available from iOS 8.2 and OS X 10.10 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + let definition = TableDefinition( + name: name, + temporary: temporary, + ifNotExists: ifNotExists, + withoutRowID: withoutRowID) body(definition) let sql = try definition.sql(self) try execute(sql: sql) @@ -84,14 +107,24 @@ extension Database { /// already exists. /// - body: A closure that defines table columns and constraints. /// - throws: A DatabaseError whenever an SQLite error occurs. - public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, body: (TableDefinition) -> Void) throws { - let definition = TableDefinition(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: false) + public func create( + table name: String, + temporary: Bool = false, + ifNotExists: Bool = false, + body: (TableDefinition) -> Void) + throws + { + let definition = TableDefinition( + name: name, + temporary: temporary, + ifNotExists: ifNotExists, + withoutRowID: false) body(definition) let sql = try definition.sql(self) try execute(sql: sql) } #endif - + /// Renames a database table. /// /// See https://www.sqlite.org/lang_altertable.html @@ -150,10 +183,25 @@ extension Database { /// - ifNotExists: If false, no error is thrown if index already exists. /// - condition: If not nil, creates a partial index /// (see https://www.sqlite.org/partialindex.html). - public func create(index name: String, on table: String, columns: [String], unique: Bool = false, ifNotExists: Bool = false, condition: SQLExpressible? = nil) throws { + public func create( + index name: String, + on table: String, + columns: [String], + unique: Bool = false, + ifNotExists: Bool = false, + condition: SQLExpressible? = nil) + throws + { // Partial indexes were introduced in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - let definition = IndexDefinition(name: name, table: table, columns: columns, unique: unique, ifNotExists: ifNotExists, condition: condition?.sqlExpression) + // It is available from iOS 8.2 and OS X 10.10 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + let definition = IndexDefinition( + name: name, + table: table, + columns: columns, + unique: unique, + ifNotExists: ifNotExists, + condition: condition?.sqlExpression) let sql = definition.sql() try execute(sql: sql) } @@ -176,10 +224,24 @@ extension Database { /// - columns: The indexed columns. /// - unique: If true, creates a unique index. /// - ifNotExists: If false, no error is thrown if index already exists. - public func create(index name: String, on table: String, columns: [String], unique: Bool = false, ifNotExists: Bool = false) throws { + public func create( + index name: String, + on table: String, + columns: [String], + unique: Bool = false, + ifNotExists: Bool = false) + throws + { // Partial indexes were introduced in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - let definition = IndexDefinition(name: name, table: table, columns: columns, unique: unique, ifNotExists: ifNotExists, condition: nil) + // It is available from iOS 8.2 and OS X 10.10 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + let definition = IndexDefinition( + name: name, + table: table, + columns: columns, + unique: unique, + ifNotExists: ifNotExists, + condition: nil) let sql = definition.sql() try execute(sql: sql) } @@ -199,10 +261,25 @@ extension Database { /// - ifNotExists: If false, no error is thrown if index already exists. /// - condition: The condition that indexed rows must verify. @available(OSX 10.10, *) - public func create(index name: String, on table: String, columns: [String], unique: Bool = false, ifNotExists: Bool = false, condition: SQLExpressible) throws { + public func create( + index name: String, + on table: String, + columns: [String], + unique: Bool = false, + ifNotExists: Bool = false, + condition: SQLExpressible) + throws + { // Partial indexes were introduced in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - let definition = IndexDefinition(name: name, table: table, columns: columns, unique: unique, ifNotExists: ifNotExists, condition: condition.sqlExpression) + // It is available from iOS 8.2 and OS X 10.10 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + let definition = IndexDefinition( + name: name, + table: table, + columns: columns, + unique: unique, + ifNotExists: ifNotExists, + condition: condition.sqlExpression) let sql = definition.sql() try execute(sql: sql) } @@ -253,7 +330,18 @@ extension Database { /// /// See https://www.sqlite.org/lang_createtable.html public final class TableDefinition { - private typealias KeyConstraint = (columns: [String], conflictResolution: Database.ConflictResolution?) + private typealias KeyConstraint = ( + columns: [String], + conflictResolution: Database.ConflictResolution?) + + private struct ForeignKeyConstraint { + var columns: [String] + var table: String + var destinationColumns: [String]? + var deleteAction: Database.ForeignKeyAction? + var updateAction: Database.ForeignKeyAction? + var deferred: Bool + } private let name: String private let temporary: Bool @@ -262,7 +350,7 @@ public final class TableDefinition { private var columns: [ColumnDefinition] = [] private var primaryKeyConstraint: KeyConstraint? private var uniqueKeyConstraints: [KeyConstraint] = [] - private var foreignKeyConstraints: [(columns: [String], table: String, destinationColumns: [String]?, deleteAction: Database.ForeignKeyAction?, updateAction: Database.ForeignKeyAction?, deferred: Bool)] = [] + private var foreignKeyConstraints: [ForeignKeyConstraint] = [] private var checkConstraints: [SQLExpression] = [] init(name: String, temporary: Bool, ifNotExists: Bool, withoutRowID: Bool) { @@ -300,10 +388,14 @@ public final class TableDefinition { /// (see https://www.sqlite.org/lang_conflict.html). /// - returns: Self so that you can further refine the column definition. @discardableResult - public func autoIncrementedPrimaryKey(_ name: String, onConflict conflictResolution: Database.ConflictResolution? = nil) -> ColumnDefinition { + public func autoIncrementedPrimaryKey( + _ name: String, + onConflict conflictResolution: Database.ConflictResolution? = nil) + -> ColumnDefinition + { return column(name, .integer).primaryKey(onConflict: conflictResolution, autoincrement: true) } - + /// Appends a table column. /// /// try db.create(table: "player") { t in @@ -383,8 +475,21 @@ public final class TableDefinition { /// - updateAction: Optional action when the referenced row is updated. /// - deferred: If true, defines a deferred foreign key constraint. /// See https://www.sqlite.org/foreignkeys.html#fk_deferred. - public func foreignKey(_ columns: [String], references table: String, columns destinationColumns: [String]? = nil, onDelete deleteAction: Database.ForeignKeyAction? = nil, onUpdate updateAction: Database.ForeignKeyAction? = nil, deferred: Bool = false) { - foreignKeyConstraints.append((columns: columns, table: table, destinationColumns: destinationColumns, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred)) + public func foreignKey( + _ columns: [String], + references table: String, + columns destinationColumns: [String]? = nil, + onDelete deleteAction: Database.ForeignKeyAction? = nil, + onUpdate updateAction: Database.ForeignKeyAction? = nil, + deferred: Bool = false) + { + foreignKeyConstraints.append(ForeignKeyConstraint( + columns: columns, + table: table, + destinationColumns: destinationColumns, + deleteAction: deleteAction, + updateAction: updateAction, + deferred: deferred)) } /// Adds a CHECK constraint. @@ -451,12 +556,14 @@ public final class TableDefinition { do { var items: [String] = [] - try items.append(contentsOf: columns.map { try $0.sql(db, tableName: name, primaryKeyColumns: primaryKeyColumns) }) + try items.append(contentsOf: columns.map { + try $0.sql(db, tableName: name, primaryKeyColumns: primaryKeyColumns) + }) if let (columns, conflictResolution) = primaryKeyConstraint { var chunks: [String] = [] chunks.append("PRIMARY KEY") - chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + chunks.append("(\(columns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", ")))") if let conflictResolution = conflictResolution { chunks.append("ON CONFLICT") chunks.append(conflictResolution.rawValue) @@ -467,7 +574,7 @@ public final class TableDefinition { for (columns, conflictResolution) in uniqueKeyConstraints { var chunks: [String] = [] chunks.append("UNIQUE") - chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + chunks.append("(\(columns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", ")))") if let conflictResolution = conflictResolution { chunks.append("ON CONFLICT") chunks.append(conflictResolution.rawValue) @@ -475,28 +582,40 @@ public final class TableDefinition { items.append(chunks.joined(separator: " ")) } - for (columns, table, destinationColumns, deleteAction, updateAction, deferred) in foreignKeyConstraints { + for constraint in foreignKeyConstraints { var chunks: [String] = [] chunks.append("FOREIGN KEY") - chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + chunks.append("(\(constraint.columns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", ")))") chunks.append("REFERENCES") - if let destinationColumns = destinationColumns { - chunks.append("\(table.quotedDatabaseIdentifier)(\((destinationColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") - } else if table == name { - chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + if let destinationColumns = constraint.destinationColumns { + chunks.append(""" + \(constraint.table.quotedDatabaseIdentifier)(\ + \(destinationColumns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", "))\ + ) + """) + } else if constraint.table == name { + chunks.append(""" + \(constraint.table.quotedDatabaseIdentifier)(\ + \(primaryKeyColumns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", "))\ + ) + """) } else { - let primaryKey = try db.primaryKey(table) - chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKey.columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + let primaryKey = try db.primaryKey(constraint.table) + chunks.append(""" + \(constraint.table.quotedDatabaseIdentifier)(\ + \(primaryKey.columns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", "))\ + ) + """) } - if let deleteAction = deleteAction { + if let deleteAction = constraint.deleteAction { chunks.append("ON DELETE") chunks.append(deleteAction.rawValue) } - if let updateAction = updateAction { + if let updateAction = constraint.updateAction { chunks.append("ON UPDATE") chunks.append(updateAction.rawValue) } - if deferred { + if constraint.deferred { chunks.append("DEFERRABLE INITIALLY DEFERRED") } items.append(chunks.joined(separator: " ")) @@ -504,7 +623,7 @@ public final class TableDefinition { for checkExpression in checkConstraints { var chunks: [String] = [] - chunks.append("CHECK (\(checkExpression.quotedSQL(wrappedInParenthesis: false)))") + chunks.append("CHECK (\(checkExpression.quotedSQL()))") items.append(chunks.joined(separator: " ")) } @@ -603,13 +722,22 @@ public final class ColumnDefinition { case index case unique(Database.ConflictResolution) } + + private struct ForeignKeyConstraint { + var table: String + var column: String? + var deleteAction: Database.ForeignKeyAction? + var updateAction: Database.ForeignKeyAction? + var deferred: Bool + } + fileprivate let name: String private let type: Database.ColumnType? fileprivate var primaryKey: (conflictResolution: Database.ConflictResolution?, autoincrement: Bool)? private var index: Index = .none private var notNullConflictResolution: Database.ConflictResolution? private var checkConstraints: [SQLExpression] = [] - private var foreignKeyConstraints: [(table: String, column: String?, deleteAction: Database.ForeignKeyAction?, updateAction: Database.ForeignKeyAction?, deferred: Bool)] = [] + private var foreignKeyConstraints: [ForeignKeyConstraint] = [] private var defaultExpression: SQLExpression? private var collationName: String? @@ -633,7 +761,11 @@ public final class ColumnDefinition { /// - autoincrement: If true, the primary key is autoincremented. /// - returns: Self so that you can further refine the column definition. @discardableResult - public func primaryKey(onConflict conflictResolution: Database.ConflictResolution? = nil, autoincrement: Bool = false) -> Self { + public func primaryKey( + onConflict conflictResolution: Database.ConflictResolution? = nil, + autoincrement: Bool = false) + -> Self + { primaryKey = (conflictResolution: conflictResolution, autoincrement: autoincrement) return self } @@ -804,8 +936,19 @@ public final class ColumnDefinition { /// See https://www.sqlite.org/foreignkeys.html#fk_deferred. /// - returns: Self so that you can further refine the column definition. @discardableResult - public func references(_ table: String, column: String? = nil, onDelete deleteAction: Database.ForeignKeyAction? = nil, onUpdate updateAction: Database.ForeignKeyAction? = nil, deferred: Bool = false) -> Self { - foreignKeyConstraints.append((table: table, column: column, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred)) + public func references( + _ table: String, + column: String? = nil, + onDelete deleteAction: Database.ForeignKeyAction? = nil, + onUpdate updateAction: Database.ForeignKeyAction? = nil, + deferred: Bool = false) -> Self + { + foreignKeyConstraints.append(ForeignKeyConstraint( + table: table, + column: column, + deleteAction: deleteAction, + updateAction: updateAction, + deferred: deferred)) return self } @@ -853,11 +996,11 @@ public final class ColumnDefinition { } for checkConstraint in checkConstraints { - chunks.append("CHECK (\(checkConstraint.quotedSQL(wrappedInParenthesis: false)))") + chunks.append("CHECK (\(checkConstraint.quotedSQL()))") } if let defaultExpression = defaultExpression { - chunks.append("DEFAULT \(defaultExpression.quotedSQL(wrappedInParenthesis: false))") + chunks.append("DEFAULT \(defaultExpression.quotedSQL())") } if let collationName = collationName { @@ -865,29 +1008,37 @@ public final class ColumnDefinition { chunks.append(collationName) } - for (table, column, deleteAction, updateAction, deferred) in foreignKeyConstraints { + for constraint in foreignKeyConstraints { chunks.append("REFERENCES") - if let column = column { + if let column = constraint.column { // explicit reference - chunks.append("\(table.quotedDatabaseIdentifier)(\(column.quotedDatabaseIdentifier))") - } else if table.lowercased() == tableName.lowercased() { + chunks.append("\(constraint.table.quotedDatabaseIdentifier)(\(column.quotedDatabaseIdentifier))") + } else if constraint.table.lowercased() == tableName.lowercased() { // implicit autoreference - let primaryKeyColumns = try primaryKeyColumns ?? db.primaryKey(table).columns - chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + let primaryKeyColumns = try primaryKeyColumns ?? db.primaryKey(constraint.table).columns + chunks.append(""" + \(constraint.table.quotedDatabaseIdentifier)(\ + \(primaryKeyColumns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", "))\ + ) + """) } else { // implicit external reference - let primaryKeyColumns = try db.primaryKey(table).columns - chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + let primaryKeyColumns = try db.primaryKey(constraint.table).columns + chunks.append(""" + \(constraint.table.quotedDatabaseIdentifier)(\ + \(primaryKeyColumns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", "))\ + ) + """) } - if let deleteAction = deleteAction { + if let deleteAction = constraint.deleteAction { chunks.append("ON DELETE") chunks.append(deleteAction.rawValue) } - if let updateAction = updateAction { + if let updateAction = constraint.updateAction { chunks.append("ON UPDATE") chunks.append(updateAction.rawValue) } - if deferred { + if constraint.deferred { chunks.append("DEFERRABLE INITIALLY DEFERRED") } } @@ -931,9 +1082,13 @@ private struct IndexDefinition { } chunks.append(name.quotedDatabaseIdentifier) chunks.append("ON") - chunks.append("\(table.quotedDatabaseIdentifier)(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + chunks.append(""" + \(table.quotedDatabaseIdentifier)(\ + \(columns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", "))\ + ) + """) if let condition = condition { - chunks.append("WHERE \(condition.quotedSQL(wrappedInParenthesis: false))") + chunks.append("WHERE \(condition.quotedSQL())") } return chunks.joined(separator: " ") } diff --git a/GRDB/QueryInterface/Schema/VirtualTableModule.swift b/GRDB/QueryInterface/Schema/VirtualTableModule.swift index 06eaa3ea2..6534816b9 100644 --- a/GRDB/QueryInterface/Schema/VirtualTableModule.swift +++ b/GRDB/QueryInterface/Schema/VirtualTableModule.swift @@ -96,7 +96,13 @@ extension Database { /// - module: a VirtualTableModule /// - body: An optional closure that defines the virtual table. /// - throws: A DatabaseError whenever an SQLite error occurs. - public func create(virtualTable tableName: String, ifNotExists: Bool = false, using module: Module, _ body: ((Module.TableDefinition) -> Void)? = nil) throws { + public func create( + virtualTable tableName: String, + ifNotExists: Bool = false, + using module: Module, + _ body: ((Module.TableDefinition) -> Void)? = nil) + throws + { // Define virtual table let definition = module.makeTableDefinition() if let body = body { diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index 5ea8bf58f..136ddb7fc 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -545,7 +545,10 @@ extension TableRecord where Self: EncodableRecord { /// /// let team: Team = ... /// let players = try team.players.fetchAll(db) // [Player] - public func request(for association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { + public func request(for association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self + { let destinationRelation = association.sqlAssociation.destinationRelation(fromOriginRows: { db in try [Row(PersistenceContainer(db, self))] }) @@ -558,35 +561,50 @@ extension TableRecord { // MARK: - Associations /// Creates a request that prefetches an association. - public static func including(all association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { + public static func including(all association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self + { return all().including(all: association) } /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned association does not /// require that the associated database table contains a matching row. - public static func including(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { + public static func including(optional association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self + { return all().including(optional: association) } /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned association requires /// that the associated database table contains a matching row. - public static func including(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { + public static func including(required association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self + { return all().including(required: association) } /// Creates a request that includes an association. The columns of the /// associated record are not selected. The returned association does not /// require that the associated database table contains a matching row. - public static func joining(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { + public static func joining(optional association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self + { return all().joining(optional: association) } /// Creates a request that includes an association. The columns of the /// associated record are not selected. The returned association requires /// that the associated database table contains a matching row. - public static func joining(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { + public static func joining(required association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == Self + { return all().joining(required: association) } diff --git a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift index fef01e1ad..fd7adae20 100644 --- a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift @@ -52,7 +52,11 @@ extension TableRecord { /// /// // SELECT id, email FROM player /// let request = Player.select(sql: "id, email") - public static func select(sql: String, arguments: StatementArguments = StatementArguments()) -> QueryInterfaceRequest { + public static func select( + sql: String, + arguments: StatementArguments = StatementArguments()) + -> QueryInterfaceRequest + { return select(literal: SQLLiteral(sql: sql, arguments: arguments)) } @@ -72,7 +76,11 @@ extension TableRecord { /// let request = Player.select([max(Column("score"))], as: Int.self) /// let maxScore: Int? = try request.fetchOne(db) /// } - public static func select(_ selection: [SQLSelectable], as type: RowDecoder.Type) -> QueryInterfaceRequest { + public static func select( + _ selection: [SQLSelectable], + as type: RowDecoder.Type) + -> QueryInterfaceRequest + { return all().select(selection, as: type) } @@ -84,7 +92,11 @@ extension TableRecord { /// let request = Player.select(max(Column("score")), as: Int.self) /// let maxScore: Int? = try request.fetchOne(db) /// } - public static func select(_ selection: SQLSelectable..., as type: RowDecoder.Type) -> QueryInterfaceRequest { + public static func select( + _ selection: SQLSelectable..., + as type: RowDecoder.Type) + -> QueryInterfaceRequest + { return all().select(selection, as: type) } @@ -96,7 +108,12 @@ extension TableRecord { /// let request = Player.select(sql: "max(score)", as: Int.self) /// let maxScore: Int? = try request.fetchOne(db) /// } - public static func select(sql: String, arguments: StatementArguments = StatementArguments(), as type: RowDecoder.Type) -> QueryInterfaceRequest { + public static func select( + sql: String, + arguments: StatementArguments = StatementArguments(), + as type: RowDecoder.Type) + -> QueryInterfaceRequest + { return all().select(literal: SQLLiteral(sql: sql, arguments: arguments), as: type) } @@ -108,7 +125,11 @@ extension TableRecord { /// let request = Player.select(literal: SQLLiteral(sql: "max(score)"), as: Int.self) /// let maxScore: Int? = try request.fetchOne(db) /// } - public static func select(literal sqlLiteral: SQLLiteral, as type: RowDecoder.Type) -> QueryInterfaceRequest { + public static func select( + literal sqlLiteral: SQLLiteral, + as type: RowDecoder.Type) + -> QueryInterfaceRequest + { return all().select(literal: sqlLiteral, as: type) } @@ -152,7 +173,10 @@ extension TableRecord { /// The selection defaults to all columns. This default can be changed for /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. - public static func filter(key: PrimaryKeyType?) -> QueryInterfaceRequest { + public static func filter(key: PrimaryKeyType?) + -> QueryInterfaceRequest + where PrimaryKeyType: DatabaseValueConvertible + { return all().filter(key: key) } @@ -164,7 +188,10 @@ extension TableRecord { /// The selection defaults to all columns. This default can be changed for /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. - public static func filter(keys: Sequence) -> QueryInterfaceRequest where Sequence.Element: DatabaseValueConvertible { + public static func filter(keys: Sequence) + -> QueryInterfaceRequest + where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible + { return all().filter(keys: keys) } @@ -206,7 +233,11 @@ extension TableRecord { /// The selection defaults to all columns. This default can be changed for /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. - public static func filter(sql: String, arguments: StatementArguments = StatementArguments()) -> QueryInterfaceRequest { + public static func filter( + sql: String, + arguments: StatementArguments = StatementArguments()) + -> QueryInterfaceRequest + { return filter(literal: SQLLiteral(sql: sql, arguments: arguments)) } @@ -277,7 +308,11 @@ extension TableRecord { /// The selection defaults to all columns. This default can be changed for /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. - public static func order(sql: String, arguments: StatementArguments = StatementArguments()) -> QueryInterfaceRequest { + public static func order( + sql: String, + arguments: StatementArguments = StatementArguments()) + -> QueryInterfaceRequest + { return all().order(literal: SQLLiteral(sql: sql, arguments: arguments)) } diff --git a/GRDB/Record/EncodableRecord+Encodable.swift b/GRDB/Record/EncodableRecord+Encodable.swift index f38439a71..d0a2e522f 100644 --- a/GRDB/Record/EncodableRecord+Encodable.swift +++ b/GRDB/Record/EncodableRecord+Encodable.swift @@ -45,7 +45,7 @@ private class RecordEncoder: Encoder { fatalError("single value encoding is not supported") } - private struct KeyedContainer : KeyedEncodingContainerProtocol { + private struct KeyedContainer: KeyedEncodingContainerProtocol { var recordEncoder: RecordEncoder var userInfo: [CodingUserInfoKey: Any] { return Record.databaseEncodingUserInfo } @@ -55,6 +55,7 @@ private class RecordEncoder: Encoder { var codingPath: [CodingKey] { return [] } + // swiftlint:disable comma func encode(_ value: Bool, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: Int, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: Int8, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } @@ -69,13 +70,15 @@ private class RecordEncoder: Encoder { func encode(_ value: Float, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: Double, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: String, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + // swiftlint:enable comma - func encode(_ value: T, forKey key: Key) throws where T : Encodable { + func encode(_ value: T, forKey key: Key) throws where T: Encodable { try recordEncoder.encode(value, forKey: key) } func encodeNil(forKey key: Key) throws { recordEncoder.persist(nil, forKey: key) } + // swiftlint:disable comma func encodeIfPresent(_ value: Bool?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: Int?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: Int8?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } @@ -90,8 +93,9 @@ private class RecordEncoder: Encoder { func encodeIfPresent(_ value: Float?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: Double?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } func encodeIfPresent(_ value: String?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } + // swiftlint:disable comma - func encodeIfPresent(_ value: T?, forKey key: Key) throws where T : Encodable { + func encodeIfPresent(_ value: T?, forKey key: Key) throws where T: Encodable { if let value = value { try recordEncoder.encode(value, forKey: key) } else { @@ -99,7 +103,11 @@ private class RecordEncoder: Encoder { } } - func nestedContainer(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer { + func nestedContainer( + keyedBy keyType: NestedKey.Type, + forKey key: Key) + -> KeyedEncodingContainer + { fatalError("Not implemented") } @@ -123,7 +131,7 @@ private class RecordEncoder: Encoder { } @inline(__always) - fileprivate func encode(_ value: T, forKey key: CodingKey) throws where T : Encodable { + fileprivate func encode(_ value: T, forKey key: CodingKey) throws where T: Encodable { if let date = value as? Date { persist(Record.databaseDateEncodingStrategy.encode(date), forKey: key) } else if let uuid = value as? UUID { @@ -151,8 +159,9 @@ private class RecordEncoder: Encoder { // database inspection. Thanks to SQLite weak typing, we won't // have any trouble decoding this string into data when we // eventually perform JSON decoding. - // TODO: possible optimization: avoid this conversion to string, and store raw data bytes as an SQLite string - let jsonString = String(data: jsonData, encoding: .utf8)! // force unwrap because json data is guaranteed to convert to String + // TODO: possible optimization: avoid this conversion to string, + // and store raw data bytes as an SQLite string + let jsonString = String(data: jsonData, encoding: .utf8)! persist(jsonString, forKey: key) } } @@ -174,7 +183,7 @@ private class ColumnEncoder: Encoder { self.key = key } - func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key : CodingKey { + func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key: CodingKey { // Keyed values require JSON encoding: we need to throw // JSONRequiredError. Since we can't throw right from here, let's // delegate the job to a dedicated container. @@ -214,7 +223,7 @@ extension ColumnEncoder: SingleValueEncodingContainer { func encode(_ value: Double) throws { recordEncoder.persist(value, forKey: key) } func encode(_ value: String) throws { recordEncoder.persist(value, forKey: key) } - func encode(_ value: T) throws where T : Encodable { + func encode(_ value: T) throws where T: Encodable { try recordEncoder.encode(value, forKey: key) } } @@ -233,7 +242,7 @@ private struct JSONRequiredEncoder: Encoder { self.codingPath = codingPath } - func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key : CodingKey { + func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key: CodingKey { let container = KeyedContainer(codingPath: codingPath) return KeyedEncodingContainer(container) } @@ -265,9 +274,14 @@ private struct JSONRequiredEncoder: Encoder { func encode(_ value: Float, forKey key: KeyType) throws { throw JSONRequiredError() } func encode(_ value: Double, forKey key: KeyType) throws { throw JSONRequiredError() } func encode(_ value: String, forKey key: KeyType) throws { throw JSONRequiredError() } - func encode(_ value: T, forKey key: KeyType) throws where T : Encodable { throw JSONRequiredError() } + func encode(_ value: T, forKey key: KeyType) throws where T: Encodable { throw JSONRequiredError() } - func nestedContainer(keyedBy keyType: NestedKey.Type, forKey key: KeyType) -> KeyedEncodingContainer where NestedKey : CodingKey { + func nestedContainer( + keyedBy keyType: NestedKey.Type, + forKey key: KeyType) + -> KeyedEncodingContainer + where NestedKey: CodingKey + { let container = KeyedContainer(codingPath: codingPath + [key]) return KeyedEncodingContainer(container) } @@ -302,13 +316,16 @@ extension JSONRequiredEncoder: SingleValueEncodingContainer { func encode(_ value: Float ) throws { throw JSONRequiredError() } func encode(_ value: Double) throws { throw JSONRequiredError() } func encode(_ value: String) throws { throw JSONRequiredError() } - func encode(_ value: T) throws where T : Encodable { throw JSONRequiredError() } + func encode(_ value: T) throws where T: Encodable { throw JSONRequiredError() } } extension JSONRequiredEncoder: UnkeyedEncodingContainer { var count: Int { return 0 } - mutating func nestedContainer(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer where NestedKey : CodingKey { + mutating func nestedContainer(keyedBy keyType: NestedKey.Type) + -> KeyedEncodingContainer + where NestedKey: CodingKey + { let container = KeyedContainer(codingPath: codingPath) return KeyedEncodingContainer(container) } @@ -329,9 +346,9 @@ fileprivate var iso8601Formatter: ISO8601DateFormatter = { return formatter }() -private extension DatabaseDateEncodingStrategy { +extension DatabaseDateEncodingStrategy { @inline(__always) - func encode(_ date: Date) -> DatabaseValueConvertible? { + fileprivate func encode(_ date: Date) -> DatabaseValueConvertible? { switch self { case .deferredToDate: return date.databaseValue @@ -357,9 +374,9 @@ private extension DatabaseDateEncodingStrategy { } } -private extension DatabaseUUIDEncodingStrategy { +extension DatabaseUUIDEncodingStrategy { @inline(__always) - func encode(_ uuid: UUID) -> DatabaseValueConvertible? { + fileprivate func encode(_ uuid: UUID) -> DatabaseValueConvertible? { switch self { case .deferredToUUID: return uuid.databaseValue diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index 378fe7950..ae3e635b9 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -171,7 +171,8 @@ extension EncodableRecord { /// same set of columns in their `encode(to:)` method, only the columns /// defined by the receiver record are considered. public func databaseChanges(from record: Record) -> [String: DatabaseValue] { - return Dictionary(uniqueKeysWithValues: PersistenceContainer(self).changesIterator(from: PersistenceContainer(record))) + let changes = PersistenceContainer(self).changesIterator(from: PersistenceContainer(record)) + return Dictionary(uniqueKeysWithValues: changes) } } diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index e37963192..fe1df46dd 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -1,10 +1,10 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif extension FetchableRecord where Self: Decodable { @@ -85,6 +85,7 @@ private struct RowDecoder: Decoder { return row[key.stringValue] == nil && (row.scopesTree[key.stringValue] == nil) } + // swiftlint:disable comma func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return decoder.row[key.stringValue] } func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return decoder.row[key.stringValue] } func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { return decoder.row[key.stringValue] } @@ -99,8 +100,9 @@ private struct RowDecoder: Decoder { func decode(_ type: Float.Type, forKey key: Key) throws -> Float { return decoder.row[key.stringValue] } func decode(_ type: Double.Type, forKey key: Key) throws -> Double { return decoder.row[key.stringValue] } func decode(_ type: String.Type, forKey key: Key) throws -> String { return decoder.row[key.stringValue] } + // swiftlint:enable comma - func decodeIfPresent(_ type: T.Type, forKey key: Key) throws -> T? where T : Decodable { + func decodeIfPresent(_ type: T.Type, forKey key: Key) throws -> T? where T: Decodable { let row = decoder.row let keyName = key.stringValue @@ -130,7 +132,7 @@ private struct RowDecoder: Decoder { return nil } - func decode(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable { + func decode(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable { let row = decoder.row let keyName = key.stringValue @@ -159,7 +161,7 @@ private struct RowDecoder: Decoder { let decoder = PrefetchedRowsDecoder(rows: prefetchedRows, codingPath: codingPath) return try T(from: decoder) } - + // Key is not a column, and not a scope. // // Should be throw an error? Well... The use case is the following: @@ -193,7 +195,9 @@ private struct RowDecoder: Decoder { return try decode(type, fromRow: row, codingPath: codingPath + [key]) } - func nestedContainer(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer where NestedKey : CodingKey { + func nestedContainer(keyedBy type: NestedKey.Type, forKey key: Key) + throws -> KeyedDecodingContainer where NestedKey: CodingKey + { fatalError("not implemented") } @@ -215,7 +219,13 @@ private struct RowDecoder: Decoder { // Helper methods @inline(__always) - private func decode(_ type: T.Type, fromRow row: Row, codingPath: [CodingKey]) throws -> T where T: Decodable { + private func decode( + _ type: T.Type, + fromRow row: Row, + codingPath: [CodingKey]) + throws -> T + where T: Decodable + { if let type = T.self as? FetchableRecord.Type { // Prefer FetchableRecord decoding over Decodable. return type.init(row: row) as! T @@ -234,7 +244,14 @@ private struct RowDecoder: Decoder { } @inline(__always) - private func decode(_ type: T.Type, fromRow row: Row, columnAtIndex index: Int, key: Key) throws -> T where T: Decodable { + private func decode( + _ type: T.Type, + fromRow row: Row, + columnAtIndex index: Int, + key: Key) + throws -> T + where T: Decodable + { do { // This decoding will fail for types that decode from keyed // or unkeyed containers, because we're decoding a single @@ -248,7 +265,10 @@ private struct RowDecoder: Decoder { } catch is JSONRequiredError { // Decode from JSON guard let data = row.dataNoCopy(atIndex: index) else { - fatalConversionError(to: T.self, from: row[index], conversionContext: ValueConversionContext(row).atColumn(index)) + fatalConversionError( + to: T.self, + from: row[index], + conversionContext: ValueConversionContext(row).atColumn(index)) } return try R .databaseJSONDecoder(for: key.stringValue) @@ -272,7 +292,7 @@ private struct PrefetchedRowsDecoder: Decoder { self.currentIndex = 0 } - func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer where Key : CodingKey { + func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer where Key: CodingKey { fatalError("keyed decoding from prefetched rows is not supported") } @@ -298,13 +318,16 @@ extension PrefetchedRowsDecoder: UnkeyedDecodingContainer { return false } - mutating func decode(_ type: T.Type) throws -> T where T : Decodable { + mutating func decode(_ type: T.Type) throws -> T where T: Decodable { defer { currentIndex += 1 } let decoder = RowDecoder(row: rows[currentIndex], codingPath: codingPath) return try T(from: decoder) } - mutating func nestedContainer(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer where NestedKey : CodingKey { + mutating func nestedContainer(keyedBy type: NestedKey.Type) + throws -> KeyedDecodingContainer + where NestedKey: CodingKey + { fatalError("not implemented") } @@ -361,7 +384,7 @@ extension ColumnDecoder: SingleValueDecodingContainer { func decode(_ type: Double.Type) throws -> Double { return row[columnIndex] } func decode(_ type: String.Type) throws -> String { return row[columnIndex] } - func decode(_ type: T.Type) throws -> T where T : Decodable { + func decode(_ type: T.Type) throws -> T where T: Decodable { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows decoding Date from String, or DatabaseValue from NULL. if type == Date.self { @@ -391,9 +414,9 @@ fileprivate var iso8601Formatter: ISO8601DateFormatter = { return formatter }() -private extension DatabaseDateDecodingStrategy { +extension DatabaseDateDecodingStrategy { @inline(__always) - func decodeIfPresent(fromRow row: Row, columnAtIndex index: Int) -> Date? { + fileprivate func decodeIfPresent(fromRow row: Row, columnAtIndex index: Int) -> Date? { if let sqliteStatement = row.sqliteStatement { return decodeIfPresent( sqliteStatement: sqliteStatement, @@ -406,7 +429,7 @@ private extension DatabaseDateDecodingStrategy { } @inline(__always) - func decode(fromRow row: Row, columnAtIndex index: Int) -> Date { + fileprivate func decode(fromRow row: Row, columnAtIndex index: Int) -> Date { if let sqliteStatement = row.sqliteStatement { return decode( sqliteStatement: sqliteStatement, @@ -419,7 +442,7 @@ private extension DatabaseDateDecodingStrategy { } @inline(__always) - func decode(sqliteStatement: SQLiteStatement, index: Int32) -> Date { + fileprivate func decode(sqliteStatement: SQLiteStatement, index: Int32) -> Date { switch self { case .deferredToDate: return Date(sqliteStatement: sqliteStatement, index: index) @@ -458,7 +481,7 @@ private extension DatabaseDateDecodingStrategy { } @inline(__always) - func decodeIfPresent(sqliteStatement: SQLiteStatement, index: Int32) -> Date? { + fileprivate func decodeIfPresent(sqliteStatement: SQLiteStatement, index: Int32) -> Date? { if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL { return nil } @@ -466,7 +489,11 @@ private extension DatabaseDateDecodingStrategy { } @inline(__always) - func decode(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date { + fileprivate func decode( + from dbValue: DatabaseValue, + conversionContext: @autoclosure () -> ValueConversionContext?) + -> Date + { if let date = dateFromDatabaseValue(dbValue) { return date } else { @@ -475,7 +502,11 @@ private extension DatabaseDateDecodingStrategy { } @inline(__always) - func decodeIfPresent(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date? { + fileprivate func decodeIfPresent( + from dbValue: DatabaseValue, + conversionContext: @autoclosure () -> ValueConversionContext?) + -> Date? + { if dbValue.isNull { return nil } else if let date = dateFromDatabaseValue(dbValue) { diff --git a/GRDB/Record/FetchableRecord+TableRecord.swift b/GRDB/Record/FetchableRecord+TableRecord.swift index 937736486..17457deab 100644 --- a/GRDB/Record/FetchableRecord+TableRecord.swift +++ b/GRDB/Record/FetchableRecord+TableRecord.swift @@ -77,7 +77,10 @@ extension FetchableRecord where Self: TableRecord { /// - keys: A sequence of primary keys. /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, keys: Sequence) throws -> RecordCursor where Sequence.Element: DatabaseValueConvertible { + public static func fetchCursor(_ db: Database, keys: Sequence) + throws -> RecordCursor + where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible + { return try filter(keys: keys).fetchCursor(db) } @@ -92,7 +95,9 @@ extension FetchableRecord where Self: TableRecord { /// - keys: A sequence of primary keys. /// - returns: An array of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, keys: Sequence) throws -> [Self] where Sequence.Element: DatabaseValueConvertible { + public static func fetchAll(_ db: Database, keys: Sequence) + throws -> [Self] + where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible { let keys = Array(keys) if keys.isEmpty { // Avoid hitting the database @@ -110,7 +115,10 @@ extension FetchableRecord where Self: TableRecord { /// - key: A primary key value. /// - returns: An optional record. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, key: PrimaryKeyType?) throws -> Self? { + public static func fetchOne(_ db: Database, key: PrimaryKeyType?) + throws -> Self? + where PrimaryKeyType: DatabaseValueConvertible + { guard let key = key else { // Avoid hitting the database return nil @@ -126,7 +134,10 @@ extension FetchableRecord where Self: TableRecord { /// Returns a cursor over records identified by the provided unique keys /// (primary key or any key with a unique index on it). /// - /// let players = try Player.fetchCursor(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // Cursor of Player + /// // Cursor of Player + /// let players = try Player.fetchCursor(db, keys: [ + /// ["email": "a@example.com"], + /// ["email": "b@example.com"]]) /// while let player = try players.next() { // Player /// ... /// } @@ -138,14 +149,19 @@ extension FetchableRecord where Self: TableRecord { /// - keys: An array of key dictionaries. /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> RecordCursor { + public static func fetchCursor(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) + throws -> RecordCursor + { return try filter(keys: keys).fetchCursor(db) } /// Returns an array of records identified by the provided unique keys /// (primary key or any key with a unique index on it). /// - /// let players = try Player.fetchAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // [Player] + /// // [Player] + /// let players = try Player.fetchAll(db, keys: [ + /// ["email": "a@example.com"], + /// ["email": "b@example.com"]]) /// /// The order of records in the returned array is undefined. /// diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index b72a6240d..b0e44598c 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -1,10 +1,10 @@ import Foundation #if SWIFT_PACKAGE - import CSQLite +import CSQLite #elseif GRDBCIPHER - import SQLCipher +import SQLCipher #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER - import SQLite3 +import SQLite3 #endif /// Types that adopt FetchableRecord can be initialized from a database Row. @@ -160,7 +160,12 @@ extension FetchableRecord { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor { + public static func fetchCursor( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> RecordCursor + { return try RecordCursor(statement: statement, arguments: arguments, adapter: adapter) } @@ -175,7 +180,12 @@ extension FetchableRecord { /// - adapter: Optional RowAdapter /// - returns: An array of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { + public static func fetchAll( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> [Self] + { return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } @@ -190,7 +200,12 @@ extension FetchableRecord { /// - adapter: Optional RowAdapter /// - returns: An optional record. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { + public static func fetchOne( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> Self? + { return try fetchCursor(statement, arguments: arguments, adapter: adapter).next() } } @@ -218,7 +233,13 @@ extension FetchableRecord { /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RecordCursor { + public static func fetchCursor( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> RecordCursor + { return try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -233,7 +254,13 @@ extension FetchableRecord { /// - adapter: Optional RowAdapter /// - returns: An array of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self] { + public static func fetchAll( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> [Self] + { return try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -248,7 +275,13 @@ extension FetchableRecord { /// - adapter: Optional RowAdapter /// - returns: An optional record. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self? { + public static func fetchOne( + _ db: Database, + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws -> Self? + { return try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } } @@ -319,7 +352,7 @@ extension FetchableRecord { return nil } try supplementaryFetch([row]) - return Self.init(row: row) + return .init(row: row) } else { return try fetchOne(request.statement, adapter: request.adapter) } @@ -385,7 +418,7 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// try dbQueue.read { db in /// let players: RecordCursor = try Player.fetchCursor(db, sql: "SELECT * FROM player") /// } -public final class RecordCursor : Cursor { +public final class RecordCursor: Cursor { @usableFromInline let _statement: SelectStatement @usableFromInline let _row: Row // Reused for performance @usableFromInline let _sqliteStatement: SQLiteStatement diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index 645783cb4..46c07301f 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -1,7 +1,7 @@ import Foundation #if os(iOS) - import UIKit +import UIKit #endif /// You use FetchedRecordsController to track changes in the results of an @@ -85,7 +85,7 @@ public final class FetchedRecordsController { if let isSameRecord = isSameRecord { itemsAreIdenticalFactory = { _ in { isSameRecord($0.record, $1.record) } } } else { - itemsAreIdenticalFactory = { _ in { _,_ in false } } + itemsAreIdenticalFactory = { _ in { _, _ in false } } } try self.init( @@ -112,7 +112,7 @@ public final class FetchedRecordsController { self.databaseWriter = databaseWriter self.queue = queue } - + /// Executes the controller's fetch request. /// /// After executing this method, you can access the the fetched objects with @@ -162,7 +162,10 @@ public final class FetchedRecordsController { /// /// This method must be used from the controller's dispatch queue (the /// main queue unless stated otherwise in the controller's initializer). - public func setRequest(_ request: Request) throws where Request: FetchRequest, Request.RowDecoder == Record { + public func setRequest(_ request: Request) + throws + where Request: FetchRequest, Request.RowDecoder == Record + { self.request = ItemRequest(request) (self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in let region = try request.databaseRegion(db) @@ -196,7 +199,12 @@ public final class FetchedRecordsController { /// /// This method must be used from the controller's dispatch queue (the /// main queue unless stated otherwise in the controller's initializer). - public func setRequest(sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws { + public func setRequest( + sql: String, + arguments: StatementArguments = StatementArguments(), + adapter: RowAdapter? = nil) + throws + { try setRequest(SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) } @@ -211,19 +219,27 @@ public final class FetchedRecordsController { /// removed, moved, or updated. /// - didChange: Invoked after records have been updated. public func trackChanges( - willChange: ((FetchedRecordsController) -> ())? = nil, - onChange: ((FetchedRecordsController, Record, FetchedRecordChange) -> ())? = nil, - didChange: ((FetchedRecordsController) -> ())? = nil) + willChange: ((FetchedRecordsController) -> Void)? = nil, + onChange: ((FetchedRecordsController, Record, FetchedRecordChange) -> Void)? = nil, + didChange: ((FetchedRecordsController) -> Void)? = nil) { - // I hate you SE-0110. - let wrappedWillChange: ((FetchedRecordsController, Void) -> ())? + // Without SE-0110, we could simply: + // + // trackChanges( + // fetchAlongside: { _ in }, + // willChange: willChange.map { callback in { (controller, _) in callback(controller) } }, + // onChange: onChange, + // didChange: didChange.map { callback in { (controller, _) in callback(controller) } }) + // + // But instead: + let wrappedWillChange: ((FetchedRecordsController, Void) -> Void)? if let willChange = willChange { wrappedWillChange = { (controller, _) in willChange(controller) } } else { wrappedWillChange = nil } - let wrappedDidChange: ((FetchedRecordsController, Void) -> ())? + let wrappedDidChange: ((FetchedRecordsController, Void) -> Void)? if let didChange = didChange { wrappedDidChange = { (controller, _) in didChange(controller) } } else { @@ -235,15 +251,8 @@ public final class FetchedRecordsController { willChange: wrappedWillChange, onChange: onChange, didChange: wrappedDidChange) - - // Without bloody SE-0110: -// trackChanges( -// fetchAlongside: { _ in }, -// willChange: willChange.map { callback in { (controller, _) in callback(controller) } }, -// onChange: onChange, -// didChange: didChange.map { callback in { (controller, _) in callback(controller) } }) } - + /// Registers changes notification callbacks. /// /// This method must be used from the controller's dispatch queue (the @@ -262,9 +271,9 @@ public final class FetchedRecordsController { /// - didChange: Invoked after records have been updated. public func trackChanges( fetchAlongside: @escaping (Database) throws -> T, - willChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> ())? = nil, - onChange: ((FetchedRecordsController, Record, FetchedRecordChange) -> ())? = nil, - didChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> ())? = nil) + willChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> Void)? = nil, + onChange: ((FetchedRecordsController, Record, FetchedRecordChange) -> Void)? = nil, + didChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> Void)? = nil) { // If some changes are currently processed, make sure they are // discarded because they would trigger previously set callbacks. @@ -276,20 +285,20 @@ public final class FetchedRecordsController { return } - var willProcessTransaction: () -> () = { } - var didProcessTransaction: () -> () = { } + var willProcessTransaction: () -> Void = { } + var didProcessTransaction: () -> Void = { } #if os(iOS) - if let application = application { - var backgroundTaskID: UIBackgroundTaskIdentifier! = nil - willProcessTransaction = { - backgroundTaskID = application.beginBackgroundTask { - application.endBackgroundTask(backgroundTaskID) - } - } - didProcessTransaction = { + if let application = application { + var backgroundTaskID: UIBackgroundTaskIdentifier! = nil + willProcessTransaction = { + backgroundTaskID = application.beginBackgroundTask { application.endBackgroundTask(backgroundTaskID) } } + didProcessTransaction = { + application.endBackgroundTask(backgroundTaskID) + } + } #endif let initialItems = fetchedItems @@ -312,7 +321,7 @@ public final class FetchedRecordsController { } } } - + /// Registers an error callback. /// /// Whenever the controller could not look for changes after a transaction @@ -325,7 +334,7 @@ public final class FetchedRecordsController { /// /// This method must be used from the controller's dispatch queue (the /// main queue unless stated otherwise in the controller's initializer). - public func trackErrors(_ errorHandler: @escaping (FetchedRecordsController, Error) -> ()) { + public func trackErrors(_ errorHandler: @escaping (FetchedRecordsController, Error) -> Void) { self.errorHandler = errorHandler } @@ -369,7 +378,7 @@ public final class FetchedRecordsController { /// Support for allowBackgroundChangeTracking(in:) var application: UIApplication? #endif - + /// The items fileprivate var fetchedItems: [Item]? @@ -378,19 +387,19 @@ public final class FetchedRecordsController { /// The record comparator factory (support for request change) private let itemsAreIdenticalFactory: ItemComparatorFactory - + /// The request fileprivate typealias ItemRequest = AnyFetchRequest> fileprivate var request: ItemRequest /// The observed database region - private var region : DatabaseRegion + private var region: DatabaseRegion /// The eventual current database observer private var observer: FetchedRecordsObserver? /// The eventual error handler - fileprivate var errorHandler: ((FetchedRecordsController, Error) -> ())? + fileprivate var errorHandler: ((FetchedRecordsController, Error) -> Void)? } extension FetchedRecordsController where Record: TableRecord { @@ -510,15 +519,15 @@ extension FetchedRecordsController where Record: TableRecord { /// FetchedRecordsController adopts TransactionObserverType so that it can /// monitor changes to its fetched records. -private final class FetchedRecordsObserver : TransactionObserver { +private final class FetchedRecordsObserver: TransactionObserver { var isValid: Bool var needsComputeChanges: Bool var items: [Item]! // ought to be not nil when observer has started tracking transactions let queue: DispatchQueue // protects items let region: DatabaseRegion - var fetchAndNotifyChanges: (FetchedRecordsObserver) -> () + var fetchAndNotifyChanges: (FetchedRecordsObserver) -> Void - init(region: DatabaseRegion, fetchAndNotifyChanges: @escaping (FetchedRecordsObserver) -> ()) { + init(region: DatabaseRegion, fetchAndNotifyChanges: @escaping (FetchedRecordsObserver) -> Void) { self.isValid = true self.items = nil self.needsComputeChanges = false @@ -565,12 +574,18 @@ private final class FetchedRecordsObserver : Transactio // MARK: - Changes +private typealias FetchCompletionHandler = ( + DatabaseResult<(fetchedItems: [Item], + fetchedAlongside: T, + observer: FetchedRecordsObserver)>) + -> Void + private func makeFetchFunction( controller: FetchedRecordsController, fetchAlongside: @escaping (Database) throws -> T, - willProcessTransaction: @escaping () -> (), - completion: @escaping (DatabaseResult<(fetchedItems: [Item], fetchedAlongside: T, observer: FetchedRecordsObserver)>) -> () - ) -> (FetchedRecordsObserver) -> () + willProcessTransaction: @escaping () -> Void, + completion: @escaping FetchCompletionHandler + ) -> (FetchedRecordsObserver) -> Void { // Make sure we keep a weak reference to the fetched records controller, // so that the user can use unowned references in callbacks: @@ -623,12 +638,12 @@ private func makeFetchAndNotifyChangesFunction( controller: FetchedRecordsController, fetchAlongside: @escaping (Database) throws -> T, itemsAreIdentical: @escaping ItemComparator, - willProcessTransaction: @escaping () -> (), - willChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> ())?, - onChange: ((FetchedRecordsController, Record, FetchedRecordChange) -> ())?, - didChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> ())?, - didProcessTransaction: @escaping () -> () - ) -> (FetchedRecordsObserver) -> () + willProcessTransaction: @escaping () -> Void, + willChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> Void)?, + onChange: ((FetchedRecordsController, Record, FetchedRecordChange) -> Void)?, + didChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> Void)?, + didProcessTransaction: @escaping () -> Void + ) -> (FetchedRecordsObserver) -> Void { // Make sure we keep a weak reference to the fetched records controller, // so that the user can use unowned references in callbacks: @@ -637,12 +652,16 @@ private func makeFetchAndNotifyChangesFunction( // // Should controller become strong at any point before callbacks are // called, such unowned reference would have an opportunity to crash. - return makeFetchFunction(controller: controller, fetchAlongside: fetchAlongside, willProcessTransaction: willProcessTransaction) { [weak controller] result in + return makeFetchFunction( + controller: controller, + fetchAlongside: fetchAlongside, + willProcessTransaction: willProcessTransaction) + { [weak controller] result in // Return if fetched records controller has been deallocated guard let callbackQueue = controller?.queue else { return } switch result { - case .failure(let error): + case let .failure(error): callbackQueue.async { // Now we can retain controller guard let strongController = controller else { return } @@ -650,7 +669,7 @@ private func makeFetchAndNotifyChangesFunction( didProcessTransaction() } - case .success((fetchedItems: let fetchedItems, fetchedAlongside: let fetchedAlongside, observer: let observer)): + case let .success((fetchedItems: fetchedItems, fetchedAlongside: fetchedAlongside, observer: observer)): // Return if there is no change let changes: [ItemChange] if onChange != nil { @@ -689,7 +708,12 @@ private func makeFetchAndNotifyChangesFunction( } } -private func computeChanges(from s: [Item], to t: [Item], itemsAreIdentical: ItemComparator) -> [ItemChange] { +private func computeChanges( + from s: [Item], + to t: [Item], + itemsAreIdentical: ItemComparator) + -> [ItemChange] +{ let m = s.count let n = t.count @@ -754,8 +778,12 @@ private func computeChanges(from s: [Item], to t: [Item] /// If *change* is a deletion or an insertion, and there is a matching inverse /// insertion/deletion with the same value in *changes*, a corresponding .move or .update is returned. /// As a convenience, the index of the matched change is returned as well. - func merge(change: ItemChange, in changes: [ItemChange], itemsAreIdentical: ItemComparator) -> (mergedChange: ItemChange, mergedIndex: Int)? { - + func merge( + change: ItemChange, + in changes: [ItemChange], + itemsAreIdentical: ItemComparator) + -> (mergedChange: ItemChange, mergedIndex: Int)? + { /// Returns the changes between two rows: a dictionary [key: oldValue] /// Precondition: both rows have the same columns func changedValues(from oldRow: Row, to newRow: Row) -> [String: DatabaseValue] { @@ -770,30 +798,52 @@ private func computeChanges(from s: [Item], to t: [Item] } switch change { - case .insertion(let newItem, let newIndexPath): + case let .insertion(newItem, newIndexPath): // Look for a matching deletion for (index, otherChange) in changes.enumerated() { - guard case .deletion(let oldItem, let oldIndexPath) = otherChange else { continue } + guard case let .deletion(oldItem, oldIndexPath) = otherChange else { continue } guard itemsAreIdentical(oldItem, newItem) else { continue } let rowChanges = changedValues(from: oldItem.row, to: newItem.row) if oldIndexPath == newIndexPath { - return (ItemChange.update(item: newItem, indexPath: oldIndexPath, changes: rowChanges), index) + return ( + ItemChange.update( + item: newItem, + indexPath: oldIndexPath, + changes: rowChanges), + index) } else { - return (ItemChange.move(item: newItem, indexPath: oldIndexPath, newIndexPath: newIndexPath, changes: rowChanges), index) + return ( + ItemChange.move( + item: newItem, + indexPath: oldIndexPath, + newIndexPath: newIndexPath, + changes: rowChanges), + index) } } return nil - case .deletion(let oldItem, let oldIndexPath): + case let .deletion(oldItem, oldIndexPath): // Look for a matching insertion for (index, otherChange) in changes.enumerated() { - guard case .insertion(let newItem, let newIndexPath) = otherChange else { continue } + guard case let .insertion(newItem, newIndexPath) = otherChange else { continue } guard itemsAreIdentical(oldItem, newItem) else { continue } let rowChanges = changedValues(from: oldItem.row, to: newItem.row) if oldIndexPath == newIndexPath { - return (ItemChange.update(item: newItem, indexPath: oldIndexPath, changes: rowChanges), index) + return ( + ItemChange.update( + item: newItem, + indexPath: oldIndexPath, + changes: rowChanges), + index) } else { - return (ItemChange.move(item: newItem, indexPath: oldIndexPath, newIndexPath: newIndexPath, changes: rowChanges), index) + return ( + ItemChange.move( + item: newItem, + indexPath: oldIndexPath, + newIndexPath: newIndexPath, + changes: rowChanges), + index) } } return nil @@ -807,7 +857,9 @@ private func computeChanges(from s: [Item], to t: [Item] var mergedChanges: [ItemChange] = [] var updateChanges: [ItemChange] = [] for change in changes { - if let (mergedChange, mergedIndex) = merge(change: change, in: mergedChanges, itemsAreIdentical: itemsAreIdentical) { + if let (mergedChange, mergedIndex) + = merge(change: change, in: mergedChanges, itemsAreIdentical: itemsAreIdentical) + { mergedChanges.remove(at: mergedIndex) switch mergedChange { case .update: @@ -829,10 +881,8 @@ private func identicalItemArrays(_ lhs: [Item], _ rhs: [Item IndexPath? { let item = Item(row: Row(record)) - guard let fetchedItems = fetchedItems, let index = fetchedItems.firstIndex(where: { itemsAreIdentical($0, item) }) else { - return nil + guard + let fetchedItems = fetchedItems, + let index = fetchedItems.firstIndex(where: { itemsAreIdentical($0, item) }) + else { + return nil } return IndexPath(indexes: [0, index]) } @@ -917,13 +970,13 @@ extension ItemChange { var fetchedRecordChange: FetchedRecordChange { switch self { - case .insertion(item: _, indexPath: let indexPath): + case let .insertion(item: _, indexPath: indexPath): return .insertion(indexPath: indexPath) - case .deletion(item: _, indexPath: let indexPath): + case let .deletion(item: _, indexPath: indexPath): return .deletion(indexPath: indexPath) - case .move(item: _, indexPath: let indexPath, newIndexPath: let newIndexPath, changes: let changes): + case let .move(item: _, indexPath: indexPath, newIndexPath: newIndexPath, changes: changes): return .move(indexPath: indexPath, newIndexPath: newIndexPath, changes: changes) - case .update(item: _, indexPath: let indexPath, changes: let changes): + case let .update(item: _, indexPath: indexPath, changes: changes): return .update(indexPath: indexPath, changes: changes) } } @@ -932,16 +985,16 @@ extension ItemChange { extension ItemChange: CustomStringConvertible { var description: String { switch self { - case .insertion(let item, let indexPath): + case let .insertion(item, indexPath): return "Insert \(item) at \(indexPath)" - case .deletion(let item, let indexPath): + case let .deletion(item, indexPath): return "Delete \(item) from \(indexPath)" - case .move(let item, let indexPath, let newIndexPath, changes: let changes): + case let .move(item, indexPath, newIndexPath, changes: changes): return "Move \(item) from \(indexPath) to \(newIndexPath) with changes: \(changes)" - case .update(let item, let indexPath, let changes): + case let .update(item, indexPath, changes): return "Update \(item) at \(indexPath) with changes: \(changes)" } } @@ -973,16 +1026,16 @@ public enum FetchedRecordChange { extension FetchedRecordChange: CustomStringConvertible { public var description: String { switch self { - case .insertion(let indexPath): + case let .insertion(indexPath): return "Insertion at \(indexPath)" - case .deletion(let indexPath): + case let .deletion(indexPath): return "Deletion from \(indexPath)" - case .move(let indexPath, let newIndexPath, changes: let changes): + case let .move(indexPath, newIndexPath, changes: changes): return "Move from \(indexPath) to \(newIndexPath) with changes: \(changes)" - case .update(let indexPath, let changes): + case let .update(indexPath, changes): return "Update at \(indexPath) with changes: \(changes)" } } @@ -1014,11 +1067,11 @@ public struct FetchedRecordsSectionInfo { // MARK: - Item -private final class Item : FetchableRecord, Equatable { +private final class Item: FetchableRecord, Equatable { let row: Row // Records are lazily loaded - lazy var record: T = T(row: self.row) + lazy var record = T(row: self.row) init(row: Row) { self.row = row.copy() diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index 1fb4772ea..e8dd673cd 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -1,6 +1,5 @@ extension Database.ConflictResolution { - @usableFromInline - var invalidatesLastInsertedRowID: Bool { + @usableFromInline var invalidatesLastInsertedRowID: Bool { switch self { case .abort, .fail, .rollback, .replace: return false @@ -55,7 +54,7 @@ public struct PersistenceConflictPolicy { } /// Types that adopt MutablePersistableRecord can be inserted, updated, and deleted. -public protocol MutablePersistableRecord : EncodableRecord, TableRecord { +public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// The policy that handles SQLite conflicts when records are inserted /// or updated. /// @@ -219,7 +218,10 @@ extension MutablePersistableRecord { /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database. - public func update(_ db: Database, columns: Sequence) throws where Sequence.Element: ColumnExpression { + public func update(_ db: Database, columns: Sequence) + throws + where Sequence: Swift.Sequence, Sequence.Element: ColumnExpression + { try update(db, columns: Set(columns.map { $0.name })) } @@ -230,7 +232,10 @@ extension MutablePersistableRecord { /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database. - public func update(_ db: Database, columns: Sequence) throws where Sequence.Element == String { + public func update(_ db: Database, columns: Sequence) + throws + where Sequence: Swift.Sequence, Sequence.Element == String + { try update(db, columns: Set(columns)) } @@ -303,7 +308,7 @@ extension MutablePersistableRecord { try change(&self) return try updateChanges(db, from: container) } - + /// Executes an INSERT or an UPDATE statement so that `self` is saved in /// the database. /// @@ -392,9 +397,13 @@ extension MutablePersistableRecord { @inlinable public func performUpdate(_ db: Database, columns: Set) throws { let dao = try DAO(db, self) - guard let statement = try dao.updateStatement(columns: columns, onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) else { - // Nil primary key - throw dao.makeRecordNotFoundError() + guard + let statement = try dao.updateStatement( + columns: columns, + onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) + else { + // Nil primary key + throw dao.makeRecordNotFoundError() } try statement.execute() if db.changesCount == 0 { @@ -463,7 +472,7 @@ extension MutablePersistableRecord { extension MutablePersistableRecord where Self: AnyObject { // MARK: - Record Comparison - + /// Mutates the record according to the provided closure, and then, if the /// record has any difference from its previous version, executes an /// UPDATE statement so that those differences and only those difference are @@ -534,7 +543,10 @@ extension MutablePersistableRecord { /// - keys: A sequence of primary keys. /// - returns: The number of deleted rows @discardableResult - public static func deleteAll(_ db: Database, keys: Sequence) throws -> Int where Sequence.Element: DatabaseValueConvertible { + public static func deleteAll(_ db: Database, keys: Sequence) + throws -> Int + where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible + { let keys = Array(keys) if keys.isEmpty { // Avoid hitting the database @@ -563,7 +575,10 @@ extension MutablePersistableRecord { /// - key: A primary key value. /// - returns: Whether a database row was deleted. @discardableResult - public static func deleteOne(_ db: Database, key: PrimaryKeyType?) throws -> Bool { + public static func deleteOne(_ db: Database, key: PrimaryKeyType?) + throws -> Bool + where PrimaryKeyType: DatabaseValueConvertible + { guard let key = key else { // Avoid hitting the database return false @@ -617,7 +632,7 @@ extension MutablePersistableRecord { /// /// Unlike MutablePersistableRecord, the insert() and save() methods are not /// mutating methods. -public protocol PersistableRecord : MutablePersistableRecord { +public protocol PersistableRecord: MutablePersistableRecord { /// Notifies the record that it was succesfully inserted. /// @@ -749,7 +764,7 @@ extension PersistableRecord { extension PersistenceContainer { /// Convenience initializer from a database connection and a record - init(_ db: Database,_ record: Record) throws { + init(_ db: Database, _ record: Record) throws { let databaseTableName = type(of: record).databaseTableName let columnCount = try db.columns(in: databaseTableName).count self.init(minimumCapacity: columnCount) @@ -916,9 +931,16 @@ extension InsertQuery { let sql: String switch onConflict { case .abort: - sql = "INSERT INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) VALUES (\(valuesSQL))" + sql = """ + INSERT INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) \ + VALUES (\(valuesSQL)) + """ default: - sql = "INSERT OR \(onConflict.rawValue) INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) VALUES (\(valuesSQL))" + sql = """ + INSERT OR \(onConflict.rawValue) \ + INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) \ + VALUES (\(valuesSQL)) + """ } InsertQuery.sqlCache.write { $0[self] = sql } return sql @@ -946,9 +968,17 @@ extension UpdateQuery { let sql: String switch onConflict { case .abort: - sql = "UPDATE \(tableName.quotedDatabaseIdentifier) SET \(updateSQL) WHERE \(whereSQL)" + sql = """ + UPDATE \(tableName.quotedDatabaseIdentifier) \ + SET \(updateSQL) \ + WHERE \(whereSQL) + """ default: - sql = "UPDATE OR \(onConflict.rawValue) \(tableName.quotedDatabaseIdentifier) SET \(updateSQL) WHERE \(whereSQL)" + sql = """ + UPDATE OR \(onConflict.rawValue) \(tableName.quotedDatabaseIdentifier) \ + SET \(updateSQL) \ + WHERE \(whereSQL) + """ } UpdateQuery.sqlCache.write { $0[self] = sql } return sql diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 4b220218e..2ee2b8a0b 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -2,7 +2,7 @@ /// Record is a class that wraps a table row, or the result of any query. It is /// designed to be subclassed. -open class Record : FetchableRecord, TableRecord, PersistableRecord { +open class Record: FetchableRecord, TableRecord, PersistableRecord { // MARK: - Initializers @@ -11,7 +11,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { } /// Creates a Record from a row. - required public init(row: Row) { + public required init(row: Row) { if row.isFetched { // Take care of the hasDatabaseChanges flag. // @@ -93,7 +93,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { return [AllColumns()] } - + /// Defines the values persisted in the database. /// /// Store in the *container* argument all values that should be stored in @@ -216,7 +216,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { /// Reference row for the *hasDatabaseChanges* property. var referenceRow: Row? - + // MARK: - CRUD /// Executes an INSERT statement. @@ -274,9 +274,13 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { // // But this would trigger two calls to `encode(to:)`. let dao = try DAO(db, self) - guard let statement = try dao.updateStatement(columns: columns, onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) else { - // Nil primary key - throw dao.makeRecordNotFoundError() + guard + let statement = try dao.updateStatement( + columns: columns, + onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) + else { + // Nil primary key + throw dao.makeRecordNotFoundError() } try statement.execute() if db.changesCount == 0 { @@ -302,7 +306,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database and record could not be updated. @discardableResult - final public func updateChanges(_ db: Database) throws -> Bool { + public final func updateChanges(_ db: Database) throws -> Bool { let changedColumns = Set(databaseChanges.keys) if changedColumns.isEmpty { return false @@ -331,7 +335,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { /// - parameter db: A database connection. /// - throws: A DatabaseError whenever an SQLite error occurs, or errors /// thrown by update(). - final public func save(_ db: Database) throws { + public final func save(_ db: Database) throws { try performSave(db) } diff --git a/GRDB/Utils/Inflections+English.swift b/GRDB/Utils/Inflections+English.swift index c9f527035..1d570786d 100644 --- a/GRDB/Utils/Inflections+English.swift +++ b/GRDB/Utils/Inflections+English.swift @@ -51,6 +51,7 @@ extension Inflections { // become more complete. This is a safety measure to keep existing // applications from breaking. // + // swiftlint:disable:next line_length // https://github.com/rails/rails/blob/b2eb1d1c55a59fee1e6c4cba7030d8ceb524267c/activesupport/lib/active_support/inflections.rb var inflections = Inflections() diff --git a/GRDB/Utils/Inflections.swift b/GRDB/Utils/Inflections.swift index f8dbabf33..ee8fc082c 100644 --- a/GRDB/Utils/Inflections.swift +++ b/GRDB/Utils/Inflections.swift @@ -59,7 +59,11 @@ public struct Inflections { /// - options: Regular expression options (defaults to /// `[.caseInsensitive]`). /// - template: A replacement template string. - public mutating func plural(_ pattern: String, options: NSRegularExpression.Options = [.caseInsensitive], _ template: String) { + public mutating func plural( + _ pattern: String, + options: NSRegularExpression.Options = [.caseInsensitive], + _ template: String) + { let reg = try! NSRegularExpression(pattern: pattern, options: options) pluralizeRules.append((reg, template)) } @@ -75,7 +79,11 @@ public struct Inflections { /// - options: Regular expression options (defaults to /// `[.caseInsensitive]`). /// - template: A replacement template string. - public mutating func singular(_ pattern: String, options: NSRegularExpression.Options = [.caseInsensitive], _ template: String) { + public mutating func singular( + _ pattern: String, + options: NSRegularExpression.Options = [.caseInsensitive], + _ template: String) + { let reg = try! NSRegularExpression(pattern: pattern, options: options) singularizeRules.append((reg, template)) } @@ -155,7 +163,9 @@ public struct Inflections { /// inflections.pluralize("bar") // "bars" private mutating func uncountableWord(_ word: String) { let escWord = NSRegularExpression.escapedPattern(for: word) - uncountablesRegularExpressions[word] = try! NSRegularExpression(pattern: "\\b\(escWord)\\Z", options: [.caseInsensitive]) + uncountablesRegularExpressions[word] = try! NSRegularExpression( + pattern: "\\b\(escWord)\\Z", + options: [.caseInsensitive]) } private func isUncountable(_ string: String) -> Bool { @@ -176,12 +186,12 @@ public struct Inflections { return string } return """ - \(string.prefix(upTo: indexOfLastWord))\ - \(inflectWord(lastWord, with: rules))\ - \(string.suffix(from: endIndexOfDigitlessRadical)) - """ + \(string.prefix(upTo: indexOfLastWord))\ + \(inflectWord(lastWord, with: rules))\ + \(string.suffix(from: endIndexOfDigitlessRadical)) + """ } - + private func inflectWord(_ string: String, with rules: [(NSRegularExpression, String)]) -> String { if string.isEmpty { return string @@ -189,8 +199,8 @@ public struct Inflections { let range = NSRange(string.startIndex.. 0 { + let matchCount = reg.replaceMatches(in: result, options: [], range: range, withTemplate: template) + if matchCount > 0 { return String(result) } } @@ -203,7 +213,7 @@ public struct Inflections { /// startIndexOfLastWord("fooBar") -> "Bar" static func startIndexOfLastWord(_ string: String) -> String.Index { let range = NSRange(string.startIndex.. { keys.reserveCapacity(minimumCapacity) dictionary = Dictionary(minimumCapacity: minimumCapacity) } - + /// Returns the value associated with key, or nil. @usableFromInline subscript(_ key: Key) -> Value? { @@ -42,14 +42,14 @@ struct OrderedDictionary { } } } - + /// Returns the value associated with key, or the default value. @inlinable subscript(_ key: Key, default defaultValue: Value) -> Value { get { return dictionary[key] ?? defaultValue } set { self[key] = newValue } } - + /// Appends the given value for the given key. /// /// - precondition: There is no value associated with key yet. @@ -111,7 +111,8 @@ struct OrderedDictionary { } extension OrderedDictionary: Collection { - @usableFromInline typealias Index = Int + @usableFromInline + typealias Index = Int @usableFromInline var startIndex: Int { return 0 @@ -121,18 +122,21 @@ extension OrderedDictionary: Collection { return keys.count } - @usableFromInline func index(after i: Int) -> Int { + @usableFromInline + func index(after i: Int) -> Int { return i + 1 } - @usableFromInline subscript(position: Int) -> (key: Key, value: Value) { + @usableFromInline + subscript(position: Int) -> (key: Key, value: Value) { let key = keys[position] return (key: key, value: dictionary[key]!) } } extension OrderedDictionary: ExpressibleByDictionaryLiteral { - @usableFromInline init(dictionaryLiteral elements: (Key, Value)...) { + @usableFromInline + init(dictionaryLiteral elements: (Key, Value)...) { self.keys = elements.map { $0.0 } self.dictionary = Dictionary(uniqueKeysWithValues: elements) } diff --git a/GRDB/Utils/Pool.swift b/GRDB/Utils/Pool.swift index 444d9262d..8c9c49657 100644 --- a/GRDB/Utils/Pool.swift +++ b/GRDB/Utils/Pool.swift @@ -58,7 +58,7 @@ final class Pool { /// Returns a tuple (element, release) /// Client MUST call release() after the element has been used. - func get() throws -> (T, () -> ()) { + func get() throws -> (T, () -> Void) { _ = semaphore.wait(timeout: .distantFuture) do { let item = try items.write { items -> Item in @@ -97,7 +97,7 @@ final class Pool { /// Performs a block on each pool element, available or not. /// The block is run is some arbitrary dispatch queue. - func forEach(_ body: (T) throws -> ()) rethrows { + func forEach(_ body: (T) throws -> Void) rethrows { try items.read { items in for item in items { try body(item.element) @@ -112,7 +112,7 @@ final class Pool { /// Empty the pool. Currently used items won't be reused. /// Eventual block is executed before any other element is dequeued. - func clear(andThen block: () throws -> ()) rethrows { + func clear(andThen block: () throws -> Void) rethrows { try items.write { items in items.removeAll() try block() diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index ae666ec52..a29d65202 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -7,8 +7,7 @@ extension String { /// SQL query. /// /// db.execute(sql: "SELECT * FROM \(tableName.quotedDatabaseIdentifier)") - @inlinable - public var quotedDatabaseIdentifier: String { + @inlinable public var quotedDatabaseIdentifier: String { // See https://www.sqlite.org/lang_keywords.html return "\"\(self)\"" } @@ -38,7 +37,7 @@ public protocol _OptionalProtocol { /// This conformance is an implementation detail of GRDB. Don't rely on it. /// /// :nodoc: -extension Optional : _OptionalProtocol { +extension Optional: _OptionalProtocol { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public typealias _Wrapped = Wrapped @@ -49,7 +48,12 @@ extension Optional : _OptionalProtocol { /// Reserved for GRDB: do not use. @inlinable -func GRDBPrecondition(_ condition: @autoclosure() -> Bool, _ message: @autoclosure() -> String = "", file: StaticString = #file, line: UInt = #line) { +func GRDBPrecondition( + _ condition: @autoclosure() -> Bool, + _ message: @autoclosure() -> String = "", + file: StaticString = #file, + line: UInt = #line) +{ /// Custom precondition function which aims at solving /// https://bugs.swift.org/browse/SR-905 and /// https://github.com/groue/GRDB.swift/issues/37 @@ -87,7 +91,7 @@ extension DispatchQueue { DispatchQueue.main.setSpecific(key: key, value: ()) return key }() - + static var isMain: Bool { return DispatchQueue.getSpecific(key: mainKey) != nil } diff --git a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift index 78c0e0266..298832ba5 100644 --- a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift +++ b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift @@ -125,9 +125,9 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: } extension ValueObservation where Reducer == Void { - + // MARK: - DatabaseValueConvertible Observation - + /// Creates a ValueObservation which observes *request*, and notifies /// fresh values whenever the request is modified by a /// database transaction. @@ -335,12 +335,15 @@ extension ValueReducers { /// :nodoc: @available(*, deprecated, renamed: "ValueReducers.AllValues") -public typealias DatabaseValuesReducer = ValueReducers.AllValues where RowDecoder: DatabaseValueConvertible +public typealias DatabaseValuesReducer = ValueReducers.AllValues + where RowDecoder: DatabaseValueConvertible /// :nodoc: @available(*, deprecated, renamed: "ValueReducers.OneValue") -public typealias DatabaseValueReducer = ValueReducers.OneValue where RowDecoder: DatabaseValueConvertible +public typealias DatabaseValueReducer = ValueReducers.OneValue + where RowDecoder: DatabaseValueConvertible /// :nodoc: @available(*, deprecated, renamed: "ValueReducers.AllOptionalValues") -public typealias OptionalDatabaseValuesReducer = ValueReducers.AllOptionalValues where RowDecoder: DatabaseValueConvertible +public typealias OptionalDatabaseValuesReducer = ValueReducers.AllOptionalValues + where RowDecoder: DatabaseValueConvertible diff --git a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift index b588a62d0..f54b4cae5 100644 --- a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift +++ b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift @@ -250,8 +250,12 @@ extension ValueReducers { /// :nodoc: @available(*, deprecated, renamed: "ValueReducers.AllRecords") -public typealias FetchableRecordsReducer = ValueReducers.AllRecords where RowDecoder: FetchableRecord +public typealias FetchableRecordsReducer + = ValueReducers.AllRecords + where RowDecoder: FetchableRecord /// :nodoc: @available(*, deprecated, renamed: "ValueReducers.OneRecord") -public typealias FetchableRecordReducer = ValueReducers.OneRecord where RowDecoder: FetchableRecord +public typealias FetchableRecordReducer + = ValueReducers.OneRecord + where RowDecoder: FetchableRecord diff --git a/GRDB/ValueObservation/ValueObservation+Row.swift b/GRDB/ValueObservation/ValueObservation+Row.swift index fa0f1ae77..43f748231 100644 --- a/GRDB/ValueObservation/ValueObservation+Row.swift +++ b/GRDB/ValueObservation/ValueObservation+Row.swift @@ -60,7 +60,7 @@ extension FetchRequest where RowDecoder == Row { } extension ValueObservation where Reducer == Void { - + // MARK: - Row Observation /// Creates a ValueObservation which observes *request*, and notifies diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 8a152f1c2..c82e6e30d 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -208,7 +208,7 @@ extension ValueObservation where Reducer: ValueReducer { { return reader.add(observation: self, onError: onError, onChange: onChange) } - + // MARK: - Fetching Values /// Returns the observed value. diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift index 99754cb22..27eab3e17 100644 --- a/GRDB/ValueObservation/ValueObserver.swift +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -8,9 +8,9 @@ class ValueObserver: TransactionObserver { var region: DatabaseRegion! var reducer: Reducer! var notificationQueue: DispatchQueue? - + private var requiresWriteAccess: Bool - unowned private var writer: DatabaseWriter + private unowned var writer: DatabaseWriter private let reduceQueue: DispatchQueue private let onError: (Error) -> Void private let onChange: (Reducer.Value) -> Void diff --git a/GRDB/ValueObservation/ValueReducer/Combine.swift b/GRDB/ValueObservation/ValueReducer/Combine.swift index 178cc06fb..d79736075 100644 --- a/GRDB/ValueObservation/ValueReducer/Combine.swift +++ b/GRDB/ValueObservation/ValueReducer/Combine.swift @@ -23,7 +23,7 @@ extension ValueReducers { r2.fetch(db)) } - mutating public func value(_ fetched: Fetched) -> Value? { + public mutating func value(_ fetched: Fetched) -> Value? { let v1 = r1.value(fetched.0) let v2 = r2.value(fetched.1) defer { @@ -102,7 +102,7 @@ extension ValueReducers { r3.fetch(db)) } - mutating public func value(_ fetched: Fetched) -> Value? { + public mutating func value(_ fetched: Fetched) -> Value? { let v1 = r1.value(fetched.0) let v2 = r2.value(fetched.1) let v3 = r3.value(fetched.2) @@ -200,7 +200,7 @@ extension ValueReducers { r4.fetch(db)) } - mutating public func value(_ fetched: Fetched) -> Value? { + public mutating func value(_ fetched: Fetched) -> Value? { let v1 = r1.value(fetched.0) let v2 = r2.value(fetched.1) let v3 = r3.value(fetched.2) @@ -313,7 +313,7 @@ extension ValueReducers { r5.fetch(db)) } - mutating public func value(_ fetched: Fetched) -> Value? { + public mutating func value(_ fetched: Fetched) -> Value? { let v1 = r1.value(fetched.0) let v2 = r2.value(fetched.1) let v3 = r3.value(fetched.2) @@ -441,7 +441,7 @@ extension ValueReducers { r6.fetch(db)) } - mutating public func value(_ fetched: Fetched) -> Value? { + public mutating func value(_ fetched: Fetched) -> Value? { let v1 = r1.value(fetched.0) let v2 = r2.value(fetched.1) let v3 = r3.value(fetched.2) @@ -556,7 +556,7 @@ extension ValueReducers { r7.fetch(db)) } - mutating public func value(_ fetched: Fetched) -> Value? { + public mutating func value(_ fetched: Fetched) -> Value? { let v1 = r1.value(fetched.0) let v2 = r2.value(fetched.1) let v3 = r3.value(fetched.2) @@ -641,6 +641,7 @@ extension ValueReducers { R7: ValueReducer, R8: ValueReducer>: ValueReducer { + // swiftlint:disable:next line_length public typealias Fetched = (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched, R6.Fetched, R7.Fetched, R8.Fetched) public typealias Value = (R1.Value, R2.Value, R3.Value, R4.Value, R5.Value, R6.Value, R7.Value, R8.Value) var r1: R1 @@ -683,7 +684,7 @@ extension ValueReducers { r8.fetch(db)) } - mutating public func value(_ fetched: Fetched) -> Value? { + public mutating func value(_ fetched: Fetched) -> Value? { let v1 = r1.value(fetched.0) let v2 = r2.value(fetched.1) let v3 = r3.value(fetched.2) diff --git a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift b/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift index 0aec4ceff..fbffa9efa 100644 --- a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift +++ b/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift @@ -66,4 +66,5 @@ extension ValueReducers { /// :nodoc: @available(*, deprecated, renamed: "ValueReducers.RemoveDuplicates") -public typealias DistinctUntilChangedValueReducer = ValueReducers.RemoveDuplicates where Base: ValueReducer, Base.Value: Equatable +public typealias DistinctUntilChangedValueReducer = ValueReducers.RemoveDuplicates + where Base: ValueReducer, Base.Value: Equatable diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index ec118c411..8e9a28fe5 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -1108,9 +1108,9 @@ 5605F1501C672E4000235C62 /* NSNull.swift */, 5605F1511C672E4000235C62 /* NSNumber.swift */, 5605F1521C672E4000235C62 /* NSString.swift */, + 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */, 5657AB0E1D10899D006283EF /* URL.swift */, 56A8C22F1D1914540096E9D4 /* UUID.swift */, - 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */, ); path = Foundation; sourceTree = ""; @@ -1877,6 +1877,7 @@ F3BA7FFA1CFB25E4003DC1BA /* Frameworks */, F3BA7FFB1CFB25E4003DC1BA /* Headers */, F3BA7FFC1CFB25E4003DC1BA /* Resources */, + 56EB54FD22C9119B00850069 /* Swiftlint */, ); buildRules = ( ); @@ -1915,6 +1916,7 @@ F3BA80561CFB2BB2003DC1BA /* Frameworks */, F3BA80571CFB2BB2003DC1BA /* Headers */, F3BA80581CFB2BB2003DC1BA /* Resources */, + 56EB54FB22C9118600850069 /* Swiftlint */, ); buildRules = ( ); @@ -2045,6 +2047,42 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ + 56EB54FB22C9118600850069 /* Swiftlint */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + name = Swiftlint; + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n"; + }; + 56EB54FD22C9119B00850069 /* Swiftlint */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + name = Swiftlint; + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n"; + }; EED476F01CFD0B290026A4EC /* Copy .example configuration files (if no USER customizations exist) */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; diff --git a/Tests/GRDBTests/DatabaseValueConvertibleEscapingTests.swift b/Tests/GRDBTests/DatabaseValueConvertibleEscapingTests.swift index 5eabe8c86..76e3a1c93 100644 --- a/Tests/GRDBTests/DatabaseValueConvertibleEscapingTests.swift +++ b/Tests/GRDBTests/DatabaseValueConvertibleEscapingTests.swift @@ -9,27 +9,27 @@ import XCTest class DatabaseValueConvertibleEscapingTests: GRDBTestCase { func testText() { - XCTAssertEqual("".databaseValue.quotedSQL(wrappedInParenthesis: false), "''") - XCTAssertEqual("foo".databaseValue.quotedSQL(wrappedInParenthesis: false), "'foo'") - XCTAssertEqual("\"foo\"".databaseValue.quotedSQL(wrappedInParenthesis: false), "'\"foo\"'") - XCTAssertEqual("'foo'".databaseValue.quotedSQL(wrappedInParenthesis: false), "'''foo'''") + XCTAssertEqual("".databaseValue.quotedSQL(), "''") + XCTAssertEqual("foo".databaseValue.quotedSQL(), "'foo'") + XCTAssertEqual("\"foo\"".databaseValue.quotedSQL(), "'\"foo\"'") + XCTAssertEqual("'foo'".databaseValue.quotedSQL(), "'''foo'''") } func testInteger() { - XCTAssertEqual(0.databaseValue.quotedSQL(wrappedInParenthesis: false), "0") - XCTAssertEqual(Int64.min.databaseValue.quotedSQL(wrappedInParenthesis: false), "-9223372036854775808") - XCTAssertEqual(Int64.max.databaseValue.quotedSQL(wrappedInParenthesis: false), "9223372036854775807") + XCTAssertEqual(0.databaseValue.quotedSQL(), "0") + XCTAssertEqual(Int64.min.databaseValue.quotedSQL(), "-9223372036854775808") + XCTAssertEqual(Int64.max.databaseValue.quotedSQL(), "9223372036854775807") } func testDouble() { - XCTAssertEqual(0.0.databaseValue.quotedSQL(wrappedInParenthesis: false), "0.0") - XCTAssertEqual(1.0.databaseValue.quotedSQL(wrappedInParenthesis: false), "1.0") - XCTAssertEqual((-1.0).databaseValue.quotedSQL(wrappedInParenthesis: false), "-1.0") - XCTAssertEqual(1.5.databaseValue.quotedSQL(wrappedInParenthesis: false), "1.5") + XCTAssertEqual(0.0.databaseValue.quotedSQL(), "0.0") + XCTAssertEqual(1.0.databaseValue.quotedSQL(), "1.0") + XCTAssertEqual((-1.0).databaseValue.quotedSQL(), "-1.0") + XCTAssertEqual(1.5.databaseValue.quotedSQL(), "1.5") } func testBlob() { - XCTAssertEqual(Data().databaseValue.quotedSQL(wrappedInParenthesis: false), "X''") - XCTAssertEqual("foo".data(using: .utf8)!.databaseValue.quotedSQL(wrappedInParenthesis: false), "X'666F6F'") + XCTAssertEqual(Data().databaseValue.quotedSQL(), "X''") + XCTAssertEqual("foo".data(using: .utf8)!.databaseValue.quotedSQL(), "X'666F6F'") } } diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index 18740104b..b9af335f6 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -127,8 +127,8 @@ class GRDBTestCase: XCTestCase { } } - func assertDidExecute(sql: String) { - XCTAssertTrue(sqlQueries.contains(sql), "Did not execute \(sql)") + func assertDidExecute(sql: String, file: StaticString = #file, line: UInt = #line) { + XCTAssertTrue(sqlQueries.contains(sql), "Did not execute \(sql)", file: file, line: line) } func assert(_ record: EncodableRecord, isEncodedIn row: Row, file: StaticString = #file, line: UInt = #line) { From 756f1b938750a97ba7482a5e24de8afad49cb32c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 26 Jul 2019 19:30:52 +0200 Subject: [PATCH 13/91] swiftlint: remove large_tuple, add unused_declaration --- .swiftlint.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.swiftlint.yml b/.swiftlint.yml index eca723179..9b7be2474 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -10,7 +10,6 @@ disabled_rules: - function_parameter_count - identifier_name - is_disjoint - - large_tuple - nesting - opening_brace - redundant_optional_initialization @@ -48,6 +47,7 @@ opt_in_rules: - redundant_type_annotation - sorted_first_last - toggle_bool + - unused_declaration - unused_import - unused_private_declaration - yoda_condition From d7a51c39ca29ac7d264a0db043ca79571a753d3b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 26 Jul 2019 19:30:59 +0200 Subject: [PATCH 14/91] Remove Swiift 5 conversion warning --- GRDBCustom.xcodeproj/project.pbxproj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 8e9a28fe5..96b44f089 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -1958,11 +1958,11 @@ TargetAttributes = { F3BA7FFD1CFB25E4003DC1BA = { CreatedOnToolsVersion = 7.3.1; - LastSwiftMigration = 0830; + LastSwiftMigration = 1020; }; F3BA80401CFB2AD7003DC1BA = { CreatedOnToolsVersion = 7.3.1; - LastSwiftMigration = 0800; + LastSwiftMigration = 1020; }; F3BA80591CFB2BB2003DC1BA = { CreatedOnToolsVersion = 7.3.1; From d9e1a04cc2bcd8039d2f0e9f4cc9c070ca86d316 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 26 Jul 2019 19:52:34 +0200 Subject: [PATCH 15/91] Fix FTS3 & FTS4 regressions --- GRDB/FTS/FTS3.swift | 8 ++++---- GRDB/FTS/FTS4.swift | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/GRDB/FTS/FTS3.swift b/GRDB/FTS/FTS3.swift index f97d29479..edc39bac3 100644 --- a/GRDB/FTS/FTS3.swift +++ b/GRDB/FTS/FTS3.swift @@ -55,10 +55,10 @@ public struct FTS3: VirtualTableModule { if tokenizer.arguments.isEmpty { arguments.append("tokenize=\(tokenizer.name)") } else { - arguments.append("tokenize=\(tokenizer.name) ") - arguments.append(tokenizer.arguments - .map { "\"\($0)\"" as String } - .joined(separator: " ")) + arguments.append( + "tokenize=\(tokenizer.name) " + tokenizer.arguments + .map { "\"\($0)\"" as String } + .joined(separator: " ")) } } return arguments diff --git a/GRDB/FTS/FTS4.swift b/GRDB/FTS/FTS4.swift index 7fcdec269..f0e1116c2 100644 --- a/GRDB/FTS/FTS4.swift +++ b/GRDB/FTS/FTS4.swift @@ -53,10 +53,10 @@ public struct FTS4: VirtualTableModule { if tokenizer.arguments.isEmpty { arguments.append("tokenize=\(tokenizer.name)") } else { - arguments.append("tokenize=\(tokenizer.name) ") - arguments.append(tokenizer.arguments - .map { "\"\($0)\"" as String } - .joined(separator: " ")) + arguments.append( + "tokenize=\(tokenizer.name) " + tokenizer.arguments + .map { "\"\($0)\"" as String } + .joined(separator: " ")) } } From 35ceeebb3ddc6e20baed7fe5fae8768e9d60e6f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 26 Jul 2019 20:11:04 +0200 Subject: [PATCH 16/91] Style tweaks --- GRDB/Core/Database.swift | 6 +- GRDB/Core/DatabasePool.swift | 2 +- GRDB/Core/Row.swift | 4 +- GRDB/Core/Statement.swift | 15 ++--- GRDB/Core/StatementAuthorizer.swift | 16 ++--- GRDB/FTS/FTS3Pattern.swift | 2 +- GRDB/FTS/FTS4.swift | 8 +-- GRDB/FTS/FTS5.swift | 8 +-- GRDB/FTS/FTS5Pattern.swift | 2 +- GRDB/FTS/FTS5Tokenizer.swift | 2 +- .../Association/AssociationAggregate.swift | 2 +- .../SQL/SQLExpression+QueryInterface.swift | 59 +++++++++---------- GRDB/Utils/Inflections.swift | 8 +-- 13 files changed, 65 insertions(+), 69 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 0194390e7..5d5b9b27b 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -53,7 +53,7 @@ public final class Database { if logError != nil { registerErrorLogCallback { (_, code, message) in guard let logError = Database.logError else { return } - guard let message = message.map({ String(cString: $0) }) else { return } + guard let message = message.map(String.init) else { return } let resultCode = ResultCode(rawValue: code) logError(resultCode, message) } @@ -278,7 +278,7 @@ extension Database { private func setupTrace_v1() { let dbPointer = Unmanaged.passUnretained(self).toOpaque() sqlite3_trace(sqliteConnection, { (dbPointer, sql) in - guard let sql = sql.map({ String(cString: $0) }) else { return } + guard let sql = sql.map(String.init) else { return } let db = Unmanaged.fromOpaque(dbPointer!).takeUnretainedValue() db.configuration.trace!(sql) }, dbPointer) @@ -891,7 +891,7 @@ extension Database { throw DatabaseError(resultCode: dbDest.lastErrorCode, message: dbDest.lastErrorMessage) } guard Int(bitPattern: backup) != Int(SQLITE_ERROR) else { - throw DatabaseError(resultCode: .SQLITE_ERROR) + throw DatabaseError() } afterBackupInit?() diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 2fd86c81e..2cc913f07 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -159,7 +159,7 @@ extension DatabasePool { // when kind is not .Passive. let code = sqlite3_wal_checkpoint_v2(db.sqliteConnection, nil, kind.rawValue, nil, nil) guard code == SQLITE_OK else { - throw DatabaseError(resultCode: code, message: db.lastErrorMessage, sql: nil) + throw DatabaseError(resultCode: code, message: db.lastErrorMessage) } } } diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 14e900892..7f8c0d4ff 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -463,7 +463,9 @@ extension Row { @inlinable public subscript(_ column: Column) -> Value - where Value: DatabaseValueConvertible & StatementColumnConvertible, Column: ColumnExpression + where + Value: DatabaseValueConvertible & StatementColumnConvertible, + Column: ColumnExpression { return self[column.name] } diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index b3a4a9949..33c64c9a8 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -249,8 +249,7 @@ extension StatementProtocol where Self: Statement { throw DatabaseError( resultCode: .SQLITE_ERROR, message: "empty statement", - sql: sql, - arguments: nil) + sql: sql) } let remainingSQL = String(cString: statementEnd!).trimmingCharacters(in: .sqlStatementSeparators) @@ -261,8 +260,7 @@ extension StatementProtocol where Self: Statement { Multiple statements found. To execute multiple statements, \ use Database.execute(sql:) instead. """, - sql: sql, - arguments: nil) + sql: sql) } return statement @@ -886,8 +884,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable, throw DatabaseError( resultCode: .SQLITE_MISUSE, message: "missing statement argument: \(argumentName)", - sql: statement.sql, - arguments: nil) + sql: statement.sql) } else { return values.removeFirst() } @@ -896,8 +893,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable, throw DatabaseError( resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)", - sql: statement.sql, - arguments: nil) + sql: statement.sql) } else { return values.removeFirst() } @@ -907,8 +903,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable, throw DatabaseError( resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)", - sql: statement.sql, - arguments: nil) + sql: statement.sql) } return bindings } diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index 679a54a3d..ec72fb117 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -50,7 +50,7 @@ final class StatementCompilationAuthorizer: StatementAuthorizer { // print(""" // StatementCompilationAuthorizer: \ // \(actionCode) \ - // \([cString1, cString2, cString3, cString4].compactMap { $0.map({ String(cString: $0) }) }) + // \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) }) // """) switch actionCode { @@ -71,8 +71,8 @@ final class StatementCompilationAuthorizer: StatementAuthorizer { return SQLITE_OK case SQLITE_READ: - guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK } - guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK } + guard let tableName = cString1.map(String.init) else { return SQLITE_OK } + guard let columnName = cString2.map(String.init) else { return SQLITE_OK } if columnName.isEmpty { // SELECT COUNT(*) FROM table databaseRegion.formUnion(DatabaseRegion(table: tableName)) @@ -83,7 +83,7 @@ final class StatementCompilationAuthorizer: StatementAuthorizer { return SQLITE_OK case SQLITE_INSERT: - guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK } + guard let tableName = cString1.map(String.init) else { return SQLITE_OK } databaseEventKinds.append(.insert(tableName: tableName)) return SQLITE_OK @@ -104,8 +104,8 @@ final class StatementCompilationAuthorizer: StatementAuthorizer { return SQLITE_IGNORE case SQLITE_UPDATE: - guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK } - guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK } + guard let tableName = cString1.map(String.init) else { return SQLITE_OK } + guard let columnName = cString2.map(String.init) else { return SQLITE_OK } insertUpdateEventKind(tableName: tableName, columnName: columnName) return SQLITE_OK @@ -122,7 +122,7 @@ final class StatementCompilationAuthorizer: StatementAuthorizer { case SQLITE_SAVEPOINT: guard let cString1 = cString1 else { return SQLITE_OK } - guard let name = cString2.map({ String(cString: $0) }) else { return SQLITE_OK } + guard let name = cString2.map(String.init) else { return SQLITE_OK } if strcmp(cString1, "BEGIN") == 0 { transactionEffect = .beginSavepoint(name) } else if strcmp(cString1, "RELEASE") == 0 { @@ -184,7 +184,7 @@ final class TruncateOptimizationBlocker: StatementAuthorizer { // print(""" // TruncateOptimizationBlocker: \ // \(actionCode) \ - // \([cString1, cString2, cString3, cString4].compactMap { $0.map({ String(cString: $0) }) }) + // \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) }) // """) return (actionCode == SQLITE_DELETE) ? SQLITE_IGNORE : SQLITE_OK } diff --git a/GRDB/FTS/FTS3Pattern.swift b/GRDB/FTS/FTS3Pattern.swift index ffabbfb4b..4859285ee 100644 --- a/GRDB/FTS/FTS3Pattern.swift +++ b/GRDB/FTS/FTS3Pattern.swift @@ -24,7 +24,7 @@ public struct FTS3Pattern { } } catch let error as DatabaseError { // Remove private SQL & arguments from the thrown error - throw DatabaseError(resultCode: error.extendedResultCode, message: error.message, sql: nil, arguments: nil) + throw DatabaseError(resultCode: error.extendedResultCode, message: error.message) } // Pattern is valid diff --git a/GRDB/FTS/FTS4.swift b/GRDB/FTS/FTS4.swift index f0e1116c2..29cfc4b85 100644 --- a/GRDB/FTS/FTS4.swift +++ b/GRDB/FTS/FTS4.swift @@ -115,16 +115,16 @@ public struct FTS4: VirtualTableModule { try db.execute(sql: """ CREATE TRIGGER \("__\(tableName)_bu".quotedDatabaseIdentifier) BEFORE UPDATE ON \(content) BEGIN - DELETE FROM \(ftsTable) WHERE docid=\(oldRowID); + DELETE FROM \(ftsTable) WHERE docid=\(oldRowID); END; CREATE TRIGGER \("__\(tableName)_bd".quotedDatabaseIdentifier) BEFORE DELETE ON \(content) BEGIN - DELETE FROM \(ftsTable) WHERE docid=\(oldRowID); + DELETE FROM \(ftsTable) WHERE docid=\(oldRowID); END; CREATE TRIGGER \("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN - INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns)); + INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns)); END; CREATE TRIGGER \("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN - INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns)); + INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns)); END; """) diff --git a/GRDB/FTS/FTS5.swift b/GRDB/FTS/FTS5.swift index 652f991f1..83c4c83e2 100644 --- a/GRDB/FTS/FTS5.swift +++ b/GRDB/FTS/FTS5.swift @@ -152,14 +152,14 @@ public struct FTS5: VirtualTableModule { try db.execute(sql: """ CREATE TRIGGER \("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN - INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); + INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); END; CREATE TRIGGER \("__\(tableName)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN - INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); + INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); END; CREATE TRIGGER \("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN - INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); - INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); + INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); + INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); END; """) diff --git a/GRDB/FTS/FTS5Pattern.swift b/GRDB/FTS/FTS5Pattern.swift index e70f480ca..72632c932 100644 --- a/GRDB/FTS/FTS5Pattern.swift +++ b/GRDB/FTS/FTS5Pattern.swift @@ -108,7 +108,7 @@ public struct FTS5Pattern { } } catch let error as DatabaseError { // Remove private SQL & arguments from the thrown error - throw DatabaseError(resultCode: error.extendedResultCode, message: error.message, sql: nil, arguments: nil) + throw DatabaseError(resultCode: error.extendedResultCode, message: error.message) } // Pattern is valid diff --git a/GRDB/FTS/FTS5Tokenizer.swift b/GRDB/FTS/FTS5Tokenizer.swift index 5517fcb29..ab659f264 100644 --- a/GRDB/FTS/FTS5Tokenizer.swift +++ b/GRDB/FTS/FTS5Tokenizer.swift @@ -152,7 +152,7 @@ extension Database { init(xTokenizer: fts5_tokenizer, contextPointer: UnsafeMutableRawPointer?, arguments: [String]) throws { guard let xCreate = xTokenizer.xCreate else { - throw DatabaseError(resultCode: .SQLITE_ERROR, message: "nil fts5_tokenizer.xCreate") + throw DatabaseError(message: "nil fts5_tokenizer.xCreate") } self.xTokenizer = xTokenizer diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index ae808050a..58b938f97 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -1,6 +1,6 @@ import Foundation -public typealias AssociationAggregatePreparation = +typealias AssociationAggregatePreparation = (QueryInterfaceRequest) -> (request: QueryInterfaceRequest, expression: SQLExpression) diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift index a1b8981e9..814dabf46 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -247,10 +247,10 @@ public struct SQLExpressionBinary: SQLExpression { return "(\(expressionSQL(&context, wrappedInParenthesis: false)))" } return """ - \(lhs.expressionSQL(&context, wrappedInParenthesis: true)) \ - \(op.sql) \ - \(rhs.expressionSQL(&context, wrappedInParenthesis: true)) - """ + \(lhs.expressionSQL(&context, wrappedInParenthesis: true)) \ + \(op.sql) \ + \(rhs.expressionSQL(&context, wrappedInParenthesis: true)) + """ } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) @@ -388,10 +388,10 @@ struct SQLExpressionEqual: SQLExpression { return "(\(expressionSQL(&context, wrappedInParenthesis: false)))" } return """ - \(lhs.expressionSQL(&context, wrappedInParenthesis: true)) \ - \(op.rawValue) \ - \(rhs.expressionSQL(&context, wrappedInParenthesis: true)) - """ + \(lhs.expressionSQL(&context, wrappedInParenthesis: true)) \ + \(op.rawValue) \ + \(rhs.expressionSQL(&context, wrappedInParenthesis: true)) + """ } var negated: SQLExpression { @@ -459,10 +459,10 @@ struct SQLExpressionContains: SQLExpression { return "(\(expressionSQL(&context, wrappedInParenthesis: false)))" } return """ - \(expression.expressionSQL(&context, wrappedInParenthesis: true)) \ - \(isNegated ? "NOT IN" : "IN") \ - (\(collection.collectionSQL(&context))) - """ + \(expression.expressionSQL(&context, wrappedInParenthesis: true)) \ + \(isNegated ? "NOT IN" : "IN") \ + (\(collection.collectionSQL(&context))) + """ } var negated: SQLExpression { @@ -527,12 +527,12 @@ struct SQLExpressionBetween: SQLExpression { return "(\(expressionSQL(&context, wrappedInParenthesis: false)))" } return """ - \(expression.expressionSQL(&context, wrappedInParenthesis: true)) \ - \(isNegated ? "NOT BETWEEN" : "BETWEEN") \ - \(lowerBound.expressionSQL(&context, wrappedInParenthesis: true)) \ - AND \ - \(upperBound.expressionSQL(&context, wrappedInParenthesis: true)) - """ + \(expression.expressionSQL(&context, wrappedInParenthesis: true)) \ + \(isNegated ? "NOT BETWEEN" : "BETWEEN") \ + \(lowerBound.expressionSQL(&context, wrappedInParenthesis: true)) \ + AND \ + \(upperBound.expressionSQL(&context, wrappedInParenthesis: true)) + """ } var negated: SQLExpression { @@ -701,9 +701,9 @@ struct SQLExpressionIsEmpty: SQLExpression { return "(\(expressionSQL(&context, wrappedInParenthesis: false)))" } return """ - \(countExpression.expressionSQL(&context, wrappedInParenthesis: true)) \ - \(isEmpty ? "= 0" : "> 0") - """ + \(countExpression.expressionSQL(&context, wrappedInParenthesis: true)) \ + \(isEmpty ? "= 0" : "> 0") + """ } func qualifiedExpression(with alias: TableAlias) -> SQLExpression { @@ -722,10 +722,10 @@ struct TableMatchExpression: SQLExpression { return "(\(expressionSQL(&context, wrappedInParenthesis: false)))" } return """ - \(context.resolvedName(for: alias).quotedDatabaseIdentifier) \ - MATCH \ - \(pattern.expressionSQL(&context, wrappedInParenthesis: true)) - """ + \(context.resolvedName(for: alias).quotedDatabaseIdentifier) \ + MATCH \ + \(pattern.expressionSQL(&context, wrappedInParenthesis: true)) + """ } func qualifiedExpression(with alias: TableAlias) -> SQLExpression { @@ -754,12 +754,11 @@ struct SQLExpressionCollate: SQLExpression { if wrappedInParenthesis { return "(\(expressionSQL(&context, wrappedInParenthesis: false)))" } - let sql = expression.expressionSQL(&context, wrappedInParenthesis: false) return """ - \(sql) \ - COLLATE \ - \(collationName.rawValue) - """ + \(expression.expressionSQL(&context, wrappedInParenthesis: false)) \ + COLLATE \ + \(collationName.rawValue) + """ } func qualifiedExpression(with alias: TableAlias) -> SQLExpression { diff --git a/GRDB/Utils/Inflections.swift b/GRDB/Utils/Inflections.swift index ee8fc082c..da6c5b176 100644 --- a/GRDB/Utils/Inflections.swift +++ b/GRDB/Utils/Inflections.swift @@ -186,10 +186,10 @@ public struct Inflections { return string } return """ - \(string.prefix(upTo: indexOfLastWord))\ - \(inflectWord(lastWord, with: rules))\ - \(string.suffix(from: endIndexOfDigitlessRadical)) - """ + \(string.prefix(upTo: indexOfLastWord))\ + \(inflectWord(lastWord, with: rules))\ + \(string.suffix(from: endIndexOfDigitlessRadical)) + """ } private func inflectWord(_ string: String, with rules: [(NSRegularExpression, String)]) -> String { From 56d355c903e342b80dac4d4ff226766a94cffdc0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 26 Jul 2019 21:09:19 +0200 Subject: [PATCH 17/91] The kiss of Xcode 10.3 --- .../xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme | 2 +- .../xcshareddata/xcschemes/GRDBDemoiOS.xcscheme | 2 +- GRDB.xcodeproj/xcshareddata/xcschemes/GRDBOSX.xcscheme | 2 +- .../xcschemes/GRDBOSXPerformanceComparisonTests.xcscheme | 2 +- .../xcshareddata/xcschemes/GRDBOSXPerformanceTests.xcscheme | 2 +- GRDB.xcodeproj/xcshareddata/xcschemes/GRDBWatchOS.xcscheme | 2 +- GRDB.xcodeproj/xcshareddata/xcschemes/GRDBiOS.xcscheme | 2 +- GRDBCustom.xcodeproj/project.pbxproj | 2 +- .../xcshareddata/xcschemes/GRDBCustomSQLiteOSX.xcscheme | 2 +- .../xcshareddata/xcschemes/GRDBCustomSQLiteiOS.xcscheme | 2 +- .../xcshareddata/xcschemes/GRDBProfiling.xcscheme | 2 +- 11 files changed, 11 insertions(+), 11 deletions(-) diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme index e7450b0c6..7c6bbd3a9 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme @@ -1,6 +1,6 @@ Date: Fri, 26 Jul 2019 21:18:51 +0200 Subject: [PATCH 18/91] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e6b4e37d..05c33ffcb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,6 +55,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: ## Next Release - [#562](https://github.com/groue/GRDB.swift/pull/562): Fix crash when using more than one DatabaseCollation +- [#574](https://github.com/groue/GRDB.swift/pull/574): SwiftLint ## 4.1.1 From b8cc4c30f99435fdb4d5456d57e20abe5edc3944 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 26 Jul 2019 21:19:44 +0200 Subject: [PATCH 19/91] TODO --- TODO.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/TODO.md b/TODO.md index b49c5103b..6d558ebee 100644 --- a/TODO.md +++ b/TODO.md @@ -68,6 +68,10 @@ - [ ] ValueObservation.flatMap: Make it possible to build a single observation where some requests depend on the result of other requests. As long as we can't express this in a single observation, we fail the "guaranteed consistency is possible" contract. +- [ ] matching (FTS3, 5) on associations and DerivableRequest +- [ ] rename fetchOne to fetchFirst +- [ ] Rename aliased() to forKey() when relevant +- [ ] new.updateChanges(from: old) vs. old.updateChanges(with: { old.a = new.a }). This is confusing. Swift 4.2 From bf73f0ded22042709878f11c66d51b6b86861dd0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jul 2019 15:22:13 +0200 Subject: [PATCH 20/91] CHANGELOG --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 05c33ffcb..f7ac7e0ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,7 +54,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: ## Next Release +- [#560](https://github.com/groue/GRDB.swift/pull/560) by [@bellebethcooper](https://github.com/bellebethcooper): Minor typo fix - [#562](https://github.com/groue/GRDB.swift/pull/562): Fix crash when using more than one DatabaseCollation +- [#563](https://github.com/groue/GRDB.swift/pull/563): More tests for eager loading of hasMany associations - [#574](https://github.com/groue/GRDB.swift/pull/574): SwiftLint From 4d558488c09f7b99c8e2d0c9c0d51d511bfe882c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jul 2019 13:00:25 +0200 Subject: [PATCH 21/91] Expose matching(_:) on TableRequest&FilteredRequest --- GRDB/QueryInterface/FTS3+QueryInterface.swift | 4 ++-- GRDB/QueryInterface/FTS5+QueryInterface.swift | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/GRDB/QueryInterface/FTS3+QueryInterface.swift b/GRDB/QueryInterface/FTS3+QueryInterface.swift index 7bdfaade4..9faee9094 100644 --- a/GRDB/QueryInterface/FTS3+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS3+QueryInterface.swift @@ -1,4 +1,4 @@ -extension QueryInterfaceRequest { +extension TableRequest where Self: FilteredRequest { // MARK: Full Text Search @@ -11,7 +11,7 @@ extension QueryInterfaceRequest { /// /// If the search pattern is nil, the request does not match any /// database row. - public func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest { + public func matching(_ pattern: FTS3Pattern?) -> Self { guard let pattern = pattern else { return none() } diff --git a/GRDB/QueryInterface/FTS5+QueryInterface.swift b/GRDB/QueryInterface/FTS5+QueryInterface.swift index b39ee6ca3..e8d74aa79 100644 --- a/GRDB/QueryInterface/FTS5+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS5+QueryInterface.swift @@ -1,5 +1,5 @@ #if SQLITE_ENABLE_FTS5 -extension QueryInterfaceRequest { +extension TableRequest where Self: FilteredRequest { // MARK: Full Text Search @@ -16,7 +16,7 @@ extension QueryInterfaceRequest { /// The selection defaults to all columns. This default can be changed for /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. - public func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest { + public func matching(_ pattern: FTS5Pattern?) -> Self { guard let pattern = pattern else { return none() } From 2d1f218ec505a0e0b6918ecd156e8c9d162dfe34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jul 2019 14:22:24 +0200 Subject: [PATCH 22/91] Force TableRecord on Association origin & destination, append TableRequest to DerivableRequest requirements --- .../QueryInterface/Request/Association/Association.swift | 8 ++++---- .../Request/Association/BelongsToAssociation.swift | 5 +---- .../Request/Association/HasManyAssociation.swift | 5 +---- .../Request/Association/HasManyThroughAssociation.swift | 5 +---- .../Request/Association/HasOneAssociation.swift | 5 +---- .../Request/Association/HasOneThroughAssociation.swift | 5 +---- GRDB/QueryInterface/Request/QueryInterfaceRequest.swift | 9 +++++++-- GRDB/QueryInterface/Request/RequestProtocols.swift | 6 ++++-- GRDB/QueryInterface/TableRecord+Association.swift | 3 --- 9 files changed, 20 insertions(+), 31 deletions(-) diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index 8099053da..20fa33f87 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -18,7 +18,7 @@ public protocol Association: DerivableRequest { /// // BelongsToAssociation /// static let author = belongsTo(Author.self) /// } - associatedtype OriginRowDecoder + associatedtype OriginRowDecoder: TableRecord /// :nodoc: var sqlAssociation: SQLAssociation { get } @@ -290,8 +290,8 @@ extension Association { } } -// Allow association.filter(key: ...) -extension Association where Self: TableRequest, RowDecoder: TableRecord { +// TableRequest +extension Association { /// :nodoc: public var databaseTableName: String { return RowDecoder.databaseTableName } } @@ -324,7 +324,7 @@ extension AssociationToMany { } } -extension AssociationToMany where OriginRowDecoder: TableRecord { +extension AssociationToMany { private func makeAggregate(_ expression: SQLExpression) -> AssociationAggregate { return AssociationAggregate { request in let tableAlias = TableAlias() diff --git a/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift index 1f459622f..1643ba69e 100644 --- a/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift @@ -58,7 +58,7 @@ /// } /// /// See ForeignKey for more information. -public struct BelongsToAssociation: AssociationToOne { +public struct BelongsToAssociation: AssociationToOne { /// :nodoc: public typealias OriginRowDecoder = Origin @@ -73,6 +73,3 @@ public struct BelongsToAssociation: AssociationToOne { self.sqlAssociation = sqlAssociation } } - -// Allow BelongsToAssociation(...).filter(key: ...) -extension BelongsToAssociation: TableRequest where Destination: TableRecord { } diff --git a/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift index d02586fde..fb263da89 100644 --- a/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift @@ -58,7 +58,7 @@ /// } /// /// See ForeignKey for more information. -public struct HasManyAssociation: AssociationToMany { +public struct HasManyAssociation: AssociationToMany { /// :nodoc: public typealias OriginRowDecoder = Origin @@ -73,6 +73,3 @@ public struct HasManyAssociation: AssociationToMany { self.sqlAssociation = sqlAssociation } } - -// Allow HasManyAssociation(...).filter(key: ...) -extension HasManyAssociation: TableRequest where Destination: TableRecord { } diff --git a/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift b/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift index e4e5cb3cc..8b1aec3f5 100644 --- a/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift @@ -41,7 +41,7 @@ /// two other associations: the `through:` and `using:` arguments. Those /// associations can be any other association (BelongsTo, HasMany, /// HasManyThrough, etc). -public struct HasManyThroughAssociation: AssociationToMany { +public struct HasManyThroughAssociation: AssociationToMany { /// :nodoc: public typealias OriginRowDecoder = Origin @@ -56,6 +56,3 @@ public struct HasManyThroughAssociation: AssociationToMany self.sqlAssociation = sqlAssociation } } - -// Allow HasManyThroughAssociation(...).filter(key: ...) -extension HasManyThroughAssociation: TableRequest where Destination: TableRecord { } diff --git a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift index 6b1f49f7c..c0ad1e021 100644 --- a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift @@ -60,7 +60,7 @@ /// } /// /// See ForeignKey for more information. -public struct HasOneAssociation: AssociationToOne { +public struct HasOneAssociation: AssociationToOne { /// :nodoc: public typealias OriginRowDecoder = Origin @@ -75,6 +75,3 @@ public struct HasOneAssociation: AssociationToOne { self.sqlAssociation = sqlAssociation } } - -// Allow HasOneAssociation(...).filter(key: ...) -extension HasOneAssociation: TableRequest where Destination: TableRecord { } diff --git a/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift b/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift index be25e3173..ccc8d5011 100644 --- a/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift @@ -21,7 +21,7 @@ /// two other associations: the `through:` and `using:` arguments. Those /// associations can be any other association to one (BelongsTo, HasOne, /// HasOneThrough). -public struct HasOneThroughAssociation: AssociationToOne { +public struct HasOneThroughAssociation: AssociationToOne { /// :nodoc: public typealias OriginRowDecoder = Origin @@ -36,6 +36,3 @@ public struct HasOneThroughAssociation: AssociationToOne { self.sqlAssociation = sqlAssociation } } - -// Allow HasOneThroughAssociation(...).filter(key: ...) -extension HasOneThroughAssociation: TableRequest where Destination: TableRecord { } diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index a6e74d751..fe9d19ce5 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -28,7 +28,7 @@ /// } /// /// See https://github.com/groue/GRDB.swift#the-query-interface -public struct QueryInterfaceRequest: DerivableRequest { +public struct QueryInterfaceRequest { var query: SQLQuery init(query: SQLQuery) { @@ -310,7 +310,7 @@ extension QueryInterfaceRequest: AggregatingRequest { } } -extension QueryInterfaceRequest: JoinableRequest { +extension QueryInterfaceRequest: _JoinableRequest { /// :nodoc: public func _including(all association: SQLAssociation) -> QueryInterfaceRequest { return mapQuery { $0._including(all: association) } @@ -337,6 +337,8 @@ extension QueryInterfaceRequest: JoinableRequest { } } +extension QueryInterfaceRequest: JoinableRequest where RowDecoder: TableRecord { } + extension QueryInterfaceRequest { // MARK: Request Derivation @@ -472,6 +474,9 @@ extension QueryInterfaceRequest: TableRequest { } } +// TODO: remove this explicit conformance when Swift is able to infer it. +extension QueryInterfaceRequest: DerivableRequest where RowDecoder: TableRecord { } + extension QueryInterfaceRequest where T: MutablePersistableRecord { // MARK: Deleting diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 1a45b4cc1..9c6a8cbf1 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -500,6 +500,8 @@ extension OrderedRequest { } } +// MARK: - JoinableRequest + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Type-unsafe support for the JoinableRequest protocol. @@ -548,7 +550,7 @@ public protocol JoinableRequest: _JoinableRequest { /// // BelongsToAssociation /// static let author = belongsTo(Author.self) /// } - associatedtype RowDecoder + associatedtype RowDecoder: TableRecord } extension JoinableRequest { @@ -593,4 +595,4 @@ extension JoinableRequest { /// The base protocol for all requests that can be refined. /// /// :nodoc: -public protocol DerivableRequest: SelectionRequest, FilteredRequest, OrderedRequest, JoinableRequest { } +public protocol DerivableRequest: FilteredRequest, JoinableRequest, OrderedRequest, SelectionRequest, TableRequest { } diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index 136ddb7fc..954418083 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -60,7 +60,6 @@ extension TableRecord { key: String? = nil, using foreignKey: ForeignKey? = nil) -> BelongsToAssociation - where Destination: TableRecord { let foreignKeyRequest = SQLForeignKeyRequest( originTable: databaseTableName, @@ -146,7 +145,6 @@ extension TableRecord { key: String? = nil, using foreignKey: ForeignKey? = nil) -> HasManyAssociation - where Destination: TableRecord { let foreignKeyRequest = SQLForeignKeyRequest( originTable: Destination.databaseTableName, @@ -314,7 +312,6 @@ extension TableRecord { key: String? = nil, using foreignKey: ForeignKey? = nil) -> HasOneAssociation - where Destination: TableRecord { let foreignKeyRequest = SQLForeignKeyRequest( originTable: Destination.databaseTableName, From 026db8f19a460a3de9167e650a1503a52bc45078 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jul 2019 14:23:36 +0200 Subject: [PATCH 23/91] Tests for TableRequest requirement on DerivableRequest, including the new support for full-text search --- .../AssociationHasManyThroughSQLTests.swift | 6 +- .../AssociationHasOneThroughSQLTests.swift | 12 +- Tests/GRDBTests/DerivableRequestTests.swift | 158 +++++++++++++++++- 3 files changed, 165 insertions(+), 11 deletions(-) diff --git a/Tests/GRDBTests/AssociationHasManyThroughSQLTests.swift b/Tests/GRDBTests/AssociationHasManyThroughSQLTests.swift index 8e443f23d..4c8c585bb 100644 --- a/Tests/GRDBTests/AssociationHasManyThroughSQLTests.swift +++ b/Tests/GRDBTests/AssociationHasManyThroughSQLTests.swift @@ -175,10 +175,10 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase { ac: CAssociation, bCondition: String, cCondition: String) throws - where BAssociation: Association, + where + BAssociation: Association, CAssociation: Association, - BAssociation.OriginRowDecoder == CAssociation.OriginRowDecoder, - BAssociation.OriginRowDecoder: TableRecord + BAssociation.OriginRowDecoder == CAssociation.OriginRowDecoder { let A = BAssociation.OriginRowDecoder.self diff --git a/Tests/GRDBTests/AssociationHasOneThroughSQLTests.swift b/Tests/GRDBTests/AssociationHasOneThroughSQLTests.swift index 52135450d..485ccc821 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughSQLTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughSQLTests.swift @@ -177,10 +177,10 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { ac: CAssociation, bCondition: String, cCondition: String) throws - where BAssociation: AssociationToOne, + where + BAssociation: AssociationToOne, CAssociation: AssociationToOne, - BAssociation.OriginRowDecoder == CAssociation.OriginRowDecoder, - BAssociation.OriginRowDecoder: TableRecord + BAssociation.OriginRowDecoder == CAssociation.OriginRowDecoder { let A = BAssociation.OriginRowDecoder.self @@ -783,14 +783,14 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { bCondition: String, cCondition: String, dCondition: String) throws - where BAssociation: AssociationToOne, + where + BAssociation: AssociationToOne, CAssociation: AssociationToOne, DCAssociation: AssociationToOne, DBAssociation: AssociationToOne, BAssociation.OriginRowDecoder == CAssociation.OriginRowDecoder, BAssociation.OriginRowDecoder == DCAssociation.OriginRowDecoder, - BAssociation.OriginRowDecoder == DBAssociation.OriginRowDecoder, - BAssociation.OriginRowDecoder: TableRecord + BAssociation.OriginRowDecoder == DBAssociation.OriginRowDecoder { let A = CAssociation.OriginRowDecoder.self diff --git a/Tests/GRDBTests/DerivableRequestTests.swift b/Tests/GRDBTests/DerivableRequestTests.swift index 9d0f991b7..c39899e66 100644 --- a/Tests/GRDBTests/DerivableRequestTests.swift +++ b/Tests/GRDBTests/DerivableRequestTests.swift @@ -1,8 +1,8 @@ import XCTest #if GRDBCUSTOMSQLITE - import GRDBCustomSQLite +import GRDBCustomSQLite #else - import GRDB +import GRDB #endif private struct Author: FetchableRecord, PersistableRecord, Codable { @@ -18,10 +18,12 @@ private struct Author: FetchableRecord, PersistableRecord, Codable { static let databaseTableName = "author" static let books = hasMany(Book.self) + var books: QueryInterfaceRequest { return request(for: Author.books) } } + private struct Book: FetchableRecord, PersistableRecord, Codable { var id: Int64 var authorId: Int64 @@ -29,11 +31,22 @@ private struct Book: FetchableRecord, PersistableRecord, Codable { static let databaseTableName = "book" static let author = belongsTo(Author.self) + static let bookFts4 = hasOne(BookFts4.self, using: ForeignKey([Column.rowID])) + #if SQLITE_ENABLE_FTS5 + static let bookFts5 = hasOne(BookFts5.self, using: ForeignKey([Column.rowID])) + #endif + var author: QueryInterfaceRequest { return request(for: Book.author) } } +private struct BookFts4: FetchableRecord, TableRecord, Decodable { } + +#if SQLITE_ENABLE_FTS5 +private struct BookFts5: FetchableRecord, TableRecord, Decodable { } +#endif + private var libraryMigrator: DatabaseMigrator = { var migrator = DatabaseMigrator() migrator.registerMigration("library") { db in @@ -48,6 +61,16 @@ private var libraryMigrator: DatabaseMigrator = { t.column("authorId", .integer).notNull().references("author") t.column("title", .text).notNull() } + try db.create(virtualTable: "bookFts4", using: FTS4()) { t in + t.synchronize(withTable: "book") + t.column("title") + } + #if SQLITE_ENABLE_FTS5 + try db.create(virtualTable: "bookFts5", using: FTS5()) { t in + t.synchronize(withTable: "book") + t.column("title") + } + #endif } migrator.registerMigration("fixture") { db in try Author(id: 1, firstName: "Herman", lastName: "Melville", country: "US").insert(db) @@ -88,6 +111,28 @@ extension DerivableRequest where RowDecoder == Book { func filter(authorCountry: String) -> Self { return joining(required: Book.author.filter(country: authorCountry)) } + + // TableRequest & FilteredRequest + func filter(id: Int) -> Self { + return filter(key: id) + } + + // TableRequest & FilteredRequest + func matchingFts4(_ pattern: FTS3Pattern?) -> Self { + return joining(required: Book.bookFts4.matching(pattern)) + } + + #if SQLITE_ENABLE_FTS5 + // TableRequest & FilteredRequest + func matchingFts5(_ pattern: FTS3Pattern?) -> Self { + return joining(required: Book.bookFts5.matching(pattern)) + } + #endif + + // TableRequest & OrderedRequest + func orderById() -> Self { + return orderByPrimaryKey() + } } class DerivableRequestTests: GRDBTestCase { @@ -263,4 +308,113 @@ class DerivableRequestTests: GRDBTestCase { } } } + + func testTableRequestFilteredRequest() throws { + let dbQueue = try makeDatabaseQueue() + try libraryMigrator.migrate(dbQueue) + try dbQueue.inDatabase { db in + // filter(id:) + do { + let title = try Book.all() + .filter(id: 2) + .fetchOne(db) + .map { $0.title } + XCTAssertEqual(title, "Du côté de chez Swann") + XCTAssertEqual(lastSQLQuery, """ + SELECT * FROM "book" WHERE "id" = 2 + """) + + let fullName = try Author + .joining(required: Author.books.filter(id: 2)) + .fetchOne(db) + .map { $0.fullName } + XCTAssertEqual(fullName, "Marcel Proust") + XCTAssertEqual(lastSQLQuery, """ + SELECT "author".* FROM "author" \ + JOIN "book" ON ("book"."authorId" = "author"."id") AND ("book"."id" = 2) \ + LIMIT 1 + """) + } + + // matchingFts4 + do { + sqlQueries.removeAll() + let title = try Book.all() + .matchingFts4(FTS3Pattern(matchingAllTokensIn: "moby dick")) + .fetchOne(db) + .map { $0.title } + XCTAssertEqual(title, "Moby-Dick") + XCTAssert(sqlQueries.contains(""" + SELECT "book".* FROM "book" \ + JOIN "bookFts4" ON ("bookFts4"."rowid" = "book"."id") AND ("bookFts4" MATCH 'moby dick') \ + LIMIT 1 + """)) + + sqlQueries.removeAll() + let fullName = try Author + .joining(required: Author.books.matchingFts4(FTS3Pattern(matchingAllTokensIn: "moby dick"))) + .fetchOne(db) + .map { $0.fullName } + XCTAssertEqual(fullName, "Herman Melville") + XCTAssert(sqlQueries.contains(""" + SELECT "author".* FROM "author" \ + JOIN "book" ON "book"."authorId" = "author"."id" \ + JOIN "bookFts4" ON ("bookFts4"."rowid" = "book"."id") AND ("bookFts4" MATCH 'moby dick') \ + LIMIT 1 + """)) + } + + #if SQLITE_ENABLE_FTS5 + // matchingFts5 + do { + sqlQueries.removeAll() + let title = try Book.all() + .matchingFts5(FTS3Pattern(matchingAllTokensIn: "cote swann")) + .fetchOne(db) + .map { $0.title } + XCTAssertEqual(title, "Du côté de chez Swann") + XCTAssert(sqlQueries.contains(""" + SELECT "book".* FROM "book" \ + JOIN "bookFts5" ON ("bookFts5"."rowid" = "book"."id") AND ("bookFts5" MATCH 'cote swann') \ + LIMIT 1 + """)) + + sqlQueries.removeAll() + let fullName = try Author + .joining(required: Author.books.matchingFts5(FTS3Pattern(matchingAllTokensIn: "cote swann"))) + .fetchOne(db) + .map { $0.fullName } + XCTAssertEqual(fullName, "Marcel Proust") + XCTAssert(sqlQueries.contains(""" + SELECT "author".* FROM "author" \ + JOIN "book" ON "book"."authorId" = "author"."id" \ + JOIN "bookFts5" ON ("bookFts5"."rowid" = "book"."id") AND ("bookFts5" MATCH 'cote swann') \ + LIMIT 1 + """)) + } + #endif + + // orderById + do { + let titles = try Book.all() + .orderById() + .fetchAll(db) + .map { $0.title } + XCTAssertEqual(titles, ["Moby-Dick", "Du côté de chez Swann"]) + XCTAssertEqual(lastSQLQuery, """ + SELECT * FROM "book" ORDER BY "id" + """) + + let fullNames = try Author + .joining(required: Author.books.orderById()) + .fetchAll(db) + .map { $0.fullName } + XCTAssertEqual(fullNames, ["Herman Melville", "Marcel Proust"]) + XCTAssertEqual(lastSQLQuery, """ + SELECT "author".* FROM "author" \ + JOIN "book" ON "book"."authorId" = "author"."id" ORDER BY "book"."id" + """) + } + } + } } From 89001f11c339950493ea849dd23a3a1fea82e9b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jul 2019 14:24:39 +0200 Subject: [PATCH 24/91] Spot that annotations are another challenge on the way to optional + required join chaining --- GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 2d3c8d7b1..56b277f66 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -471,6 +471,10 @@ private struct SQLQualifiedJoin { case .innerJoin: guard allowsInnerJoin else { // TODO: chainOptionalRequired + // + // When we eventually implement this, make sure we both support: + // - joining(optional: assoc.joining(required: ...)) + // - having(assoc.joining(required: ...).isEmpty) fatalError("Not implemented: chaining a required association behind an optional association") } case .leftJoin: From c1a0b7f9e2cbdac9ebe0ecda3c7e20154f0acb90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jul 2019 14:27:51 +0200 Subject: [PATCH 25/91] Add missing Foundation imports (https://github.com/openbitapp/GRDB.swift/commit/9669e3007f42359e4165759208c5df8455531b12) --- GRDB/FTS/FTS5.swift | 1 + GRDB/FTS/FTS5Tokenizer.swift | 1 + GRDB/FTS/FTS5WrapperTokenizer.swift | 1 + 3 files changed, 3 insertions(+) diff --git a/GRDB/FTS/FTS5.swift b/GRDB/FTS/FTS5.swift index 83c4c83e2..381d0bb4c 100644 --- a/GRDB/FTS/FTS5.swift +++ b/GRDB/FTS/FTS5.swift @@ -1,4 +1,5 @@ #if SQLITE_ENABLE_FTS5 +import Foundation #if SWIFT_PACKAGE import CSQLite #elseif GRDBCIPHER diff --git a/GRDB/FTS/FTS5Tokenizer.swift b/GRDB/FTS/FTS5Tokenizer.swift index ab659f264..b5fbea527 100644 --- a/GRDB/FTS/FTS5Tokenizer.swift +++ b/GRDB/FTS/FTS5Tokenizer.swift @@ -1,4 +1,5 @@ #if SQLITE_ENABLE_FTS5 +import Foundation #if SWIFT_PACKAGE import CSQLite #elseif GRDBCIPHER diff --git a/GRDB/FTS/FTS5WrapperTokenizer.swift b/GRDB/FTS/FTS5WrapperTokenizer.swift index bfa346335..f3318f8ad 100644 --- a/GRDB/FTS/FTS5WrapperTokenizer.swift +++ b/GRDB/FTS/FTS5WrapperTokenizer.swift @@ -1,4 +1,5 @@ #if SQLITE_ENABLE_FTS5 +import Foundation #if SWIFT_PACKAGE import CSQLite #elseif GRDBCIPHER From 462e5eee24bb6f8fa8c75317f0b66536a0767da3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jul 2019 14:57:41 +0200 Subject: [PATCH 26/91] Cleanup --- Tests/GRDBTests/DerivableRequestTests.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/GRDBTests/DerivableRequestTests.swift b/Tests/GRDBTests/DerivableRequestTests.swift index c39899e66..9b0798516 100644 --- a/Tests/GRDBTests/DerivableRequestTests.swift +++ b/Tests/GRDBTests/DerivableRequestTests.swift @@ -41,10 +41,10 @@ private struct Book: FetchableRecord, PersistableRecord, Codable { } } -private struct BookFts4: FetchableRecord, TableRecord, Decodable { } +private struct BookFts4: TableRecord { } #if SQLITE_ENABLE_FTS5 -private struct BookFts5: FetchableRecord, TableRecord, Decodable { } +private struct BookFts5: TableRecord { } #endif private var libraryMigrator: DatabaseMigrator = { From ae60bc6e1899f67aa714283dcc830d0258ae6f6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jul 2019 15:01:41 +0200 Subject: [PATCH 27/91] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f7ac7e0ae..b3d7445b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -58,6 +58,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: - [#562](https://github.com/groue/GRDB.swift/pull/562): Fix crash when using more than one DatabaseCollation - [#563](https://github.com/groue/GRDB.swift/pull/563): More tests for eager loading of hasMany associations - [#574](https://github.com/groue/GRDB.swift/pull/574): SwiftLint +- [#576](https://github.com/groue/GRDB.swift/pull/576): Expose table name and full-text filtering methods to DerivableRequest ## 4.1.1 From 3f8e9945018db7589656dbfe08508c1923091e68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jul 2019 15:12:03 +0200 Subject: [PATCH 28/91] API diff --- CHANGELOG.md | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b3d7445b8..3a7e932eb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -60,6 +60,44 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: - [#574](https://github.com/groue/GRDB.swift/pull/574): SwiftLint - [#576](https://github.com/groue/GRDB.swift/pull/576): Expose table name and full-text filtering methods to DerivableRequest +### API Diff + +```diff +-extension QueryInterfaceRequest { +- func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest +-} +-extension QueryInterfaceRequest { +- func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest +-} ++extension TableRequest where Self: FilteredRequest { ++ func matching(_ pattern: FTS3Pattern?) -> Self ++} ++extension TableRequest where Self: FilteredRequest { ++ func matching(_ pattern: FTS5Pattern?) -> Self ++} + + protocol Association: DerivableRequest { +- associatedtype OriginRowDecoder ++ associatedtype OriginRowDecoder: TableRecord + } + +-struct BelongsToAssociation: AssociationToOne { } +-struct HasManyAssociation: AssociationToMany { } +-struct HasManyThroughAssociation: AssociationToMany { } +-struct HasOneAssociation: AssociationToOne { } +-struct HasOneThroughAssociation: AssociationToOne { } ++struct BelongsToAssociation: AssociationToOne { } ++struct HasManyAssociation: AssociationToMany { } ++struct HasManyThroughAssociation: AssociationToMany { } ++struct HasOneAssociation: AssociationToOne { } ++struct HasOneThroughAssociation: AssociationToOne { } + +-struct QueryInterfaceRequest: DerivableRequest { } ++struct QueryInterfaceRequest: FilteredRequest, JoinableRequest, OrderedRequest, SelectionRequest { } ++extension QueryInterfaceRequest: TableRequest where RowDecoder: TableRecord { } ++extension QueryInterfaceRequest: DerivableRequest where RowDecoder: TableRecord { } +``` + ## 4.1.1 From 5cced46a616f6eab85329f93c7f29a391ace52b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jul 2019 15:17:04 +0200 Subject: [PATCH 29/91] API diff --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a7e932eb..793c959e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -63,6 +63,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: ### API Diff ```diff +-protocol DerivableRequest: FilteredRequest, JoinableRequest, OrderedRequest, SelectionRequest { } ++protocol DerivableRequest: FilteredRequest, JoinableRequest, OrderedRequest, SelectionRequest, TableRequest { } + -extension QueryInterfaceRequest { - func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest -} From 52cd98547dfe35d4723453d0ba88756c145bad73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jul 2019 15:58:33 +0200 Subject: [PATCH 30/91] Fix DerivableRequest.matching(_:) tests so that OSX 10.0 is not required --- Tests/GRDBTests/DerivableRequestTests.swift | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Tests/GRDBTests/DerivableRequestTests.swift b/Tests/GRDBTests/DerivableRequestTests.swift index 9b0798516..bc77b5ba5 100644 --- a/Tests/GRDBTests/DerivableRequestTests.swift +++ b/Tests/GRDBTests/DerivableRequestTests.swift @@ -340,7 +340,7 @@ class DerivableRequestTests: GRDBTestCase { do { sqlQueries.removeAll() let title = try Book.all() - .matchingFts4(FTS3Pattern(matchingAllTokensIn: "moby dick")) + .matchingFts4(FTS3Pattern(rawPattern: "moby dick")) .fetchOne(db) .map { $0.title } XCTAssertEqual(title, "Moby-Dick") @@ -352,7 +352,7 @@ class DerivableRequestTests: GRDBTestCase { sqlQueries.removeAll() let fullName = try Author - .joining(required: Author.books.matchingFts4(FTS3Pattern(matchingAllTokensIn: "moby dick"))) + .joining(required: Author.books.matchingFts4(FTS3Pattern(rawPattern: "moby dick"))) .fetchOne(db) .map { $0.fullName } XCTAssertEqual(fullName, "Herman Melville") @@ -369,7 +369,7 @@ class DerivableRequestTests: GRDBTestCase { do { sqlQueries.removeAll() let title = try Book.all() - .matchingFts5(FTS3Pattern(matchingAllTokensIn: "cote swann")) + .matchingFts5(FTS3Pattern(rawPattern: "cote swann")) .fetchOne(db) .map { $0.title } XCTAssertEqual(title, "Du côté de chez Swann") @@ -381,7 +381,7 @@ class DerivableRequestTests: GRDBTestCase { sqlQueries.removeAll() let fullName = try Author - .joining(required: Author.books.matchingFts5(FTS3Pattern(matchingAllTokensIn: "cote swann"))) + .joining(required: Author.books.matchingFts5(FTS3Pattern(rawPattern: "cote swann"))) .fetchOne(db) .map { $0.fullName } XCTAssertEqual(fullName, "Marcel Proust") From b4929bb63879c59b90e2db4622fff90715c9ad74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jul 2019 16:29:09 +0200 Subject: [PATCH 31/91] Rename aliased(_:) to forKey(_:) --- .../Request/Association/Association.swift | 12 ++-- .../Association/AssociationAggregate.swift | 50 ++++++++++--- .../QueryInterfaceRequest+Association.swift | 4 +- .../Request/QueryInterfaceRequest.swift | 4 +- ...QLSpecificExpressible+QueryInterface.swift | 72 +++++++++++++++++-- 5 files changed, 118 insertions(+), 24 deletions(-) diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index 8099053da..a3a7603fd 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -353,7 +353,7 @@ extension AssociationToMany where OriginRowDecoder: TableRecord { /// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db) public var count: AssociationAggregate { return makeAggregate(SQLExpressionCountDistinct(Column.rowID)) - .aliased("\(key.singularizedName)Count") + .forKey("\(key.singularizedName)Count") } /// Creates an aggregate that is true if there exists no associated records. @@ -373,7 +373,7 @@ extension AssociationToMany where OriginRowDecoder: TableRecord { /// let teams: [Team] = try Team.having(Team.players.isEmpty() == false) public var isEmpty: AssociationAggregate { return makeAggregate(SQLExpressionIsEmpty(SQLExpressionCountDistinct(Column.rowID))) - .aliased("hasNo\(key.singularizedName.uppercasingFirstCharacter)") + .forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)") } /// Creates an aggregate which evaluate to the average value of the given @@ -397,7 +397,7 @@ extension AssociationToMany where OriginRowDecoder: TableRecord { let aggregate = makeAggregate(SQLExpressionFunction(.avg, arguments: expression)) if let column = expression as? ColumnExpression { let name = key.singularizedName - return aggregate.aliased("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") + return aggregate.forKey("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") } else { return aggregate } @@ -424,7 +424,7 @@ extension AssociationToMany where OriginRowDecoder: TableRecord { let aggregate = makeAggregate(SQLExpressionFunction(.max, arguments: expression)) if let column = expression as? ColumnExpression { let name = key.singularizedName - return aggregate.aliased("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") + return aggregate.forKey("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") } else { return aggregate } @@ -451,7 +451,7 @@ extension AssociationToMany where OriginRowDecoder: TableRecord { let aggregate = makeAggregate(SQLExpressionFunction(.min, arguments: expression)) if let column = expression as? ColumnExpression { let name = key.singularizedName - return aggregate.aliased("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") + return aggregate.forKey("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") } else { return aggregate } @@ -478,7 +478,7 @@ extension AssociationToMany where OriginRowDecoder: TableRecord { let aggregate = makeAggregate(SQLExpressionFunction(.sum, arguments: expression)) if let column = expression as? ColumnExpression { let name = key.singularizedName - return aggregate.aliased("\(name)\(column.name.uppercasingFirstCharacter)Sum") + return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum") } else { return aggregate } diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index 58b938f97..1befcbd00 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -62,8 +62,8 @@ public struct AssociationAggregate { /// - It helps implementing aggregate operators such as `&&`, `+`, etc. let prepare: AssociationAggregatePreparation - /// The SQL alias for the value of this aggregate. See aliased(_:). - var alias: String? + /// The SQL name for the value of this aggregate. See forKey(_:). + var key: String? init(_ prepare: @escaping AssociationAggregatePreparation) { self.prepare = prepare @@ -75,14 +75,28 @@ extension AssociationAggregate { /// /// For example: /// - /// let aggregate = Author.books.count.aliased("foo") + /// let aggregate = Author.books.count.aliased("numberOfBooks") /// let request = Author.annotated(with: aggregate) /// if let row = try Row.fetchOne(db, request) { - /// let bookCount: Int = row["foo"] + /// let bookCount: Int = row["numberOfBooks"] /// } + @available(*, deprecated, renamed: "forKey(_:)") public func aliased(_ name: String) -> AssociationAggregate { + return forKey(name) + } + + /// Returns an aggregate that is selected in a column with the given name. + /// + /// For example: + /// + /// let aggregate = Author.books.count.forKey("numberOfBooks") + /// let request = Author.annotated(with: aggregate) + /// if let row = try Row.fetchOne(db, request) { + /// let bookCount: Int = row["numberOfBooks"] + /// } + public func forKey(_ key: String) -> AssociationAggregate { var aggregate = self - aggregate.alias = name + aggregate.key = key return aggregate } @@ -101,8 +115,28 @@ extension AssociationAggregate { /// return try AuthorInfo.fetchAll(db, request) /// } /// } + @available(*, deprecated, renamed: "forKey(_:)") public func aliased(_ key: CodingKey) -> AssociationAggregate { - return aliased(key.stringValue) + return forKey(key) + } + + /// Returns an aggregate that is selected in a column named like the given + /// coding key. + /// + /// For example: + /// + /// struct AuthorInfo: Decodable, FetchableRecord { + /// var author: Author + /// var bookCount: Int + /// + /// static func fetchAll(_ db: Database) throws -> [AuthorInfo] { + /// let aggregate = Author.books.count.forKey(CodingKeys.bookCount) + /// let request = Author.annotated(with: aggregate) + /// return try AuthorInfo.fetchAll(db, request) + /// } + /// } + public func forKey(_ key: CodingKey) -> AssociationAggregate { + return forKey(key.stringValue) } } @@ -876,8 +910,8 @@ public func ?? ( return (request: request, expression: expression ?? rhs) } - // Preserve alias - aggregate.alias = lhs.alias + // Preserve key + aggregate.key = lhs.key return aggregate } diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift index 0d43f4f9e..403376c33 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift @@ -4,8 +4,8 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { private func annotated(with aggregate: AssociationAggregate) -> QueryInterfaceRequest { let (request, expression) = aggregate.prepare(self) - if let alias = aggregate.alias { - return request.annotated(with: [expression.aliased(alias)]) + if let key = aggregate.key { + return request.annotated(with: [expression.forKey(key)]) } else { return request.annotated(with: [expression]) } diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index a6e74d751..d3810b49b 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -101,7 +101,7 @@ extension QueryInterfaceRequest: FetchRequest { let prefetchedRelation = association .mapPivotRelation { $0.qualified(with: pivotAlias) } .destinationRelation(fromOriginRows: { _ in [] /* no origin row */ }) - .annotated(with: pivotColumns.map { pivotAlias[Column($0)].aliased("grdb_\($0)") }) + .annotated(with: pivotColumns.map { pivotAlias[Column($0)].forKey("grdb_\($0)") }) let prefetchedQuery = SQLQuery(relation: prefetchedRelation) // Union region @@ -529,7 +529,7 @@ private func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [ let prefetchedRelation = association .mapPivotRelation { $0.qualified(with: pivotAlias) } .destinationRelation(fromOriginRows: { _ in rows }) - .annotated(with: pivotColumns.map { pivotAlias[Column($0)].aliased("grdb_\($0)") }) + .annotated(with: pivotColumns.map { pivotAlias[Column($0)].forKey("grdb_\($0)") }) prefetchedRows = try QueryInterfaceRequest(relation: prefetchedRelation) .fetchAll(db) .grouped(byDatabaseValuesOnColumns: pivotColumns.map { "grdb_\($0)" }) diff --git a/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift index 3c9c39d56..25e8bfceb 100644 --- a/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift @@ -24,18 +24,78 @@ extension SQLSpecificExpressible { /// :nodoc: extension SQLSpecificExpressible { - /// Returns a value that can be used as an argument to QueryInterfaceRequest.select() + /// Give the expression the given SQL name. /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// For example: + /// + /// // SELECT (width * height) AS area FROM shape + /// let area = (Column("width") * Column("height")).aliased("area") + /// let request = Shape.select(area) + /// if let row = try Row.fetchOne(db, request) { + /// let area: Int = row["area"] + /// } + @available(*, deprecated, renamed: "forKey(_:)") public func aliased(_ name: String) -> SQLSelectable { - return SQLAliasedExpression(sqlExpression, name: name) + return forKey(name) } - /// Returns a value that can be used as an argument to QueryInterfaceRequest.select() + /// Give the expression the given SQL name. /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface + /// For example: + /// + /// // SELECT (width * height) AS area FROM shape + /// let area = (Column("width") * Column("height")).forKey("area") + /// let request = Shape.select(area) + /// if let row = try Row.fetchOne(db, request) { + /// let area: Int = row["area"] + /// } + public func forKey(_ key: String) -> SQLSelectable { + return SQLAliasedExpression(sqlExpression, name: key) + } + + /// Give the expression the same SQL name as the coding key. + /// + /// For example: + /// + /// struct Shape: Decodable, FetchableRecord, TableRecord { + /// let width: Int + /// let height: Int + /// let area: Int + /// + /// static let databaseSelection: [SQLSelectable] = [ + /// Column(CodingKeys.width), + /// Column(CodingKeys.height), + /// (Column(CodingKeys.width) * Column(CodingKeys.height)).aliased(CodingKeys.area), + /// ] + /// } + /// + /// // SELECT width, height, (width * height) AS area FROM shape + /// let shapes: [Shape] = try Shape.fetchAll(db) + @available(*, deprecated, renamed: "forKey(_:)") public func aliased(_ key: CodingKey) -> SQLSelectable { - return aliased(key.stringValue) + return forKey(key) + } + + /// Give the expression the same SQL name as the coding key. + /// + /// For example: + /// + /// struct Shape: Decodable, FetchableRecord, TableRecord { + /// let width: Int + /// let height: Int + /// let area: Int + /// + /// static let databaseSelection: [SQLSelectable] = [ + /// Column(CodingKeys.width), + /// Column(CodingKeys.height), + /// (Column(CodingKeys.width) * Column(CodingKeys.height)).forKey(CodingKeys.area), + /// ] + /// } + /// + /// // SELECT width, height, (width * height) AS area FROM shape + /// let shapes: [Shape] = try Shape.fetchAll(db) + public func forKey(_ key: CodingKey) -> SQLSelectable { + return forKey(key.stringValue) } } From ede4572da362b7613b82a9db63faf1572435f860 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jul 2019 16:34:17 +0200 Subject: [PATCH 32/91] Update tests for the new forKey(_:) methods --- .../GRDBTests/AssociationAggregateTests.swift | 20 +++++++++---------- ...sociationBelongsToSQLDerivationTests.swift | 2 +- .../AssociationHasOneSQLDerivationTests.swift | 2 +- ...ationHasOneThroughSQLDerivationTests.swift | 2 +- .../QueryInterfaceRequestTests.swift | 6 +++--- ...bleRecord+QueryInterfaceRequestTests.swift | 2 +- 6 files changed, 17 insertions(+), 17 deletions(-) diff --git a/Tests/GRDBTests/AssociationAggregateTests.swift b/Tests/GRDBTests/AssociationAggregateTests.swift index 7ddc99b49..28123e05d 100644 --- a/Tests/GRDBTests/AssociationAggregateTests.swift +++ b/Tests/GRDBTests/AssociationAggregateTests.swift @@ -653,15 +653,15 @@ class AssociationAggregateTests: GRDBTestCase { } } - func testAnnotatedWithHasManyAggregateAlias() throws { + func testAnnotatedWithHasManyAggregateWithCustomKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.players.average(Column("score")).aliased("a1")) - .annotated(with: Team.players.count.aliased("a2")) - .annotated(with: Team.players.max(Column("score")).aliased("a3")) - .annotated(with: Team.players.min(Column("score")).aliased("a4")) - .annotated(with: Team.players.sum(Column("score")).aliased("a5")) + .annotated(with: Team.players.average(Column("score")).forKey("a1")) + .annotated(with: Team.players.count.forKey("a2")) + .annotated(with: Team.players.max(Column("score")).forKey("a3")) + .annotated(with: Team.players.min(Column("score")).forKey("a4")) + .annotated(with: Team.players.sum(Column("score")).forKey("a5")) try assertEqualSQL(db, request, """ SELECT "team".*, \ @@ -681,10 +681,10 @@ class AssociationAggregateTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.players.average(Column("score") * Column("score")).aliased("a1")) - .annotated(with: Team.players.max(Column("score") * 10).aliased("a3")) - .annotated(with: Team.players.min(-Column("score")).aliased("a4")) - .annotated(with: Team.players.sum(Column("score") * Column("score")).aliased("a5")) + .annotated(with: Team.players.average(Column("score") * Column("score")).forKey("a1")) + .annotated(with: Team.players.max(Column("score") * 10).forKey("a3")) + .annotated(with: Team.players.min(-Column("score")).forKey("a4")) + .annotated(with: Team.players.sum(Column("score") * Column("score")).forKey("a5")) try assertEqualSQL(db, request, """ SELECT "team".*, \ AVG("player"."score" * "player"."score") AS "a1", \ diff --git a/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift index 747e8f80b..3b938b8cf 100644 --- a/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift @@ -95,7 +95,7 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase { .including(required: A.b .select( Column("name"), - (Column("id") + aAlias[Column("id")]).aliased("foo"))) + (Column("id") + aAlias[Column("id")]).forKey("foo"))) try assertEqualSQL(db, request, """ SELECT "a".*, "b"."name", "b"."id" + "a"."id" AS "foo" \ FROM "a" \ diff --git a/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift index aae37ab09..d9e4d3d15 100644 --- a/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift +++ b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift @@ -95,7 +95,7 @@ class AssociationHasOneSQLDerivationTests: GRDBTestCase { .including(required: A.b .select( Column("name"), - (Column("id") + aAlias[Column("id")]).aliased("foo"))) + (Column("id") + aAlias[Column("id")]).forKey("foo"))) try assertEqualSQL(db, request, """ SELECT "a".*, "b"."name", "b"."id" + "a"."id" AS "foo" \ FROM "a" \ diff --git a/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift b/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift index 01303f108..f4039353e 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift @@ -107,7 +107,7 @@ class AssociationHasOneThroughSQLDerivationTests: GRDBTestCase { .including(required: A.c .select( Column("name"), - (Column("id") + aAlias[Column("id")]).aliased("foo"))) + (Column("id") + aAlias[Column("id")]).forKey("foo"))) try assertEqualSQL(db, request, """ SELECT "a".*, "c"."name", "c"."id" + "a"."id" AS "foo" \ FROM "a" \ diff --git a/Tests/GRDBTests/QueryInterfaceRequestTests.swift b/Tests/GRDBTests/QueryInterfaceRequestTests.swift index f97bee356..203c01efc 100644 --- a/Tests/GRDBTests/QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/QueryInterfaceRequestTests.swift @@ -122,7 +122,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { XCTAssertEqual(try tableRequest.select(Col.age * 2).distinct().fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(DISTINCT \"age\" * 2) FROM \"readers\"") - XCTAssertEqual(try tableRequest.select((Col.age * 2).aliased("ignored")).distinct().fetchCount(db), 0) + XCTAssertEqual(try tableRequest.select((Col.age * 2).forKey("ignored")).distinct().fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(DISTINCT \"age\" * 2) FROM \"readers\"") XCTAssertEqual(try tableRequest.select(Col.name, Col.age).fetchCount(db), 0) @@ -229,12 +229,12 @@ class QueryInterfaceRequestTests: GRDBTestCase { } } - func testSelectAliased() throws { + func testSelectionCustomKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Arthur", 42]) - let request = tableRequest.select(Col.name.aliased("nom"), (Col.age + 1).aliased("agePlusOne")) + let request = tableRequest.select(Col.name.forKey("nom"), (Col.age + 1).forKey("agePlusOne")) let row = try Row.fetchOne(db, request)! XCTAssertEqual(lastSQLQuery, "SELECT \"name\" AS \"nom\", \"age\" + 1 AS \"agePlusOne\" FROM \"readers\" LIMIT 1") XCTAssertEqual(row["nom"] as String, "Arthur") diff --git a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift index a8ca2be03..b7791daf7 100644 --- a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift @@ -65,7 +65,7 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase { XCTAssertEqual(try Reader.select(Col.age * 2).distinct().fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(DISTINCT \"age\" * 2) FROM \"readers\"") - XCTAssertEqual(try Reader.select((Col.age * 2).aliased("ignored")).distinct().fetchCount(db), 0) + XCTAssertEqual(try Reader.select((Col.age * 2).forKey("ignored")).distinct().fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(DISTINCT \"age\" * 2) FROM \"readers\"") XCTAssertEqual(try Reader.select(Col.name, Col.age).fetchCount(db), 0) From d15bb190ebab8b188296ae8166b4dd053ccfceb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jul 2019 16:36:53 +0200 Subject: [PATCH 33/91] Enable Code Coverage in GRDBCustomSQLiteOSX target --- .../xcshareddata/xcschemes/GRDBCustomSQLiteOSX.xcscheme | 1 + 1 file changed, 1 insertion(+) diff --git a/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustomSQLiteOSX.xcscheme b/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustomSQLiteOSX.xcscheme index f3821823a..fb8c9c1a0 100644 --- a/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustomSQLiteOSX.xcscheme +++ b/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustomSQLiteOSX.xcscheme @@ -40,6 +40,7 @@ buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + codeCoverageEnabled = "YES" shouldUseLaunchSchemeArgsEnv = "YES"> Date: Sat, 27 Jul 2019 16:45:06 +0200 Subject: [PATCH 34/91] Fix documentation --- .../Request/Association/AssociationAggregate.swift | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index 1befcbd00..37990fa3b 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -78,7 +78,7 @@ extension AssociationAggregate { /// let aggregate = Author.books.count.aliased("numberOfBooks") /// let request = Author.annotated(with: aggregate) /// if let row = try Row.fetchOne(db, request) { - /// let bookCount: Int = row["numberOfBooks"] + /// let numberOfBooks: Int = row["numberOfBooks"] /// } @available(*, deprecated, renamed: "forKey(_:)") public func aliased(_ name: String) -> AssociationAggregate { @@ -92,7 +92,7 @@ extension AssociationAggregate { /// let aggregate = Author.books.count.forKey("numberOfBooks") /// let request = Author.annotated(with: aggregate) /// if let row = try Row.fetchOne(db, request) { - /// let bookCount: Int = row["numberOfBooks"] + /// let numberOfBooks: Int = row["numberOfBooks"] /// } public func forKey(_ key: String) -> AssociationAggregate { var aggregate = self @@ -107,10 +107,10 @@ extension AssociationAggregate { /// /// struct AuthorInfo: Decodable, FetchableRecord { /// var author: Author - /// var bookCount: Int + /// var numberOfBooks: Int /// /// static func fetchAll(_ db: Database) throws -> [AuthorInfo] { - /// let aggregate = Author.books.count.aliased(CodingKeys.bookCount) + /// let aggregate = Author.books.count.aliased(CodingKeys.numberOfBooks) /// let request = Author.annotated(with: aggregate) /// return try AuthorInfo.fetchAll(db, request) /// } @@ -127,10 +127,10 @@ extension AssociationAggregate { /// /// struct AuthorInfo: Decodable, FetchableRecord { /// var author: Author - /// var bookCount: Int + /// var numberOfBooks: Int /// /// static func fetchAll(_ db: Database) throws -> [AuthorInfo] { - /// let aggregate = Author.books.count.forKey(CodingKeys.bookCount) + /// let aggregate = Author.books.count.forKey(CodingKeys.numberOfBooks) /// let request = Author.annotated(with: aggregate) /// return try AuthorInfo.fetchAll(db, request) /// } From b4ef6a3dad27c4bfe46da9290b8189796288f914 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jul 2019 17:08:11 +0200 Subject: [PATCH 35/91] CHANGELOG --- CHANGELOG.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f7ac7e0ae..16a6b79b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -58,6 +58,31 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: - [#562](https://github.com/groue/GRDB.swift/pull/562): Fix crash when using more than one DatabaseCollation - [#563](https://github.com/groue/GRDB.swift/pull/563): More tests for eager loading of hasMany associations - [#574](https://github.com/groue/GRDB.swift/pull/574): SwiftLint +- [#577](https://github.com/groue/GRDB.swift/pull/577): Rename aliased(_:) methods to forKey(_:) + +### API Diff + +```diff + extension AssociationAggregate { ++ @available(*, deprecated, renamed: "forKey(_:)") + func aliased(_ name: String) -> AssociationAggregate ++ func forKey(_ name: String) -> AssociationAggregate + ++ @available(*, deprecated, renamed: "forKey(_:)") + func aliased(_ key: CodingKey) -> AssociationAggregate ++ func forKey(_ key: CodingKey) -> AssociationAggregate + } + + extension SQLSpecificExpressible { ++ @available(*, deprecated, renamed: "forKey(_:)") + func aliased(_ name: String) -> SQLSelectable ++ func forKey(_ name: String) -> SQLSelectable + ++ @available(*, deprecated, renamed: "forKey(_:)") + func aliased(_ key: CodingKey) -> SQLSelectable ++ func forKey(_ key: CodingKey) -> SQLSelectable + } +``` ## 4.1.1 From 05fdf5cfdd3b73cf9fb9dce63e25e5c6171219c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jul 2019 17:08:53 +0200 Subject: [PATCH 36/91] CHANGELOG --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 16a6b79b9..6877826db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -58,7 +58,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: - [#562](https://github.com/groue/GRDB.swift/pull/562): Fix crash when using more than one DatabaseCollation - [#563](https://github.com/groue/GRDB.swift/pull/563): More tests for eager loading of hasMany associations - [#574](https://github.com/groue/GRDB.swift/pull/574): SwiftLint -- [#577](https://github.com/groue/GRDB.swift/pull/577): Rename aliased(_:) methods to forKey(_:) +- [#577](https://github.com/groue/GRDB.swift/pull/577): Rename `aliased(_:)` methods to `forKey(_:)` ### API Diff From faa7bf7e53b869a347d9470ba884eacc2b72486f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jul 2019 17:10:01 +0200 Subject: [PATCH 37/91] Less TODO --- TODO.md | 1 - 1 file changed, 1 deletion(-) diff --git a/TODO.md b/TODO.md index 6d558ebee..0789f82ab 100644 --- a/TODO.md +++ b/TODO.md @@ -70,7 +70,6 @@ Make it possible to build a single observation where some requests depend on the result of other requests. As long as we can't express this in a single observation, we fail the "guaranteed consistency is possible" contract. - [ ] matching (FTS3, 5) on associations and DerivableRequest - [ ] rename fetchOne to fetchFirst -- [ ] Rename aliased() to forKey() when relevant - [ ] new.updateChanges(from: old) vs. old.updateChanges(with: { old.a = new.a }). This is confusing. Swift 4.2 From dba8d636bb7b6e9987cbdb1fa1ddc47b61fb75b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jul 2019 17:10:31 +0200 Subject: [PATCH 38/91] Less TODO --- TODO.md | 1 - 1 file changed, 1 deletion(-) diff --git a/TODO.md b/TODO.md index 6d558ebee..46d20a6d2 100644 --- a/TODO.md +++ b/TODO.md @@ -68,7 +68,6 @@ - [ ] ValueObservation.flatMap: Make it possible to build a single observation where some requests depend on the result of other requests. As long as we can't express this in a single observation, we fail the "guaranteed consistency is possible" contract. -- [ ] matching (FTS3, 5) on associations and DerivableRequest - [ ] rename fetchOne to fetchFirst - [ ] Rename aliased() to forKey() when relevant - [ ] new.updateChanges(from: old) vs. old.updateChanges(with: { old.a = new.a }). This is confusing. From 23678ab9daf67e0fcfb7477d68de0c3004bca586 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jul 2019 23:06:36 +0200 Subject: [PATCH 39/91] Update documentatiion for #577 --- Documentation/AssociationsBasics.md | 18 +++++++++--------- README.md | 2 +- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 93976fbea..f20f176b6 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -1791,14 +1791,14 @@ The default name is built from the aggregating method, the **[association key](# Those default names are lost whenever an aggregate is modified (negated, added, multiplied, whatever). -You can name or rename aggregates with the `aliased` method: +You can name or rename aggregates with the `forKey` method: ```swift struct AuthorInfo: Decodable, FetchableRecord { var author: Author var numberOfBooks: Int } -let numberOfBooks = Author.books.count.aliased("numberOfBooks") // <-- +let numberOfBooks = Author.books.count.forKey("numberOfBooks") // <-- let request = Author.annotated(with: numberOfBooks) let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request) @@ -1806,7 +1806,7 @@ struct AuthorInfo: Decodable, FetchableRecord { var author: Author var hasBooks: Bool } -let hasBooks = (Author.books.isEmpty == false).aliased("hasBooks") // <-- +let hasBooks = (Author.books.isEmpty == false).forKey("hasBooks") // <-- let request = Author.annotated(with: hasBooks) let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request) @@ -1814,7 +1814,7 @@ struct AuthorInfo: Decodable, FetchableRecord { var author: Author var workCount: Int } -let workCount = (Author.books.count + Author.paintings.count).aliased("workCount") // <-- +let workCount = (Author.books.count + Author.paintings.count).forKey("workCount") // <-- let request = Author.annotated(with: workCount) let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request) ``` @@ -1827,7 +1827,7 @@ struct AuthorInfo: Decodable, FetchableRecord { var numberOfBooks: Int static func all() -> QueryInterfaceRequest { - let numberOfBooks = Author.books.count.aliased(CodingKey.numberOfBooks) // <-- + let numberOfBooks = Author.books.count.forKey(CodingKey.numberOfBooks) // <-- return Author .annotated(with: numberOfBooks) .asRequest(of: AuthorInfo.self) @@ -2041,7 +2041,7 @@ Aggregates can be modified and combined with Swift operators: ```swift let workCount = Author.books.count + Author.paintings.count) - let request = Author.annotated(with: workCount.aliased("workCount")) + let request = Author.annotated(with: workCount.forKey("workCount")) ``` - IFNULL operator `??` @@ -2133,7 +2133,7 @@ In this other example, the `Author.books` and `Author.paintings` have the distin let aggregate = Author.books.count + // association key "books" Author.paintings.count // association key "paintings" - let request = Author.annotated(with: aggregate.aliased("workCount")) + let request = Author.annotated(with: aggregate.forKey("workCount")) let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request) ``` @@ -2201,11 +2201,11 @@ But in the following example, we use the same association `Author.books` twice, let novelCount = Author.books // association key "books" .filter(Column("kind") == "novel") .count - .aliased("novelCount") + .forKey("novelCount") let theatrePlayCount = Author.books // association key "books" .filter(Column("kind") == "theatrePlay") .count - .aliased("theatrePlayCount") + .forKey("theatrePlayCount") let request = Author.annotated(with: novelCount, theatrePlayCount) let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request) ``` diff --git a/README.md b/README.md index 872d13324..98ceec3fc 100644 --- a/README.md +++ b/README.md @@ -4275,7 +4275,7 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: ```swift // SELECT ((temperature * 1.8) + 32) AS farenheit FROM planet - Planet.select((temperatureColumn * 1.8 + 32).aliased("farenheit")) + Planet.select((temperatureColumn * 1.8 + 32).forKey("farenheit")) ``` > :point_up: **Note**: an expression like `nameColumn + "rrr"` will be interpreted by SQLite as a numerical addition (with funny results), not as a string concatenation. From e8ad3871f7a388562903218611fa03b2ce0d1785 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 28 Jul 2019 08:59:23 +0200 Subject: [PATCH 40/91] Fix for Xcode 10.0, 10.1 --- CHANGELOG.md | 6 +++--- GRDB/QueryInterface/Request/QueryInterfaceRequest.swift | 5 ++--- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 36c529ebb..3938897cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -97,9 +97,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: +struct HasOneThroughAssociation: AssociationToOne { } -struct QueryInterfaceRequest: DerivableRequest { } -+struct QueryInterfaceRequest: FilteredRequest, JoinableRequest, OrderedRequest, SelectionRequest { } -+extension QueryInterfaceRequest: TableRequest where RowDecoder: TableRecord { } -+extension QueryInterfaceRequest: DerivableRequest where RowDecoder: TableRecord { } ++struct QueryInterfaceRequest: FilteredRequest, OrderedRequest, SelectionRequest, TableRequuest { } ++extension QueryInterfaceRequest: JoinableRequest where T: TableRecord { } ++extension QueryInterfaceRequest: DerivableRequest where T: TableRecord { } extension AssociationAggregate { + @available(*, deprecated, renamed: "forKey(_:)") diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 0593ce5e5..2694ba92c 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -337,7 +337,7 @@ extension QueryInterfaceRequest: _JoinableRequest { } } -extension QueryInterfaceRequest: JoinableRequest where RowDecoder: TableRecord { } +extension QueryInterfaceRequest: JoinableRequest where T: TableRecord { } extension QueryInterfaceRequest { @@ -474,8 +474,7 @@ extension QueryInterfaceRequest: TableRequest { } } -// TODO: remove this explicit conformance when Swift is able to infer it. -extension QueryInterfaceRequest: DerivableRequest where RowDecoder: TableRecord { } +extension QueryInterfaceRequest: DerivableRequest where T: TableRecord { } extension QueryInterfaceRequest where T: MutablePersistableRecord { From bb0c11f7d5aa583f5b85f4d7fb5b2f414817d37c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 29 Jul 2019 09:11:47 +0200 Subject: [PATCH 41/91] TODO --- GRDB/Migration/Migration.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/GRDB/Migration/Migration.swift b/GRDB/Migration/Migration.swift index ac17249da..098667d76 100644 --- a/GRDB/Migration/Migration.swift +++ b/GRDB/Migration/Migration.swift @@ -76,6 +76,7 @@ struct Migration { return .commit } + // TODO: we should restore foreign_keys in case of error as well // > 12. If foreign keys constraints were originally enabled, reenable them now. try db.execute(sql: "PRAGMA foreign_keys = ON") } From 4ffb59719a6db5c583d33685d6452c514a987b9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 30 Jul 2019 06:57:03 +0200 Subject: [PATCH 42/91] Fix #580 --- GRDB.swift.podspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 1cb1a41da..e3f17ba63 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -9,7 +9,7 @@ Pod::Spec.new do |s| s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" } s.module_name = 'GRDB' - s.swift_versions = ['4.2', '5'] + s.swift_versions = ['4.2', '5.0'] s.ios.deployment_target = '9.0' s.osx.deployment_target = '10.9' s.watchos.deployment_target = '2.0' From 56af3ceff66186d60fd9dcd27ffe0682907813ca Mon Sep 17 00:00:00 2001 From: Chris Ballinger Date: Wed, 17 Jul 2019 13:40:09 -0700 Subject: [PATCH 43/91] Remove modulemap from podspec --- GRDB.swift.podspec | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index e3f17ba63..6499f1333 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -13,17 +13,16 @@ Pod::Spec.new do |s| s.ios.deployment_target = '9.0' s.osx.deployment_target = '10.9' s.watchos.deployment_target = '2.0' - s.module_map = 'Support/module.modulemap' s.default_subspec = 'standard' s.subspec 'standard' do |ss| - ss.source_files = 'GRDB/**/*.swift', 'Support/*.h' + ss.source_files = 'GRDB/**/*.swift', 'Support/grdb_config.h' ss.framework = 'Foundation' ss.library = 'sqlite3' end s.subspec 'SQLCipher' do |ss| - ss.source_files = 'GRDB/**/*.swift', 'Support/*.h' + ss.source_files = 'GRDB/**/*.swift', 'Support/grdb_config.h' ss.framework = 'Foundation' ss.dependency 'SQLCipher', '>= 3.4.0' ss.xcconfig = { From 507ae0dfdcd27a947919a8c0c63d353e2fc824a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 28 Jul 2019 09:35:50 +0200 Subject: [PATCH 44/91] Tests for framework & static CocoaPods integration --- .travis.yml | 46 +- Makefile | 22 +- .../{GRDBiOS => GRDBiOS-framework}/Podfile | 2 +- .../iOS.xcodeproj/project.pbxproj | 46 +- .../contents.xcworkspacedata | 0 .../iOS.xcworkspace/contents.xcworkspacedata | 0 Tests/CocoaPods/GRDBiOS-static/Podfile | 4 + .../iOS.xcodeproj/project.pbxproj | 401 ++++++++++++++++++ .../contents.xcworkspacedata | 7 + .../iOS.xcworkspace/contents.xcworkspacedata | 10 + 10 files changed, 497 insertions(+), 41 deletions(-) rename Tests/CocoaPods/{GRDBiOS => GRDBiOS-framework}/Podfile (74%) rename Tests/CocoaPods/{GRDBiOS => GRDBiOS-framework}/iOS.xcodeproj/project.pbxproj (97%) rename Tests/CocoaPods/{GRDBiOS => GRDBiOS-framework}/iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata (100%) rename Tests/CocoaPods/{GRDBiOS => GRDBiOS-framework}/iOS.xcworkspace/contents.xcworkspacedata (100%) create mode 100644 Tests/CocoaPods/GRDBiOS-static/Podfile create mode 100644 Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.pbxproj create mode 100644 Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata create mode 100644 Tests/CocoaPods/GRDBiOS-static/iOS.xcworkspace/contents.xcworkspacedata diff --git a/.travis.yml b/.travis.yml index c87f1fece..fb7fdf576 100644 --- a/.travis.yml +++ b/.travis.yml @@ -146,8 +146,16 @@ jobs: gemfile: .ci/gemfiles/Gemfile.travis osx_image: xcode10.2 env: - - TID=CocoaPods GRDB - script: make test_install_GRDB_CocoaPods + - TID=CocoaPods GRDB (framework) + script: make test_install_GRDB_CocoaPods_framework + + # CocoaPods Install GRDB + - stage: Test Installation Xcode 10.2 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode10.2 + env: + - TID=CocoaPods GRDB (static) + script: make test_install_GRDB_CocoaPods_static # SPM Install - stage: Test Installation Xcode 10.2 @@ -297,10 +305,10 @@ jobs: # env: # - TID=SQLCipher 4 # script: make test_framework_SQLCipher4 - # - # ########################################### - # ## Test Installation Xcode 10 - # + + ########################################### + ## Test Installation Xcode 10 + # # Manual Install # - stage: Test Installation Xcode 10 # gemfile: .ci/gemfiles/Gemfile.travis @@ -316,15 +324,23 @@ jobs: # env: # - TID=CocoaPods Lint # script: make test_CocoaPodsLint_GRDB - # - # # CocoaPods Install GRDB - # - stage: Test Installation Xcode 10 - # gemfile: .ci/gemfiles/Gemfile.travis - # osx_image: xcode10 - # env: - # - TID=CocoaPods GRDB - # script: make test_install_GRDB_CocoaPods - # + + # CocoaPods Install GRDB + - stage: Test Installation Xcode 10 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode10 + env: + - TID=CocoaPods GRDB (framework) + script: make test_install_GRDB_CocoaPods_framework + + # CocoaPods Install GRDB + - stage: Test Installation Xcode 10 + gemfile: .ci/gemfiles/Gemfile.travis + osx_image: xcode10 + env: + - TID=CocoaPods GRDB (static) + script: make test_install_GRDB_CocoaPods_static + # # SPM Install # - stage: Test Installation Xcode 10 # gemfile: .ci/gemfiles/Gemfile.travis diff --git a/Makefile b/Makefile index f8949a3ff..b030b97e5 100644 --- a/Makefile +++ b/Makefile @@ -272,9 +272,27 @@ test_install_SPM: ./.build/debug/SPM && \ $(SWIFT) package unedit --force GRDB -test_install_GRDB_CocoaPods: +test_install_GRDB_CocoaPods: test_install_GRDB_CocoaPods_framework test_install_GRDB_CocoaPods_static + +test_install_GRDB_CocoaPods_framework: ifdef POD - cd Tests/CocoaPods/GRDBiOS && \ + cd Tests/CocoaPods/GRDBiOS-framework && \ + $(POD) install && \ + $(XCODEBUILD) \ + -workspace iOS.xcworkspace \ + -scheme iOS \ + -configuration Release \ + -destination $(MAX_IOS_DESTINATION) \ + clean build \ + $(XCPRETTY) +else + @echo CocoaPods must be installed for test_install_GRDB_CocoaPods + @exit 1 +endif + +test_install_GRDB_CocoaPods_static: +ifdef POD + cd Tests/CocoaPods/GRDBiOS-static && \ $(POD) install && \ $(XCODEBUILD) \ -workspace iOS.xcworkspace \ diff --git a/Tests/CocoaPods/GRDBiOS/Podfile b/Tests/CocoaPods/GRDBiOS-framework/Podfile similarity index 74% rename from Tests/CocoaPods/GRDBiOS/Podfile rename to Tests/CocoaPods/GRDBiOS-framework/Podfile index 7648899ac..55aeffee7 100644 --- a/Tests/CocoaPods/GRDBiOS/Podfile +++ b/Tests/CocoaPods/GRDBiOS-framework/Podfile @@ -1,5 +1,5 @@ use_frameworks! - target 'iOS' platform :ios, '9.0' +supports_swift_versions '4.2' pod 'GRDB.swift', :path => '../../..' diff --git a/Tests/CocoaPods/GRDBiOS/iOS.xcodeproj/project.pbxproj b/Tests/CocoaPods/GRDBiOS-framework/iOS.xcodeproj/project.pbxproj similarity index 97% rename from Tests/CocoaPods/GRDBiOS/iOS.xcodeproj/project.pbxproj rename to Tests/CocoaPods/GRDBiOS-framework/iOS.xcodeproj/project.pbxproj index 05a63958b..458f4e78e 100644 --- a/Tests/CocoaPods/GRDBiOS/iOS.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/GRDBiOS-framework/iOS.xcodeproj/project.pbxproj @@ -15,7 +15,7 @@ 567374431B4D46600089DE44 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567374411B4D46600089DE44 /* Main.storyboard */; }; 567374451B4D46600089DE44 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567374441B4D46600089DE44 /* Assets.xcassets */; }; 567374481B4D46600089DE44 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567374461B4D46600089DE44 /* LaunchScreen.storyboard */; }; - A1CCD2E34F7DE41D2EC4186E /* Pods_iOS.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C57F470F1DCB1126DFB5EB63 /* Pods_iOS.framework */; }; + 905ECD161513DA7089DC0E4F /* Pods_iOS.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 44319992BE6EA64810E8982A /* Pods_iOS.framework */; }; /* End PBXBuildFile section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -32,6 +32,7 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + 44319992BE6EA64810E8982A /* Pods_iOS.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_iOS.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 5626974C2110308E0066800A /* PlayersViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayersViewController.swift; sourceTree = ""; }; 5626974D2110308E0066800A /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = ""; }; 5626974E2110308E0066800A /* PlayerEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionViewController.swift; sourceTree = ""; }; @@ -44,7 +45,6 @@ 567374491B4D46600089DE44 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 62C5B84AA50DF194B4DDDFD0 /* Pods-iOS.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-iOS.debug.xcconfig"; path = "Pods/Target Support Files/Pods-iOS/Pods-iOS.debug.xcconfig"; sourceTree = ""; }; 9573251A237B01D90415D0D7 /* Pods-iOS.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-iOS.release.xcconfig"; path = "Pods/Target Support Files/Pods-iOS/Pods-iOS.release.xcconfig"; sourceTree = ""; }; - C57F470F1DCB1126DFB5EB63 /* Pods_iOS.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_iOS.framework; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -52,7 +52,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - A1CCD2E34F7DE41D2EC4186E /* Pods_iOS.framework in Frameworks */, + 905ECD161513DA7089DC0E4F /* Pods_iOS.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -97,7 +97,7 @@ 8D9BFC4007F760CC8E01ACC6 /* Frameworks */ = { isa = PBXGroup; children = ( - C57F470F1DCB1126DFB5EB63 /* Pods_iOS.framework */, + 44319992BE6EA64810E8982A /* Pods_iOS.framework */, ); name = Frameworks; sourceTree = ""; @@ -123,7 +123,7 @@ 567374351B4D46600089DE44 /* Frameworks */, 567374361B4D46600089DE44 /* Resources */, 5644E4071C1072CA0090716E /* Embed Frameworks */, - CED3A5EE3229C5F98D69D6AF /* [CP] Embed Pods Frameworks */, + 42992B3BE6585CF939B0D8EF /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); @@ -183,6 +183,24 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ + 42992B3BE6585CF939B0D8EF /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-iOS/Pods-iOS-frameworks.sh", + "${BUILT_PRODUCTS_DIR}/GRDB.swift/GRDB.framework", + ); + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/GRDB.framework", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-iOS/Pods-iOS-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; C5E9DF0928754FE22F481D3A /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; @@ -201,24 +219,6 @@ shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; showEnvVarsInLog = 0; }; - CED3A5EE3229C5F98D69D6AF /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-iOS/Pods-iOS-frameworks.sh", - "${BUILT_PRODUCTS_DIR}/GRDB.swift/GRDB.framework", - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/GRDB.framework", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-iOS/Pods-iOS-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ diff --git a/Tests/CocoaPods/GRDBiOS/iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Tests/CocoaPods/GRDBiOS-framework/iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata similarity index 100% rename from Tests/CocoaPods/GRDBiOS/iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata rename to Tests/CocoaPods/GRDBiOS-framework/iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata diff --git a/Tests/CocoaPods/GRDBiOS/iOS.xcworkspace/contents.xcworkspacedata b/Tests/CocoaPods/GRDBiOS-framework/iOS.xcworkspace/contents.xcworkspacedata similarity index 100% rename from Tests/CocoaPods/GRDBiOS/iOS.xcworkspace/contents.xcworkspacedata rename to Tests/CocoaPods/GRDBiOS-framework/iOS.xcworkspace/contents.xcworkspacedata diff --git a/Tests/CocoaPods/GRDBiOS-static/Podfile b/Tests/CocoaPods/GRDBiOS-static/Podfile new file mode 100644 index 000000000..c20cb2f16 --- /dev/null +++ b/Tests/CocoaPods/GRDBiOS-static/Podfile @@ -0,0 +1,4 @@ +target 'iOS' +platform :ios, '9.0' +supports_swift_versions '4.2' +pod 'GRDB.swift', :path => '../../..' diff --git a/Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.pbxproj b/Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.pbxproj new file mode 100644 index 000000000..a4c9947c5 --- /dev/null +++ b/Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.pbxproj @@ -0,0 +1,401 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 562697512110308F0066800A /* PlayersViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5626974C2110308E0066800A /* PlayersViewController.swift */; }; + 562697522110308F0066800A /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5626974D2110308E0066800A /* Player.swift */; }; + 562697532110308F0066800A /* PlayerEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5626974E2110308E0066800A /* PlayerEditionViewController.swift */; }; + 562697542110308F0066800A /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5626974F2110308E0066800A /* AppDatabase.swift */; }; + 562697552110308F0066800A /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562697502110308E0066800A /* AppDelegate.swift */; }; + 567374431B4D46600089DE44 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567374411B4D46600089DE44 /* Main.storyboard */; }; + 567374451B4D46600089DE44 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567374441B4D46600089DE44 /* Assets.xcassets */; }; + 567374481B4D46600089DE44 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567374461B4D46600089DE44 /* LaunchScreen.storyboard */; }; + D246CFB4904D46E7D400E2CE /* libPods-iOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 9E46153E91609427B4025BC7 /* libPods-iOS.a */; }; +/* End PBXBuildFile section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 5644E4071C1072CA0090716E /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 5626974C2110308E0066800A /* PlayersViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayersViewController.swift; sourceTree = ""; }; + 5626974D2110308E0066800A /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = ""; }; + 5626974E2110308E0066800A /* PlayerEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionViewController.swift; sourceTree = ""; }; + 5626974F2110308E0066800A /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = ""; }; + 562697502110308E0066800A /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 567374381B4D46600089DE44 /* iOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = iOS.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 567374421B4D46600089DE44 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 567374441B4D46600089DE44 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 567374471B4D46600089DE44 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 567374491B4D46600089DE44 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 62C5B84AA50DF194B4DDDFD0 /* Pods-iOS.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-iOS.debug.xcconfig"; path = "Pods/Target Support Files/Pods-iOS/Pods-iOS.debug.xcconfig"; sourceTree = ""; }; + 9573251A237B01D90415D0D7 /* Pods-iOS.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-iOS.release.xcconfig"; path = "Pods/Target Support Files/Pods-iOS/Pods-iOS.release.xcconfig"; sourceTree = ""; }; + 9E46153E91609427B4025BC7 /* libPods-iOS.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-iOS.a"; sourceTree = BUILT_PRODUCTS_DIR; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 567374351B4D46600089DE44 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + D246CFB4904D46E7D400E2CE /* libPods-iOS.a in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 5673742F1B4D46600089DE44 = { + isa = PBXGroup; + children = ( + 5673743A1B4D46600089DE44 /* GRDBDemoiOS */, + 567374391B4D46600089DE44 /* Products */, + 9ABB37395508D35C98A292E7 /* Pods */, + 8D9BFC4007F760CC8E01ACC6 /* Frameworks */, + ); + sourceTree = ""; + }; + 567374391B4D46600089DE44 /* Products */ = { + isa = PBXGroup; + children = ( + 567374381B4D46600089DE44 /* iOS.app */, + ); + name = Products; + sourceTree = ""; + }; + 5673743A1B4D46600089DE44 /* GRDBDemoiOS */ = { + isa = PBXGroup; + children = ( + 5626974F2110308E0066800A /* AppDatabase.swift */, + 562697502110308E0066800A /* AppDelegate.swift */, + 5626974D2110308E0066800A /* Player.swift */, + 5626974E2110308E0066800A /* PlayerEditionViewController.swift */, + 5626974C2110308E0066800A /* PlayersViewController.swift */, + 567374441B4D46600089DE44 /* Assets.xcassets */, + 567374491B4D46600089DE44 /* Info.plist */, + 567374461B4D46600089DE44 /* LaunchScreen.storyboard */, + 567374411B4D46600089DE44 /* Main.storyboard */, + ); + name = GRDBDemoiOS; + path = ../../../DemoApps/GRDBDemoiOS/GRDBDemoiOS; + sourceTree = ""; + }; + 8D9BFC4007F760CC8E01ACC6 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 9E46153E91609427B4025BC7 /* libPods-iOS.a */, + ); + name = Frameworks; + sourceTree = ""; + }; + 9ABB37395508D35C98A292E7 /* Pods */ = { + isa = PBXGroup; + children = ( + 62C5B84AA50DF194B4DDDFD0 /* Pods-iOS.debug.xcconfig */, + 9573251A237B01D90415D0D7 /* Pods-iOS.release.xcconfig */, + ); + name = Pods; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 567374371B4D46600089DE44 /* iOS */ = { + isa = PBXNativeTarget; + buildConfigurationList = 567374621B4D46600089DE44 /* Build configuration list for PBXNativeTarget "iOS" */; + buildPhases = ( + C5E9DF0928754FE22F481D3A /* [CP] Check Pods Manifest.lock */, + 567374341B4D46600089DE44 /* Sources */, + 567374351B4D46600089DE44 /* Frameworks */, + 567374361B4D46600089DE44 /* Resources */, + 5644E4071C1072CA0090716E /* Embed Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = iOS; + productName = iOS; + productReference = 567374381B4D46600089DE44 /* iOS.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 567374301B4D46600089DE44 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0730; + LastUpgradeCheck = 0940; + ORGANIZATIONNAME = "Gwendal Roué"; + TargetAttributes = { + 567374371B4D46600089DE44 = { + CreatedOnToolsVersion = 7.0; + DevelopmentTeam = AMD8W895CT; + LastSwiftMigration = 0940; + }; + }; + }; + buildConfigurationList = 567374331B4D46600089DE44 /* Build configuration list for PBXProject "iOS" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 5673742F1B4D46600089DE44; + productRefGroup = 567374391B4D46600089DE44 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 567374371B4D46600089DE44 /* iOS */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 567374361B4D46600089DE44 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 567374481B4D46600089DE44 /* LaunchScreen.storyboard in Resources */, + 567374451B4D46600089DE44 /* Assets.xcassets in Resources */, + 567374431B4D46600089DE44 /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + C5E9DF0928754FE22F481D3A /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-iOS-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 567374341B4D46600089DE44 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 562697522110308F0066800A /* Player.swift in Sources */, + 562697532110308F0066800A /* PlayerEditionViewController.swift in Sources */, + 562697542110308F0066800A /* AppDatabase.swift in Sources */, + 562697552110308F0066800A /* AppDelegate.swift in Sources */, + 562697512110308F0066800A /* PlayersViewController.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXVariantGroup section */ + 567374411B4D46600089DE44 /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 567374421B4D46600089DE44 /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 567374461B4D46600089DE44 /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 567374471B4D46600089DE44 /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 567374601B4D46600089DE44 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 567374611B4D46600089DE44 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 567374631B4D46600089DE44 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 62C5B84AA50DF194B4DDDFD0 /* Pods-iOS.debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + INFOPLIST_FILE = ../../../DemoApps/GRDBDemoiOS/GRDBDemoiOS/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = GRDB.CarthageTest; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 4.2; + }; + name = Debug; + }; + 567374641B4D46600089DE44 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9573251A237B01D90415D0D7 /* Pods-iOS.release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + INFOPLIST_FILE = ../../../DemoApps/GRDBDemoiOS/GRDBDemoiOS/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = GRDB.CarthageTest; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE = ""; + SWIFT_VERSION = 4.2; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 567374331B4D46600089DE44 /* Build configuration list for PBXProject "iOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 567374601B4D46600089DE44 /* Debug */, + 567374611B4D46600089DE44 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 567374621B4D46600089DE44 /* Build configuration list for PBXNativeTarget "iOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 567374631B4D46600089DE44 /* Debug */, + 567374641B4D46600089DE44 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 567374301B4D46600089DE44 /* Project object */; +} diff --git a/Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..92a930669 --- /dev/null +++ b/Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/Tests/CocoaPods/GRDBiOS-static/iOS.xcworkspace/contents.xcworkspacedata b/Tests/CocoaPods/GRDBiOS-static/iOS.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..7f03e784a --- /dev/null +++ b/Tests/CocoaPods/GRDBiOS-static/iOS.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + From bdf802ab349eab20afdb6b69886de888c816567f Mon Sep 17 00:00:00 2001 From: Chris Ballinger Date: Tue, 30 Jul 2019 16:31:50 -0700 Subject: [PATCH 45/91] Update CHANGELOG and README --- CHANGELOG.md | 1 + README.md | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3938897cd..eefa06a36 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -56,6 +56,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: - [#560](https://github.com/groue/GRDB.swift/pull/560) by [@bellebethcooper](https://github.com/bellebethcooper): Minor typo fix - [#562](https://github.com/groue/GRDB.swift/pull/562): Fix crash when using more than one DatabaseCollation +- [#570](https://github.com/groue/GRDB.swift/pull/570): Allow Swift static library integration via CocoaPods - [#563](https://github.com/groue/GRDB.swift/pull/563): More tests for eager loading of hasMany associations - [#574](https://github.com/groue/GRDB.swift/pull/574): SwiftLint - [#576](https://github.com/groue/GRDB.swift/pull/576): Expose table name and full-text filtering methods to DerivableRequest diff --git a/README.md b/README.md index 98ceec3fc..6ac370a9d 100644 --- a/README.md +++ b/README.md @@ -324,10 +324,10 @@ See [Enabling FTS5 Support](#enabling-fts5-support) for the installation procedu [CocoaPods](http://cocoapods.org/) is a dependency manager for Xcode projects. To use GRDB with CocoaPods (version 1.2 or higher), specify in your `Podfile`: ```ruby -use_frameworks! pod 'GRDB.swift' ``` +GRDB can be installed as a framework, or a static library. ## Swift Package Manager From 19cf5690363603a3b555f3ba63782434087565fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 31 Jul 2019 07:43:16 +0200 Subject: [PATCH 46/91] Add @chrisballinger to the thank you notice --- CHANGELOG.md | 2 +- README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index eefa06a36..489f04391 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -56,8 +56,8 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: - [#560](https://github.com/groue/GRDB.swift/pull/560) by [@bellebethcooper](https://github.com/bellebethcooper): Minor typo fix - [#562](https://github.com/groue/GRDB.swift/pull/562): Fix crash when using more than one DatabaseCollation -- [#570](https://github.com/groue/GRDB.swift/pull/570): Allow Swift static library integration via CocoaPods - [#563](https://github.com/groue/GRDB.swift/pull/563): More tests for eager loading of hasMany associations +- [#570](https://github.com/groue/GRDB.swift/pull/570) by [@chrisballinger](https://github.com/chrisballinger): Allow Swift static library integration via CocoaPods - [#574](https://github.com/groue/GRDB.swift/pull/574): SwiftLint - [#576](https://github.com/groue/GRDB.swift/pull/576): Expose table name and full-text filtering methods to DerivableRequest - [#577](https://github.com/groue/GRDB.swift/pull/577): Rename `aliased(_:)` methods to `forKey(_:)` diff --git a/README.md b/README.md index 6ac370a9d..35bc0252d 100644 --- a/README.md +++ b/README.md @@ -9039,7 +9039,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), [@darrenclark](https://github.com/darrenclark), [@davidkraus](https://github.com/davidkraus), [@fpillet](http://github.com/fpillet), [@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), [@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), [@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), [@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), [@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), [@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 63cb9f2ad27c6525098c0f35ba4478c4e732f253 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 31 Jul 2019 08:01:39 +0200 Subject: [PATCH 47/91] CONTRIBUTING: mention #575 --- CONTRIBUTING.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 65b6b22c8..12528290b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -292,6 +292,8 @@ There are several SQLite features that GRDB could natively support: - [Windows Functions](https://www.sqlite.org/windowfunctions.html) - [More ideas](https://www.sqlite.org/lang.html) +See [issue #575](https://github.com/groue/GRDB.swift/issues/575) for more information and guidance about the implementation of extra table alterations. + ### Reactive Database Observation From 62f5bd1940c06106fef0e43074fa9b3fd420f2fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 31 Jul 2019 08:03:04 +0200 Subject: [PATCH 48/91] CONTRIBUTING: fix inner link --- CONTRIBUTING.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 12528290b..c7fe3dbd0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -378,6 +378,7 @@ Features that blur this focus are non-goals: [JSON]: #json [Linux]: #linux [More SQL Generation]: #more-sql-generation +[Reactive Database Observation]: #reactive-database-observation [Records: Splitting Database Encoding from Ability to Write in the Database]: #records-splitting-database-encoding-from-ability-to-write-in-the-database [Non-Goals]: #non-goals [Report Bugs]: #report-bugs From e58b652970ee93cc928086ded79be09c15719da6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 31 Jul 2019 08:04:38 +0200 Subject: [PATCH 49/91] CONTRIBUTING: static libray is possible since #570 --- CONTRIBUTING.md | 9 --------- 1 file changed, 9 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c7fe3dbd0..01586c105 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -88,7 +88,6 @@ The ideas, in alphabetical order: - [Reactive Database Observation] - [SQL Console in the Debugger] - [SQLCipher in a Shared App Container] -- [Static Library] - [Typed Expressions] @@ -318,13 +317,6 @@ Sometimes one needs, in lldb, a console similar to the [Command Line Shell For S See issue [#302](https://github.com/groue/GRDB.swift/issues/302). -### Static Library - -:question: Unknown Difficulty :hammer: Tooling - -It would be nice to be able to integrate GRDB as a static library. - - ### Typed Expressions :bowtie: Public API Challenge :muscle: Hard :fire: Experimental @@ -384,7 +376,6 @@ Features that blur this focus are non-goals: [Report Bugs]: #report-bugs [RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB [Concurrency]: #concurrency -[Static Library]: #static-library [Sponsoring and Professional Support]: #sponsoring-and-professional-support [SQL Console in the Debugger]: #sql-console-in-the-debugger [SQLCipher in a Shared App Container]: #sqlcipher-in-a-shared-app-container From 2b3e5a06db58e107b0a7b5c2b448ef6c21279895 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 31 Jul 2019 08:07:52 +0200 Subject: [PATCH 50/91] CONTRIBUTING: mention GRDBCombine --- CONTRIBUTING.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 01586c105..833b6245e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -298,9 +298,9 @@ See [issue #575](https://github.com/groue/GRDB.swift/issues/575) for more inform :baby: Starter Task -We already have the [RxGRDB] companion library, which offers [RxSwift](https://github.com/ReactiveX/RxSwift) bindings. +We already have the [GRDBCombine](http://github.com/groue/GRDBCombine) and [RxGRDB] companion libraries. -We need more choices of reactive engines. +More choices of reactive engines would help more developers enjoy GRDB. ### SQL Console in the Debugger From bb959fa5c32ba78ee185e8551085c96c5ba4b092 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 2 Aug 2019 14:14:48 +0200 Subject: [PATCH 51/91] Add failing test for #583 --- Tests/GRDBTests/DatabaseCursorTests.swift | 58 +++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/Tests/GRDBTests/DatabaseCursorTests.swift b/Tests/GRDBTests/DatabaseCursorTests.swift index 02a2733e5..f90d35839 100644 --- a/Tests/GRDBTests/DatabaseCursorTests.swift +++ b/Tests/GRDBTests/DatabaseCursorTests.swift @@ -70,4 +70,62 @@ class DatabaseCursorTests: GRDBTestCase { } } } + + func testIssue583() throws { + struct User: Codable, TableRecord, FetchableRecord, MutablePersistableRecord { + static let databaseTableName: String = "user" + + var id: Int64? + var username: String + var isFlagged: Bool + + init(id: Int64? = nil, username: String, isFlagged: Bool = false) { + self.id = id + self.username = username + self.isFlagged = isFlagged + } + + mutating func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } + } + + struct FlagUser: Codable, TableRecord, FetchableRecord, MutablePersistableRecord { + static let databaseTableName: String = "flagUser" + + var username: String + } + + let queue = try makeDatabaseQueue() + try queue.write { database in + try database.create(table: User.databaseTableName) { definition in + definition.column("id", .integer).primaryKey(autoincrement: true) + definition.column("username", .text).notNull() + definition.column("isFlagged", .boolean).notNull().defaults(to: false) + } + + try database.create(table: FlagUser.databaseTableName) { definition in + definition.column("username", .text).notNull() + } + + try [Int](0...50).forEach { + var user = User(username: "User\($0)") + try user.insert(database) + } + + try [Int](40...60).forEach { + var flag = FlagUser(username: "User\($0)") + try flag.insert(database) + } + } + + let query = "SELECT * FROM flagUser WHERE (SELECT COUNT(id) FROM user WHERE username = flagUser.username AND isFlagged = 1) = 0" + try queue.inDatabase { database in + let cursor = try FlagUser.fetchCursor(database, sql: query) + while let flagged = try cursor.next() { + _ = try User.fetchOne(database, sql: "SELECT * FROM user WHERE username = '\(flagged.username)' LIMIT 1") ?? + User(username: flagged.username) + } + } + } } From a59f4ef096d65e80c6997baa3c9f9e01c4865a17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 2 Aug 2019 14:17:48 +0200 Subject: [PATCH 52/91] Fix #583 by keeping a single authorizer active for the whole lifetime of a database connection SQLite invalidates statements when authorizer changes, which can lead to undesired behaviors. This is why we now call sqlite3_set_authorizer only once. See http://sqlite.1065341.n5.nabble.com/Issue-report-sqlite3-set-authorizer-triggers-error-4-516-SQLITE-ABORT-ROLLBACK-during-statement-itern-td107972.html --- GRDB/Core/Database.swift | 36 ++++++++++++++++-------------------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 5d5b9b27b..d52a66b3d 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -130,26 +130,7 @@ public final class Database { var lastErrorMessage: String? { return String(cString: sqlite3_errmsg(sqliteConnection)) } // Statement authorizer - var authorizer: StatementAuthorizer? { - didSet { - switch (oldValue, authorizer) { - case (.some, nil): - sqlite3_set_authorizer(sqliteConnection, nil, nil) - case (nil, .some): - let dbPointer = Unmanaged.passUnretained(self).toOpaque() - sqlite3_set_authorizer( - sqliteConnection, - { (dbPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in - guard let dbPointer = dbPointer else { return SQLITE_OK } - let db = Unmanaged.fromOpaque(dbPointer).takeUnretainedValue() - return db.authorizer!.authorize(actionCode, cString1, cString2, cString3, cString4) - }, - dbPointer) - default: - break - } - } - } + var authorizer: StatementAuthorizer? // Transaction observers management lazy var observationBroker = DatabaseObservationBroker(self) @@ -221,6 +202,7 @@ extension Database { setupBusyMode() setupDefaultFunctions() setupDefaultCollations() + setupAuthorizer() observationBroker.installCommitAndRollbackHooks() try activateExtendedCodes() @@ -352,6 +334,20 @@ extension Database { add(collation: .localizedStandardCompare) } + private func setupAuthorizer() { + let dbPointer = Unmanaged.passUnretained(self).toOpaque() + sqlite3_set_authorizer( + sqliteConnection, + { (dbPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in + guard let dbPointer = dbPointer else { return SQLITE_OK } + let db = Unmanaged.fromOpaque(dbPointer).takeUnretainedValue() + guard let authorizer = db.authorizer else { return SQLITE_OK } + return authorizer.authorize(actionCode, cString1, cString2, cString3, cString4) + }, + dbPointer) + } + + private func activateExtendedCodes() throws { let code = sqlite3_extended_result_codes(sqliteConnection, 1) guard code == SQLITE_OK else { From e351b795264566933c4aedb7b3f4ecaab5de3c07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 2 Aug 2019 15:16:48 +0200 Subject: [PATCH 53/91] Database only exposes its current authorizer with the `withAuthorizer(_:_:)` wrapper method. --- GRDB/Core/Database+Statements.swift | 70 ++++++++++++++++----- GRDB/Core/Database.swift | 19 +++++- GRDB/Core/Statement.swift | 98 +++++++++-------------------- GRDB/Core/TransactionObserver.swift | 11 ++-- 4 files changed, 109 insertions(+), 89 deletions(-) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 8b39b5643..f9ae27fba 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -180,16 +180,15 @@ extension Database { // Compile do { - let statementCompilationAuthorizer = StatementCompilationAuthorizer() - authorizer = statementCompilationAuthorizer - defer { authorizer = nil } - - nextStatement = try UpdateStatement( - database: self, - statementStart: statementStart, - statementEnd: &statementEnd, - prepFlags: 0, - authorizer: statementCompilationAuthorizer) + let authorizer = StatementCompilationAuthorizer() + nextStatement = try withAuthorizer(authorizer) { + try UpdateStatement( + database: self, + statementStart: statementStart, + statementEnd: &statementEnd, + prepFlags: 0, + authorizer: authorizer) + } } guard let statement = nextStatement else { @@ -222,11 +221,54 @@ extension Database { extension Database { - func updateStatementWillExecute(_ statement: UpdateStatement) { - observationBroker.updateStatementWillExecute(statement) + func executeUpdateStatement(_ statement: UpdateStatement) throws { + let authorizer = observationBroker.updateStatementWillExecute(statement) + let sqliteStatement = statement.sqliteStatement + var code: Int32 = SQLITE_OK + withAuthorizer(authorizer) { + while true { + code = sqlite3_step(sqliteStatement) + if code == SQLITE_ROW { + // Statement returns a row, but the user ignores the + // content of this row: + // + // try db.execute(sql: "SELECT ...") + // + // That's OK: maybe the selected rows perform side effects. + // For example: + // + // try db.execute(sql: "SELECT sqlcipher_export(...)") + // + // Or maybe the user doesn't know that the executed statement + // return rows (https://github.com/groue/GRDB.swift/issues/15); + // + // try db.execute(sql: "PRAGMA journal_mode=WAL") + // + // It is thus important that we consume *all* rows. + continue + } else { + break + } + } + } + + // Statement has been fully executed, and authorizer has been reset. + // We can now move on further tasks. + + if code == SQLITE_DONE { + try updateStatementDidExecute(statement) + } else { + assert(code != SQLITE_ROW) + try updateStatementDidFail(statement) + throw DatabaseError( + resultCode: code, + message: lastErrorMessage, + sql: statement.sql, + arguments: statement.arguments) + } } - func updateStatementDidExecute(_ statement: UpdateStatement) throws { + private func updateStatementDidExecute(_ statement: UpdateStatement) throws { if statement.invalidatesDatabaseSchemaCache { clearSchemaCache() } @@ -234,7 +276,7 @@ extension Database { try observationBroker.updateStatementDidExecute(statement) } - func updateStatementDidFail(_ statement: UpdateStatement) throws { + private func updateStatementDidFail(_ statement: UpdateStatement) throws { // Failed statements can not be reused, because sqlite3_reset won't // be able to restore the statement to its initial state: // https://www.sqlite.org/c3ref/reset.html diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index d52a66b3d..d2af9d6b1 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -129,8 +129,8 @@ public final class Database { var lastErrorCode: ResultCode { return ResultCode(rawValue: sqlite3_errcode(sqliteConnection)) } var lastErrorMessage: String? { return String(cString: sqlite3_errmsg(sqliteConnection)) } - // Statement authorizer - var authorizer: StatementAuthorizer? + // Statement authorizer. Use withAuthorizer(_:_:). + fileprivate var _authorizer: StatementAuthorizer? // // Transaction observers management lazy var observationBroker = DatabaseObservationBroker(self) @@ -341,7 +341,7 @@ extension Database { { (dbPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in guard let dbPointer = dbPointer else { return SQLITE_OK } let db = Unmanaged.fromOpaque(dbPointer).takeUnretainedValue() - guard let authorizer = db.authorizer else { return SQLITE_OK } + guard let authorizer = db._authorizer else { return SQLITE_OK } return authorizer.authorize(actionCode, cString1, cString2, cString3, cString4) }, dbPointer) @@ -594,6 +594,19 @@ extension Database { } } +extension Database { + + // MARK: - Authorizer + + func withAuthorizer(_ authorizer: StatementAuthorizer?, _ block: () throws -> T) rethrows -> T { + SchedulingWatchdog.preconditionValidQueue(self) + let old = self._authorizer + self._authorizer = authorizer + defer { self._authorizer = old } + return try block() + } +} + extension Database { // MARK: - Transactions & Savepoint diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 33c64c9a8..df924bd04 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -224,46 +224,41 @@ public class Statement { // MARK: - Statement Preparation -/// A common protocol for UpdateStatement and SelectStatement, only used as -/// support for SelectStatement.prepare(...) and UpdateStatement.prepare(...). -protocol StatementProtocol { } -extension Statement: StatementProtocol { } -extension StatementProtocol where Self: Statement { +extension Statement { // Static method instead of an initializer because initializer can't run // inside `sqlCodeUnits.withUnsafeBufferPointer`. static func prepare(sql: String, prepFlags: Int32, in database: Database) throws -> Self { let authorizer = StatementCompilationAuthorizer() - database.authorizer = authorizer - defer { database.authorizer = nil } - - return try sql.utf8CString.withUnsafeBufferPointer { buffer in - let statementStart = buffer.baseAddress! - var statementEnd: UnsafePointer? = nil - guard let statement = try self.init( - database: database, - statementStart: statementStart, - statementEnd: &statementEnd, - prepFlags: prepFlags, - authorizer: authorizer) else - { - throw DatabaseError( - resultCode: .SQLITE_ERROR, - message: "empty statement", - sql: sql) - } - - let remainingSQL = String(cString: statementEnd!).trimmingCharacters(in: .sqlStatementSeparators) - guard remainingSQL.isEmpty else { - throw DatabaseError( - resultCode: .SQLITE_MISUSE, - message: """ + return try database.withAuthorizer(authorizer) { + try sql.utf8CString.withUnsafeBufferPointer { buffer in + let statementStart = buffer.baseAddress! + var statementEnd: UnsafePointer? = nil + guard let statement = try self.init( + database: database, + statementStart: statementStart, + statementEnd: &statementEnd, + prepFlags: prepFlags, + authorizer: authorizer) else + { + throw DatabaseError( + resultCode: .SQLITE_ERROR, + message: "empty statement", + sql: sql) + } + + let remainingSQL = String(cString: statementEnd!).trimmingCharacters(in: .sqlStatementSeparators) + guard remainingSQL.isEmpty else { + throw DatabaseError( + resultCode: .SQLITE_MISUSE, + message: """ Multiple statements found. To execute multiple statements, \ use Database.execute(sql:) instead. """, - sql: sql) + sql: sql) + } + + return statement } - - return statement } } } @@ -484,42 +479,11 @@ public final class UpdateStatement: Statement { SchedulingWatchdog.preconditionValidQueue(database) prepare(withArguments: arguments) try reset() - database.updateStatementWillExecute(self) - while true { - switch sqlite3_step(sqliteStatement) { - case SQLITE_ROW: - // The statement did return a row, and the user ignores the - // content of this row: - // - // try db.execute(sql: "SELECT ...") - // - // That's OK: maybe the selected rows perform side effects. - // For example: - // - // try db.execute(sql: "SELECT sqlcipher_export(...)") - // - // Or maybe the user doesn't know that the executed statement - // return rows (https://github.com/groue/GRDB.swift/issues/15); - // - // try db.execute(sql: "PRAGMA journal_mode=WAL") - // - // It is thus important that we consume *all* rows. - continue - - case SQLITE_DONE: - try database.updateStatementDidExecute(self) - return - - case let code: - try database.updateStatementDidFail(self) - throw DatabaseError( - resultCode: code, - message: database.lastErrorMessage, - sql: sql, - arguments: self.arguments) // Error uses self.arguments, not the optional arguments parameter. - } - } + // Statement does not know how to execute itself, because it does not + // know how to handle its errors, or if truncate optimisation should be + // prevented or not. Database knows. + try database.executeUpdateStatement(self) } } diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index c86139207..13cd61a2e 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -206,7 +206,10 @@ class DatabaseObservationBroker { // MARK: - Statement execution - func updateStatementWillExecute(_ statement: UpdateStatement) { + /// Setups observation of changes that are about to be performed by the + /// statement, and returns the authorizer that should be used during + /// statement execution. + func updateStatementWillExecute(_ statement: UpdateStatement) -> StatementAuthorizer? { // As statement executes, it may trigger database changes that will // be notified to transaction observers. As a consequence, observers // may disable themselves with stopObservingDatabaseChangesUntilNextTransaction() @@ -285,16 +288,15 @@ class DatabaseObservationBroker { } if observesRowDeletion { - database.authorizer = TruncateOptimizationBlocker() + return TruncateOptimizationBlocker() } else { - database.authorizer = nil + return nil } } func updateStatementDidFail(_ statement: UpdateStatement) throws { // Undo updateStatementWillExecute statementObservations = [] - database.authorizer = nil SchedulingWatchdog.current!.databaseObservationBroker = nil // Reset transactionState before databaseDidRollback eventually @@ -319,7 +321,6 @@ class DatabaseObservationBroker { func updateStatementDidExecute(_ statement: UpdateStatement) throws { // Undo updateStatementWillExecute statementObservations = [] - database.authorizer = nil SchedulingWatchdog.current!.databaseObservationBroker = nil // Has statement any effect on transaction/savepoints? From bd9104d29f68bf6420bb3d2be6ee02fadc9643e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 2 Aug 2019 15:34:25 +0200 Subject: [PATCH 54/91] Cleanup --- GRDB/Core/Database+Statements.swift | 4 ++-- GRDB/Core/Statement.swift | 17 +++++++++-------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index f9ae27fba..98de74548 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -36,7 +36,7 @@ extension Database { /// - returns: A SelectStatement. /// - throws: A DatabaseError whenever SQLite could not parse the sql query. func makeSelectStatement(sql: String, prepFlags: Int32) throws -> SelectStatement { - return try SelectStatement.prepare(sql: sql, prepFlags: prepFlags, in: self) + return try SelectStatement.prepare(self, sql: sql, prepFlags: prepFlags) } /// Returns a prepared statement that can be reused. @@ -85,7 +85,7 @@ extension Database { /// - returns: An UpdateStatement. /// - throws: A DatabaseError whenever SQLite could not parse the sql query. func makeUpdateStatement(sql: String, prepFlags: Int32) throws -> UpdateStatement { - return try UpdateStatement.prepare(sql: sql, prepFlags: prepFlags, in: self) + return try UpdateStatement.prepare(self, sql: sql, prepFlags: prepFlags) } /// Returns a prepared statement that can be reused. diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index df924bd04..772025711 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -43,6 +43,7 @@ public class Statement { /// statement in the C string. /// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from /// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html) + /// - parameter authorizer: A StatementCompilationAuthorizer /// - throws: DatabaseError in case of compilation error. required init?( database: Database, @@ -227,14 +228,14 @@ public class Statement { extension Statement { // Static method instead of an initializer because initializer can't run // inside `sqlCodeUnits.withUnsafeBufferPointer`. - static func prepare(sql: String, prepFlags: Int32, in database: Database) throws -> Self { + static func prepare(_ db: Database, sql: String, prepFlags: Int32) throws -> Self { let authorizer = StatementCompilationAuthorizer() - return try database.withAuthorizer(authorizer) { + return try db.withAuthorizer(authorizer) { try sql.utf8CString.withUnsafeBufferPointer { buffer in let statementStart = buffer.baseAddress! var statementEnd: UnsafePointer? = nil guard let statement = try self.init( - database: database, + database: db, statementStart: statementStart, statementEnd: &statementEnd, prepFlags: prepFlags, @@ -251,9 +252,9 @@ extension Statement { throw DatabaseError( resultCode: .SQLITE_MISUSE, message: """ - Multiple statements found. To execute multiple statements, \ - use Database.execute(sql:) instead. - """, + Multiple statements found. To execute multiple statements, \ + use Database.execute(sql:) instead. + """, sql: sql) } @@ -288,7 +289,7 @@ public final class SelectStatement: Statement { /// statement in the C string. /// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from /// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html) - /// - authorizer: A StatementCompilationAuthorizer + /// - parameter authorizer: A StatementCompilationAuthorizer /// - throws: DatabaseError in case of compilation error. required init?( database: Database, @@ -451,7 +452,7 @@ public final class UpdateStatement: Statement { /// statement in the C string. /// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from /// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html) - /// - authorizer: A StatementCompilationAuthorizer + /// - parameter authorizer: A StatementCompilationAuthorizer /// - throws: DatabaseError in case of compilation error. required init?( database: Database, From 3ab8a34d58c3689166a9ae9f6194f52b95dbadfb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 2 Aug 2019 15:34:49 +0200 Subject: [PATCH 55/91] Fix a Swiftlint warning --- GRDB/Record/EncodableRecord+Encodable.swift | 2 +- GRDB/Record/FetchableRecord+Decodable.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/GRDB/Record/EncodableRecord+Encodable.swift b/GRDB/Record/EncodableRecord+Encodable.swift index d0a2e522f..85fbb95e9 100644 --- a/GRDB/Record/EncodableRecord+Encodable.swift +++ b/GRDB/Record/EncodableRecord+Encodable.swift @@ -340,7 +340,7 @@ extension JSONRequiredEncoder: UnkeyedEncodingContainer { } @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) -fileprivate var iso8601Formatter: ISO8601DateFormatter = { +private var iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime return formatter diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index fe1df46dd..fb6d49a94 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -408,7 +408,7 @@ private struct MissingColumnError: Error { } @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) -fileprivate var iso8601Formatter: ISO8601DateFormatter = { +private var iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime return formatter From c6cb92d75739391c3e356767fc2f0c7de785dd84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 2 Aug 2019 15:40:19 +0200 Subject: [PATCH 56/91] Cleanup --- GRDB/Core/Database.swift | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index d2af9d6b1..0b73cc721 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -339,9 +339,10 @@ extension Database { sqlite3_set_authorizer( sqliteConnection, { (dbPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in - guard let dbPointer = dbPointer else { return SQLITE_OK } - let db = Unmanaged.fromOpaque(dbPointer).takeUnretainedValue() - guard let authorizer = db._authorizer else { return SQLITE_OK } + let db = Unmanaged.fromOpaque(dbPointer.unsafelyUnwrapped).takeUnretainedValue() + guard let authorizer = db._authorizer else { + return SQLITE_OK + } return authorizer.authorize(actionCode, cString1, cString2, cString3, cString4) }, dbPointer) From 870d22fd95d7b1ad469c3418ee864d82ec8c6c70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 2 Aug 2019 16:04:28 +0200 Subject: [PATCH 57/91] Explain why we call sqlite3_set_authorizer once per database connection --- GRDB/Core/Database.swift | 8 ++++++++ Tests/GRDBTests/DatabaseCursorTests.swift | 1 + 2 files changed, 9 insertions(+) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 0b73cc721..95c6d3e5a 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -335,6 +335,14 @@ extension Database { } private func setupAuthorizer() { + // SQLite authorizer is set only once per database connection. + // + // This is because authorizer changes have SQLite invalidate statements, + // with undesired side effects. See: + // + // - DatabaseCursorTests.testIssue583() + // - http://sqlite.1065341.n5.nabble.com/Issue-report-sqlite3-set-authorizer-triggers-error-4-516-SQLITE-ABORT-ROLLBACK-during-statement-itern-td107972.html + // swiftlint:disable:previous line_length let dbPointer = Unmanaged.passUnretained(self).toOpaque() sqlite3_set_authorizer( sqliteConnection, diff --git a/Tests/GRDBTests/DatabaseCursorTests.swift b/Tests/GRDBTests/DatabaseCursorTests.swift index f90d35839..70baca926 100644 --- a/Tests/GRDBTests/DatabaseCursorTests.swift +++ b/Tests/GRDBTests/DatabaseCursorTests.swift @@ -71,6 +71,7 @@ class DatabaseCursorTests: GRDBTestCase { } } + // Regression test for http://github.com/groue/GRDB.swift/issues/583 func testIssue583() throws { struct User: Codable, TableRecord, FetchableRecord, MutablePersistableRecord { static let databaseTableName: String = "user" From 55803b29b0fb908288086a4288c1c1c9a681651b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 2 Aug 2019 17:56:47 +0200 Subject: [PATCH 58/91] Keep a memory of how to trigger #583 error --- Tests/GRDBTests/DatabaseCursorTests.swift | 41 +++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/Tests/GRDBTests/DatabaseCursorTests.swift b/Tests/GRDBTests/DatabaseCursorTests.swift index 70baca926..f6e82c1f4 100644 --- a/Tests/GRDBTests/DatabaseCursorTests.swift +++ b/Tests/GRDBTests/DatabaseCursorTests.swift @@ -128,5 +128,46 @@ class DatabaseCursorTests: GRDBTestCase { User(username: flagged.username) } } + + // For the record, the lines below show how this test used to fail, + // with raw C SQLite3 apis. The faulty line is the call to + // sqlite3_set_authorizer during the statement iteration. + +// if #available(OSX 10.14, *) { +// var connection: SQLiteConnection? = nil +// sqlite3_open_v2(":memory:", &connection, SQLITE_OPEN_READWRITE | SQLITE_OPEN_NOMUTEX, nil) +// sqlite3_extended_result_codes(connection, 1) +// +// sqlite3_exec(connection, """ +// CREATE TABLE user (username TEXT NOT NULL); +// CREATE TABLE flagUser (username TEXT NOT NULL); +// INSERT INTO flagUser (username) VALUES ('User1'); +// INSERT INTO flagUser (username) VALUES ('User2'); +// """, nil, nil, nil) +// +// var statement: SQLiteStatement? = nil +// sqlite3_set_authorizer(connection, { (_, _, _, _, _, _) in SQLITE_OK }, nil) +// sqlite3_prepare_v3(connection, """ +// SELECT * FROM flagUser WHERE (SELECT COUNT(*) FROM user WHERE username = flagUser.username) = 0 +// """, -1, 0, &statement, nil) +// sqlite3_set_authorizer(connection, nil, nil) +// while true { +// let code = sqlite3_step(statement) +// if code == SQLITE_DONE { +// break +// } else if code == SQLITE_ROW { +// // part of the compilation of another statement, here +// // reduced to the strict minimum that reproduces +// // the error. +// sqlite3_set_authorizer(connection, nil, nil) +// } else { +// print(String(cString: sqlite3_errmsg(connection))) +// XCTFail("Error \(code)") +// break +// } +// } +// sqlite3_finalize(statement) +// sqlite3_close_v2(connection) +// } } } From d32b5271bd01f08ab1afde2d465cdb358b8e8922 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 3 Aug 2019 06:43:31 +0200 Subject: [PATCH 59/91] Performance tests: update paths for Xcode 10.3 --- GRDB.xcodeproj/project.pbxproj | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index f31dcb2ba..c9803add0 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -1233,8 +1233,8 @@ 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = ""; }; 56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = ""; }; 56B86E72220FF4E000524C16 /* SQLLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLLiteralTests.swift; sourceTree = ""; }; - 56B8C2401CA1758F00510325 /* Realm.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Realm.framework; path = "Realm/build/osx/swift-10.2.1/Realm.framework"; sourceTree = ""; }; - 56B8C2411CA1758F00510325 /* RealmSwift.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = RealmSwift.framework; path = "Realm/build/osx/swift-10.2.1/RealmSwift.framework"; sourceTree = ""; }; + 56B8C2401CA1758F00510325 /* Realm.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Realm.framework; path = "Realm/build/osx/swift-10.3/Realm.framework"; sourceTree = ""; }; + 56B8C2411CA1758F00510325 /* RealmSwift.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = RealmSwift.framework; path = "Realm/build/osx/swift-10.3/RealmSwift.framework"; sourceTree = ""; }; 56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDB.xcconfig; sourceTree = ""; }; 56B9649C1DA51B4C0002DA19 /* FTS5.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5.swift; sourceTree = ""; }; 56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TokenizerDescriptor.swift; sourceTree = ""; }; @@ -3538,7 +3538,7 @@ DEBUG_INFORMATION_FORMAT = dwarf; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", - "$(PROJECT_DIR)/Tests/Performance/Realm/build/osx/swift-10.2.1", + "$(PROJECT_DIR)/Tests/Performance/Realm/build/osx/swift-10.3", ); GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; @@ -3561,7 +3561,7 @@ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", - "$(PROJECT_DIR)/Tests/Performance/Realm/build/osx/swift-10.2.1", + "$(PROJECT_DIR)/Tests/Performance/Realm/build/osx/swift-10.3", ); GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = Tests/Info.plist; From 5908c26a79ffa5a7364f68887cad6c4d3c3de4a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 3 Aug 2019 06:48:08 +0200 Subject: [PATCH 60/91] Fix Makefile so that it can checkoutt the FMDB submodule --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index b030b97e5..debe2b326 100644 --- a/Makefile +++ b/Makefile @@ -330,7 +330,7 @@ Tests/Performance/Realm/build/osx/swift-10.2.1/RealmSwift.framework: FMDB: Tests/Performance/fmdb/src/fmdb/FMDatabase.h # Makes sure the Tests/Performance/fmdb submodule has been downloaded -Tests/Performance/fmdb/FMDatabase.h: +Tests/Performance/fmdb/src/fmdb/FMDatabase.h: $(GIT) submodule update --init Tests/Performance/fmdb SQLite.swift: Tests/Performance/SQLite.swift/SQLite.xcodeproj From 38599b007fce0d2376f933bedae512025a6085d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 3 Aug 2019 07:15:55 +0200 Subject: [PATCH 61/91] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 489f04391..7bea46a5b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -61,6 +61,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: - [#574](https://github.com/groue/GRDB.swift/pull/574): SwiftLint - [#576](https://github.com/groue/GRDB.swift/pull/576): Expose table name and full-text filtering methods to DerivableRequest - [#577](https://github.com/groue/GRDB.swift/pull/577): Rename `aliased(_:)` methods to `forKey(_:)` +- [#585](https://github.com/groue/GRDB.swift/pull/585): Fix use of SQLite authorizers ### API Diff From af0ac156aa0057334f5a519f21c69831e4443d91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 3 Aug 2019 14:21:46 +0200 Subject: [PATCH 62/91] More explicit observation initializers --- GRDB/Core/DatabaseRegion.swift | 12 ++- GRDB/Core/DatabaseRegionObservation.swift | 25 ++---- GRDB/Core/DatabaseWriter.swift | 10 +-- .../ValueObservation+MapReducer.swift | 11 ++- GRDB/ValueObservation/ValueObservation.swift | 34 +++----- .../ValueReducer/Combine.swift | 84 ++++++++++++++----- 6 files changed, 100 insertions(+), 76 deletions(-) diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index c754ca697..af22ad1e8 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -142,10 +142,16 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable { self = union(other) } - func ignoring(_ tables: Set) -> DatabaseRegion { - guard tables.isEmpty == false else { return self } + /// Returns a region suitable for database observation by removing views. + /// + /// We can do it because modifications only happen in actual tables. And we + /// want to do it because we have a fast path for regions that span a + /// single table. + func ignoringViews(_ db: Database) throws -> DatabaseRegion { guard let tableRegions = tableRegions else { return .fullDatabase } - let filteredRegions = tableRegions.filter { tables.contains($0.key) == false } + let viewNames = try db.schema().names(ofType: .view) + guard viewNames.isEmpty == false else { return self } + let filteredRegions = tableRegions.filter { viewNames.contains($0.key) == false } return DatabaseRegion(tableRegions: filteredRegions) } } diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index 847525b53..b7985bae7 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -13,25 +13,14 @@ public struct DatabaseRegionObservation { /// `.observerLifetime`: the observation lasts until the /// observer returned by the `start(in:onChange:)` method /// is deallocated. - public var extent = Database.TransactionObservationExtent.observerLifetime + public var extent: Database.TransactionObservationExtent /// A closure that is evaluated when the observation starts, and returns /// the observed database region. var observedRegion: (Database) throws -> DatabaseRegion - - // Not public because we foster DatabaseRegionConvertible. - init(tracking region: @escaping (Database) throws -> DatabaseRegion) { - self.observedRegion = { db in - // Remove views from the observed region. - // - // We can do it because we are only interested in modifications in - // actual tables. And we want to do it because we have a fast path - // for simple regions that span a single table. - let views = try db.schema().names(ofType: .view) - return try region(db).ignoring(views) - } - } - +} + +extension DatabaseRegionObservation { /// Creates a DatabaseRegionObservation which observes *regions*, and /// notifies whenever one of the observed regions is modified by a /// database transaction. @@ -75,7 +64,9 @@ public struct DatabaseRegionObservation { /// /// - parameter regions: A list of observed regions. public init(tracking regions: [DatabaseRegionConvertible]) { - self.init(tracking: DatabaseRegion.union(regions)) + self.init( + extent: .observerLifetime, + observedRegion: DatabaseRegion.union(regions)) } } @@ -95,7 +86,7 @@ extension DatabaseRegionObservation { // Use unsafeReentrantWrite so that observation can start from any // dispatch queue. return try dbWriter.unsafeReentrantWrite { db -> TransactionObserver in - let region = try observedRegion(db) + let region = try observedRegion(db).ignoringViews(db) let observer = DatabaseRegionObserver(region: region, onChange: onChange) db.add(transactionObserver: observer, extent: extent) return observer diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 20da6b446..79fe742dc 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -363,7 +363,7 @@ extension DatabaseWriter { do { try unsafeReentrantWrite { db in - let region = try observation.observedRegion(db) + let region = try observation.observedRegion(db).ignoringViews(db) var reducer = try observation.makeReducer(db) // Fetch initial value @@ -385,7 +385,7 @@ extension DatabaseWriter { // has the default scheduling .mainQueue asyncWriteWithoutTransaction { db in do { - let region = try observation.observedRegion(db) + let region = try observation.observedRegion(db).ignoringViews(db) var reducer = try observation.makeReducer(db) // Fetch initial value @@ -412,7 +412,7 @@ extension DatabaseWriter { // Use case: observation must not block the target queue asyncWriteWithoutTransaction { db in do { - let region = try observation.observedRegion(db) + let region = try observation.observedRegion(db).ignoringViews(db) var reducer = try observation.makeReducer(db) // Fetch initial value @@ -458,7 +458,7 @@ extension DatabaseWriter { do { try unsafeReentrantWrite { db in - let region = try observation.observedRegion(db) + let region = try observation.observedRegion(db).ignoringViews(db) var reducer = try observation.makeReducer(db) // Fetch initial value @@ -484,7 +484,7 @@ extension DatabaseWriter { // queue on which the onChange and onError callbacks are called. asyncWriteWithoutTransaction { db in do { - let region = try observation.observedRegion(db) + let region = try observation.observedRegion(db).ignoringViews(db) let reducer = try observation.makeReducer(db) // Start observing the database diff --git a/GRDB/ValueObservation/ValueObservation+MapReducer.swift b/GRDB/ValueObservation/ValueObservation+MapReducer.swift index 0f9705c3b..33f440a0a 100644 --- a/GRDB/ValueObservation/ValueObservation+MapReducer.swift +++ b/GRDB/ValueObservation/ValueObservation+MapReducer.swift @@ -4,11 +4,10 @@ extension ValueObservation { /// Returns a ValueObservation with a transformed reducer. public func mapReducer(_ transform: @escaping (Database, Reducer) throws -> R) -> ValueObservation { let makeReducer = self.makeReducer - var observation = ValueObservation( - tracking: observedRegion, - reducer: { db in try transform(db, makeReducer(db)) }) - observation.scheduling = scheduling - observation.requiresWriteAccess = requiresWriteAccess - return observation + return ValueObservation( + observedRegion: observedRegion, + makeReducer: { db in try transform(db, makeReducer(db)) }, + requiresWriteAccess: requiresWriteAccess, + scheduling: scheduling) } } diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index c82e6e30d..d23fd0fd6 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -87,7 +87,7 @@ public struct ValueObservation { /// /// Don't set this flag to true unless you really need it. A read/write /// observation is less efficient than a read-only observation. - public var requiresWriteAccess: Bool = false + public var requiresWriteAccess: Bool /// `scheduling` controls how fresh values are notified. Default /// is `.mainQueue`. @@ -144,25 +144,7 @@ public struct ValueObservation { /// /// When the database changes, other values are notified on /// unspecified queues. - public var scheduling: ValueScheduling = .mainQueue - - // Not public because we foster DatabaseRegionConvertible. - // See ValueObservation.tracking(_:reducer:) - init( - tracking region: @escaping (Database) throws -> DatabaseRegion, - reducer: @escaping (Database) throws -> Reducer) - { - self.observedRegion = { db in - // Remove views from the observed region. - // - // We can do it because we are only interested in modifications in - // actual tables. And we want to do it because we have a fast path - // for simple regions that span a single table. - let views = try db.schema().names(ofType: .view) - return try region(db).ignoring(views) - } - self.makeReducer = reducer - } + public var scheduling: ValueScheduling } extension ValueObservation where Reducer: ValueReducer { @@ -323,8 +305,10 @@ extension ValueObservation { -> ValueObservation { return ValueObservation( - tracking: DatabaseRegion.union(regions), - reducer: reducer) + observedRegion: DatabaseRegion.union(regions), + makeReducer: reducer, + requiresWriteAccess: false, + scheduling: .mainQueue) } } @@ -396,7 +380,9 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> { return ValueObservation>( - tracking: DatabaseRegion.union(regions), - reducer: { _ in ValueReducers.Fetch(fetch) }) + observedRegion: DatabaseRegion.union(regions), + makeReducer: { _ in ValueReducers.Fetch(fetch) }, + requiresWriteAccess: false, + scheduling: .mainQueue) } } diff --git a/GRDB/ValueObservation/ValueReducer/Combine.swift b/GRDB/ValueObservation/ValueReducer/Combine.swift index d79736075..45f880777 100644 --- a/GRDB/ValueObservation/ValueReducer/Combine.swift +++ b/GRDB/ValueObservation/ValueReducer/Combine.swift @@ -51,12 +51,15 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> { return ValueObservation( - tracking: { try DatabaseRegion.union( + observedRegion: { try DatabaseRegion.union( o1.observedRegion($0), o2.observedRegion($0)) }, - reducer: { try ValueReducers.Combine2( + makeReducer: { try ValueReducers.Combine2( o1.makeReducer($0), - o2.makeReducer($0)) }) + o2.makeReducer($0)) }, + requiresWriteAccess: o1.requiresWriteAccess + || o2.requiresWriteAccess, + scheduling: .mainQueue) } } @@ -135,14 +138,18 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> { return ValueObservation( - tracking: { try DatabaseRegion.union( + observedRegion: { try DatabaseRegion.union( o1.observedRegion($0), o2.observedRegion($0), o3.observedRegion($0)) }, - reducer: { try ValueReducers.Combine3( + makeReducer: { try ValueReducers.Combine3( o1.makeReducer($0), o2.makeReducer($0), - o3.makeReducer($0)) }) + o3.makeReducer($0)) }, + requiresWriteAccess: o1.requiresWriteAccess + || o2.requiresWriteAccess + || o3.requiresWriteAccess, + scheduling: .mainQueue) } } @@ -238,16 +245,21 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> { return ValueObservation( - tracking: { try DatabaseRegion.union( + observedRegion: { try DatabaseRegion.union( o1.observedRegion($0), o2.observedRegion($0), o3.observedRegion($0), o4.observedRegion($0)) }, - reducer: { try ValueReducers.Combine4( + makeReducer: { try ValueReducers.Combine4( o1.makeReducer($0), o2.makeReducer($0), o3.makeReducer($0), - o4.makeReducer($0)) }) + o4.makeReducer($0)) }, + requiresWriteAccess: o1.requiresWriteAccess + || o2.requiresWriteAccess + || o3.requiresWriteAccess + || o4.requiresWriteAccess, + scheduling: .mainQueue) } } @@ -356,18 +368,24 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> { return ValueObservation( - tracking: { try DatabaseRegion.union( + observedRegion: { try DatabaseRegion.union( o1.observedRegion($0), o2.observedRegion($0), o3.observedRegion($0), o4.observedRegion($0), o5.observedRegion($0)) }, - reducer: { try ValueReducers.Combine5( + makeReducer: { try ValueReducers.Combine5( o1.makeReducer($0), o2.makeReducer($0), o3.makeReducer($0), o4.makeReducer($0), - o5.makeReducer($0)) }) + o5.makeReducer($0)) }, + requiresWriteAccess: o1.requiresWriteAccess + || o2.requiresWriteAccess + || o3.requiresWriteAccess + || o4.requiresWriteAccess + || o5.requiresWriteAccess, + scheduling: .mainQueue) } } @@ -489,20 +507,27 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> { return ValueObservation( - tracking: { try DatabaseRegion.union( + observedRegion: { try DatabaseRegion.union( o1.observedRegion($0), o2.observedRegion($0), o3.observedRegion($0), o4.observedRegion($0), o5.observedRegion($0), o6.observedRegion($0)) }, - reducer: { try ValueReducers.Combine6( + makeReducer: { try ValueReducers.Combine6( o1.makeReducer($0), o2.makeReducer($0), o3.makeReducer($0), o4.makeReducer($0), o5.makeReducer($0), - o6.makeReducer($0)) }) + o6.makeReducer($0)) }, + requiresWriteAccess: o1.requiresWriteAccess + || o2.requiresWriteAccess + || o3.requiresWriteAccess + || o4.requiresWriteAccess + || o5.requiresWriteAccess + || o6.requiresWriteAccess, + scheduling: .mainQueue) } } @@ -609,7 +634,7 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> { return ValueObservation( - tracking: { try DatabaseRegion.union( + observedRegion: { try DatabaseRegion.union( o1.observedRegion($0), o2.observedRegion($0), o3.observedRegion($0), @@ -617,14 +642,22 @@ extension ValueObservation where Reducer == Void { o5.observedRegion($0), o6.observedRegion($0), o7.observedRegion($0)) }, - reducer: { try ValueReducers.Combine7( + makeReducer: { try ValueReducers.Combine7( o1.makeReducer($0), o2.makeReducer($0), o3.makeReducer($0), o4.makeReducer($0), o5.makeReducer($0), o6.makeReducer($0), - o7.makeReducer($0)) }) + o7.makeReducer($0)) }, + requiresWriteAccess: o1.requiresWriteAccess + || o2.requiresWriteAccess + || o3.requiresWriteAccess + || o4.requiresWriteAccess + || o5.requiresWriteAccess + || o6.requiresWriteAccess + || o7.requiresWriteAccess, + scheduling: .mainQueue) } } @@ -742,7 +775,7 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> { return ValueObservation( - tracking: { try DatabaseRegion.union( + observedRegion: { try DatabaseRegion.union( o1.observedRegion($0), o2.observedRegion($0), o3.observedRegion($0), @@ -751,7 +784,7 @@ extension ValueObservation where Reducer == Void { o6.observedRegion($0), o7.observedRegion($0), o8.observedRegion($0)) }, - reducer: { try ValueReducers.Combine8( + makeReducer: { try ValueReducers.Combine8( o1.makeReducer($0), o2.makeReducer($0), o3.makeReducer($0), @@ -759,6 +792,15 @@ extension ValueObservation where Reducer == Void { o5.makeReducer($0), o6.makeReducer($0), o7.makeReducer($0), - o8.makeReducer($0)) }) + o8.makeReducer($0)) }, + requiresWriteAccess: o1.requiresWriteAccess + || o2.requiresWriteAccess + || o3.requiresWriteAccess + || o4.requiresWriteAccess + || o5.requiresWriteAccess + || o6.requiresWriteAccess + || o7.requiresWriteAccess + || o8.requiresWriteAccess, + scheduling: .mainQueue) } } From a5c8f23ba447c9bc0c7e0d6a83d4cc2846df0a9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 3 Aug 2019 16:32:33 +0200 Subject: [PATCH 63/91] Support for variable observed region of ValueObservation based on actual selection --- GRDB.xcodeproj/project.pbxproj | 6 + GRDB/Core/Database+Statements.swift | 7 + GRDB/Core/Database.swift | 31 ++++- GRDB/Core/DatabaseValueConvertible.swift | 6 + GRDB/Core/DatabaseWriter.swift | 125 +++++++++++------- GRDB/Core/Row.swift | 3 + GRDB/Core/Statement.swift | 3 + GRDB/Core/StatementColumnConvertible.swift | 6 + GRDB/Record/FetchableRecord.swift | 3 + .../ValueObservation+MapReducer.swift | 3 +- GRDB/ValueObservation/ValueObservation.swift | 54 +++++++- GRDB/ValueObservation/ValueObserver.swift | 68 +++++++++- .../ValueReducer/Combine.swift | 119 +++++++++++------ .../ValueReducer/ValueReducer.swift | 19 --- GRDBCustom.xcodeproj/project.pbxproj | 6 + .../GRDBTests.xcodeproj/project.pbxproj | 12 +- .../GRDBTests.xcodeproj/project.pbxproj | 12 +- ...rvationDatabaseValueConvertibleTests.swift | 2 +- ...ValueObservationRegionRecordingTests.swift | 91 +++++++++++++ 19 files changed, 449 insertions(+), 127 deletions(-) create mode 100644 Tests/GRDBTests/ValueObservationRegionRecordingTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index c9803add0..8e93a465e 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -461,6 +461,8 @@ 5674A7231F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */; }; 5674A72A1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; 5674A72D1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; + 5676FBA622F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FB9F22F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift */; }; + 5676FBA722F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FB9F22F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift */; }; 567A80571D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; 567DAF1C1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; }; 567DAF1F1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; }; @@ -1129,6 +1131,7 @@ 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEncodableTests.swift; sourceTree = ""; }; 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordEncodableTests.swift; sourceTree = ""; }; 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchableRecordDecodableTests.swift; sourceTree = ""; }; + 5676FB9F22F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = ""; }; 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; 567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = ""; }; 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = ""; }; @@ -1628,6 +1631,7 @@ 563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */, 563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */, 563B06BC2185CCD300B38F35 /* ValueObservationReducerTests.swift */, + 5676FB9F22F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift */, 563B0704218627F700B38F35 /* ValueObservationRowTests.swift */, 563B06C12185D29F00B38F35 /* ValueObservationSchedulingTests.swift */, ); @@ -3092,6 +3096,7 @@ 568068351EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 565D5D751BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */, 56703298212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, + 5676FBA722F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 5623931C1DECC02000A6B01F /* RowFetchTests.swift in Sources */, 5653EAD720944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */, 569BBA28228DE51800478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, @@ -3291,6 +3296,7 @@ 5623934E1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, 568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, + 5676FBA622F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */, 56D496951D81317B008276D7 /* MutablePersistableRecordTests.swift in Sources */, 569BBA27228DE51800478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 98de74548..e0eefa72e 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -288,6 +288,13 @@ extension Database { try observationBroker.updateStatementDidFail(statement) } + @inline(__always) + func selectStatementWillExecute(_ statement: SelectStatement) { + if _isRecordingSelectedRegion { + _selectedRegion.formUnion(statement.databaseRegion) + } + } + func selectStatementDidFail(_ statement: SelectStatement) { // Failed statements can not be reused, because sqlite3_reset won't // be able to restore the statement to its initial state: diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 95c6d3e5a..f6e29f84c 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -129,8 +129,8 @@ public final class Database { var lastErrorCode: ResultCode { return ResultCode(rawValue: sqlite3_errcode(sqliteConnection)) } var lastErrorMessage: String? { return String(cString: sqlite3_errmsg(sqliteConnection)) } - // Statement authorizer. Use withAuthorizer(_:_:). - fileprivate var _authorizer: StatementAuthorizer? // + /// Statement authorizer. Use withAuthorizer(_:_:). + fileprivate var _authorizer: StatementAuthorizer? // Transaction observers management lazy var observationBroker = DatabaseObservationBroker(self) @@ -140,6 +140,11 @@ public final class Database { try! Set(String.fetchCursor($0, sql: "PRAGMA COMPILE_OPTIONS")) } + /// If true, select statement execution is recorded. + /// Use recordingSelectedRegion(_:), see `selectStatementWillExecute(_:)` + var _isRecordingSelectedRegion: Bool = false + var _selectedRegion = DatabaseRegion() + // MARK: - Private properties private var busyCallback: BusyCallback? @@ -616,6 +621,28 @@ extension Database { } } +extension Database { + + // MARK: - Recording of the selected region + + func recordingSelectedRegion(_ block: () throws -> T) rethrows -> (T, DatabaseRegion) { + SchedulingWatchdog.preconditionValidQueue(self) + let oldFlag = self._isRecordingSelectedRegion + let oldRegion = self._selectedRegion + self._isRecordingSelectedRegion = true + self._selectedRegion = DatabaseRegion() + defer { + self._isRecordingSelectedRegion = oldFlag + if self._isRecordingSelectedRegion { + self._selectedRegion = oldRegion.union(self._selectedRegion) + } else { + self._selectedRegion = oldRegion + } + } + return try (block(), _selectedRegion) + } +} + extension Database { // MARK: - Transactions & Savepoint diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 936b1da73..6836906f6 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -65,6 +65,9 @@ public final class DatabaseValueCursor: Cursor _columnIndex = 0 } _statement.reset(withArguments: arguments) + + // Assume cursor is created for iteration + statement.database.selectStatementWillExecute(statement) } deinit { @@ -118,6 +121,9 @@ public final class NullableDatabaseValueCursor: _columnIndex = 0 } _statement.reset(withArguments: arguments) + + // Assume cursor is created for iteration + statement.database.selectStatementWillExecute(statement) } deinit { diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 79fe742dc..ec6d88065 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -343,6 +343,7 @@ extension DatabaseWriter { let requiresWriteAccess = observation.requiresWriteAccess let observer = ValueObserver( requiresWriteAccess: requiresWriteAccess, + observesSelectedRegion: observation.observesSelectedRegion, writer: self, reduceQueue: configuration.makeDispatchQueue(defaultLabel: "GRDB", purpose: "ValueObservation.reducer"), onError: onError, @@ -363,18 +364,23 @@ extension DatabaseWriter { do { try unsafeReentrantWrite { db in - let region = try observation.observedRegion(db).ignoringViews(db) - var reducer = try observation.makeReducer(db) + observer.notificationQueue = DispatchQueue.main + observer.baseRegion = try observation.baseRegion(db).ignoringViews(db) + observer.reducer = try observation.makeReducer(db) - // Fetch initial value - if let value = try reducer.value(reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)) { + // Initial value & selected region + let fetchedValue: Reducer.Fetched + if observation.observesSelectedRegion { + (fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion { + try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + } + } else { + fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + } + if let value = observer.reducer.value(fetchedValue) { startValue = value } - - // Start observing the database - observer.region = region - observer.reducer = reducer - observer.notificationQueue = DispatchQueue.main + db.add(transactionObserver: observer, extent: .observerLifetime) } } catch { @@ -385,20 +391,25 @@ extension DatabaseWriter { // has the default scheduling .mainQueue asyncWriteWithoutTransaction { db in do { - let region = try observation.observedRegion(db).ignoringViews(db) - var reducer = try observation.makeReducer(db) + observer.notificationQueue = DispatchQueue.main + observer.baseRegion = try observation.baseRegion(db).ignoringViews(db) + observer.reducer = try observation.makeReducer(db) - // Fetch initial value - if let value = try reducer.value(reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)) { + // Initial value & selected region + let fetchedValue: Reducer.Fetched + if observation.observesSelectedRegion { + (fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion { + try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + } + } else { + fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + } + if let value = observer.reducer.value(fetchedValue) { DispatchQueue.main.async { onChange(value) } } - // Start observing the database - observer.region = region - observer.reducer = reducer - observer.notificationQueue = DispatchQueue.main db.add(transactionObserver: observer, extent: .observerLifetime) } catch { DispatchQueue.main.async { @@ -412,22 +423,31 @@ extension DatabaseWriter { // Use case: observation must not block the target queue asyncWriteWithoutTransaction { db in do { - let region = try observation.observedRegion(db).ignoringViews(db) - var reducer = try observation.makeReducer(db) + observer.notificationQueue = queue + observer.baseRegion = try observation.baseRegion(db).ignoringViews(db) + observer.reducer = try observation.makeReducer(db) - // Fetch initial value - if startImmediately, - let value = try reducer.value(reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)) - { - queue.async { - onChange(value) + // Initial value & selected region + if startImmediately { + let fetchedValue: Reducer.Fetched + if observation.observesSelectedRegion { + (fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion { + try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + } + } else { + fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + } + if let value = observer.reducer.value(fetchedValue) { + queue.async { + onChange(value) + } + } + } else if observation.observesSelectedRegion { + (_, observer.selectedRegion) = try db.recordingSelectedRegion { + try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) } } - // Start observing the database - observer.region = region - observer.reducer = reducer - observer.notificationQueue = queue db.add(transactionObserver: observer, extent: .observerLifetime) } catch { queue.async { @@ -458,20 +478,29 @@ extension DatabaseWriter { do { try unsafeReentrantWrite { db in - let region = try observation.observedRegion(db).ignoringViews(db) - var reducer = try observation.makeReducer(db) + observer.notificationQueue = nil + observer.baseRegion = try observation.baseRegion(db).ignoringViews(db) + observer.reducer = try observation.makeReducer(db) - // Fetch initial value - if startImmediately, - let value = try reducer.value(reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)) - { - startValue = value + // Initial value & selected region + if startImmediately { + let fetchedValue: Reducer.Fetched + if observation.observesSelectedRegion { + (fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion { + try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + } + } else { + fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + } + if let value = observer.reducer.value(fetchedValue) { + startValue = value + } + } else if observation.observesSelectedRegion { + (_, observer.selectedRegion) = try db.recordingSelectedRegion { + try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + } } - // Start observing the database - observer.region = region - observer.reducer = reducer - observer.notificationQueue = nil db.add(transactionObserver: observer, extent: .observerLifetime) } } catch { @@ -484,13 +513,17 @@ extension DatabaseWriter { // queue on which the onChange and onError callbacks are called. asyncWriteWithoutTransaction { db in do { - let region = try observation.observedRegion(db).ignoringViews(db) - let reducer = try observation.makeReducer(db) - - // Start observing the database - observer.region = region - observer.reducer = reducer observer.notificationQueue = nil + observer.baseRegion = try observation.baseRegion(db).ignoringViews(db) + observer.reducer = try observation.makeReducer(db) + + // Selected region + if observation.observesSelectedRegion { + (_, observer.selectedRegion) = try db.recordingSelectedRegion { + try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + } + } + db.add(transactionObserver: observer, extent: .observerLifetime) } catch { onError(error) diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 7f8c0d4ff..d0328e5af 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -790,6 +790,9 @@ public final class RowCursor: Cursor { self._row = try Row(statement: statement).adapted(with: adapter, layout: statement) self._sqliteStatement = statement.sqliteStatement statement.reset(withArguments: arguments) + + // Assume cursor is created for iteration + statement.database.selectStatementWillExecute(statement) } deinit { diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 772025711..991ca93f1 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -384,6 +384,9 @@ final class StatementCursor: Cursor { _statement = statement _sqliteStatement = statement.sqliteStatement _statement.reset(withArguments: arguments) + + // Assume cursor is created for iteration + statement.database.selectStatementWillExecute(statement) } deinit { diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 734acdb3f..dd0077f59 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -77,6 +77,9 @@ public final class FastDatabaseValueCursor: Cursor _columnIndex = 0 } _statement.reset(withArguments: arguments) + + // Assume cursor is created for iteration + statement.database.selectStatementWillExecute(statement) } deinit { diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index b0e44598c..7dbb8b73f 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -429,6 +429,9 @@ public final class RecordCursor: Cursor { _row = try Row(statement: statement).adapted(with: adapter, layout: statement) _sqliteStatement = statement.sqliteStatement _statement.reset(withArguments: arguments) + + // Assume cursor is created for iteration + statement.database.selectStatementWillExecute(statement) } deinit { diff --git a/GRDB/ValueObservation/ValueObservation+MapReducer.swift b/GRDB/ValueObservation/ValueObservation+MapReducer.swift index 33f440a0a..b40084420 100644 --- a/GRDB/ValueObservation/ValueObservation+MapReducer.swift +++ b/GRDB/ValueObservation/ValueObservation+MapReducer.swift @@ -5,7 +5,8 @@ extension ValueObservation { public func mapReducer(_ transform: @escaping (Database, Reducer) throws -> R) -> ValueObservation { let makeReducer = self.makeReducer return ValueObservation( - observedRegion: observedRegion, + baseRegion: baseRegion, + observesSelectedRegion: observesSelectedRegion, makeReducer: { db in try transform(db, makeReducer(db)) }, requiresWriteAccess: requiresWriteAccess, scheduling: scheduling) diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index d23fd0fd6..16f20eb10 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -74,9 +74,15 @@ public enum ValueScheduling { /// } public struct ValueObservation { /// A closure that is evaluated when the observation starts, and returns - /// the observed database region. - var observedRegion: (Database) throws -> DatabaseRegion + /// a "base" observed database region. + /// + /// See also `observesSelectedRegion` + var baseRegion: (Database) throws -> DatabaseRegion + /// If true, the region selected by the reducer is observed as well + /// as `baseRegion`. + var observesSelectedRegion: Bool + /// The reducer is created when observation starts, and is triggered upon /// each database change in *observedRegion*. var makeReducer: (Database) throws -> Reducer @@ -221,7 +227,7 @@ private class ErrorCatcher { var error: Error? } -extension ValueObservation { +extension ValueObservation where Reducer: ValueReducer { // MARK: - Creating ValueObservation from ValueReducer @@ -305,7 +311,8 @@ extension ValueObservation { -> ValueObservation { return ValueObservation( - observedRegion: DatabaseRegion.union(regions), + baseRegion: DatabaseRegion.union(regions), + observesSelectedRegion: false, makeReducer: reducer, requiresWriteAccess: false, scheduling: .mainQueue) @@ -316,6 +323,42 @@ extension ValueObservation where Reducer == Void { // MARK: - Creating ValueObservation from Fetch Closures + /// Creates a ValueObservation which notifies the values returned by the + /// *fetch* closure whenever a database transaction changes them. + /// + /// For example: + /// + /// let observation = ValueObservation.tracking { db in + /// try Player.fetchAll(db) + /// } + /// + /// let observer = try observation.start(in: dbQueue) { players: [Player] in + /// print("Players have changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter regions: A list of observed regions. + /// - parameter fetch: A closure that fetches a value. + public static func tracking( + fetch: @escaping (Database) throws -> Value) + -> ValueObservation> + { + return ValueObservation>( + baseRegion: { _ in DatabaseRegion() }, + observesSelectedRegion: true, + makeReducer: { _ in ValueReducers.Fetch(fetch) }, + requiresWriteAccess: false, + scheduling: .mainQueue) + } + /// Creates a ValueObservation which observes *regions*, and notifies the /// values returned by the *fetch* closure whenever one of the observed /// regions is modified by a database transaction. @@ -380,7 +423,8 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> { return ValueObservation>( - observedRegion: DatabaseRegion.union(regions), + baseRegion: DatabaseRegion.union(regions), + observesSelectedRegion: false, makeReducer: { _ in ValueReducers.Fetch(fetch) }, requiresWriteAccess: false, scheduling: .mainQueue) diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift index 27eab3e17..78954e043 100644 --- a/GRDB/ValueObservation/ValueObserver.swift +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -3,13 +3,20 @@ import Foundation /// Support for ValueObservation. /// See DatabaseWriter.add(observation:onError:onChange:) class ValueObserver: TransactionObserver { - // Region, reducer, and notificationQueue must be set before observer is + // Reducer and notificationQueue must be set before observer is // added to a database. - var region: DatabaseRegion! var reducer: Reducer! var notificationQueue: DispatchQueue? + var baseRegion = DatabaseRegion() { + didSet { observedRegion = baseRegion.union(selectedRegion) } + } + var selectedRegion = DatabaseRegion() { + didSet { observedRegion = baseRegion.union(selectedRegion) } + } + var observedRegion: DatabaseRegion! // internal for testability private var requiresWriteAccess: Bool + private var observesSelectedRegion: Bool private unowned var writer: DatabaseWriter private let reduceQueue: DispatchQueue private let onError: (Error) -> Void @@ -19,6 +26,7 @@ class ValueObserver: TransactionObserver { init( requiresWriteAccess: Bool, + observesSelectedRegion: Bool, writer: DatabaseWriter, reduceQueue: DispatchQueue, onError: @escaping (Error) -> Void, @@ -26,6 +34,7 @@ class ValueObserver: TransactionObserver { { self.writer = writer self.requiresWriteAccess = requiresWriteAccess + self.observesSelectedRegion = observesSelectedRegion self.reduceQueue = reduceQueue self.onError = onError self.onChange = onChange @@ -37,12 +46,12 @@ class ValueObserver: TransactionObserver { func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { if isCancelled { return false } - return region.isModified(byEventsOfKind: eventKind) + return observedRegion.isModified(byEventsOfKind: eventKind) } func databaseDidChange(with event: DatabaseEvent) { if isCancelled { return } - if region.isModified(by: event) { + if observedRegion.isModified(by: event) { isChanged = true stopObservingDatabaseChangesUntilNextTransaction() } @@ -54,7 +63,56 @@ class ValueObserver: TransactionObserver { isChanged = false // Grab future fetched value - let future = reducer.fetchFuture(db, writer: writer, requiringWriteAccess: requiresWriteAccess) + let future: DatabaseFuture + if requiresWriteAccess { + // Synchronous read/write fetch + if observesSelectedRegion { + do { + var fetchedValue: Reducer.Fetched! + var selectedRegion: DatabaseRegion! + try db.inTransaction { + let (_fetchedValue, _selectedRegion) = try db.recordingSelectedRegion { + try reducer.fetch(db) + } + fetchedValue = _fetchedValue + selectedRegion = _selectedRegion + return .commit + } + self.selectedRegion = selectedRegion + future = DatabaseFuture(Result.success(fetchedValue)) + } catch { + future = DatabaseFuture(Result.failure(error)) + } + } else { + // Synchronous read/write fetch + future = DatabaseFuture(DatabaseResult { + var fetchedValue: Reducer.Fetched! + try db.inTransaction { + fetchedValue = try reducer.fetch(db) + return .commit + } + return fetchedValue + }) + } + } else { + if observesSelectedRegion { + // Synchronous read-only fetch + do { + let (fetchedValue, selectedRegion) = try db.readOnly { + try db.recordingSelectedRegion { + try reducer.fetch(db) + } + } + self.selectedRegion = selectedRegion + future = DatabaseFuture(Result.success(fetchedValue)) + } catch { + future = DatabaseFuture(Result.failure(error)) + } + } else { + // Concurrent fetch + future = writer.concurrentRead(reducer.fetch) + } + } // Wait for future fetched value in reduceQueue. This guarantees: // - that notifications have the same ordering as transactions. diff --git a/GRDB/ValueObservation/ValueReducer/Combine.swift b/GRDB/ValueObservation/ValueReducer/Combine.swift index 45f880777..d15cd102f 100644 --- a/GRDB/ValueObservation/ValueReducer/Combine.swift +++ b/GRDB/ValueObservation/ValueReducer/Combine.swift @@ -51,9 +51,11 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> { return ValueObservation( - observedRegion: { try DatabaseRegion.union( - o1.observedRegion($0), - o2.observedRegion($0)) }, + baseRegion: { try DatabaseRegion.union( + o1.baseRegion($0), + o2.baseRegion($0)) }, + observesSelectedRegion: o1.observesSelectedRegion + || o2.observesSelectedRegion, makeReducer: { try ValueReducers.Combine2( o1.makeReducer($0), o2.makeReducer($0)) }, @@ -138,10 +140,13 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> { return ValueObservation( - observedRegion: { try DatabaseRegion.union( - o1.observedRegion($0), - o2.observedRegion($0), - o3.observedRegion($0)) }, + baseRegion: { try DatabaseRegion.union( + o1.baseRegion($0), + o2.baseRegion($0), + o3.baseRegion($0)) }, + observesSelectedRegion: o1.observesSelectedRegion + || o2.observesSelectedRegion + || o3.observesSelectedRegion, makeReducer: { try ValueReducers.Combine3( o1.makeReducer($0), o2.makeReducer($0), @@ -245,11 +250,15 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> { return ValueObservation( - observedRegion: { try DatabaseRegion.union( - o1.observedRegion($0), - o2.observedRegion($0), - o3.observedRegion($0), - o4.observedRegion($0)) }, + baseRegion: { try DatabaseRegion.union( + o1.baseRegion($0), + o2.baseRegion($0), + o3.baseRegion($0), + o4.baseRegion($0)) }, + observesSelectedRegion: o1.observesSelectedRegion + || o2.observesSelectedRegion + || o3.observesSelectedRegion + || o4.observesSelectedRegion, makeReducer: { try ValueReducers.Combine4( o1.makeReducer($0), o2.makeReducer($0), @@ -368,12 +377,17 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> { return ValueObservation( - observedRegion: { try DatabaseRegion.union( - o1.observedRegion($0), - o2.observedRegion($0), - o3.observedRegion($0), - o4.observedRegion($0), - o5.observedRegion($0)) }, + baseRegion: { try DatabaseRegion.union( + o1.baseRegion($0), + o2.baseRegion($0), + o3.baseRegion($0), + o4.baseRegion($0), + o5.baseRegion($0)) }, + observesSelectedRegion: o1.observesSelectedRegion + || o2.observesSelectedRegion + || o3.observesSelectedRegion + || o4.observesSelectedRegion + || o5.observesSelectedRegion, makeReducer: { try ValueReducers.Combine5( o1.makeReducer($0), o2.makeReducer($0), @@ -507,13 +521,19 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> { return ValueObservation( - observedRegion: { try DatabaseRegion.union( - o1.observedRegion($0), - o2.observedRegion($0), - o3.observedRegion($0), - o4.observedRegion($0), - o5.observedRegion($0), - o6.observedRegion($0)) }, + baseRegion: { try DatabaseRegion.union( + o1.baseRegion($0), + o2.baseRegion($0), + o3.baseRegion($0), + o4.baseRegion($0), + o5.baseRegion($0), + o6.baseRegion($0)) }, + observesSelectedRegion: o1.observesSelectedRegion + || o2.observesSelectedRegion + || o3.observesSelectedRegion + || o4.observesSelectedRegion + || o5.observesSelectedRegion + || o6.observesSelectedRegion, makeReducer: { try ValueReducers.Combine6( o1.makeReducer($0), o2.makeReducer($0), @@ -634,14 +654,21 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> { return ValueObservation( - observedRegion: { try DatabaseRegion.union( - o1.observedRegion($0), - o2.observedRegion($0), - o3.observedRegion($0), - o4.observedRegion($0), - o5.observedRegion($0), - o6.observedRegion($0), - o7.observedRegion($0)) }, + baseRegion: { try DatabaseRegion.union( + o1.baseRegion($0), + o2.baseRegion($0), + o3.baseRegion($0), + o4.baseRegion($0), + o5.baseRegion($0), + o6.baseRegion($0), + o7.baseRegion($0)) }, + observesSelectedRegion: o1.observesSelectedRegion + || o2.observesSelectedRegion + || o3.observesSelectedRegion + || o4.observesSelectedRegion + || o5.observesSelectedRegion + || o6.observesSelectedRegion + || o7.observesSelectedRegion, makeReducer: { try ValueReducers.Combine7( o1.makeReducer($0), o2.makeReducer($0), @@ -775,15 +802,23 @@ extension ValueObservation where Reducer == Void { -> ValueObservation> { return ValueObservation( - observedRegion: { try DatabaseRegion.union( - o1.observedRegion($0), - o2.observedRegion($0), - o3.observedRegion($0), - o4.observedRegion($0), - o5.observedRegion($0), - o6.observedRegion($0), - o7.observedRegion($0), - o8.observedRegion($0)) }, + baseRegion: { try DatabaseRegion.union( + o1.baseRegion($0), + o2.baseRegion($0), + o3.baseRegion($0), + o4.baseRegion($0), + o5.baseRegion($0), + o6.baseRegion($0), + o7.baseRegion($0), + o8.baseRegion($0)) }, + observesSelectedRegion: o1.observesSelectedRegion + || o2.observesSelectedRegion + || o3.observesSelectedRegion + || o4.observesSelectedRegion + || o5.observesSelectedRegion + || o6.observesSelectedRegion + || o7.observesSelectedRegion + || o8.observesSelectedRegion, makeReducer: { try ValueReducers.Combine8( o1.makeReducer($0), o2.makeReducer($0), diff --git a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift index f77027198..198a9b611 100644 --- a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift +++ b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift @@ -34,25 +34,6 @@ extension ValueReducer { } } } - - /// Synchronous or asynchronous fetch - /// Support for ValueObserver - func fetchFuture(_ db: Database, writer: DatabaseWriter, requiringWriteAccess: Bool) -> DatabaseFuture { - if requiringWriteAccess { - // Synchronous fetch - return DatabaseFuture(DatabaseResult { - var fetchedValue: Fetched! - try db.inTransaction { - fetchedValue = try fetch(db) - return .commit - } - return fetchedValue - }) - } else { - // Concurrent fetch - return writer.concurrentRead(fetch) - } - } } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index ead8fd693..a25ad20d2 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -303,6 +303,8 @@ 5674A71F1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */; }; 5674A7271F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; 5674A7291F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; + 5676FBAA22F5CEB9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBA822F5CEB8004717D9 /* ValueObservationRegionRecordingTests.swift */; }; + 5676FBAB22F5CEB9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBA822F5CEB8004717D9 /* ValueObservationRegionRecordingTests.swift */; }; 567A80561D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; 567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; 567DAF1E1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; }; @@ -886,6 +888,7 @@ 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEncodableTests.swift; sourceTree = ""; }; 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordEncodableTests.swift; sourceTree = ""; }; 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchableRecordDecodableTests.swift; sourceTree = ""; }; + 5676FBA822F5CEB8004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = ""; }; 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; 567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = ""; }; 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = ""; }; @@ -1312,6 +1315,7 @@ 563B06CD2185E04600B38F35 /* ValueObservationReadonlyTests.swift */, 563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */, 563B06CF2185E04600B38F35 /* ValueObservationReducerTests.swift */, + 5676FBA822F5CEB8004717D9 /* ValueObservationRegionRecordingTests.swift */, 563B0701218627DE00B38F35 /* ValueObservationRowTests.swift */, 563B06D02185E04600B38F35 /* ValueObservationSchedulingTests.swift */, ); @@ -2416,6 +2420,7 @@ 56DF0018228DDB8300D611F3 /* AssociationPrefetchingRowTests.swift in Sources */, F3BA80541CFB2B59003DC1BA /* DatabaseRegionTests.swift in Sources */, 567DAF3C1EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */, + 5676FBAB22F5CEB9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 566A84442041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, F3BA81171CFB305E003DC1BA /* QueryInterfaceExpressionsTests.swift in Sources */, 569BBA2C228DE53200478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, @@ -2747,6 +2752,7 @@ 56DF0017228DDB8300D611F3 /* AssociationPrefetchingRowTests.swift in Sources */, F3BA812E1CFB3064003DC1BA /* RecordPrimaryKeyMultipleTests.swift in Sources */, F3BA81021CFB3032003DC1BA /* CGFloatTests.swift in Sources */, + 5676FBAA22F5CEB9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 566A84432041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */, 569BBA2B228DE53200478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index c3bfffee0..b68c3c6f9 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 50; + objectVersion = 51; objects = { /* Begin PBXBuildFile section */ @@ -383,13 +383,15 @@ 564A2151226B8E18001F64F1 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 564A1F6F226B89D6001F64F1 /* Betty.jpeg */; }; 5656A802229474DD001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A801229474DC001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; }; 5656A803229474DD001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A801229474DC001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; }; + 5676FBB022F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBAF22F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift */; }; + 5676FBB122F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBAF22F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift */; }; 569BBA31228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA30228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift */; }; 569BBA32228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA30228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift */; }; 56DF0027228DE00900D611F3 /* AssociationPrefetchingCodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0025228DE00900D611F3 /* AssociationPrefetchingCodableRecordTests.swift */; }; 56DF0028228DE00900D611F3 /* AssociationPrefetchingCodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0025228DE00900D611F3 /* AssociationPrefetchingCodableRecordTests.swift */; }; 56DF0029228DE00900D611F3 /* AssociationPrefetchingRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0026228DE00900D611F3 /* AssociationPrefetchingRowTests.swift */; }; 56DF002A228DE00900D611F3 /* AssociationPrefetchingRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0026228DE00900D611F3 /* AssociationPrefetchingRowTests.swift */; }; - 5B33E6E34F941B4C839A714F /* BuildFile in Frameworks */ = {isa = PBXBuildFile; }; + 5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; }; 98AB0B01EB11B33719AE412E /* Pods_GRDBTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FE2436BF42B9FCD6552E7076 /* Pods_GRDBTests.framework */; }; F2B3C4250D67969FF3948955 /* Pods_GRDBTestsEncrypted.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */; }; /* End PBXBuildFile section */ @@ -589,6 +591,7 @@ 564A1FDD226B89E1001F64F1 /* FTS5RecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5RecordTests.swift; sourceTree = ""; }; 564A2156226B8E18001F64F1 /* GRDBTestsEncrypted.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTestsEncrypted.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 5656A801229474DC001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationQueryInterfaceRequestTests.swift; sourceTree = ""; }; + 5676FBAF22F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = ""; }; 569BBA30228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingFetchableRecordTests.swift; sourceTree = ""; }; 56DF0025228DE00900D611F3 /* AssociationPrefetchingCodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingCodableRecordTests.swift; sourceTree = ""; }; 56DF0026228DE00900D611F3 /* AssociationPrefetchingRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRowTests.swift; sourceTree = ""; }; @@ -603,7 +606,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 5B33E6E34F941B4C839A714F /* BuildFile in Frameworks */, + 5B33E6E34F941B4C839A714F /* (null) in Frameworks */, 98AB0B01EB11B33719AE412E /* Pods_GRDBTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; @@ -831,6 +834,7 @@ 564A1F85226B89D8001F64F1 /* ValueObservationReadonlyTests.swift */, 564A1F44226B89D0001F64F1 /* ValueObservationRecordTests.swift */, 564A1F87226B89D8001F64F1 /* ValueObservationReducerTests.swift */, + 5676FBAF22F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift */, 564A1F9C226B89DA001F64F1 /* ValueObservationRowTests.swift */, 564A1F48226B89D1001F64F1 /* ValueObservationSchedulingTests.swift */, 564A1FBA226B89DD001F64F1 /* VirtualTableModuleTests.swift */, @@ -1097,6 +1101,7 @@ 564A2078226B89E1001F64F1 /* ForeignKeyInfoTests.swift in Sources */, 564A2050226B89E1001F64F1 /* RecordPrimaryKeySingleTests.swift in Sources */, 564A2091226B89E1001F64F1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, + 5676FBB022F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 564A208F226B89E1001F64F1 /* AssociationParallelRowScopesTests.swift in Sources */, 564A2047226B89E1001F64F1 /* AnyCursorTests.swift in Sources */, 564A1FFC226B89E1001F64F1 /* DatabaseValueTests.swift in Sources */, @@ -1294,6 +1299,7 @@ 564A20CE226B8E18001F64F1 /* ForeignKeyInfoTests.swift in Sources */, 564A20CF226B8E18001F64F1 /* RecordPrimaryKeySingleTests.swift in Sources */, 564A20D0226B8E18001F64F1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, + 5676FBB122F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 564A20D1226B8E18001F64F1 /* AssociationParallelRowScopesTests.swift in Sources */, 564A20D2226B8E18001F64F1 /* AnyCursorTests.swift in Sources */, 564A20D3226B8E18001F64F1 /* DatabaseValueTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index 83c84248a..573504ba6 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 50; + objectVersion = 51; objects = { /* Begin PBXBuildFile section */ @@ -385,13 +385,15 @@ 564A215A226C8F25001F64F1 /* db.SQLCipher3 in Resources */ = {isa = PBXBuildFile; fileRef = 564A2158226C8F24001F64F1 /* db.SQLCipher3 */; }; 5656A805229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A804229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; }; 5656A806229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A804229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; }; + 5676FBAD22F5CEF6004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBAC22F5CEF5004717D9 /* ValueObservationRegionRecordingTests.swift */; }; + 5676FBAE22F5CEF6004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBAC22F5CEF5004717D9 /* ValueObservationRegionRecordingTests.swift */; }; 569BBA2E228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA2D228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift */; }; 569BBA2F228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA2D228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift */; }; 56DF0021228DDFF000D611F3 /* AssociationPrefetchingRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF001F228DDFF000D611F3 /* AssociationPrefetchingRowTests.swift */; }; 56DF0022228DDFF000D611F3 /* AssociationPrefetchingRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF001F228DDFF000D611F3 /* AssociationPrefetchingRowTests.swift */; }; 56DF0023228DDFF000D611F3 /* AssociationPrefetchingCodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0020228DDFF000D611F3 /* AssociationPrefetchingCodableRecordTests.swift */; }; 56DF0024228DDFF000D611F3 /* AssociationPrefetchingCodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0020228DDFF000D611F3 /* AssociationPrefetchingCodableRecordTests.swift */; }; - 5B33E6E34F941B4C839A714F /* BuildFile in Frameworks */ = {isa = PBXBuildFile; }; + 5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; }; E158370AAEED49ECD53CE24A /* Pods_GRDBTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 67377FE4CDAD675809F93AD4 /* Pods_GRDBTests.framework */; }; F2B3C4250D67969FF3948955 /* Pods_GRDBTestsEncrypted.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */; }; /* End PBXBuildFile section */ @@ -592,6 +594,7 @@ 564A2156226B8E18001F64F1 /* GRDBTestsEncrypted.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTestsEncrypted.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 564A2158226C8F24001F64F1 /* db.SQLCipher3 */ = {isa = PBXFileReference; lastKnownFileType = file; path = db.SQLCipher3; sourceTree = SOURCE_ROOT; }; 5656A804229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationQueryInterfaceRequestTests.swift; sourceTree = ""; }; + 5676FBAC22F5CEF5004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = ""; }; 569BBA2D228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingFetchableRecordTests.swift; sourceTree = ""; }; 56DF001F228DDFF000D611F3 /* AssociationPrefetchingRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRowTests.swift; sourceTree = ""; }; 56DF0020228DDFF000D611F3 /* AssociationPrefetchingCodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingCodableRecordTests.swift; sourceTree = ""; }; @@ -606,7 +609,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 5B33E6E34F941B4C839A714F /* BuildFile in Frameworks */, + 5B33E6E34F941B4C839A714F /* (null) in Frameworks */, E158370AAEED49ECD53CE24A /* Pods_GRDBTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; @@ -835,6 +838,7 @@ 564A1F85226B89D8001F64F1 /* ValueObservationReadonlyTests.swift */, 564A1F44226B89D0001F64F1 /* ValueObservationRecordTests.swift */, 564A1F87226B89D8001F64F1 /* ValueObservationReducerTests.swift */, + 5676FBAC22F5CEF5004717D9 /* ValueObservationRegionRecordingTests.swift */, 564A1F9C226B89DA001F64F1 /* ValueObservationRowTests.swift */, 564A1F48226B89D1001F64F1 /* ValueObservationSchedulingTests.swift */, 564A1FBA226B89DD001F64F1 /* VirtualTableModuleTests.swift */, @@ -1103,6 +1107,7 @@ 564A2078226B89E1001F64F1 /* ForeignKeyInfoTests.swift in Sources */, 564A2050226B89E1001F64F1 /* RecordPrimaryKeySingleTests.swift in Sources */, 564A2091226B89E1001F64F1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, + 5676FBAD22F5CEF6004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 564A208F226B89E1001F64F1 /* AssociationParallelRowScopesTests.swift in Sources */, 564A2047226B89E1001F64F1 /* AnyCursorTests.swift in Sources */, 564A1FFC226B89E1001F64F1 /* DatabaseValueTests.swift in Sources */, @@ -1300,6 +1305,7 @@ 564A20CE226B8E18001F64F1 /* ForeignKeyInfoTests.swift in Sources */, 564A20CF226B8E18001F64F1 /* RecordPrimaryKeySingleTests.swift in Sources */, 564A20D0226B8E18001F64F1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, + 5676FBAE22F5CEF6004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 564A20D1226B8E18001F64F1 /* AssociationParallelRowScopesTests.swift in Sources */, 564A20D2226B8E18001F64F1 /* AnyCursorTests.swift in Sources */, 564A20D3226B8E18001F64F1 /* DatabaseValueTests.swift in Sources */, diff --git a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift index eb42f82ab..6bf7e7ca1 100644 --- a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift +++ b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift @@ -334,7 +334,7 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { notificationExpectation.fulfill() } let token = observer as! ValueObserverToken> // Non-public implementation detail - XCTAssertEqual(token.observer.region.description, "t(id,name)") // view is not tracked + XCTAssertEqual(token.observer.observedRegion.description, "t(id,name)") // view is not tracked try withExtendedLifetime(observer) { // Test view observation try dbQueue.inDatabase { db in diff --git a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift new file mode 100644 index 000000000..d7d30fdf7 --- /dev/null +++ b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift @@ -0,0 +1,91 @@ +import XCTest +#if GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +class ValueObservationRegionRecordingTests: GRDBTestCase { + func testRegionRecording() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { + try $0.execute(sql: """ + CREATE TABLE source(name TEXT); + INSERT INTO source VALUES ('a'); + CREATE TABLE a(value INTEGER); + CREATE TABLE b(value INTEGER); + """) + } + + var results: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 4 + + let observation = ValueObservation.tracking { db -> Int in + let table = try String.fetchOne(db, sql: "SELECT name FROM source")! + return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM \(table)")! + } + + let observer = try observation.start(in: dbQueue) { count in + results.append(count) + notificationExpectation.fulfill() + } + + try withExtendedLifetime(observer) { + try dbQueue.inDatabase { db in + try db.execute(sql: "INSERT INTO a VALUES (1)") // 1 + try db.execute(sql: "INSERT INTO b VALUES (1)") // - + try db.execute(sql: "INSERT INTO b VALUES (1)") // - + try db.execute(sql: "UPDATE source SET name = 'b'") // 2 + try db.execute(sql: "INSERT INTO a VALUES (1)") // - + try db.execute(sql: "INSERT INTO b VALUES (1)") // 3 + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(results, [0, 1, 2, 3]) + } + } + + func testRegionRecordingWithoutInitialFetch() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { + try $0.execute(sql: """ + CREATE TABLE source(name TEXT); + INSERT INTO source VALUES ('a'); + CREATE TABLE a(value INTEGER); + CREATE TABLE b(value INTEGER); + """) + } + + var results: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 3 + + var observation = ValueObservation.tracking { db -> Int in + let table = try String.fetchOne(db, sql: "SELECT name FROM source")! + return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM \(table)")! + } + observation.scheduling = .async(onQueue: DispatchQueue.main, startImmediately: false) + + let observer = try observation.start(in: dbQueue) { count in + results.append(count) + notificationExpectation.fulfill() + } + + try withExtendedLifetime(observer) { + try dbQueue.inDatabase { db in + try db.execute(sql: "INSERT INTO a VALUES (1)") // 1 + try db.execute(sql: "INSERT INTO b VALUES (1)") // - + try db.execute(sql: "INSERT INTO b VALUES (1)") // - + try db.execute(sql: "UPDATE source SET name = 'b'") // 2 + try db.execute(sql: "INSERT INTO a VALUES (1)") // - + try db.execute(sql: "INSERT INTO b VALUES (1)") // 3 + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(results, [1, 2, 3]) + } + } +} From f556fc39ab17f79b84a8cfa3958d8bafe5090ffa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 3 Aug 2019 16:56:47 +0200 Subject: [PATCH 64/91] Documentation --- README.md | 52 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 49 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 35bc0252d..342aa76fb 100644 --- a/README.md +++ b/README.md @@ -6173,6 +6173,7 @@ Changes are only notified after they have been committed in the database. No ins - **[ValueObservation Usage](#valueobservation-usage)** - [observationForCount, observationForAll, observationForFirst](#observationforcount-observationforall-observationforfirst) +- [ValueObservation.tracking(fetch:)](#valueobservationtrackingfetch) - [ValueObservation.tracking(_:fetch:)](#valueobservationtracking_fetch) - [ValueObservation Transformations](#valueobservation-transformations): [map](#valueobservationmap), [compactMap](#valueobservationcompactmap), ... - [ValueObservation Error Handling](#valueobservation-error-handling) @@ -6327,7 +6328,7 @@ Those observations match the `fetchCount`, `fetchAll`, and `fetchOne` request me > :point_up: **Note**: observations returned by those methods perform a filtering of consecutive identical values, based on raw database values. -### ValueObservation.tracking(_:fetch:) +### ValueObservation.tracking(fetch:) Observing the database is not always easy to express with simple requests, as above. @@ -6358,12 +6359,57 @@ print(""" """) ``` -In order to track changes in the Hall of Fame, we'll use the `ValueObservation.tracking(_:fetch:)` method. It accepts two parameters: +In order to track changes in the Hall of Fame, we'll use the `ValueObservation.tracking(fetch:)` method. It accepts a closure that fetches the observed values: + +```swift +let observation = ValueObservation.tracking { db in + try HallOfFame.fetch(db) +} + +let observer = observation.start( + in: dbQueue, + onError: { error in ... }, + onChange:{ (hallOfFame: HallOfFame) in + print(""" + Best players out of \(hallOfFame.totalPlayerCount): + \(hallOfFame.bestPlayers) + """) + }) +``` + +Such an observation can observe several tables. For example: + +```swift +// Observe several tables +let teamId = 123 +let observation = ValueObservation.tracking { db -> (Team, [Player])? in + guard let team = try Team.fetchOne(db, key: teamId) else { + return nil + } + let players = Player.filter(teamId: teamId).fetchAll(db) + return (team, players) +} +``` + +When you use a [database pool](#database-pools), and the fetch is slow, you may optimize the observation by using the [`ValueObservation.tracking(_:fetch:)`](#valueobservationtracking_fetch) method. See below. + + +### ValueObservation.tracking(_:fetch:) + +The `ValueObservation.tracking(_:fetch:)` method is an optimized version of the [`ValueObservation.tracking(fetch:)`](#valueobservationtrackingfetch) method seen above. + +It performs better when you use a [database pool](#database-pools), and the fetch is slow. It reduces write contention. + +When you use a [database queue](#database-queues), the results are the same, but no optimization is applied. + +It accepts two arguments: 1. A list of observed requests. 2. A closure that fetches a fresh value whenever one of the observed requests are modified. -In our case, any change to the `player` table can impact the Hall of Fame. We thus track the request for all players, `Player.all()`, and fetch a new Hall of Fame whenever players change: +Changes that happen outside of the observed requests are ignored, so make sure you cover the database region you want to observe. + +In the Hall Of Fame example seen above, any change to the `player` table can impact the Hall of Fame. We thus track the request for all players, `Player.all()`, and fetch a new Hall of Fame whenever players change: ```swift let observation = ValueObservation.tracking(Player.all(), fetch: { db in From 1b94c38b4f35d2bb7e50d6db7dcb699232637664 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 3 Aug 2019 17:16:03 +0200 Subject: [PATCH 65/91] Documentation --- README.md | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 342aa76fb..8fb5224c3 100644 --- a/README.md +++ b/README.md @@ -6359,7 +6359,7 @@ print(""" """) ``` -In order to track changes in the Hall of Fame, we'll use the `ValueObservation.tracking(fetch:)` method. It accepts a closure that fetches the observed values: +In order to track changes in the Hall of Fame, we'll use the `ValueObservation.tracking(fetch:)` method. Just make it fetch the observed values: ```swift let observation = ValueObservation.tracking { db in @@ -6398,7 +6398,7 @@ When you use a [database pool](#database-pools), and the fetch is slow, you may The `ValueObservation.tracking(_:fetch:)` method is an optimized version of the [`ValueObservation.tracking(fetch:)`](#valueobservationtrackingfetch) method seen above. -It performs better when you use a [database pool](#database-pools), and the fetch is slow. It reduces write contention. +It only performs better when you use a [database pool](#database-pools), and the fetch is slow, because it reduces write contention by fetching fresh values without blocking write accesses. When you use a [database queue](#database-queues), the results are the same, but no optimization is applied. @@ -6432,7 +6432,7 @@ let observer = observation.start( It may happen that a database change does not modify the observed values. The Hall of Fame, for example, is not affected by changes that happen to the worst players. -When such a database change happens, `ValueObservation.tracking(_:fetch:)` is triggered, just in case the best players would be modified, and ends up notifying identical consecutive values. +When such a database change happens, [`ValueObservation.tracking(fetch:)`](#valueobservationtrackingfetch) and [`ValueObservation.tracking(_:fetch:)`](#valueobservationtracking_fetch) are triggered, just in case the best players would be modified, and ends up notifying identical consecutive values. You can filter out those duplicates with the [ValueObservation.removeDuplicates](#valueobservationremoveduplicates) method. It requires the observed value to adopt the Equatable protocol: @@ -6440,7 +6440,7 @@ You can filter out those duplicates with the [ValueObservation.removeDuplicates] extension HallOfFame: Equatable { ... } let observation = ValueObservation - .tracking(Player.all(), fetch: HallOfFame.fetch) + .tracking(fetch: HallOfFame.fetch) .removeDuplicates() let observer = observation.start( @@ -6457,7 +6457,7 @@ let observer = observation.start( #### DatabaseRegionConvertible Observation -The initial parameter of the `ValueObservation.tracking(_:fetch:)` method can be fed with requests, and generally speaking, values that adopt the [DatabaseRegionConvertible] protocol. +The initial parameter of the [`ValueObservation.tracking(_:fetch:)`](#valueobservationtracking_fetch) method can be fed with requests, and generally speaking, values that adopt the [DatabaseRegionConvertible] protocol. Thanks to DatabaseRegionConvertible, `TeamInfoRequest` below is not only able to fetch a team and its players, but also to be observed. @@ -6774,9 +6774,10 @@ The `scheduling` property lets you control how fresh values are notified: The `requiresWriteAccess` property is false by default. When true, a ValueObservation has a write access to the database, and its fetches are automatically wrapped in a [savepoint](#transactions-and-savepoints): ```swift -var observation = ValueObservation.tracking(..., fetch: { db in +var observation = ValueObservation.tracking { db in // write access allowed -}) + ... +} observation.requiresWriteAccess = true ``` From 2039cd48744d8a0b6fd8227ecbdc64a2ed328478 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 3 Aug 2019 17:18:47 +0200 Subject: [PATCH 66/91] Documentation --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8fb5224c3..a99c4d06b 100644 --- a/README.md +++ b/README.md @@ -6369,7 +6369,7 @@ let observation = ValueObservation.tracking { db in let observer = observation.start( in: dbQueue, onError: { error in ... }, - onChange:{ (hallOfFame: HallOfFame) in + onChange: { (hallOfFame: HallOfFame) in print(""" Best players out of \(hallOfFame.totalPlayerCount): \(hallOfFame.bestPlayers) @@ -6419,7 +6419,7 @@ let observation = ValueObservation.tracking(Player.all(), fetch: { db in let observer = observation.start( in: dbQueue, onError: { error in ... }, - onChange:{ (hallOfFame: HallOfFame) in + onChange: { (hallOfFame: HallOfFame) in print(""" Best players out of \(hallOfFame.totalPlayerCount): \(hallOfFame.bestPlayers) From 4f025e59af885ae68d1f40a22882dad70a5905a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 3 Aug 2019 17:21:42 +0200 Subject: [PATCH 67/91] Documentation --- README.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index a99c4d06b..7280f555a 100644 --- a/README.md +++ b/README.md @@ -6396,18 +6396,16 @@ When you use a [database pool](#database-pools), and the fetch is slow, you may ### ValueObservation.tracking(_:fetch:) -The `ValueObservation.tracking(_:fetch:)` method is an optimized version of the [`ValueObservation.tracking(fetch:)`](#valueobservationtrackingfetch) method seen above. +The `ValueObservation.tracking(_:fetch:)` method is an **optimized** version of the [`ValueObservation.tracking(fetch:)`](#valueobservationtrackingfetch) method seen above. -It only performs better when you use a [database pool](#database-pools), and the fetch is slow, because it reduces write contention by fetching fresh values without blocking write accesses. - -When you use a [database queue](#database-queues), the results are the same, but no optimization is applied. +It ouputs exactly the same results, but it can perform better when you use a [database pool](#database-pools), and the fetch is slow. It reduces write contention by fetching fresh values without blocking write accesses. When you use a [database queue](#database-queues), no optimization is applied. It accepts two arguments: 1. A list of observed requests. 2. A closure that fetches a fresh value whenever one of the observed requests are modified. -Changes that happen outside of the observed requests are ignored, so make sure you cover the database region you want to observe. +Changes that happen outside of the observed requests are ignored, so make sure you fully cover the database region you want to observe. This is the price you pay for the optimization. In the Hall Of Fame example seen above, any change to the `player` table can impact the Hall of Fame. We thus track the request for all players, `Player.all()`, and fetch a new Hall of Fame whenever players change: From 62a12d94ce9ad545c0fbbe0ea1ca8fc6fa49b439 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 3 Aug 2019 17:41:39 +0200 Subject: [PATCH 68/91] CHANGELOG --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7bea46a5b..693906ae7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -62,6 +62,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: - [#576](https://github.com/groue/GRDB.swift/pull/576): Expose table name and full-text filtering methods to DerivableRequest - [#577](https://github.com/groue/GRDB.swift/pull/577): Rename `aliased(_:)` methods to `forKey(_:)` - [#585](https://github.com/groue/GRDB.swift/pull/585): Fix use of SQLite authorizers +- [#586](https://github.com/groue/GRDB.swift/pull/586): Automatic region tracking for ValueObservation ### API Diff @@ -122,6 +123,10 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: func aliased(_ key: CodingKey) -> SQLSelectable + func forKey(_ key: CodingKey) -> SQLSelectable } + + extension ValueObservation where Reducer == Void { ++ static func tracking(fetch: @escaping (Database) throws -> Value) -> ValueObservation> + } ``` From 731a83908d7ddcaf2603253db3b2018c4a461b93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 3 Aug 2019 18:03:05 +0200 Subject: [PATCH 69/91] Test automatic ValueObservation region tracking with various schedulings --- ...ValueObservationRegionRecordingTests.swift | 161 +++++++++++++++++- 1 file changed, 157 insertions(+), 4 deletions(-) diff --git a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift index d7d30fdf7..779e9485c 100644 --- a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift +++ b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift @@ -1,12 +1,12 @@ import XCTest #if GRDBCUSTOMSQLITE - import GRDBCustomSQLite + @testable import GRDBCustomSQLite #else - import GRDB + @testable import GRDB #endif class ValueObservationRegionRecordingTests: GRDBTestCase { - func testRegionRecording() throws { + func testMainQueueScheduling() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { try $0.execute(sql: """ @@ -32,6 +32,9 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { notificationExpectation.fulfill() } + let token = observer as! ValueObserverToken> // Non-public implementation detail + XCTAssertEqual(token.observer.observedRegion.description, "a(*),source(name)") + try withExtendedLifetime(observer) { try dbQueue.inDatabase { db in try db.execute(sql: "INSERT INTO a VALUES (1)") // 1 @@ -44,10 +47,13 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(results, [0, 1, 2, 3]) + + let token = observer as! ValueObserverToken> // Non-public implementation detail + XCTAssertEqual(token.observer.observedRegion.description, "b(*),source(name)") } } - func testRegionRecordingWithoutInitialFetch() throws { + func testAsyncSchedulingWithoutInitialFetch() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { try $0.execute(sql: """ @@ -74,6 +80,8 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { notificationExpectation.fulfill() } + // Can't test observedRegion because it is defined asynchronously + try withExtendedLifetime(observer) { try dbQueue.inDatabase { db in try db.execute(sql: "INSERT INTO a VALUES (1)") // 1 @@ -86,6 +94,151 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(results, [1, 2, 3]) + + let token = observer as! ValueObserverToken> // Non-public implementation detail + XCTAssertEqual(token.observer.observedRegion.description, "b(*),source(name)") + } + } + + func testAsyncSchedulingWithInitialFetch() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { + try $0.execute(sql: """ + CREATE TABLE source(name TEXT); + INSERT INTO source VALUES ('a'); + CREATE TABLE a(value INTEGER); + CREATE TABLE b(value INTEGER); + """) + } + + var results: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 4 + + var observation = ValueObservation.tracking { db -> Int in + let table = try String.fetchOne(db, sql: "SELECT name FROM source")! + return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM \(table)")! + } + observation.scheduling = .async(onQueue: DispatchQueue.main, startImmediately: true) + + let observer = try observation.start(in: dbQueue) { count in + results.append(count) + notificationExpectation.fulfill() + } + + // Can't test observedRegion because it is defined asynchronously + + try withExtendedLifetime(observer) { + try dbQueue.inDatabase { db in + try db.execute(sql: "INSERT INTO a VALUES (1)") // 1 + try db.execute(sql: "INSERT INTO b VALUES (1)") // - + try db.execute(sql: "INSERT INTO b VALUES (1)") // - + try db.execute(sql: "UPDATE source SET name = 'b'") // 2 + try db.execute(sql: "INSERT INTO a VALUES (1)") // - + try db.execute(sql: "INSERT INTO b VALUES (1)") // 3 + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(results, [0, 1, 2, 3]) + + let token = observer as! ValueObserverToken> // Non-public implementation detail + XCTAssertEqual(token.observer.observedRegion.description, "b(*),source(name)") + } + } + + func testUnsafeSchedulingWithoutInitialFetch() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { + try $0.execute(sql: """ + CREATE TABLE source(name TEXT); + INSERT INTO source VALUES ('a'); + CREATE TABLE a(value INTEGER); + CREATE TABLE b(value INTEGER); + """) + } + + var results: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 3 + + var observation = ValueObservation.tracking { db -> Int in + let table = try String.fetchOne(db, sql: "SELECT name FROM source")! + return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM \(table)")! + } + observation.scheduling = .unsafe(startImmediately: false) + + let observer = try observation.start(in: dbQueue) { count in + results.append(count) + notificationExpectation.fulfill() + } + + // Can't test observedRegion because it is defined asynchronously + + try withExtendedLifetime(observer) { + try dbQueue.inDatabase { db in + try db.execute(sql: "INSERT INTO a VALUES (1)") // 1 + try db.execute(sql: "INSERT INTO b VALUES (1)") // - + try db.execute(sql: "INSERT INTO b VALUES (1)") // - + try db.execute(sql: "UPDATE source SET name = 'b'") // 2 + try db.execute(sql: "INSERT INTO a VALUES (1)") // - + try db.execute(sql: "INSERT INTO b VALUES (1)") // 3 + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(results, [1, 2, 3]) + + let token = observer as! ValueObserverToken> // Non-public implementation detail + XCTAssertEqual(token.observer.observedRegion.description, "b(*),source(name)") + } + } + + func testUnsafeSchedulingWithInitialFetch() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { + try $0.execute(sql: """ + CREATE TABLE source(name TEXT); + INSERT INTO source VALUES ('a'); + CREATE TABLE a(value INTEGER); + CREATE TABLE b(value INTEGER); + """) + } + + var results: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 4 + + var observation = ValueObservation.tracking { db -> Int in + let table = try String.fetchOne(db, sql: "SELECT name FROM source")! + return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM \(table)")! + } + observation.scheduling = .unsafe(startImmediately: true) + + let observer = try observation.start(in: dbQueue) { count in + results.append(count) + notificationExpectation.fulfill() + } + + let token = observer as! ValueObserverToken> // Non-public implementation detail + XCTAssertEqual(token.observer.observedRegion.description, "a(*),source(name)") + + try withExtendedLifetime(observer) { + try dbQueue.inDatabase { db in + try db.execute(sql: "INSERT INTO a VALUES (1)") // 1 + try db.execute(sql: "INSERT INTO b VALUES (1)") // - + try db.execute(sql: "INSERT INTO b VALUES (1)") // - + try db.execute(sql: "UPDATE source SET name = 'b'") // 2 + try db.execute(sql: "INSERT INTO a VALUES (1)") // - + try db.execute(sql: "INSERT INTO b VALUES (1)") // 3 + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(results, [0, 1, 2, 3]) + + let token = observer as! ValueObserverToken> // Non-public implementation detail + XCTAssertEqual(token.observer.observedRegion.description, "b(*),source(name)") } } } From c4481f4e795ecf803ff5a39ec96cca4d13a6bcae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 4 Aug 2019 10:44:08 +0200 Subject: [PATCH 70/91] Fix ValueObservationRegionRecordingTests for SQLite < 3.19.0 --- ...ValueObservationRegionRecordingTests.swift | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift index 779e9485c..74c3200b9 100644 --- a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift +++ b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift @@ -24,7 +24,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { let observation = ValueObservation.tracking { db -> Int in let table = try String.fetchOne(db, sql: "SELECT name FROM source")! - return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM \(table)")! + return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! } let observer = try observation.start(in: dbQueue) { count in @@ -33,7 +33,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { } let token = observer as! ValueObserverToken> // Non-public implementation detail - XCTAssertEqual(token.observer.observedRegion.description, "a(*),source(name)") + XCTAssertEqual(token.observer.observedRegion.description, "a(value),source(name)") try withExtendedLifetime(observer) { try dbQueue.inDatabase { db in @@ -49,7 +49,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { XCTAssertEqual(results, [0, 1, 2, 3]) let token = observer as! ValueObserverToken> // Non-public implementation detail - XCTAssertEqual(token.observer.observedRegion.description, "b(*),source(name)") + XCTAssertEqual(token.observer.observedRegion.description, "b(value),source(name)") } } @@ -71,7 +71,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { var observation = ValueObservation.tracking { db -> Int in let table = try String.fetchOne(db, sql: "SELECT name FROM source")! - return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM \(table)")! + return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! } observation.scheduling = .async(onQueue: DispatchQueue.main, startImmediately: false) @@ -96,7 +96,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { XCTAssertEqual(results, [1, 2, 3]) let token = observer as! ValueObserverToken> // Non-public implementation detail - XCTAssertEqual(token.observer.observedRegion.description, "b(*),source(name)") + XCTAssertEqual(token.observer.observedRegion.description, "b(value),source(name)") } } @@ -118,7 +118,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { var observation = ValueObservation.tracking { db -> Int in let table = try String.fetchOne(db, sql: "SELECT name FROM source")! - return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM \(table)")! + return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! } observation.scheduling = .async(onQueue: DispatchQueue.main, startImmediately: true) @@ -143,7 +143,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { XCTAssertEqual(results, [0, 1, 2, 3]) let token = observer as! ValueObserverToken> // Non-public implementation detail - XCTAssertEqual(token.observer.observedRegion.description, "b(*),source(name)") + XCTAssertEqual(token.observer.observedRegion.description, "b(value),source(name)") } } @@ -165,7 +165,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { var observation = ValueObservation.tracking { db -> Int in let table = try String.fetchOne(db, sql: "SELECT name FROM source")! - return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM \(table)")! + return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! } observation.scheduling = .unsafe(startImmediately: false) @@ -190,7 +190,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { XCTAssertEqual(results, [1, 2, 3]) let token = observer as! ValueObserverToken> // Non-public implementation detail - XCTAssertEqual(token.observer.observedRegion.description, "b(*),source(name)") + XCTAssertEqual(token.observer.observedRegion.description, "b(value),source(name)") } } @@ -212,7 +212,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { var observation = ValueObservation.tracking { db -> Int in let table = try String.fetchOne(db, sql: "SELECT name FROM source")! - return try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM \(table)")! + return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! } observation.scheduling = .unsafe(startImmediately: true) @@ -222,7 +222,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { } let token = observer as! ValueObserverToken> // Non-public implementation detail - XCTAssertEqual(token.observer.observedRegion.description, "a(*),source(name)") + XCTAssertEqual(token.observer.observedRegion.description, "a(value),source(name)") try withExtendedLifetime(observer) { try dbQueue.inDatabase { db in @@ -238,7 +238,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { XCTAssertEqual(results, [0, 1, 2, 3]) let token = observer as! ValueObserverToken> // Non-public implementation detail - XCTAssertEqual(token.observer.observedRegion.description, "b(*),source(name)") + XCTAssertEqual(token.observer.observedRegion.description, "b(value),source(name)") } } } From d61522ee5f48da15b1c7e060942556a11a0f3257 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 4 Aug 2019 11:42:54 +0200 Subject: [PATCH 71/91] Update ValueObservation documentation --- README.md | 287 +++++++++++++----------------------------------------- 1 file changed, 70 insertions(+), 217 deletions(-) diff --git a/README.md b/README.md index 7280f555a..df44847e4 100644 --- a/README.md +++ b/README.md @@ -231,8 +231,10 @@ See the [Query Interface](#the-query-interface) Be notified of database changes ```swift -let request = Place.order(Column("title")) -request.observationForAll().start( +let observation = ValueObservation.tracking { db in + try Place.fetchAll(db) +} +observation.start( in: dbQueue, onError: { error in print("fresh places could not be fetched") @@ -2890,44 +2892,7 @@ extension Player: FetchableRecord, PersistableRecord { } ``` -Those columns let you build requests with the [query interface](#the-query-interface): - -```swift -extension Player { - static func filter(name: String) -> QueryInterfaceRequest { - return filter(Columns.name == name) - } - - static var maximumScore: QueryInterfaceRequest { - return select(max(Columns.score), as: Int.self) - } -} -``` - -Those requests can both fetch... - -```swift -// Fetch values -try dbQueue.read { db in - // SELECT * FROM player WHERE name = 'Arthur' - let arthur = try Player.filter(name: "Arthur").fetchOne(db) // Player? - - // SELECT MAX(score) FROM player - let maxScore = try Player.maximumScore.fetchOne(db) // Int? -} -``` - -... and feed database observation tools such as [ValueObservation]: - -```swift -// Observe changes -Player.maximumScore.observationForFirst().start( - in: dbQueue, - onError: { error in ... }, - onChange: { (maxScore: Int?) in - print("The maximum score has changed") - }) -``` +See the [query interface](#the-query-interface) and [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) for further information. ## Record Class @@ -4475,29 +4440,9 @@ let minScore = row[0] as Int? let maxScore = row[1] as Int? ``` -When you also want to use database observation tools such as [ValueObservation], you have to go one step further, and change the type of the request: +You can also change the request so that it knows the type it has to fetch: -- When you change the selection, prefer the `select(..., as:)` method: - - ```swift - // A request of Int - let request = Player.select(max(scoreColumn), as: Int.self) - - // Simple fetch - let maxScore = try dbQueue.read { db in - try request.fetchOne(db) // Int? - } - - // Observe with ValueObservation - request.observationForFirst().start( - in: dbQueue, - onError: { error in ... }, - onChange: { (maxScore: Int?) in - print("The maximum score has changed") - }) - ``` - -- Otherwise, use `asRequest(of:)`. Here is an example that uses [Associations]: +- With `asRequest(of:)`, useful when you use [Associations]: ```swift struct BookInfo: FetchableRecord, Decodable { @@ -4510,18 +4455,20 @@ When you also want to use database observation tools such as [ValueObservation], .including(required: Book.author) .asRequest(of: BookInfo.self) - // Simple fetch let bookInfos = try dbQueue.read { db in try request.fetchAll(db) // [BookInfo] } + ``` - // Observe with ValueObservation - request.observationForAll().start( - in: dbQueue, - onError: { error in ... }, - onChange: { (bookInfos: [BookInfo]) in - print("Books have changed") - }) +- With `select(..., as:)`, which is handy when you change the selection: + + ```swift + // A request of Int + let request = Player.select(max(scoreColumn), as: Int.self) + + let maxScore = try dbQueue.read { db in + try request.fetchOne(db) // Int? + } ``` @@ -4588,17 +4535,6 @@ let request = Player.filter(key: ["email": "arthur@example.com"]) let player = try request.fetchOne(db) // Player? ``` -Those requests can feed [ValueObservation]: - -```swift -Player.filter(key: 1).observationForFirst().start( - in: dbQueue, - onError: { error in ... }, - onChange: { (player: Player?) in - print("Player 1 has changed") - }) -``` - ## Fetching Aggregated Values @@ -4709,17 +4645,6 @@ But you may prefer to bring some elegance back in, and build custom requests: try Player.customRequest().fetchAll(db) // [Player] ``` -Custom requests can also feed [ValueObservation]: - -```swift -Player.customRequest(...).observationForAll().start( - in: dbQueue, - onError: { error in ... }, - onChange: { (players: [Player]) in - print("Players have changed") - }) -``` - - [FetchRequest Protocol](#fetchrequest-protocol) - [Building Custom Requests](#building-custom-requests) - [Fetching From Custom Requests](#fetching-from-custom-requests) @@ -6259,9 +6184,10 @@ The observer returned by the `start` method is stored in a property of the view > > See [ValueObservation.scheduling](#valueobservationscheduling) for more information. + ### observationForCount, observationForAll, observationForFirst -Given a [request](#requests), you can observe its number of results, all results, or the first one: +Given a [request](#requests), even a [custom request](#custom-requests), you can observe its number of results, all results, or the first one: ```swift request.observationForCount() @@ -6269,7 +6195,9 @@ request.observationForAll() request.observationForFirst() ``` -Those observations match the `fetchCount`, `fetchAll`, and `fetchOne` request methods: +Those observations match the `fetchCount`, `fetchAll`, and `fetchOne` request methods. + +They perform a filtering of consecutive identical values, based on raw database values, so that you are not notified of database changes that do not impact the result of the request. - `observationForCount()` notifies counts: @@ -6325,12 +6253,10 @@ Those observations match the `fetchCount`, `fetchAll`, and `fetchOne` request me }) ``` -> :point_up: **Note**: observations returned by those methods perform a filtering of consecutive identical values, based on raw database values. - ### ValueObservation.tracking(fetch:) -Observing the database is not always easy to express with simple requests, as above. +Observing the database is not always a matter of tracking a single request, as above. For example, let's say that we have a struct that defines a "Hall of Fame": @@ -6338,7 +6264,13 @@ For example, let's say that we have a struct that defines a "Hall of Fame": struct HallOfFame { var totalPlayerCount: Int var bestPlayers: [Player] +} +``` +To fetch the Hall of Fame from the database, we perform two requests: the 10 best players, and the total number of players. Following the Rule 2 of the [Concurrency Guide](#guarantees-and-rules), we make sure the two requests are always performed in a single database access, as below: + +```swift +extension { /// Fetch a HallOfFame static fetch(_ db: Database) throws -> HallOfFame { let totalPlayerCount = try Player.fetchCount(db) @@ -6359,7 +6291,7 @@ print(""" """) ``` -In order to track changes in the Hall of Fame, we'll use the `ValueObservation.tracking(fetch:)` method. Just make it fetch the observed values: +Now, in order to track changes in the Hall of Fame, we'll use the `ValueObservation.tracking(fetch:)` method. Just make it fetch the observed values: ```swift let observation = ValueObservation.tracking { db in @@ -6377,21 +6309,33 @@ let observer = observation.start( }) ``` -Such an observation can observe several tables. For example: +- Observation built from `ValueObservation.tracking(fetch:)` can observe several tables: -```swift -// Observe several tables -let teamId = 123 -let observation = ValueObservation.tracking { db -> (Team, [Player])? in - guard let team = try Team.fetchOne(db, key: teamId) else { - return nil + ```swift + // Observe several tables + let teamId = 123 + let observation = ValueObservation.tracking { db -> (Team, [Player])? in + guard let team = try Team.fetchOne(db, key: teamId) else { + return nil + } + let players = Player.filter(teamId: teamId).fetchAll(db) + return (team, players) } - let players = Player.filter(teamId: teamId).fetchAll(db) - return (team, players) -} -``` + ``` -When you use a [database pool](#database-pools), and the fetch is slow, you may optimize the observation by using the [`ValueObservation.tracking(_:fetch:)`](#valueobservationtracking_fetch) method. See below. +- Unlike [observationForCount, observationForAll, observationForFirst](#observationforcount-observationforall-observationforfirst), `ValueObservation.tracking(fetch:)` does not filter out consecutive identical values. For example, database changes that happen to the worst players trigger the observation of the Hall of Fame, just in case the best players would be modified. + + You can filter out those duplicates with the [ValueObservation.removeDuplicates](#valueobservationremoveduplicates) method. It requires the observed value to adopt the Equatable protocol: + + ```swift + extension HallOfFame: Equatable { ... } + + let observation = ValueObservation + .tracking(fetch: HallOfFame.fetch) + .removeDuplicates() + ``` + +- When you use a [database pool](#database-pools), and the fetch is slow, you may optimize the observation by using the [`ValueObservation.tracking(_:fetch:)`](#valueobservationtracking_fetch) method. See below. ### ValueObservation.tracking(_:fetch:) @@ -6426,95 +6370,7 @@ let observer = observation.start( ``` -#### Filtering out Consecutive Identical Values - -It may happen that a database change does not modify the observed values. The Hall of Fame, for example, is not affected by changes that happen to the worst players. - -When such a database change happens, [`ValueObservation.tracking(fetch:)`](#valueobservationtrackingfetch) and [`ValueObservation.tracking(_:fetch:)`](#valueobservationtracking_fetch) are triggered, just in case the best players would be modified, and ends up notifying identical consecutive values. - -You can filter out those duplicates with the [ValueObservation.removeDuplicates](#valueobservationremoveduplicates) method. It requires the observed value to adopt the Equatable protocol: - -```swift -extension HallOfFame: Equatable { ... } - -let observation = ValueObservation - .tracking(fetch: HallOfFame.fetch) - .removeDuplicates() - -let observer = observation.start( - in: dbQueue, - onError: { error in ... }, - onChange: { (hallOfFame: HallOfFame) in - print(""" - Best players out of \(hallOfFame.totalPlayerCount): - \(hallOfFame.bestPlayers) - """) - }) -``` - - -#### DatabaseRegionConvertible Observation - -The initial parameter of the [`ValueObservation.tracking(_:fetch:)`](#valueobservationtracking_fetch) method can be fed with requests, and generally speaking, values that adopt the [DatabaseRegionConvertible] protocol. - -Thanks to DatabaseRegionConvertible, `TeamInfoRequest` below is not only able to fetch a team and its players, but also to be observed. - -```swift -/// A team and its players -struct TeamInfo { - var team: Team - var players: [Player] -} - -/// A request that can fetch TeamInfo, given a team id. -struct TeamInfoRequest { - var teamId: Int64 - - /// The request for the team - private var teamRequest: QueryInterfaceRequest { - return Team.filter(key: teamId) - } - - /// The request for the players - private var playersRequest: QueryInterfaceRequest { - return Player.filter(Column("teamId") == teamId) - } - - /// Fetch a TeamInfo - func fetch(_ db: Database) throws -> TeamInfo? { - guard let team = try teamRequest.fetchOne(db) else { - return nil - } - let players = try playersRequest.fetchAll(db) - return TeamInfo(team: team, players: players) - } -} - -/// Make TeamInfoRequest observable -extension TeamInfoRequest: DatabaseRegionConvertible { - func databaseRegion(_ db: Database) throws -> DatabaseRegion { - // Returns the union of the team region and the players region - let teamRegion = try teamRequest.databaseRegion(db) - let playersRegion = try playersRequest.databaseRegion(db) - return teamRegion.union(playersRegion) - } -} - -let request = TeamInfoRequest(teamId: 1) - -// Simple fetch -let teamInfo: TeamInfo? = try dbQueue.read(request.fetch) - -// Observation -let observer = ValueObservation - .tracking(request, fetch: request.fetch) - .start( - in: dbQueue, - onError: { error in ... }, - onChange: { (teamInfo: TeamInfo?) in - print("Team and its players have hanged.") - }) -``` +> :point_up: **Note**: the initial parameter of `ValueObservation.tracking(_:fetch:)` can be fed with requests, and generally speaking, values that adopt the [DatabaseRegionConvertible] protocol. ### ValueObservation Transformations @@ -6597,20 +6453,10 @@ let observer = observation.start( #### ValueObservation.combine(...) -Sometimes you need to observe several requests at the same time. - -When this happens, **combine** several observations together with the `ValueObservation.combine(...)` method: +The `ValueObservation.combine(...)` method builds a single observation from several: ```swift -struct HallOfFame { - /// Total number of players - var playerCount: Int - - /// The best ones - var bestPlayers: [Player] -} - -// The two base observations +// Two base observations let playerCountObservation = Player.observationForCount() let bestPlayersObservation = Player .limit(10) @@ -6620,22 +6466,29 @@ let bestPlayersObservation = Player // The combined observation let observation = ValueObservation .combine(playerCountObservation, bestPlayersObservation) - .map { HallOfFame(playerCount: $0, bestPlayers: $1) } - + // Start tracking the hall of fame let observer = observation.start( in: dbQueue, onError: { error in ... }, - onChange: { (hallOfFame: HallOfFame) in - print("The hall of fame has changed.") + onChange: { (totalPlayerCount, bestPlayers) in + print(""" + Best players out of \(totalPlayerCount): + \(bestPlayers) + """) }) ``` `combine` also exists as an instance method: ```swift +struct HallOfFame { + var totalPlayerCount: Int + var bestPlayers: [Player] +} + let observation = playerCountObservation.combine(bestPlayersObservation) { - HallOfFame(playerCount: $0, bestPlayers: $1) + HallOfFame(totalPlayerCount: $0, bestPlayers: $1) } ``` @@ -7531,7 +7384,7 @@ protocol DatabaseRegionConvertible { All [requests](#requests) adopt this protocol, and this allows them to be observed with [DatabaseRegionObservation] and [ValueObservation]. -Use this protocol when you want to encapsulate your complex requests in a dedicated type, and still profit from observation APIs. See [DatabaseRegionConvertible Observation](#databaseregionconvertible-observation) for more information. +Use this protocol when you want to encapsulate your complex requests in a dedicated type, and still profit from optimized observation APIs. See [`ValueObservation.tracking(_:fetch:)`](#valueobservationtracking_fetch) for more information. ### Support for SQLite Pre-Update Hooks From c71888941866587ab46f8b71cb65125369d06957 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 4 Aug 2019 11:45:43 +0200 Subject: [PATCH 72/91] Update ValueObservation documentation --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index df44847e4..936d12807 100644 --- a/README.md +++ b/README.md @@ -6284,7 +6284,10 @@ extension { } } -let hallOfFame = try dbQueue.read { db in try HallOfFame.fetch(db) } +let hallOfFame = try dbQueue.read { db in + try HallOfFame.fetch(db) +} + print(""" Best players out of \(hallOfFame.totalPlayerCount): \(hallOfFame.bestPlayers) From dc146a431c15d30a33ab009f9109b28a56939467 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 4 Aug 2019 14:36:20 +0200 Subject: [PATCH 73/91] Tests for Database.recordingSelectedRegion --- ...ValueObservationRegionRecordingTests.swift | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift index 74c3200b9..67b498048 100644 --- a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift +++ b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift @@ -6,6 +6,64 @@ import XCTest #endif class ValueObservationRegionRecordingTests: GRDBTestCase { + func testRecordingSelectedRegion() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.execute(sql: """ + CREATE TABLE team(id INTEGER PRIMARY KEY, name TEXT); + CREATE TABLE player(id INTEGER PRIMARY KEY, name TEXT); + """) + + do { + let (_, region) = db.recordingSelectedRegion { } + XCTAssertTrue(region.isEmpty) + } + + do { + let (_, region) = try db.recordingSelectedRegion { + _ = try Row.fetchAll(db, sql: "SELECT * FROM team") + } + XCTAssertEqual(region.description, "team(id,name)") + } + + do { + let (_, region) = try db.recordingSelectedRegion { + _ = try Row.fetchAll(db, sql: "SELECT name FROM player") + } + XCTAssertEqual(region.description, "player(name)") + } + + do { + let (_, region) = try db.recordingSelectedRegion { + _ = try Row.fetchAll(db, sql: "SELECT * FROM team") + _ = try Row.fetchAll(db, sql: "SELECT * FROM player") + } + XCTAssertEqual(region.description, "player(id,name),team(id,name)") + } + + do { + var region1 = DatabaseRegion() + var region2 = DatabaseRegion() + var region3 = DatabaseRegion() + var region4 = DatabaseRegion() + (_, region1) = try db.recordingSelectedRegion { + _ = try Row.fetchAll(db, sql: "SELECT * FROM team") + (_, region2) = try db.recordingSelectedRegion { + _ = try Row.fetchAll(db, sql: "SELECT name FROM player") + (_, region3) = db.recordingSelectedRegion { } + } + (_, region4) = try db.recordingSelectedRegion { + _ = try Row.fetchAll(db, sql: "SELECT * FROM player") + } + } + XCTAssertEqual(region1.description, "player(id,name),team(id,name)") + XCTAssertEqual(region2.description, "player(name)") + XCTAssertTrue(region3.isEmpty) + XCTAssertEqual(region4.description, "player(id,name)") + } + } + } + func testMainQueueScheduling() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { From 9c864bc7687f44ce76ca41beb0e06efdbc3fb459 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 4 Aug 2019 14:37:10 +0200 Subject: [PATCH 74/91] Failling test for rowid optimization in Database.recordingSelectedRegion --- .../GRDBTests/ValueObservationRegionRecordingTests.swift | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift index 67b498048..944cf2821 100644 --- a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift +++ b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift @@ -33,6 +33,15 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { XCTAssertEqual(region.description, "player(name)") } + do { + // Test for rowID optimization + struct Player: TableRecord, FetchableRecord, Decodable { } + let (_, region) = try db.recordingSelectedRegion { + _ = try Player.fetchOne(db, key: 123) + } + XCTAssertEqual(region.description, "player(id,name)[123]") + } + do { let (_, region) = try db.recordingSelectedRegion { _ = try Row.fetchAll(db, sql: "SELECT * FROM team") From 0f2c5cd8a0ecf424c0a6c916535040a43ba8b69e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 4 Aug 2019 14:37:40 +0200 Subject: [PATCH 75/91] Fix failling test for rowid optimization in Database.recordingSelectedRegion --- GRDB/Core/Database+Statements.swift | 17 ++++- GRDB/Core/DatabaseRegion.swift | 7 ++ GRDB/Core/Statement.swift | 2 +- .../Request/QueryInterfaceRequest.swift | 4 +- .../SQLGeneration/SQLQueryGenerator.swift | 10 +-- .../AssociationPrefetchingSQLTests.swift | 68 +++++++++---------- 6 files changed, 65 insertions(+), 43 deletions(-) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index e0eefa72e..859882b91 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -291,7 +291,22 @@ extension Database { @inline(__always) func selectStatementWillExecute(_ statement: SelectStatement) { if _isRecordingSelectedRegion { - _selectedRegion.formUnion(statement.databaseRegion) + // Don't record schema introspection queries, which may be + // run, or not, depending on the state of the schema cache. + // + // This gives us a quick way to make sure that the observation + // below, which runs schema introspection queries as a side effect, + // only tracks the "player" table: + // + // let observation = ValueObservation.tracking { db in + // try Player.fetchOne(db, key: 1) + // } + // + // Strictly speaking, this prevents the recording of all schema + // queries. But we assume, until proven wrong, that such recording + // isn't needed by anyone. + let region = statement.databaseRegion.ignoringInternalSQLiteTables() + _selectedRegion.formUnion(region) } } diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index af22ad1e8..793c82f4b 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -154,6 +154,13 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable { let filteredRegions = tableRegions.filter { viewNames.contains($0.key) == false } return DatabaseRegion(tableRegions: filteredRegions) } + + /// Returns a region which doesn't contain any SQLite internal table. + func ignoringInternalSQLiteTables() -> DatabaseRegion { + guard let tableRegions = tableRegions else { return .fullDatabase } + let filteredRegions = tableRegions.filter { !$0.key.starts(with: "sqlite_") } + return DatabaseRegion(tableRegions: filteredRegions) + } } extension DatabaseRegion { diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 991ca93f1..66fdbb6d7 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -277,7 +277,7 @@ extension Statement { /// } public final class SelectStatement: Statement { /// The database region that the statement looks into. - public private(set) var databaseRegion = DatabaseRegion() + public internal(set) var databaseRegion = DatabaseRegion() /// Creates a prepared statement. Returns nil if the compiled string is /// blank or empty. diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 2694ba92c..d9b715ce8 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -86,7 +86,7 @@ extension QueryInterfaceRequest: FetchRequest { /// - parameter db: A database connection. /// :nodoc: public func databaseRegion(_ db: Database) throws -> DatabaseRegion { - var region = try SQLQueryGenerator(query).databaseRegion(db) + var region = try SQLQueryGenerator(query).makeSelectStatement(db).databaseRegion // Iterate all prefetched associations var fifo = query.relation.prefetchedAssociations @@ -105,7 +105,7 @@ extension QueryInterfaceRequest: FetchRequest { let prefetchedQuery = SQLQuery(relation: prefetchedRelation) // Union region - try region.formUnion(SQLQueryGenerator(prefetchedQuery).databaseRegion(db)) + try region.formUnion(SQLQueryGenerator(prefetchedQuery).makeSelectStatement(db).databaseRegion) // Append nested prefetched associations (support for // A.including(all: A.bs.including(all: B.cs)) diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 56b277f66..c3c5e1467 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -100,10 +100,7 @@ struct SQLQueryGenerator { return try (makeSelectStatement(db), rowAdapter(db)) } - func databaseRegion(_ db: Database) throws -> DatabaseRegion { - let statement = try makeSelectStatement(db) - let databaseRegion = statement.databaseRegion - + private func optimizedDatabaseRegion(_ db: Database, _ databaseRegion: DatabaseRegion) throws -> DatabaseRegion { // Can we intersect the region with rowIds? // // Give up unless request feeds from a single database table @@ -178,7 +175,7 @@ struct SQLQueryGenerator { } /// Returns a select statement - private func makeSelectStatement(_ db: Database) throws -> SelectStatement { + func makeSelectStatement(_ db: Database) throws -> SelectStatement { // Build an SQK generation context with all aliases found in the query, // so that we can disambiguate tables that are used several times with // SQL aliases. @@ -190,6 +187,9 @@ struct SQLQueryGenerator { // Compile & set arguments let statement = try db.makeSelectStatement(sql: sql) statement.arguments = context.arguments! // not nil for this kind of context + + // Optimize databaseRegion + statement.databaseRegion = try optimizedDatabaseRegion(db, statement.databaseRegion) return statement } diff --git a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift index a10f90cd1..8d4d38f16 100644 --- a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift @@ -87,7 +87,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "a" ORDER BY "cola1" @@ -112,7 +112,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM \"a\" WHERE 0 ORDER BY \"cola1\" @@ -138,7 +138,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "a" \ @@ -196,7 +196,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "parent" ORDER BY "parentA", "parentB" @@ -219,7 +219,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "parent" WHERE 0 ORDER BY "parentA", "parentB" @@ -238,7 +238,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "parent" WHERE "parentA" = 'foo' ORDER BY "parentA", "parentB" @@ -268,7 +268,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "a" ORDER BY "cola1" @@ -302,7 +302,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "a" ORDER BY "cola1" @@ -354,7 +354,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * \ @@ -419,7 +419,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "a" ORDER BY "cola1" @@ -448,7 +448,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "a" ORDER BY "cola1" @@ -501,7 +501,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * \ @@ -543,7 +543,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "a" ORDER BY "cola1" @@ -579,7 +579,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "a" \ @@ -623,7 +623,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "b" ORDER BY "colb1" @@ -658,7 +658,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "b" ORDER BY "colb1" @@ -696,7 +696,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "b" ORDER BY "colb1" @@ -738,7 +738,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "b" ORDER BY "colb1" @@ -772,7 +772,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "a" ORDER BY "cola1" @@ -812,7 +812,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "a" ORDER BY "cola1" @@ -854,7 +854,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "a" ORDER BY "cola1" @@ -900,7 +900,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT * FROM "a" ORDER BY "cola1" @@ -941,7 +941,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT "b".*, "a".* \ @@ -993,7 +993,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT "b".*, "a1".*, "a2".* \ @@ -1051,7 +1051,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT "a".*, "c".* \ @@ -1103,7 +1103,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT "a".*, "c1".*, "c2".* \ @@ -1163,7 +1163,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT "d".*, "c".*, "a".* \ @@ -1201,7 +1201,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } XCTAssertEqual(selectQueries, [ """ SELECT "d".*, "a".* \ @@ -1239,7 +1239,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } // LEFT JOIN in the first query are useless but harmless. // And SQLite may well optimize them out. // So don't bother removing them. @@ -1294,7 +1294,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } // LEFT JOIN in the first query are useless but harmless. // And SQLite may well optimize them out. // So don't bother removing them. @@ -1355,7 +1355,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } // LEFT JOIN in the first query are useless but harmless. // And SQLite may well optimize them out. // So don't bother removing them. @@ -1410,7 +1410,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } // LEFT JOIN in the first query are useless but harmless. // And SQLite may well optimize them out. // So don't bother removing them. @@ -1473,7 +1473,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } // LEFT JOIN in the first query are useless but harmless. // And SQLite may well optimize them out. // So don't bother removing them. @@ -1514,7 +1514,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { sqlQueries.removeAll() _ = try Row.fetchAll(db, request) - let selectQueries = sqlQueries.filter { $0.contains("SELECT") } + let selectQueries = sqlQueries.filter { $0.contains("SELECT") && !$0.contains("sqlite_") } // LEFT JOIN in the first query are useless but harmless. // And SQLite may well optimize them out. // So don't bother removing them. From fe9c4381e09f297b4ad27f0136fab5fecad7701e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 4 Aug 2019 14:59:48 +0200 Subject: [PATCH 76/91] Makefile: support for Xcode 10.3, and fix test_performance target --- Makefile | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index debe2b326..164025d43 100644 --- a/Makefile +++ b/Makefile @@ -49,7 +49,12 @@ 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),10.2) +ifeq ($(XCODEVERSION),10.3) + MAX_SWIFT_VERSION = 5 + MIN_SWIFT_VERSION = 4.2 + MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone X,OS=12.4" + MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 4s,OS=9.0" +else ifeq ($(XCODEVERSION),10.2) MAX_SWIFT_VERSION = 5 MIN_SWIFT_VERSION = 4.2 MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone X,OS=12.2" @@ -320,10 +325,10 @@ test_performance: Realm FMDB SQLite.swift -scheme GRDBOSXPerformanceComparisonTests \ build-for-testing test-without-building -Realm: Tests/Performance/Realm/build/osx/swift-10.2.1/RealmSwift.framework +Realm: Tests/Performance/Realm/build/osx/swift-10.3/RealmSwift.framework # Makes sure the Tests/Performance/Realm submodule has been downloaded, and Realm framework has been built. -Tests/Performance/Realm/build/osx/swift-10.2.1/RealmSwift.framework: +Tests/Performance/Realm/build/osx/swift-10.3/RealmSwift.framework: $(GIT) submodule update --init --recursive Tests/Performance/Realm cd Tests/Performance/Realm && sh build.sh osx-swift From fd18a7b75d8ccd19378733e22b0097d2b810a4d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 5 Aug 2019 07:48:34 +0200 Subject: [PATCH 77/91] Fix for Xcode < 10.2 --- GRDB/ValueObservation/ValueObserver.swift | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift index 78954e043..c7852174f 100644 --- a/GRDB/ValueObservation/ValueObserver.swift +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -79,9 +79,9 @@ class ValueObserver: TransactionObserver { return .commit } self.selectedRegion = selectedRegion - future = DatabaseFuture(Result.success(fetchedValue)) + future = DatabaseFuture(DatabaseResult.success(fetchedValue)) } catch { - future = DatabaseFuture(Result.failure(error)) + future = DatabaseFuture(DatabaseResult.failure(error)) } } else { // Synchronous read/write fetch @@ -104,9 +104,9 @@ class ValueObserver: TransactionObserver { } } self.selectedRegion = selectedRegion - future = DatabaseFuture(Result.success(fetchedValue)) + future = DatabaseFuture(DatabaseResult.success(fetchedValue)) } catch { - future = DatabaseFuture(Result.failure(error)) + future = DatabaseFuture(DatabaseResult.failure(error)) } } else { // Concurrent fetch From ea43468a6f69045872d23e6a41e601783eec86fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 5 Aug 2019 07:52:32 +0200 Subject: [PATCH 78/91] Documentation --- GRDB/Core/Statement.swift | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 66fdbb6d7..19aa651b0 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -276,6 +276,10 @@ extension Statement { /// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])! /// } public final class SelectStatement: Statement { + // Database region is computed during statement compilation, and maybe + // optimized when statement is compiled for a QueryInterfaceRequest, in + // order to perform focused database observation. See + // SQLQueryGenerator.optimizedDatabaseRegion(_:_:) /// The database region that the statement looks into. public internal(set) var databaseRegion = DatabaseRegion() From f849c38f43fbeed45e96996f984a4494038e42ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 5 Aug 2019 08:34:47 +0200 Subject: [PATCH 79/91] Foster ValueObservation.tracking(fetch:) in README --- README.md | 91 +++++++++++++++++++++++++++++-------------------------- 1 file changed, 48 insertions(+), 43 deletions(-) diff --git a/README.md b/README.md index 936d12807..18a846bb9 100644 --- a/README.md +++ b/README.md @@ -6054,7 +6054,9 @@ let request = Player.all() [ValueObservation] notifies your application with **fresh values** (this is what most applications need :+1:): ```swift -let observation = request.observationForAll() +let observation = ValueObservation.tracking { db in + try request.fetchAll(db) +} let observer = observation.start( in: dbQueue, onError: { error in @@ -6119,8 +6121,9 @@ class PlayerViewController: UIViewController { super.viewWillAppear(animated) // Define a ValueObservation which tracks a player - let request = Player.filter(key: 42) - let observation = request.observationForFirst() + let observation = ValueObservation.tracking { db in + try Player.fetchOne(db, key: 42) + } // Start observing the database observer = observation.start( @@ -6158,8 +6161,9 @@ The observer returned by the `start` method is stored in a property of the view > super.viewWillAppear(animated) > > // Define a ValueObservation which tracks a player -> let request = Player.filter(key: 42) -> var observation = request.observationForFirst() +> let observation = ValueObservation.tracking { db in +> try Player.fetchOne(db, key: 42) +> } > > // Observation is asynchronous > observation.scheduling = .async(onQueue: .main, startImmediately: true) @@ -6392,7 +6396,8 @@ For example: ```swift // Observe a player's profile image -let observation = Player.filter(key: 42).observationForFirst() +let observation = ValueObservation + .tracking { db in try Player.fetchOne(db, key: 42) } .map { player in player?.image } let observer = observation.start( @@ -6414,7 +6419,8 @@ For example: ```swift // Observe a player -let observation = Player.filter(key: 42).observationForFirst() +let observation = ValueObservation + .tracking { db in try Player.fetchOne(db, key: 42) } .compactMap { $0 } let observer = observation.start( @@ -6435,19 +6441,15 @@ The `removeDuplicates` method filters out the consecutive equal values notified For example: ```swift -let observation = Player.filter(key: 42).observationForFirst() - .map { player in player != nil } // existence test +let observation = ValueObservation + .tracking { db in try Player.fetchOne(db, key: 42) } .removeDuplicates() let observer = observation.start( in: dbQueue, onError: { error in ... }, - onChange: { (exists: Bool) in - if exists { - print("Player 42 exists.") - } else { - print("Player 42 does not exist.") - } + onChange: { (player: Player) in + print("Player: \(player)") }) ``` @@ -6460,15 +6462,20 @@ The `ValueObservation.combine(...)` method builds a single observation from seve ```swift // Two base observations -let playerCountObservation = Player.observationForCount() -let bestPlayersObservation = Player - .limit(10) - .order(Column("score").desc) - .observationForAll() +let playerCountObservation = ValueObservation.tracking { db in + try Player.fetchCount(db) +} +let bestPlayersObservation = ValueObservation.tracking { db in + try Player + .limit(10) + .order(Column("score").desc) + .fetchAll(db) +} // The combined observation -let observation = ValueObservation - .combine(playerCountObservation, bestPlayersObservation) +let observation = ValueObservation.combine( + playerCountObservation, + bestPlayersObservation) // Start tracking the hall of fame let observer = observation.start( @@ -6549,36 +6556,34 @@ The `scheduling` property lets you control how fresh values are notified: ```swift // On main queue - let observer = Player.observationForAll().start( + let observer = observation.start( in: dbQueue, onError: { error in ... }, - onChange: { (players: [Player]) in + onChange: { value in // On main queue - print("fresh players: \(players)") + print("fresh value: \(value)") }) - // <- here "fresh players" is already printed. + // <- Here "fresh value" is already printed. ``` If the observation does not start on the main queue, an initial value is also notified on the main queue, but asynchronously: ```swift // Not on the main queue - let observer = Player.observationForAll().start( + let observer = observation.start( in: dbQueue, onError: { error in ... }, - onChange: { (players: [Player]) in + onChange: { value in // On main queue - print("fresh players: \(players)") + print("fresh value: \(value)") }) ``` - When the database changes, fresh values are asynchronously notified: + After the initial value has been notified, all subsequent values are notified asynchronously: ```swift - // Eventually prints "fresh players" on the main queue - try dbQueue.write { db in - try Player(...).insert(db) - } + try dbQueue.write { db in ... } + // <- Eventually prints "fresh value" on the main queue ``` - `.async(onQueue:startImmediately:)`: all values are asychronously notified on the specified queue. @@ -6589,16 +6594,16 @@ The `scheduling` property lets you control how fresh values are notified: ```swift // On main queue - var observation = Player.observationForAll() + var observation = ... observation.scheduling = .async(onQueue: .main, startImmediately: true) let observer = observation.start( in: dbQueue, onError: { error in ... }, - onChange: { (players: [Player]) in + onChange: { value in // On main queue - print("fresh players: \(players)")s + print("fresh value: \(value)") }) - // <- here "fresh players" is not printed yet. + // <- Eventually prints "fresh value" ``` - `unsafe(startImmediately:)`: values are not all notified on the same dispatch queue. @@ -6607,18 +6612,18 @@ The `scheduling` property lets you control how fresh values are notified: ```swift // On any queue - var observation = Player.observationForAll() + var observation = ... observation.scheduling = .unsafe(startImmediately: true) let observer = observation.start( in: dbQueue, onError: { error in ... }, - onChange: { (players: [Player]) in - print("fresh players: \(players)") + onChange: { value in + print("fresh value: \(value)") }) - // <- here "fresh players" is already printed. + // <- Here "fresh value" is already printed. ``` - When the database changes, other values are notified on unspecified queues. + After the initial value has been notified, all subsequent values are notified on unspecified queues. > :point_up: **Note**: this unsafe mode is intended for third-party libraries that provide their own scheduling engine. From efaa387ee24c5a8f8350e87f908b3d28c37832f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 5 Aug 2019 08:38:25 +0200 Subject: [PATCH 80/91] Remove useless documentation paragraph --- Documentation/AssociationsBasics.md | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index f20f176b6..a47f1d8b9 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -822,19 +822,6 @@ let novels = try author .fetchAll(db) // [Book] ``` -Those requests can also turn out useful when you want to track their changes with [database observation tools] like [ValueObservation]: - -```swift -// Track changes in the author's books: -let author: Author = ... -author.books.observationForAll().start( - in: dbQueue, - onError: { error in ... }, - onChange: { (books: [Book]) in - print("Author's book have changed") - }) -``` - ## Joining And Prefetching Associated Records From a770d468437bf7b72b6997217c8d27491c1abc72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 5 Aug 2019 09:03:05 +0200 Subject: [PATCH 81/91] Rename ValueObservation.tracking(fetch:) to ValueObservation.tracking(value:) --- GRDB/ValueObservation/ValueObservation.swift | 7 +++---- README.md | 12 ++++++------ 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 16f20eb10..0f11dd39d 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -345,16 +345,15 @@ extension ValueObservation where Reducer == Void { /// - The observation lasts until the observer returned by /// `start` is deallocated. /// - /// - parameter regions: A list of observed regions. - /// - parameter fetch: A closure that fetches a value. + /// - parameter value: A closure that fetches a value. public static func tracking( - fetch: @escaping (Database) throws -> Value) + value: @escaping (Database) throws -> Value) -> ValueObservation> { return ValueObservation>( baseRegion: { _ in DatabaseRegion() }, observesSelectedRegion: true, - makeReducer: { _ in ValueReducers.Fetch(fetch) }, + makeReducer: { _ in ValueReducers.Fetch(value) }, requiresWriteAccess: false, scheduling: .mainQueue) } diff --git a/README.md b/README.md index 18a846bb9..dbb2408ee 100644 --- a/README.md +++ b/README.md @@ -6100,7 +6100,7 @@ Changes are only notified after they have been committed in the database. No ins - **[ValueObservation Usage](#valueobservation-usage)** - [observationForCount, observationForAll, observationForFirst](#observationforcount-observationforall-observationforfirst) -- [ValueObservation.tracking(fetch:)](#valueobservationtrackingfetch) +- [ValueObservation.tracking(value:)](#valueobservationtrackingvalue) - [ValueObservation.tracking(_:fetch:)](#valueobservationtracking_fetch) - [ValueObservation Transformations](#valueobservation-transformations): [map](#valueobservationmap), [compactMap](#valueobservationcompactmap), ... - [ValueObservation Error Handling](#valueobservation-error-handling) @@ -6258,7 +6258,7 @@ They perform a filtering of consecutive identical values, based on raw database ``` -### ValueObservation.tracking(fetch:) +### ValueObservation.tracking(value:) Observing the database is not always a matter of tracking a single request, as above. @@ -6298,7 +6298,7 @@ print(""" """) ``` -Now, in order to track changes in the Hall of Fame, we'll use the `ValueObservation.tracking(fetch:)` method. Just make it fetch the observed values: +Now, in order to track changes in the Hall of Fame, we'll use the `ValueObservation.tracking(value:)` method. Just make it fetch the observed value: ```swift let observation = ValueObservation.tracking { db in @@ -6316,7 +6316,7 @@ let observer = observation.start( }) ``` -- Observation built from `ValueObservation.tracking(fetch:)` can observe several tables: +- Observation built from `ValueObservation.tracking(value:)` can observe several tables: ```swift // Observe several tables @@ -6330,7 +6330,7 @@ let observer = observation.start( } ``` -- Unlike [observationForCount, observationForAll, observationForFirst](#observationforcount-observationforall-observationforfirst), `ValueObservation.tracking(fetch:)` does not filter out consecutive identical values. For example, database changes that happen to the worst players trigger the observation of the Hall of Fame, just in case the best players would be modified. +- Unlike [observationForCount, observationForAll, observationForFirst](#observationforcount-observationforall-observationforfirst), `ValueObservation.tracking(value:)` does not filter out consecutive identical values. For example, database changes that happen to the worst players trigger the observation of the Hall of Fame, just in case the best players would be modified. You can filter out those duplicates with the [ValueObservation.removeDuplicates](#valueobservationremoveduplicates) method. It requires the observed value to adopt the Equatable protocol: @@ -6347,7 +6347,7 @@ let observer = observation.start( ### ValueObservation.tracking(_:fetch:) -The `ValueObservation.tracking(_:fetch:)` method is an **optimized** version of the [`ValueObservation.tracking(fetch:)`](#valueobservationtrackingfetch) method seen above. +The `ValueObservation.tracking(_:fetch:)` method is an **optimized** version of the [`ValueObservation.tracking(value:)`](#valueobservationtrackingvalue) method seen above. It ouputs exactly the same results, but it can perform better when you use a [database pool](#database-pools), and the fetch is slow. It reduces write contention by fetching fresh values without blocking write accesses. When you use a [database queue](#database-queues), no optimization is applied. From 8af3b58e546fcd845ed3842221b3d11680f8d22c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 5 Aug 2019 09:04:14 +0200 Subject: [PATCH 82/91] Fix documentation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index dbb2408ee..f90eb2d5a 100644 --- a/README.md +++ b/README.md @@ -6338,7 +6338,7 @@ let observer = observation.start( extension HallOfFame: Equatable { ... } let observation = ValueObservation - .tracking(fetch: HallOfFame.fetch) + .tracking(value: HallOfFame.fetch) .removeDuplicates() ``` From 87b474029e7fc6c9f18b0492ee2c951370498cb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 5 Aug 2019 12:31:39 +0200 Subject: [PATCH 83/91] Test that observations of tuples are easy to consume. --- .../ValueObservationRegionRecordingTests.swift | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift index 944cf2821..baa448377 100644 --- a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift +++ b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift @@ -73,6 +73,20 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { } } + func testTupleObservation() throws { + // Here we just test that user can destructure an observed tuple. + // I'm completely paranoid about tuple destructuring - I can't wrap my + // head about the rules that allow or disallow it. + let dbQueue = try makeDatabaseQueue() + let observation = ValueObservation.tracking { db -> (Int, String) in + (0, "") + } + _ = observation.start( + in: dbQueue, + onError: { _ in }, + onChange: { (int: Int, string: String) in }) // <- destructure + } + func testMainQueueScheduling() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { From e279d287b907df4f9db63044eb3c955f93927420 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 5 Aug 2019 12:32:12 +0200 Subject: [PATCH 84/91] Even more fostering of ValueObservation.tracking(fetch:) in README --- README.md | 249 +++++++++++++++++++----------------------------------- 1 file changed, 89 insertions(+), 160 deletions(-) diff --git a/README.md b/README.md index f90eb2d5a..34b29a917 100644 --- a/README.md +++ b/README.md @@ -6099,9 +6099,9 @@ Changes are only notified after they have been committed in the database. No ins - **[ValueObservation Usage](#valueobservation-usage)** -- [observationForCount, observationForAll, observationForFirst](#observationforcount-observationforall-observationforfirst) - [ValueObservation.tracking(value:)](#valueobservationtrackingvalue) - [ValueObservation.tracking(_:fetch:)](#valueobservationtracking_fetch) +- [observationForCount, observationForAll, observationForFirst](#observationforcount-observationforall-observationforfirst) - [ValueObservation Transformations](#valueobservation-transformations): [map](#valueobservationmap), [compactMap](#valueobservationcompactmap), ... - [ValueObservation Error Handling](#valueobservation-error-handling) - [ValueObservation Options](#valueobservation-options) @@ -6131,8 +6131,9 @@ class PlayerViewController: UIViewController { onError: { error in print("player could not be fetched") }, - onChange: { [unowned self] (player: Player?) in + onChange: { [weak self] (player: Player?) in // Player has been refreshed: update view + guard let self = self else { return } self.nameLabel.text = player?.name }) } @@ -6174,8 +6175,9 @@ The observer returned by the `start` method is stored in a property of the view > onError: { error in > print("player could not be fetched") > }, -> onChange: { [unowned self] (player: Player?) in +> onChange: { [weak self] (player: Player?) in > // Player has been refreshed: update view +> guard let self = self else { return } > self.activityIndicator.stopAnimating() > self.nameLabel.text = player?.name > }) @@ -6189,80 +6191,66 @@ The observer returned by the `start` method is stored in a property of the view > See [ValueObservation.scheduling](#valueobservationscheduling) for more information. -### observationForCount, observationForAll, observationForFirst - -Given a [request](#requests), even a [custom request](#custom-requests), you can observe its number of results, all results, or the first one: - -```swift -request.observationForCount() -request.observationForAll() -request.observationForFirst() -``` - -Those observations match the `fetchCount`, `fetchAll`, and `fetchOne` request methods. - -They perform a filtering of consecutive identical values, based on raw database values, so that you are not notified of database changes that do not impact the result of the request. - -- `observationForCount()` notifies counts: - - ```swift - // Observe number of players - let observer = Player.observationForCount().start( - in: dbQueue, - onError: { error in ... }, - onChange: { (count: Int) in - print("Number of players have changed: \(count)") - }) - ``` - -- `observationForAll()` notifies arrays: - - ```swift - // Observe all players - let observer = Player.observationForAll().start( - in: dbQueue, - onError: { error in ... }, - onChange: { (players: [Player]) in - print("Players have changed: \(players)") - }) - - // Observe all player names - let request = SQLRequest(sql: "SELECT name FROM player") - let observer = request.observationForAll().start( - in: dbQueue, - onError: { error in ... }, - onChange: { (names: [String]) in - print("Player names have changed: \(names)") - }) - ``` - -- `observationForFirst()` notifies optional values, built from a single database row (if any): - - ```swift - // Observe a single player - let observer = Player.filter(key: 1).observationForFirst().start( - in: dbQueue, - onError: { error in ... }, - onChange: { (player: Player?) in - print("Player has changed: \(player)") - }) - - // Observe the maximum score - let request = Player.select(max(Column("score")), as: Int.self) - let observer = request.observationForFirst().start( - in: dbQueue, - onError: { error in ... }, - onChange: { (maximumScore: Int?) in - print("Maximum score has changed: \(maximumScore)") - }) - ``` - - ### ValueObservation.tracking(value:) -Observing the database is not always a matter of tracking a single request, as above. +In order to observe database values, you will generally define a **ValueObservation** which tracks the value you are interested in, and then start the observation. -For example, let's say that we have a struct that defines a "Hall of Fame": +For example: + +```swift +// Track changes in a single player +let observation = ValueObservation.tracking { db in + try Player.fetchOne(db, key: 42) +} + +observer = observation.start( + in: dbQueue, + onError: { error in ... }, + onChange: { (player: Player?) in + print("Fresh player: \(player)") + }) +``` + +**You can observe several requests and several tables if you need**: all writes that have an impact on the fetched values will trigger the observation, and call the `onChange` function. + +**It may happen that such an observation notifies identical consecutive values.** This is because it will fetch a fresh value whenever a change *could* happen. For example, the observation for the maximum player score will notify a fresh value everytime a score is changed, inserted, or deleted, even if the maximum score is unchanged: + +```swift +// Track changes in the maximum player score +// This observation may notify duplicate values +let observation = ValueObservation.tracking { db in + try Player.select(max(Column("score")), as: Int.self).fetchOne(db) +} +``` + +You can filter out those duplicates with the [ValueObservation.removeDuplicates](#valueobservationremoveduplicates) method. It requires the observed value to adopt the Equatable protocol: + +```swift +let observation = ValueObservation + .tracking { db in + try Player.select(max(Column("score")), as: Int.self).fetchOne(db) + } + .removeDuplicates() +``` + + +We will see below other ways to define observations. They all add a little convenience, or optimization. + + +### ValueObservation.tracking(_:fetch:) + +The `ValueObservation.tracking(_:fetch:)` method is an **optimized** version of the [`ValueObservation.tracking(value:)`](#valueobservationtrackingvalue) method seen above. + +The returned observation ouputs exactly the same results, but it can perform better when you use a [database pool](#database-pools), and the fetch is slow. It reduces write contention by fetching fresh values without blocking write accesses. When you use a [database queue](#database-queues), no optimization is applied. + +It accepts two arguments: + +1. A list of observed requests. +2. A closure that fetches a fresh value whenever one of the observed requests are modified. + +Changes that happen outside of the observed requests are ignored, so make sure you fully cover the database region you want to observe. This is the price you pay for the optimization. + +Let's give a practical example, and observe the "Hall of Fame": ```swift struct HallOfFame { @@ -6271,11 +6259,8 @@ struct HallOfFame { } ``` -To fetch the Hall of Fame from the database, we perform two requests: the 10 best players, and the total number of players. Following the Rule 2 of the [Concurrency Guide](#guarantees-and-rules), we make sure the two requests are always performed in a single database access, as below: - -```swift -extension { - /// Fetch a HallOfFame +extension HallOfFame { + /// Fetch the HallOfFame static fetch(_ db: Database) throws -> HallOfFame { let totalPlayerCount = try Player.fetchCount(db) let bestPlayers = try Player @@ -6287,99 +6272,43 @@ extension { bestPlayers: bestPlayers) } } - -let hallOfFame = try dbQueue.read { db in - try HallOfFame.fetch(db) -} - -print(""" - Best players out of \(hallOfFame.totalPlayerCount): - \(hallOfFame.bestPlayers) - """) ``` -Now, in order to track changes in the Hall of Fame, we'll use the `ValueObservation.tracking(value:)` method. Just make it fetch the observed value: - -```swift -let observation = ValueObservation.tracking { db in - try HallOfFame.fetch(db) -} - -let observer = observation.start( - in: dbQueue, - onError: { error in ... }, - onChange: { (hallOfFame: HallOfFame) in - print(""" - Best players out of \(hallOfFame.totalPlayerCount): - \(hallOfFame.bestPlayers) - """) - }) -``` - -- Observation built from `ValueObservation.tracking(value:)` can observe several tables: - - ```swift - // Observe several tables - let teamId = 123 - let observation = ValueObservation.tracking { db -> (Team, [Player])? in - guard let team = try Team.fetchOne(db, key: teamId) else { - return nil - } - let players = Player.filter(teamId: teamId).fetchAll(db) - return (team, players) - } - ``` - -- Unlike [observationForCount, observationForAll, observationForFirst](#observationforcount-observationforall-observationforfirst), `ValueObservation.tracking(value:)` does not filter out consecutive identical values. For example, database changes that happen to the worst players trigger the observation of the Hall of Fame, just in case the best players would be modified. - - You can filter out those duplicates with the [ValueObservation.removeDuplicates](#valueobservationremoveduplicates) method. It requires the observed value to adopt the Equatable protocol: - - ```swift - extension HallOfFame: Equatable { ... } - - let observation = ValueObservation - .tracking(value: HallOfFame.fetch) - .removeDuplicates() - ``` - -- When you use a [database pool](#database-pools), and the fetch is slow, you may optimize the observation by using the [`ValueObservation.tracking(_:fetch:)`](#valueobservationtracking_fetch) method. See below. - - -### ValueObservation.tracking(_:fetch:) - -The `ValueObservation.tracking(_:fetch:)` method is an **optimized** version of the [`ValueObservation.tracking(value:)`](#valueobservationtrackingvalue) method seen above. - -It ouputs exactly the same results, but it can perform better when you use a [database pool](#database-pools), and the fetch is slow. It reduces write contention by fetching fresh values without blocking write accesses. When you use a [database queue](#database-queues), no optimization is applied. - -It accepts two arguments: - -1. A list of observed requests. -2. A closure that fetches a fresh value whenever one of the observed requests are modified. - -Changes that happen outside of the observed requests are ignored, so make sure you fully cover the database region you want to observe. This is the price you pay for the optimization. - -In the Hall Of Fame example seen above, any change to the `player` table can impact the Hall of Fame. We thus track the request for all players, `Player.all()`, and fetch a new Hall of Fame whenever players change: +In order to track changes in the Hall of Fame in an optimized way, we see that any change to the `player` table can impact the Hall of Fame. We thus track the request for all players, `Player.all()`, and fetch a new Hall of Fame whenever players change: ```swift let observation = ValueObservation.tracking(Player.all(), fetch: { db in try HallOfFame.fetch(db) }) - -let observer = observation.start( - in: dbQueue, - onError: { error in ... }, - onChange: { (hallOfFame: HallOfFame) in - print(""" - Best players out of \(hallOfFame.totalPlayerCount): - \(hallOfFame.bestPlayers) - """) - }) ``` - > :point_up: **Note**: the initial parameter of `ValueObservation.tracking(_:fetch:)` can be fed with requests, and generally speaking, values that adopt the [DatabaseRegionConvertible] protocol. +### observationForCount, observationForAll, observationForFirst + +Given a [request](#requests), even a [custom request](#custom-requests), you can observe its number of results, all results, or the first one: + +```swift +request.observationForCount() +request.observationForAll() +request.observationForFirst() +``` + +Those observations are equivalent to the following ones, defined with [`ValueObservation.tracking(value:)`](#valueobservationtrackingvalue): + +```swift +ValueObservation.tracking { db in try request.fetchCount(db) } +ValueObservation.tracking { db in try request.fetchAll(db) } +ValueObservation.tracking { db in try request.fetchOne(db) } +``` + +Yet they are **optimized**: + +- They perform a filtering of consecutive identical values, based on raw database values, so that you are not notified of database changes that do not impact the result of the request. +- They can perform better when you use a [database pool](#database-pools), and the fetch is slow. + + ### ValueObservation Transformations - [ValueObservation.map](#valueobservationmap) From ba1142ac5863895428b94661295e0e201f74aa2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 5 Aug 2019 12:34:23 +0200 Subject: [PATCH 85/91] Fix typo --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 34b29a917..533222a7f 100644 --- a/README.md +++ b/README.md @@ -6257,7 +6257,6 @@ struct HallOfFame { var totalPlayerCount: Int var bestPlayers: [Player] } -``` extension HallOfFame { /// Fetch the HallOfFame From 80baa798d6550e3e3b8ca9028bca3cb629eef18d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 5 Aug 2019 12:39:37 +0200 Subject: [PATCH 86/91] CHANGELOG --- CHANGELOG.md | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 693906ae7..e71e5e4b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,15 +54,29 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: ## Next Release +**New** + +- [#570](https://github.com/groue/GRDB.swift/pull/570) by [@chrisballinger](https://github.com/chrisballinger): Allow Swift static library integration via CocoaPods +- [#576](https://github.com/groue/GRDB.swift/pull/576): Expose table name and full-text filtering methods to DerivableRequest +- [#586](https://github.com/groue/GRDB.swift/pull/586): Automatic region tracking for ValueObservation + +**Fixed** + - [#560](https://github.com/groue/GRDB.swift/pull/560) by [@bellebethcooper](https://github.com/bellebethcooper): Minor typo fix - [#562](https://github.com/groue/GRDB.swift/pull/562): Fix crash when using more than one DatabaseCollation -- [#563](https://github.com/groue/GRDB.swift/pull/563): More tests for eager loading of hasMany associations -- [#570](https://github.com/groue/GRDB.swift/pull/570) by [@chrisballinger](https://github.com/chrisballinger): Allow Swift static library integration via CocoaPods -- [#574](https://github.com/groue/GRDB.swift/pull/574): SwiftLint -- [#576](https://github.com/groue/GRDB.swift/pull/576): Expose table name and full-text filtering methods to DerivableRequest - [#577](https://github.com/groue/GRDB.swift/pull/577): Rename `aliased(_:)` methods to `forKey(_:)` - [#585](https://github.com/groue/GRDB.swift/pull/585): Fix use of SQLite authorizers -- [#586](https://github.com/groue/GRDB.swift/pull/586): Automatic region tracking for ValueObservation + +**Other** + +- [#563](https://github.com/groue/GRDB.swift/pull/563): More tests for eager loading of hasMany associations +- [#574](https://github.com/groue/GRDB.swift/pull/574): SwiftLint + + +### Documentation Diff + +The [ValueObservation](README.md#valueobservation) chapter has been updated so that it fosters the new `ValueObservation.tracking(value:)` method. Other ways to define observations are now described as optimizations. + ### API Diff From 226410caf8a64924e59badad13cd81761f3dc5f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 5 Aug 2019 20:19:48 +0200 Subject: [PATCH 87/91] TODO cleanup --- TODO.md | 105 ++++++++++++++++++++++---------------------------------- 1 file changed, 41 insertions(+), 64 deletions(-) diff --git a/TODO.md b/TODO.md index 1491711e7..78a5974bc 100644 --- a/TODO.md +++ b/TODO.md @@ -1,6 +1,17 @@ -- [ ] Attach databases. Interesting question: what happens when one attaches a non-WAL db to a databasePool? +## Cleanup + - [ ] SQLCipher: sqlite3_rekey is discouraged (https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320) -- [ ] Query builder +- [ ] Write regression tests for #156 and #157 +- [ ] Fix matchingRowIds (todo: what is the problem, already?) +- [ ] deprecate ScopeAdapter(base, scopes), because base.addingScopes has a better implementation +- [ ] https://github.com/groue/GRDB.swift/issues/514 +- [ ] Test NOT TESTED methods + + +## Features + +- [ ] Attach databases. Interesting question: what happens when one attaches a non-WAL db to a databasePool? +- [ ] SQL Generation - [ ] date functions - [ ] NOW/CURRENT_TIMESTAMP - [ ] ROUND() http://marc.info/?l=sqlite-users&m=130419182719263 @@ -8,82 +19,54 @@ - [ ] GLOB https://www.sqlite.org/lang_expr.html - [ ] REGEXP https://www.sqlite.org/lang_expr.html - [ ] CASE x WHEN w1 THEN r1 WHEN w2 THEN r2 ELSE r3 END https://www.sqlite.org/lang_expr.html -- [ ] Write regression tests for #156 and #157 - [ ] Allow concurrent reads from a snapshot - [ ] Decode NSDecimalNumber from text database values - [ ] Check https://sqlite.org/sqlar.html -- [ ] filter(rowid:), filter(rowids:) -- [ ] Fix matchingRowIds -- [ ] Simplify Range extensions for Swift 4.1 -- [ ] https://forums.swift.org/t/how-to-encode-objects-of-unknown-type/12253/6 -- [ ] deprecate ScopeAdapter(base, scopes), because base.addingScopes has a better implementation -- [ ] Joins and full-text tables -- [ ] UPSERT https://www.sqlite.org/lang_UPSERT.html -- [ ] https://github.com/apple/swift-evolution/blob/master/proposals/0075-import-test.md -- [ ] Avoid code duplication: https://forums.swift.org/t/c-interoperability-combinations-of-library-and-os-versions/14029/4 -- [ ] Allow joining methods on DerivableRequest -- [ ] DatabaseWriter.assertWriteAccess() -- [ ] Configuration.crashOnError = true -- [ ] Support for "INSERT INTO ... SELECT ...". For example: - - ```swift - // INSERT INTO rigth (id, name) SELECT id, name FROM left - let lefts = Left.select(Left.Columns.id, Left.Columns.name) - try Right.insert(lefts) - ``` -- [ ] select values from a JSON column: - - ```swift - let nesteds = try Record - .select(Column("nested"), as: Nested.self) - .fetchAll(db) - ``` -- [ ] Consider renaming dbQueue.inDatabase, dbPool.writeWithoutTransaction -> dbQueue/Pool.exclusive -- [ ] FetchedRecordsController diff algorithm: check https://github.com/RxSwiftCommunity/RxDataSources/issues/256 -- [ ] https://github.com/groue/GRDB.swift/issues/514 -- [ ] Look at the jazzy configuration of https://github.com/bignerdranch/Deferred - [ ] FTS: prefix queries -- [ ] Test NOT TESTED methods - [ ] A way to stop a ValueObservation observer without waiting for deinit -- [ ] Glossary (Database Access Methods, etc.) -- [ ] One use case for query interface updates that is uneasy to deal with raw SQL: +- [ ] More schema alterations +- [ ] Query interface updates. One use case for query interface updates that is uneasy to deal with raw SQL: - ``` + ```swift // Uneasy to do with raw SQL let players = Player.filter(...) // Returns a request that filters on column A or column B depending on the argument players.update(...) // Runs the expected UPDATE statement ``` + +## Unsure if necessary + +- [ ] filter(rowid:), filter(rowids:) +- [ ] https://github.com/apple/swift-evolution/blob/master/proposals/0075-import-test.md +- [ ] https://forums.swift.org/t/how-to-encode-objects-of-unknown-type/12253/6 +- [ ] Configuration.crashOnError = true +- [ ] Glossary (Database Access Methods, etc.) +- [ ] ValueObservation.flatMap. Not sure it is still useful now that we have ValueObservation.tracking(value:) +- [ ] rename fetchOne to fetchFirst. Not sure because it is a big breaking change. Not sure because ValueObservation.tracking(value:) has reduced the need for observationForFirst. +- [ ] Not sure: type safety for SQL expressions + - [ ] Introduce some record protocol with an associated primary key type. Restrict filter(key:) methods to this type. Allow distinguishing FooId from BarId types. + - [ ] Replace Column with TypedColumn. How to avoid code duplication (repeated types)? Keypaths? +- [ ] Cursor.underestimatedCount, which could speed up Array(cursor) and fetchAll() + + +## Unsure how + +- [ ] Joins and full-text tables +- [ ] UPSERT https://www.sqlite.org/lang_UPSERT.html +- [ ] Support for "INSERT INTO ... SELECT ...". +- [ ] Look at the jazzy configuration of https://github.com/bignerdranch/Deferred - [ ] Predicates, so that a filter can be evaluated both on the database, and on a record instance. After investigation, we can't do it reliably without knowing the collation used by a column. And SQLite does not provide this information elsewhere than in the full CREATE TABLE statement stored in sqlite_master. - - [ ] ValueObservation erasure ``` // Do better than this observation.mapReducer { _, reducer in AnyValueReducer(reducer) } ``` - -- [ ] ValueObservation.flatMap: - - Make it possible to build a single observation where some requests depend on the result of other requests. As long as we can't express this in a single observation, we fail the "guaranteed consistency is possible" contract. -- [ ] rename fetchOne to fetchFirst + +- [ ] FetchedRecordsController diff algorithm: check https://github.com/RxSwiftCommunity/RxDataSources/issues/256 - [ ] new.updateChanges(from: old) vs. old.updateChanges(with: { old.a = new.a }). This is confusing. - -Swift 4.2 - -- [ ] https://github.com/apple/swift-evolution/blob/master/proposals/0208-package-manager-system-library-targets.md -- [ ] https://github.com/apple/swift-evolution/blob/master/proposals/0201-package-manager-local-dependencies.md - -Not sure - -- [ ] HiddenColumnsAdapter -- [ ] Not sure: type safety for SQL expressions - - [ ] Introduce some record protocol with an associated primary key type. Restrict filter(key:) methods to this type. Allow distinguishing FooId from BarId types. - - [ ] Replace Column with TypedColumn. How to avoid code duplication (repeated types)? Keypaths? -- [ ] Encode/decode nested records/arrays/dictionaries as JSON? -- [ ] Cursor.underestimatedCount, which could speed up Array(cursor) and fetchAll() - [ ] Support for OR ROLLBACK, and mismatch between the Swift depth and the SQLite depth of nested transactions/savepoint: ```swift @@ -125,13 +108,7 @@ Not sure ``` -Requires recompilation of SQLite: - -- [ ] https://www.sqlite.org/c3ref/column_database_name.html could help extracting out of a row a subrow only made of columns that come from a specific table. Requires SQLITE_ENABLE_COLUMN_METADATA which is not set on the sqlite3 lib that ships with OSX. - - - -Reading list: +## Reading list - Documentation generation: https://twitter.com/jckarter/status/987525569196650496: cmark is the implementation the Swift compiler uses for doc comments etc. - VACUUM (https://blogs.gnome.org/jnelson/) From 71bf6fdbcf12a194dfd90c4878204d8925d67c97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 5 Aug 2019 20:30:29 +0200 Subject: [PATCH 88/91] TODO --- TODO.md | 1 + 1 file changed, 1 insertion(+) diff --git a/TODO.md b/TODO.md index 78a5974bc..ceca30204 100644 --- a/TODO.md +++ b/TODO.md @@ -47,6 +47,7 @@ - [ ] Introduce some record protocol with an associated primary key type. Restrict filter(key:) methods to this type. Allow distinguishing FooId from BarId types. - [ ] Replace Column with TypedColumn. How to avoid code duplication (repeated types)? Keypaths? - [ ] Cursor.underestimatedCount, which could speed up Array(cursor) and fetchAll() +- [ ] Remove prefix from association keys when association name is namespaced: https://github.com/groue/GRDB.swift/issues/584#issuecomment-517658122 ## Unsure how From c734eba2451676247905393bea062c1edd0fceb7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 5 Aug 2019 20:51:49 +0200 Subject: [PATCH 89/91] Upgrade performance tests Upgrade Realm to v3.17.3 Upgrade FMDB to v2.7.4 Upgrade SQLite.swift to v0.12.2 --- Tests/Performance/Realm | 2 +- Tests/Performance/SQLite.swift | 2 +- Tests/Performance/fmdb | 2 +- Tests/generatePerformanceReport.rb | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Tests/Performance/Realm b/Tests/Performance/Realm index 83824b6af..413515f82 160000 --- a/Tests/Performance/Realm +++ b/Tests/Performance/Realm @@ -1 +1 @@ -Subproject commit 83824b6afd64ce068d45ed1ad86310d1ea37ce6c +Subproject commit 413515f82af5e2eda8901fd6cd20c8be2c67ed1c diff --git a/Tests/Performance/SQLite.swift b/Tests/Performance/SQLite.swift index 691fc89e7..0a9893ec0 160000 --- a/Tests/Performance/SQLite.swift +++ b/Tests/Performance/SQLite.swift @@ -1 +1 @@ -Subproject commit 691fc89e75873d417d700920e79a63cf210d1d71 +Subproject commit 0a9893ec030501a3956bee572d6b4fdd3ae158a1 diff --git a/Tests/Performance/fmdb b/Tests/Performance/fmdb index 7397e456a..e0fcde9a0 160000 --- a/Tests/Performance/fmdb +++ b/Tests/Performance/fmdb @@ -1 +1 @@ -Subproject commit 7397e456a68ee344737bf377b1b76ba4fdd7a1fa +Subproject commit e0fcde9a0e5868e7400032448133f929c64500d1 diff --git a/Tests/generatePerformanceReport.rb b/Tests/generatePerformanceReport.rb index d803520d1..4c50ffe99 100755 --- a/Tests/generatePerformanceReport.rb +++ b/Tests/generatePerformanceReport.rb @@ -27,7 +27,7 @@ end samples = JSON.parse(STDIN.read) grdb_version = info_plist_version('Support/Info.plist') fmdb_version = info_plist_version('Tests/Performance/fmdb/src/fmdb/Info.plist') -sqlite_swift_version = '0.12.0' # not up-to-date: info_plist_version('Tests/Performance/SQLite.swift/Sources/SQLite/Info.plist') +sqlite_swift_version = info_plist_version('Tests/Performance/SQLite.swift/Sources/SQLite/Info.plist') realm_version = info_plist_version('Tests/Performance/Realm/build/osx/Realm.framework/Versions/A/Resources/Info.plist') puts <<-REPORT From eea8f7b1e9bb3a6402a7836bba1401c4e2a4a594 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 6 Aug 2019 06:54:39 +0200 Subject: [PATCH 90/91] Use ValueObservation.tracking(value:) in demo app --- DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift index 36554d7f6..5dfb42133 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift @@ -71,7 +71,10 @@ class PlayersViewController: UITableViewController { private func configureTitle() { // Track changes in the number of players - playerCountObserver = playersRequest.observationForCount().start( + let observation = ValueObservation.tracking { db in + try Player.fetchCount(db) + } + playerCountObserver = observation.start( in: dbQueue, onError: { error in fatalError("Unexpected error: \(error)") From bd81f6e7a63f53c021b6f3c80935c63418b3e436 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 6 Aug 2019 06:58:13 +0200 Subject: [PATCH 91/91] v4.2.0 --- CHANGELOG.md | 9 +++++ Documentation/CustomSQLiteBuilds.md | 2 +- GRDB.swift.podspec | 2 +- Makefile | 6 +-- README.md | 62 ++++++++++++++--------------- Support/Info.plist | 2 +- 6 files changed, 46 insertions(+), 37 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e71e5e4b4..1ab0c698d 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 expection: 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.2.x` Releases - [4.2.0](#420) - `4.1.x` Releases - [4.1.0](#410) | [4.1.1](#411) - `4.0.x` Releases - [4.0.0](#400) | [4.0.1](#401) @@ -52,7 +55,13 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: - [0.110.0](#01100), ... + + +## 4.2.0 + +Released August 6, 2019 • [diff](https://github.com/groue/GRDB.swift/compare/v4.1.1...v4.2.0) **New** diff --git a/Documentation/CustomSQLiteBuilds.md b/Documentation/CustomSQLiteBuilds.md index 1daf7e909..dabcadaa0 100644 --- a/Documentation/CustomSQLiteBuilds.md +++ b/Documentation/CustomSQLiteBuilds.md @@ -15,7 +15,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal ```sh cd [GRDB directory] - git checkout v4.1.1 + git checkout v4.2.0 git submodule update --init SQLiteCustom/src ```` diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 6499f1333..44cf88639 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.1.1' + s.version = '4.2.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 164025d43..8ec295e4d 100644 --- a/Makefile +++ b/Makefile @@ -370,10 +370,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.1.1 \ - --module-version 4.1 \ + --github-file-prefix https://github.com/groue/GRDB.swift/tree/v4.2.0 \ + --module-version 4.2.0 \ --module GRDB \ - --root-url http://groue.github.io/GRDB.swift/docs/4.1/ \ + --root-url http://groue.github.io/GRDB.swift/docs/4.2/ \ --output Documentation/Reference \ --xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS else diff --git a/README.md b/README.md index 533222a7f..683d8e286 100644 --- a/README.md +++ b/README.md @@ -5,14 +5,14 @@ GRDB 4 [![Swift 4.2](https://img.shields.io/badge/swift-4.2-orange.svg?style=fla --- -**Latest release**: June 22, 2019 • version 4.1.1 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 3 to GRDB 4](Documentation/GRDB3MigrationGuide.md) +**Latest release**: August 6, 2019 • version 4.2.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 3 to GRDB 4](Documentation/GRDB3MigrationGuide.md) **Requirements**: iOS 9.0+ / macOS 10.9+ / watchOS 2.0+ • Swift 4.2+ / Xcode 10.0+ | Swift version | GRDB version | | ------------- | ----------------------------------------------------------- | -| **Swift 5** | **v4.1.1** | -| **Swift 4.2** | **v4.1.1** | +| **Swift 5** | **v4.2.0** | +| **Swift 4.2** | **v4.2.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) | @@ -256,7 +256,7 @@ Documentation #### Reference -- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/4.1/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) +- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/4.2/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) #### Getting Started @@ -338,7 +338,7 @@ The [Swift Package Manager](https://swift.org/package-manager/) automates the di ```swift let package = Package( dependencies: [ - .package(url: "https://github.com/groue/GRDB.swift.git", .upToNextMajor(from: "4.1.1")) + .package(url: "https://github.com/groue/GRDB.swift.git", .upToNextMajor(from: "4.2.0")) ] ) ``` @@ -353,7 +353,7 @@ Note that Linux is not currently supported. ## Manually -1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v4.1.1) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v4.1.1` command. +1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v4.2.0) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v4.2.0` command. 2. Embed the `GRDB.xcodeproj` project in your own project. @@ -468,7 +468,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/4.1/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/4.2/Structs/Configuration.html) for more details. ## Database Pools @@ -549,7 +549,7 @@ let dbPool = try DatabasePool( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/4.1/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/4.2/Structs/Configuration.html) for more details. Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information. @@ -609,7 +609,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.1/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.2/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. @@ -810,7 +810,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.1/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.2/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 @@ -892,7 +892,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.1/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.2/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: @@ -1175,7 +1175,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.1/Structs/StatementArguments.html): +Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/4.2/Structs/StatementArguments.html): ```swift let url: URL = ... @@ -1582,7 +1582,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.1/Structs/Configuration.html) configuration flag: +Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/4.2/Structs/Configuration.html) configuration flag: ```swift // fatal error: A transaction has been left opened at the end of a database access @@ -1696,7 +1696,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.1/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.2/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). ```swift updateStatement.arguments = ["name": "Arthur", "score": 1000] @@ -1955,7 +1955,7 @@ row["consumed"] // "Hello" row["produced"] // nil ``` -Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/4.1/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.2/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). @@ -2101,8 +2101,8 @@ Before jumping in the low-level wagon, here is the list of all SQLite APIs used - `sqlite3_aggregate_context`, `sqlite3_create_function_v2`, `sqlite3_result_blob`, `sqlite3_result_double`, `sqlite3_result_error`, `sqlite3_result_error_code`, `sqlite3_result_int64`, `sqlite3_result_null`, `sqlite3_result_text`, `sqlite3_user_data`, `sqlite3_value_blob`, `sqlite3_value_bytes`, `sqlite3_value_double`, `sqlite3_value_int64`, `sqlite3_value_text`, `sqlite3_value_type`: see [Custom SQL Functions and Aggregates](#custom-sql-functions-and-aggregates) - `sqlite3_backup_finish`, `sqlite3_backup_init`, `sqlite3_backup_step`: see [Backup](#backup) - `sqlite3_bind_blob`, `sqlite3_bind_double`, `sqlite3_bind_int64`, `sqlite3_bind_null`, `sqlite3_bind_parameter_count`, `sqlite3_bind_parameter_name`, `sqlite3_bind_text`, `sqlite3_clear_bindings`, `sqlite3_column_blob`, `sqlite3_column_bytes`, `sqlite3_column_count`, `sqlite3_column_double`, `sqlite3_column_int64`, `sqlite3_column_name`, `sqlite3_column_text`, `sqlite3_column_type`, `sqlite3_exec`, `sqlite3_finalize`, `sqlite3_prepare_v2`, `sqlite3_reset`, `sqlite3_step`: see [Executing Updates](#executing-updates), [Fetch Queries](#fetch-queries), [Prepared Statements](#prepared-statements), [Values](#values) -- `sqlite3_busy_handler`, `sqlite3_busy_timeout`: see [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/4.1/Structs/Configuration.html) -- `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/4.1/Classes/Database.html) +- `sqlite3_busy_handler`, `sqlite3_busy_timeout`: see [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/4.2/Structs/Configuration.html) +- `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/4.2/Classes/Database.html) - `sqlite3_close`, `sqlite3_close_v2`, `sqlite3_next_stmt`, `sqlite3_open_v2`: see [Database Connections](#database-connections) - `sqlite3_commit_hook`, `sqlite3_rollback_hook`, `sqlite3_update_hook`: see [TransactionObserver Protocol](#transactionobserver-protocol), [DatabaseRegionObservation], [ValueObservation], [FetchedRecordsController] - `sqlite3_config`: see [Error Log](#error-log) @@ -2113,9 +2113,9 @@ Before jumping in the low-level wagon, here is the list of all SQLite APIs used - `sqlite3_last_insert_rowid`: see [Executing Updates](#executing-updates) - `sqlite3_preupdate_count`, `sqlite3_preupdate_depth`, `sqlite3_preupdate_hook`, `sqlite3_preupdate_new`, `sqlite3_preupdate_old`: see [Support for SQLite Pre-Update Hooks](#support-for-sqlite-pre-update-hooks) - `sqlite3_set_authorizer`: **reserved by GRDB** -- `sqlite3_sql`: see [Statement.sql](http://groue.github.io/GRDB.swift/docs/4.1/Classes/Statement.html) -- `sqlite3_trace`: see [Configuration.trace](http://groue.github.io/GRDB.swift/docs/4.1/Structs/Configuration.html) -- `sqlite3_wal_checkpoint_v2`: see [DatabasePool.checkpoint](http://groue.github.io/GRDB.swift/docs/4.1/Classes/DatabasePool.html) +- `sqlite3_sql`: see [Statement.sql](http://groue.github.io/GRDB.swift/docs/4.2/Classes/Statement.html) +- `sqlite3_trace`: see [Configuration.trace](http://groue.github.io/GRDB.swift/docs/4.2/Structs/Configuration.html) +- `sqlite3_wal_checkpoint_v2`: see [DatabasePool.checkpoint](http://groue.github.io/GRDB.swift/docs/4.2/Classes/DatabasePool.html) Records @@ -2434,7 +2434,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.1/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.2/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()`. @@ -2812,7 +2812,7 @@ protocol EncodableRecord { } ``` -See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/4.1/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.1/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.1/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. +See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/4.2/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.2/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.2/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). @@ -4155,7 +4155,7 @@ Player // SELECT * FROM player ``` -Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/4.1/Structs/StatementArguments.html): +Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/4.2/Structs/StatementArguments.html): ```swift // SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate) @@ -4688,7 +4688,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.1/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example: +- [SQLRequest](http://groue.github.io/GRDB.swift/docs/4.2/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example: ```swift extension Player { @@ -4732,7 +4732,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.1/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.2/Structs/AnyFetchRequest.html): a [type-erased](http://chris.eidhof.nl/post/type-erasers-in-swift/) request. ### Fetching From Custom Requests @@ -5162,7 +5162,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS3Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.1/Structs/StatementArguments.html): +FTS3Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.2/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, @@ -5411,7 +5411,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS5Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.1/Structs/StatementArguments.html): +FTS5Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.2/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, @@ -7295,7 +7295,7 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan ### DatabaseRegion -**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/4.1/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.2/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. @@ -7305,7 +7305,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.1/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). +For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/4.2/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). #### The DatabaseRegionConvertible Protocol @@ -8170,7 +8170,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.1/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/4.1/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only. +Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/4.2/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/4.2/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: @@ -8424,7 +8424,7 @@ If you absolutely need multiple connections, then: - Read about [isolation in SQLite](https://www.sqlite.org/isolation.html) - Learn about [locks and transactions](https://www.sqlite.org/lang_transaction.html) - Become a master of the [WAL mode](https://www.sqlite.org/wal.html) -- Prepare to setup a [busy handler](https://www.sqlite.org/c3ref/busy_handler.html) with [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/4.1/Structs/Configuration.html) +- Prepare to setup a [busy handler](https://www.sqlite.org/c3ref/busy_handler.html) with [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/4.2/Structs/Configuration.html) - [Ask questions](https://github.com/groue/GRDB.swift/issues) diff --git a/Support/Info.plist b/Support/Info.plist index 29e41ada3..33a5640f0 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 4.1.1 + 4.2.0 CFBundleSignature ???? CFBundleVersion