From 0929fe72b83d9054d34c01b0aa8aa162528c45d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 14 May 2020 12:28:52 +0200 Subject: [PATCH 01/28] Cleanup detection of queries that return a single row --- .../QueryInterface/SQLGeneration/SQLQueryGenerator.swift | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index fd5e94076..628c10b04 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -209,18 +209,18 @@ struct SQLQueryGenerator: Refinable { } if equalExpression.lhs is DatabaseValue, - let qualifiedColumn = equalExpression.rhs as? QualifiedColumn + let qualifiedColumn = equalExpression.rhs as? QualifiedColumn, + qualifiedColumn.alias == sourceAlias { // value == Column("foo") - assert(qualifiedColumn.alias == sourceAlias) return qualifiedColumn.name } if equalExpression.rhs is DatabaseValue, - let qualifiedColumn = equalExpression.lhs as? QualifiedColumn + let qualifiedColumn = equalExpression.lhs as? QualifiedColumn, + qualifiedColumn.alias == sourceAlias { // Column("foo") == value - assert(qualifiedColumn.alias == sourceAlias) return qualifiedColumn.name } @@ -250,6 +250,7 @@ struct SQLQueryGenerator: Refinable { let functionName = expression.functionName.sql.uppercased() guard aggregateFunctionNames.contains(functionName) else { // Not an aggregate function. + // (We miss custom aggregates) continue } guard expression.arguments.allSatisfy({ $0 is QualifiedColumn }) else { From 2bb53026ef1a38d4b30f51006913d6e8bf431ac9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 25 May 2020 09:34:11 +0200 Subject: [PATCH 02/28] Fix #783 --- .../Request/QueryInterfaceRequest.swift | 36 +------------------ .../SQLGeneration/SQLQueryGenerator.swift | 36 +++++++++++++++++++ 2 files changed, 37 insertions(+), 35 deletions(-) diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 8b52ac2d2..cc0449967 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -44,43 +44,9 @@ extension QueryInterfaceRequest: Refinable { } extension QueryInterfaceRequest: DatabaseRegionConvertible { public func databaseRegion(_ db: Database) throws -> DatabaseRegion { - var region = try SQLQueryGenerator(query: query) + try SQLQueryGenerator(query: query) .makeSelectStatement(db) .selectedRegion - - // Iterate all prefetched associations - var fifo = query.relation.prefetchedAssociations - while !fifo.isEmpty { - let association = fifo.removeFirst() - - // Build the query for prefetched rows. - // CAUTION: Keep this code in sync with prefetch(_:associations:in:) - let pivotMappings = try association.pivot.condition.columnMappings(db) - let pivotColumns = pivotMappings.map(\.right) - let pivotAlias = TableAlias() - let prefetchedRelation = association - .map(\.pivot.relation, { $0.qualified(with: pivotAlias) }) - // Use a `NullRow` in order to make sure all join condition - // columns are made visible to SQLite, and present in the - // selected region: - // ... JOIN right ON right.leftId IS NULL - // ^ content of the NullRow - .destinationRelation(fromOriginRows: { _ in [NullRow()] }) - .annotated(with: pivotColumns.map { pivotAlias[Column($0)].forKey("grdb_\($0)") }) - let prefetchedQuery = SQLQuery(relation: prefetchedRelation) - - // Union prefetched region - let prefetchedRegion = try SQLQueryGenerator(query: prefetchedQuery) - .makeSelectStatement(db) - .selectedRegion - region.formUnion(prefetchedRegion) - - // Append nested prefetched associations (support for - // A.including(all: A.bs.including(all: B.cs)) - fifo.append(contentsOf: prefetchedRelation.prefetchedAssociations) - } - - return region } } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 628c10b04..e0572cf80 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -6,6 +6,8 @@ struct SQLQueryGenerator: Refinable { private let havingExpressionsPromise: DatabasePromise<[SQLExpression]> private let limit: SQLLimit? private let singleResult: Bool + // For database region + private let prefetchedAssociations: [SQLAssociation] /// Creates an SQL query generator. /// @@ -57,6 +59,7 @@ struct SQLQueryGenerator: Refinable { limit = query.limit isDistinct = query.isDistinct self.singleResult = singleResult + prefetchedAssociations = query.relation.prefetchedAssociations } func requestSQL(_ context: SQLGenerationContext) throws -> String { @@ -155,6 +158,39 @@ struct SQLQueryGenerator: Refinable { // Optimize databaseRegion statement.selectedRegion = try optimizedSelectedRegion(db, statement.selectedRegion) + + // Append region of prefetched associations + var fifo = prefetchedAssociations + while !fifo.isEmpty { + let association = fifo.removeFirst() + + // Build the query for prefetched rows. + // CAUTION: Keep this code in sync with prefetch(_:associations:in:) + let pivotMappings = try association.pivot.condition.columnMappings(db) + let pivotColumns = pivotMappings.map(\.right) + let pivotAlias = TableAlias() + let prefetchedRelation = association + .map(\.pivot.relation, { $0.qualified(with: pivotAlias) }) + // Use a `NullRow` in order to make sure all join condition + // columns are made visible to SQLite, and present in the + // selected region: + // ... JOIN right ON right.leftId IS NULL + // ^ content of the NullRow + .destinationRelation(fromOriginRows: { _ in [NullRow()] }) + .annotated(with: pivotColumns.map { pivotAlias[Column($0)].forKey("grdb_\($0)") }) + let prefetchedQuery = SQLQuery(relation: prefetchedRelation) + + // Union prefetched region + let prefetchedRegion = try SQLQueryGenerator(query: prefetchedQuery) + .makeSelectStatement(db) + .selectedRegion + statement.selectedRegion.formUnion(prefetchedRegion) + + // Append nested prefetched associations (support for + // A.including(all: A.bs.including(all: B.cs)) + fifo.append(contentsOf: prefetchedRelation.prefetchedAssociations) + } + return statement } From af0946fd21d0d39ebb1497eb15d4f3243ac180e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 25 May 2020 09:34:35 +0200 Subject: [PATCH 03/28] Regression tests for #783 (WIP) --- ...bservationQueryInterfaceRequestTests.swift | 57 ++++++++++++++++--- 1 file changed, 48 insertions(+), 9 deletions(-) diff --git a/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift b/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift index 42ffae10e..24d4c1623 100644 --- a/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift @@ -29,13 +29,39 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { t.column("parentId", .integer).references("parent", onDelete: .cascade) t.column("name", .text) } - try db.execute(sql: """ + } + + private func performDatabaseModifications(in writer: DatabaseWriter) throws { + try writer.write { db in + try db.execute(sql: """ INSERT INTO parent (id, name) VALUES (1, 'foo'); INSERT INTO parent (id, name) VALUES (2, 'bar'); + """) + } + try writer.write { db in + try db.execute(sql: """ INSERT INTO child (id, parentId, name) VALUES (1, 1, 'fooA'); INSERT INTO child (id, parentId, name) VALUES (2, 1, 'fooB'); INSERT INTO child (id, parentId, name) VALUES (3, 2, 'barA'); """) + } + try writer.write { db in + try db.execute(sql: """ + UPDATE child SET name = 'fooA2' WHERE id = 1; + """) + } + try writer.write { db in + try db.execute(sql: """ + INSERT INTO parent (id, name) VALUES (3, 'baz'); + INSERT INTO child (id, parentId, name) VALUES (4, 3, 'bazA'); + """) + } + try writer.write { db in + try db.execute(sql: """ + DELETE FROM parent WHERE id = 1; + DELETE FROM child; + """) + } } func testOneRowWithPrefetchedRows() throws { @@ -48,18 +74,31 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { let observation = ValueObservation.tracking(request.fetchOne) let recorder = observation.record(in: dbQueue) - try dbQueue.inDatabase { db in - try db.execute(sql: "DELETE FROM child") - } - let results = try wait(for: recorder.next(2), timeout: 1) + try performDatabaseModifications(in: dbQueue) + let results = try wait(for: recorder.next(6), timeout: 1) - XCTAssertEqual(results[0]!.unscoped, ["id": 1, "name": "foo"]) - XCTAssertEqual(results[0]!.prefetchedRows["children"], [ - ["id": 1, "parentId": 1, "name": "fooA", "grdb_parentId": 1], - ["id": 2, "parentId": 1, "name": "fooB", "grdb_parentId": 1]]) + XCTAssertNil(results[0]) XCTAssertEqual(results[1]!.unscoped, ["id": 1, "name": "foo"]) XCTAssertEqual(results[1]!.prefetchedRows["children"], []) + + XCTAssertEqual(results[2]!.unscoped, ["id": 1, "name": "foo"]) + XCTAssertEqual(results[2]!.prefetchedRows["children"], [ + ["id": 1, "parentId": 1, "name": "fooA", "grdb_parentId": 1], + ["id": 2, "parentId": 1, "name": "fooB", "grdb_parentId": 1]]) + + XCTAssertEqual(results[3]!.unscoped, ["id": 1, "name": "foo"]) + XCTAssertEqual(results[3]!.prefetchedRows["children"], [ + ["id": 1, "parentId": 1, "name": "fooA2", "grdb_parentId": 1], + ["id": 2, "parentId": 1, "name": "fooB", "grdb_parentId": 1]]) + + XCTAssertEqual(results[4]!.unscoped, ["id": 1, "name": "foo"]) + XCTAssertEqual(results[4]!.prefetchedRows["children"], [ + ["id": 1, "parentId": 1, "name": "fooA2", "grdb_parentId": 1], + ["id": 2, "parentId": 1, "name": "fooB", "grdb_parentId": 1]]) + + XCTAssertEqual(results[5]!.unscoped, ["id": 2, "name": "bar"]) + XCTAssertEqual(results[5]!.prefetchedRows["children"], []) } func testAllRowsWithPrefetchedRows() throws { From 4c2042c3cea7c2980771de6897a265343b752855 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 25 May 2020 13:04:10 +0200 Subject: [PATCH 04/28] Cleanup 2bb53026ef1a38d4b30f51006913d6e8bf431ac9 --- GRDB/Core/Database+Statements.swift | 4 +- GRDB/Core/FetchRequest.swift | 2 +- GRDB/Core/SQLRequest.swift | 2 +- GRDB/Core/Statement.swift | 14 +++--- .../Request/QueryInterfaceRequest.swift | 30 ++++++++++++- .../SQLGeneration/SQLQueryGenerator.swift | 43 +++++-------------- 6 files changed, 48 insertions(+), 47 deletions(-) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index be75a9d98..e1275308c 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -240,7 +240,7 @@ extension Database { try checkForSuspensionViolation(from: statement) if _isRecordingSelectedRegion { - _selectedRegion.formUnion(statement.selectedRegion) + _selectedRegion.formUnion(statement.databaseRegion) } let authorizer = observationBroker.updateStatementWillExecute(statement) @@ -317,7 +317,7 @@ extension Database { try checkForSuspensionViolation(from: statement) if _isRecordingSelectedRegion { - _selectedRegion.formUnion(statement.selectedRegion) + _selectedRegion.formUnion(statement.databaseRegion) } } diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index db259452e..06a71330d 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -129,7 +129,7 @@ extension FetchRequest { let context = SQLGenerationContext(db) let sql = try requestSQL(context, forSingleResult: false) let statement = try db.makeSelectStatement(sql: sql) - return statement.selectedRegion + return statement.databaseRegion } /// Returns a PreparedRequest that is ready to be executed. diff --git a/GRDB/Core/SQLRequest.swift b/GRDB/Core/SQLRequest.swift index 0fdf988f0..a46a2d1b4 100644 --- a/GRDB/Core/SQLRequest.swift +++ b/GRDB/Core/SQLRequest.swift @@ -111,7 +111,7 @@ extension SQLRequest: SQLRequestProtocol { extension SQLRequest: DatabaseRegionConvertible { public func databaseRegion(_ db: Database) throws -> DatabaseRegion { - try makePreparedRequest(db, forSingleResult: false).statement.selectedRegion + try makePreparedRequest(db, forSingleResult: false).statement.databaseRegion } } diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index f9aad76b9..85e743bf8 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -24,11 +24,12 @@ public class Statement { .trimmingCharacters(in: .sqlStatementSeparators) } - // Selected region is computed during statement compilation, and maybe - // optimized for select statements compiled by QueryInterfaceRequest, in + // Database region is computed during statement compilation, and maybe + // extended for select statements compiled by QueryInterfaceRequest, in // order to perform focused database observation. See - // SQLQueryGenerator.optimizedSelectedRegion(_:_:) - var selectedRegion = DatabaseRegion() + // SQLQueryGenerator.makeSelectStatement(_:) + /// The database region that the statement looks into. + public internal(set) var databaseRegion = DatabaseRegion() var isReadonly: Bool { sqlite3_stmt_readonly(sqliteStatement) != 0 @@ -87,7 +88,7 @@ public class Statement { self.database = database self.sqliteStatement = statement - self.selectedRegion = authorizer.selectedRegion + self.databaseRegion = authorizer.selectedRegion } deinit { @@ -356,9 +357,6 @@ public final class SelectStatement: Statement { "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.") } - /// The database region that the statement looks into. - public var databaseRegion: DatabaseRegion { selectedRegion } - /// The number of columns in the resulting rows. public var columnCount: Int { Int(sqlite3_column_count(self.sqliteStatement)) diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index cc0449967..b93b3d105 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -46,7 +46,7 @@ extension QueryInterfaceRequest: DatabaseRegionConvertible { public func databaseRegion(_ db: Database) throws -> DatabaseRegion { try SQLQueryGenerator(query: query) .makeSelectStatement(db) - .selectedRegion + .databaseRegion } } @@ -473,7 +473,7 @@ private func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [ return } - // CAUTION: Keep this code in sync with QueryInterfaceRequest.databaseRegion(_:) + // CAUTION: Keep this code in sync with prefetchedRegion(_:_:) for association in associations { let pivotMappings = try association.pivot.condition.columnMappings(db) @@ -521,6 +521,32 @@ private func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [ } } +// Returns the region of prefetched associations +func prefetchedRegion(_ db: Database, associations: [SQLAssociation]) throws -> DatabaseRegion { + try associations.reduce(into: DatabaseRegion()) { (region, association) in + // CAUTION: Keep this code in sync with prefetch(_:associations:in:) + let pivotMappings = try association.pivot.condition.columnMappings(db) + let pivotColumns = pivotMappings.map(\.right) + let pivotAlias = TableAlias() + let prefetchedRelation = association + .map(\.pivot.relation, { $0.qualified(with: pivotAlias) }) + // Use a `NullRow` in order to make sure all join condition + // columns are made visible to SQLite, and present in the + // selected region: + // ... JOIN right ON right.leftId IS NULL + // ^ content of the NullRow + .destinationRelation(fromOriginRows: { _ in [NullRow()] }) + .annotated(with: pivotColumns.map { pivotAlias[Column($0)].forKey("grdb_\($0)") }) + let prefetchedQuery = SQLQuery(relation: prefetchedRelation) + + // Union prefetched region + let prefetchedRegion = try SQLQueryGenerator(query: prefetchedQuery) + .makeSelectStatement(db) + .databaseRegion // contains region of nested associations + region.formUnion(prefetchedRegion) + } +} + extension Array where Element == Row { /// - precondition: Columns all exist in all rows. All rows have the same /// columnns, in the same order. diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index e0572cf80..28c55b80a 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -156,40 +156,17 @@ struct SQLQueryGenerator: Refinable { let statement = try db.makeSelectStatement(sql: sql) statement.arguments = context.arguments - // Optimize databaseRegion - statement.selectedRegion = try optimizedSelectedRegion(db, statement.selectedRegion) + // Optimize statement region. This allows us to track individual rowids. + statement.databaseRegion = try optimizedSelectedRegion(db, statement.databaseRegion) - // Append region of prefetched associations - var fifo = prefetchedAssociations - while !fifo.isEmpty { - let association = fifo.removeFirst() - - // Build the query for prefetched rows. - // CAUTION: Keep this code in sync with prefetch(_:associations:in:) - let pivotMappings = try association.pivot.condition.columnMappings(db) - let pivotColumns = pivotMappings.map(\.right) - let pivotAlias = TableAlias() - let prefetchedRelation = association - .map(\.pivot.relation, { $0.qualified(with: pivotAlias) }) - // Use a `NullRow` in order to make sure all join condition - // columns are made visible to SQLite, and present in the - // selected region: - // ... JOIN right ON right.leftId IS NULL - // ^ content of the NullRow - .destinationRelation(fromOriginRows: { _ in [NullRow()] }) - .annotated(with: pivotColumns.map { pivotAlias[Column($0)].forKey("grdb_\($0)") }) - let prefetchedQuery = SQLQuery(relation: prefetchedRelation) - - // Union prefetched region - let prefetchedRegion = try SQLQueryGenerator(query: prefetchedQuery) - .makeSelectStatement(db) - .selectedRegion - statement.selectedRegion.formUnion(prefetchedRegion) - - // Append nested prefetched associations (support for - // A.including(all: A.bs.including(all: B.cs)) - fifo.append(contentsOf: prefetchedRelation.prefetchedAssociations) - } + // Also append the prefetched region. This makes sure we observe the + // correct database region when the statement is executed, even if we + // don't execute all request statements due to lacking database content. + // For example, fetching `parent.including(all: children)` will select + // parents, but won't attempt to select any children if there is no + // parent in the database. And yet we need to observe the table for + // children. This is why we include the prefetched region. + try statement.databaseRegion.formUnion(prefetchedRegion(db, associations: prefetchedAssociations)) return statement } From f825c52ecf22affe8591891c8ac8d3c757e4fb8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 25 May 2020 13:04:48 +0200 Subject: [PATCH 05/28] Update request region tests for both DatabaseRegionConvertible and statement region --- ...sociationPrefetchingObservationTests.swift | 50 +++++++++++++------ 1 file changed, 34 insertions(+), 16 deletions(-) diff --git a/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift b/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift index d72848aef..b67a85078 100644 --- a/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift @@ -7,6 +7,24 @@ private struct C: TableRecord { } private struct D: TableRecord { } class AssociationPrefetchingObservationTests: GRDBTestCase { + private func assertRequestRegionEqual( + _ db: Database, + _ request: QueryInterfaceRequest, + _ expectedDescriptions: String..., + file: StaticString = #file, line: UInt = #line) throws + { + // Test DatabaseRegionConvertible + let region1 = try request.databaseRegion(db) + XCTAssertTrue(expectedDescriptions.contains(region1.description), description, file: file, line: line) + + // Test raw statement region, as support for Database.recordingSelection + let region2 = try request + .makePreparedRequest(db, forSingleResult: false) + .statement + .databaseRegion + XCTAssertTrue(expectedDescriptions.contains(region2.description), description, file: file, line: line) + } + override func setup(_ dbWriter: DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "a") { t in @@ -72,7 +90,7 @@ class AssociationPrefetchingObservationTests: GRDBTestCase { .including(all: A .hasMany(B.self)) - try XCTAssertEqual(request.databaseRegion(db).description, "a(cola1,cola2),b(colb1,colb2,colb3)") + try assertRequestRegionEqual(db, request, "a(cola1,cola2),b(colb1,colb2,colb3)") } // Request with filters @@ -88,7 +106,7 @@ class AssociationPrefetchingObservationTests: GRDBTestCase { .filter(Column("colb1") != 4) .forKey("bs2")) - try XCTAssertEqual(request.databaseRegion(db).description, "a(cola1,cola2),b(colb1,colb2,colb3)") + try assertRequestRegionEqual(db, request, "a(cola1,cola2),b(colb1,colb2,colb3)") } // Request with altered selection @@ -98,7 +116,7 @@ class AssociationPrefetchingObservationTests: GRDBTestCase { .hasMany(B.self) .select(Column("colb1"))) - try XCTAssertEqual(request.databaseRegion(db).description, "a(cola1,cola2),b(colb1,colb2)") + try assertRequestRegionEqual(db, request, "a(cola1,cola2),b(colb1,colb2)") } } } @@ -114,7 +132,7 @@ class AssociationPrefetchingObservationTests: GRDBTestCase { .including(all: C .hasMany(D.self))) - try XCTAssertEqual(request.databaseRegion(db).description, "a(cola1,cola2),c(colc1,colc2),d(cold1,cold2,cold3)") + try assertRequestRegionEqual(db, request, "a(cola1,cola2),c(colc1,colc2),d(cold1,cold2,cold3)") } // Request with filters @@ -146,7 +164,7 @@ class AssociationPrefetchingObservationTests: GRDBTestCase { .forKey("ds2")) .forKey("cs2")) - try XCTAssertEqual(request.databaseRegion(db).description, "a(cola1,cola2),c(colc1,colc2),d(cold1,cold2,cold3)") + try assertRequestRegionEqual(db, request, "a(cola1,cola2),c(colc1,colc2),d(cold1,cold2,cold3)") } } } @@ -162,7 +180,7 @@ class AssociationPrefetchingObservationTests: GRDBTestCase { .including(required: C .hasMany(D.self))) - try XCTAssertEqual(request.databaseRegion(db).description, "a(cola1,cola2),c(colc1,colc2),d(cold1,cold2,cold3)") + try assertRequestRegionEqual(db, request, "a(cola1,cola2),c(colc1,colc2),d(cold1,cold2,cold3)") } // Request with filters @@ -194,7 +212,7 @@ class AssociationPrefetchingObservationTests: GRDBTestCase { .forKey("d2")) .forKey("cs2")) - try XCTAssertEqual(request.databaseRegion(db).description, "a(cola1,cola2),c(colc1,colc2),d(cold1,cold2,cold3)") + try assertRequestRegionEqual(db, request, "a(cola1,cola2),c(colc1,colc2),d(cold1,cold2,cold3)") } } } @@ -208,7 +226,7 @@ class AssociationPrefetchingObservationTests: GRDBTestCase { .including(all: A .hasMany(D.self, through: A.hasMany(C.self), using: C.hasMany(D.self))) - try XCTAssertEqual(request.databaseRegion(db).description, "a(cola1,cola2),c(colc1,colc2),d(cold1,cold2,cold3)") + try assertRequestRegionEqual(db, request, "a(cola1,cola2),c(colc1,colc2),d(cold1,cold2,cold3)") } // Request with filters @@ -227,7 +245,7 @@ class AssociationPrefetchingObservationTests: GRDBTestCase { .filter(Column("cold1") == 11) .forKey("ds3")) - try XCTAssertEqual(request.databaseRegion(db).description, "a(cola1,cola2),c(colc1,colc2),d(cold1,cold2,cold3)") + try assertRequestRegionEqual(db, request, "a(cola1,cola2),c(colc1,colc2),d(cold1,cold2,cold3)") } } } @@ -244,10 +262,10 @@ class AssociationPrefetchingObservationTests: GRDBTestCase { .hasMany(C.self)) ) - try XCTAssert([ + try assertRequestRegionEqual( + db, request, "a(*),b(colb1,colb2,colb3),c(colc1,colc2)", // iOS 12 - "a(cola1,cola2),b(colb1,colb2,colb3),c(colc1,colc2)", // iOS 9 - ].contains(request.databaseRegion(db).description)) + "a(cola1,cola2),b(colb1,colb2,colb3),c(colc1,colc2)") // iOS 9 } // Request with filters @@ -278,7 +296,7 @@ class AssociationPrefetchingObservationTests: GRDBTestCase { .forKey("cs2")) .forKey("a2")) - try XCTAssertEqual(request.databaseRegion(db).description, "a(cola1,cola2),b(colb1,colb2,colb3),c(colc1,colc2)") + try assertRequestRegionEqual(db, request, "a(cola1,cola2),b(colb1,colb2,colb3),c(colc1,colc2)") } } } @@ -296,10 +314,10 @@ class AssociationPrefetchingObservationTests: GRDBTestCase { .orderByPrimaryKey())) .orderByPrimaryKey() - try XCTAssert([ + try assertRequestRegionEqual( + db, request, "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)) + "a(cola1),b(colb1,colb2,colb3),c(colc1,colc2),d(cold1,cold2,cold3)") // iOS 9 } } } From 449c0e37b184d8369ee6b8349c5a4521f0d541a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 25 May 2020 13:24:25 +0200 Subject: [PATCH 06/28] Update regression tests for #783 --- ...bservationQueryInterfaceRequestTests.swift | 200 +++++++++++++++--- 1 file changed, 165 insertions(+), 35 deletions(-) diff --git a/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift b/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift index 24d4c1623..8ef808c27 100644 --- a/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift @@ -31,36 +31,41 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { } } - private func performDatabaseModifications(in writer: DatabaseWriter) throws { - try writer.write { db in + private func performDatabaseModifications(_ db: Database) throws { + try db.inTransaction { try db.execute(sql: """ INSERT INTO parent (id, name) VALUES (1, 'foo'); INSERT INTO parent (id, name) VALUES (2, 'bar'); """) + return .commit } - try writer.write { db in + try db.inTransaction { try db.execute(sql: """ INSERT INTO child (id, parentId, name) VALUES (1, 1, 'fooA'); INSERT INTO child (id, parentId, name) VALUES (2, 1, 'fooB'); INSERT INTO child (id, parentId, name) VALUES (3, 2, 'barA'); """) + return .commit } - try writer.write { db in + try db.inTransaction { try db.execute(sql: """ UPDATE child SET name = 'fooA2' WHERE id = 1; """) + return .commit } - try writer.write { db in + try db.inTransaction { try db.execute(sql: """ INSERT INTO parent (id, name) VALUES (3, 'baz'); INSERT INTO child (id, parentId, name) VALUES (4, 3, 'bazA'); """) + return .commit } - try writer.write { db in + try db.inTransaction { try db.execute(sql: """ DELETE FROM parent WHERE id = 1; DELETE FROM child; """) + return .commit } } @@ -74,14 +79,14 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { let observation = ValueObservation.tracking(request.fetchOne) let recorder = observation.record(in: dbQueue) - try performDatabaseModifications(in: dbQueue) + try dbQueue.writeWithoutTransaction(performDatabaseModifications) let results = try wait(for: recorder.next(6), timeout: 1) XCTAssertNil(results[0]) XCTAssertEqual(results[1]!.unscoped, ["id": 1, "name": "foo"]) XCTAssertEqual(results[1]!.prefetchedRows["children"], []) - + XCTAssertEqual(results[2]!.unscoped, ["id": 1, "name": "foo"]) XCTAssertEqual(results[2]!.prefetchedRows["children"], [ ["id": 1, "parentId": 1, "name": "fooA", "grdb_parentId": 1], @@ -111,27 +116,54 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { let observation = ValueObservation.tracking(request.fetchAll) let recorder = observation.record(in: dbQueue) - try dbQueue.inDatabase { db in - try db.execute(sql: "DELETE FROM child") - } - let results = try wait(for: recorder.next(2), timeout: 1) + try dbQueue.writeWithoutTransaction(performDatabaseModifications) + let results = try wait(for: recorder.next(6), timeout: 1) - XCTAssertEqual(results[0].count, 2) - XCTAssertEqual(results[0][0].unscoped, ["id": 1, "name": "foo"]) - XCTAssertEqual(results[0][0].prefetchedRows["children"], [ - ["id": 1, "parentId": 1, "name": "fooA", "grdb_parentId": 1], - ["id": 2, "parentId": 1, "name": "fooB", "grdb_parentId": 1]]) - XCTAssertEqual(results[0][1].unscoped, ["id": 2, "name": "bar"]) - XCTAssertEqual(results[0][1].prefetchedRows["children"], [ - ["id": 3, "parentId": 2, "name": "barA", "grdb_parentId": 2]]) + XCTAssertEqual(results[0].count, 0) XCTAssertEqual(results[1].count, 2) XCTAssertEqual(results[1][0].unscoped, ["id": 1, "name": "foo"]) XCTAssertEqual(results[1][0].prefetchedRows["children"], []) XCTAssertEqual(results[1][1].unscoped, ["id": 2, "name": "bar"]) XCTAssertEqual(results[1][1].prefetchedRows["children"], []) + + XCTAssertEqual(results[2].count, 2) + XCTAssertEqual(results[2][0].unscoped, ["id": 1, "name": "foo"]) + XCTAssertEqual(results[2][0].prefetchedRows["children"], [ + ["id": 1, "parentId": 1, "name": "fooA", "grdb_parentId": 1], + ["id": 2, "parentId": 1, "name": "fooB", "grdb_parentId": 1]]) + XCTAssertEqual(results[2][1].unscoped, ["id": 2, "name": "bar"]) + XCTAssertEqual(results[2][1].prefetchedRows["children"], [ + ["id": 3, "parentId": 2, "name": "barA", "grdb_parentId": 2]]) + + XCTAssertEqual(results[3].count, 2) + XCTAssertEqual(results[3][0].unscoped, ["id": 1, "name": "foo"]) + XCTAssertEqual(results[3][0].prefetchedRows["children"], [ + ["id": 1, "parentId": 1, "name": "fooA2", "grdb_parentId": 1], + ["id": 2, "parentId": 1, "name": "fooB", "grdb_parentId": 1]]) + XCTAssertEqual(results[3][1].unscoped, ["id": 2, "name": "bar"]) + XCTAssertEqual(results[3][1].prefetchedRows["children"], [ + ["id": 3, "parentId": 2, "name": "barA", "grdb_parentId": 2]]) + + XCTAssertEqual(results[4].count, 3) + XCTAssertEqual(results[4][0].unscoped, ["id": 1, "name": "foo"]) + XCTAssertEqual(results[4][0].prefetchedRows["children"], [ + ["id": 1, "parentId": 1, "name": "fooA2", "grdb_parentId": 1], + ["id": 2, "parentId": 1, "name": "fooB", "grdb_parentId": 1]]) + XCTAssertEqual(results[4][1].unscoped, ["id": 2, "name": "bar"]) + XCTAssertEqual(results[4][1].prefetchedRows["children"], [ + ["id": 3, "parentId": 2, "name": "barA", "grdb_parentId": 2]]) + XCTAssertEqual(results[4][2].unscoped, ["id": 3, "name": "baz"]) + XCTAssertEqual(results[4][2].prefetchedRows["children"], [ + ["id": 4, "parentId": 3, "name": "bazA", "grdb_parentId": 3]]) + + XCTAssertEqual(results[5].count, 2) + XCTAssertEqual(results[5][0].unscoped, ["id": 2, "name": "bar"]) + XCTAssertEqual(results[5][0].prefetchedRows["children"], []) + XCTAssertEqual(results[5][1].unscoped, ["id": 3, "name": "baz"]) + XCTAssertEqual(results[5][1].prefetchedRows["children"], []) } - + func testOneRecordWithPrefetchedRows() throws { let request = Parent .including(all: Parent.children.orderByPrimaryKey()) @@ -141,6 +173,10 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { try assertValueObservation( ValueObservation.tracking(request.fetchOne), records: [ + nil, + ParentInfo( + parent: Parent(id: 1, name: "foo"), + children: []), ParentInfo( parent: Parent(id: 1, name: "foo"), children: [ @@ -149,12 +185,22 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { ]), ParentInfo( parent: Parent(id: 1, name: "foo"), + children: [ + Child(id: 1, parentId: 1, name: "fooA2"), + Child(id: 2, parentId: 1, name: "fooB"), + ]), + ParentInfo( + parent: Parent(id: 1, name: "foo"), + children: [ + Child(id: 1, parentId: 1, name: "fooA2"), + Child(id: 2, parentId: 1, name: "fooB"), + ]), + ParentInfo( + parent: Parent(id: 2, name: "bar"), children: []), ], setup: setup, - recordedUpdates: { db in - try db.execute(sql: "DELETE FROM child") - }) + recordedUpdates: performDatabaseModifications) // The fundamental technique for removing duplicates of non-Equatable types try assertValueObservation( @@ -163,6 +209,10 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { .removeDuplicates() .map { row in row.map(ParentInfo.init(row:)) }, records: [ + nil, + ParentInfo( + parent: Parent(id: 1, name: "foo"), + children: []), ParentInfo( parent: Parent(id: 1, name: "foo"), children: [ @@ -171,12 +221,16 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { ]), ParentInfo( parent: Parent(id: 1, name: "foo"), + children: [ + Child(id: 1, parentId: 1, name: "fooA2"), + Child(id: 2, parentId: 1, name: "fooB"), + ]), + ParentInfo( + parent: Parent(id: 2, name: "bar"), children: []), ], setup: setup, - recordedUpdates: { db in - try db.execute(sql: "DELETE FROM child") - }) + recordedUpdates: performDatabaseModifications) } func testAllRecordsWithPrefetchedRows() throws { @@ -188,6 +242,15 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { try assertValueObservation( ValueObservation.tracking(request.fetchAll), records: [ + [], + [ + ParentInfo( + parent: Parent(id: 1, name: "foo"), + children: []), + ParentInfo( + parent: Parent(id: 2, name: "bar"), + children: []), + ], [ ParentInfo( parent: Parent(id: 1, name: "foo"), @@ -204,16 +267,45 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { [ ParentInfo( parent: Parent(id: 1, name: "foo"), - children: []), + children: [ + Child(id: 1, parentId: 1, name: "fooA2"), + Child(id: 2, parentId: 1, name: "fooB"), + ]), ParentInfo( parent: Parent(id: 2, name: "bar"), + children: [ + Child(id: 3, parentId: 2, name: "barA"), + ]), + ], + [ + ParentInfo( + parent: Parent(id: 1, name: "foo"), + children: [ + Child(id: 1, parentId: 1, name: "fooA2"), + Child(id: 2, parentId: 1, name: "fooB"), + ]), + ParentInfo( + parent: Parent(id: 2, name: "bar"), + children: [ + Child(id: 3, parentId: 2, name: "barA"), + ]), + ParentInfo( + parent: Parent(id: 3, name: "baz"), + children: [ + Child(id: 4, parentId: 3, name: "bazA"), + ]), + ], + [ + ParentInfo( + parent: Parent(id: 2, name: "bar"), + children: []), + ParentInfo( + parent: Parent(id: 3, name: "baz"), children: []), ], ], setup: setup, - recordedUpdates: { db in - try db.execute(sql: "DELETE FROM child") - }) + recordedUpdates: performDatabaseModifications) // The fundamental technique for removing duplicates of non-Equatable types try assertValueObservation( @@ -222,6 +314,15 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { .removeDuplicates() .map { rows in rows.map(ParentInfo.init(row:)) }, records: [ + [], + [ + ParentInfo( + parent: Parent(id: 1, name: "foo"), + children: []), + ParentInfo( + parent: Parent(id: 2, name: "bar"), + children: []), + ], [ ParentInfo( parent: Parent(id: 1, name: "foo"), @@ -238,15 +339,44 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { [ ParentInfo( parent: Parent(id: 1, name: "foo"), - children: []), + children: [ + Child(id: 1, parentId: 1, name: "fooA2"), + Child(id: 2, parentId: 1, name: "fooB"), + ]), ParentInfo( parent: Parent(id: 2, name: "bar"), + children: [ + Child(id: 3, parentId: 2, name: "barA"), + ]), + ], + [ + ParentInfo( + parent: Parent(id: 1, name: "foo"), + children: [ + Child(id: 1, parentId: 1, name: "fooA2"), + Child(id: 2, parentId: 1, name: "fooB"), + ]), + ParentInfo( + parent: Parent(id: 2, name: "bar"), + children: [ + Child(id: 3, parentId: 2, name: "barA"), + ]), + ParentInfo( + parent: Parent(id: 3, name: "baz"), + children: [ + Child(id: 4, parentId: 3, name: "bazA"), + ]), + ], + [ + ParentInfo( + parent: Parent(id: 2, name: "bar"), + children: []), + ParentInfo( + parent: Parent(id: 3, name: "baz"), children: []), ], ], setup: setup, - recordedUpdates: { db in - try db.execute(sql: "DELETE FROM child") - }) + recordedUpdates: performDatabaseModifications) } } From 80f0379d7199ad1bcdcac09aca77648370feb3c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 25 May 2020 13:39:35 +0200 Subject: [PATCH 07/28] Remove database content unused by test --- ...sociationPrefetchingObservationTests.swift | 33 ------------------- 1 file changed, 33 deletions(-) diff --git a/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift b/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift index b67a85078..3f0c28014 100644 --- a/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift @@ -45,39 +45,6 @@ class AssociationPrefetchingObservationTests: GRDBTestCase { t.column("cold2", .integer).references("c") t.column("cold3", .text) } - try db.execute( - sql: """ - INSERT INTO a (cola1, cola2) VALUES (?, ?); - INSERT INTO a (cola1, cola2) VALUES (?, ?); - INSERT INTO a (cola1, cola2) VALUES (?, ?); - INSERT INTO b (colb1, colb2, colb3) VALUES (?, ?, ?); - INSERT INTO b (colb1, colb2, colb3) VALUES (?, ?, ?); - INSERT INTO b (colb1, colb2, colb3) VALUES (?, ?, ?); - INSERT INTO b (colb1, colb2, colb3) VALUES (?, ?, ?); - INSERT INTO c (colc1, colc2) VALUES (?, ?); - INSERT INTO c (colc1, colc2) VALUES (?, ?); - INSERT INTO c (colc1, colc2) VALUES (?, ?); - 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", - 2, "a2", - 3, "a3", - 4, 1, "b1", - 5, 1, "b2", - 6, 2, "b3", - 14, nil, "b4", - 7, 1, - 8, 2, - 9, 2, - 10, 7, "d1", - 11, 8, "d2", - 12, 8, "d3", - 13, 9, "d4", - ]) } } From e82ecfee9f0cdfae04fd727f1a14d6b240ac8e39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 25 May 2020 13:41:41 +0200 Subject: [PATCH 08/28] CHANGELOG --- CHANGELOG.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 56ddad500..94e2d3194 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,9 +5,7 @@ All notable changes to this project will be documented in this file. GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library. - #### 5.x Releases @@ -70,9 +68,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [0.110.0](#01100), ... - + +### Fixed + +- [#784](https://github.com/groue/GRDB.swift/pull/784): Fix observation of eager-loaded to-many associations ## 5.0.0-beta.2 From a5de2b9288dbbdfde34ba1ebbc6f4ce6254039e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 30 May 2020 10:30:07 +0200 Subject: [PATCH 09/28] Breaking: AnyFetchRequest.asRequest(of:) --- GRDB/Core/FetchRequest.swift | 34 ++++++++++++++----- GRDB/Fixit/GRDB-5.0.swift | 4 +++ .../Request/QueryInterfaceRequest.swift | 8 ++--- GRDB/Record/FetchedRecordsController.swift | 7 ++-- Tests/GRDBTests/DatabaseRegionTests.swift | 2 +- 5 files changed, 37 insertions(+), 18 deletions(-) diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index 06a71330d..c1cc14648 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -216,16 +216,19 @@ public struct AnyFetchRequest: FetchRequest { private let _requestSQL: (SQLGenerationContext, _ singleResult: Bool) throws -> String // FetchRequest - private let _preparedRequest: (Database, _ singleResult: Bool) throws -> PreparedRequest + private let _makePreparedRequest: (Database, _ singleResult: Bool) throws -> PreparedRequest private let _fetchCount: (Database) throws -> Int - #warning("TODO: force same RowDecoder, and expose asRequest(of:)") - /// Creates a request that wraps and forwards operations to `request`. - public init(_ request: Request) { - _databaseRegion = request.databaseRegion - _requestSQL = request.requestSQL - _preparedRequest = request.makePreparedRequest - _fetchCount = request.fetchCount + /// Creates a request bound to type RowDecoder. + /// + /// - parameter type: The fetched type RowDecoder + /// - returns: A request bound to type RowDecoder. + public func asRequest(of type: RowDecoder.Type) -> AnyFetchRequest { + AnyFetchRequest( + _databaseRegion: _databaseRegion, + _requestSQL: _requestSQL, + _makePreparedRequest: _makePreparedRequest, + _fetchCount: _fetchCount) } /// :nodoc: @@ -241,7 +244,7 @@ public struct AnyFetchRequest: FetchRequest { /// :nodoc: public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { - try _preparedRequest(db, singleResult) + try _makePreparedRequest(db, singleResult) } /// :nodoc: @@ -249,3 +252,16 @@ public struct AnyFetchRequest: FetchRequest { try _fetchCount(db) } } + +extension AnyFetchRequest { + /// Creates a request that wraps and forwards operations to `request`. + public init(_ request: Request) + where Request.RowDecoder == RowDecoder + { + self.init( + _databaseRegion: request.databaseRegion, + _requestSQL: request.requestSQL, + _makePreparedRequest: request.makePreparedRequest, + _fetchCount: request.fetchCount) + } +} diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift index b61de20ee..0a39c5ea0 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -10,6 +10,10 @@ extension AnyFetchRequest { @available(*, unavailable, renamed: "RowDecoder") typealias T = RowDecoder + @available(*, unavailable, message: "Use AnyFetchRequest(request).asRequest(of: SomeType.self) instead.") + public init(_ request: Request) + { preconditionFailure() } + @available(*, unavailable, message: "Define your own FetchRequest type instead.") public init(_ prepare: @escaping (Database, _ singleResult: Bool) throws -> (SelectStatement, RowAdapter?)) { preconditionFailure() } diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index b93b3d105..fb763ed10 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -366,9 +366,9 @@ extension QueryInterfaceRequest { map(\.query) { $0.limit(limit, offset: offset) } } - /// Creates a request bound to type Target. + /// Creates a request bound to type RowDecoder. /// - /// The returned request can fetch if the type Target is fetchable (Row, + /// The returned request can fetch if the type RowDecoder is fetchable (Row, /// value, record). /// /// // Int? @@ -377,8 +377,8 @@ extension QueryInterfaceRequest { /// .asRequest(of: Int.self) // <-- /// .fetchOne(db) /// - /// - parameter type: The fetched type Target - /// - returns: A typed request bound to type Target. + /// - parameter type: The fetched type RowDecoder + /// - returns: A request bound to type RowDecoder. public func asRequest(of type: RowDecoder.Type) -> QueryInterfaceRequest { QueryInterfaceRequest(query: query) } diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index 95c602062..f4f20cd47 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -103,7 +103,7 @@ public final class FetchedRecordsController { where Request: FetchRequest, Request.RowDecoder == Record { self.itemsAreIdenticalFactory = itemsAreIdenticalFactory - self.request = ItemRequest(request) + self.request = AnyFetchRequest(request).asRequest(of: Item.self) (self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in let region = try request.databaseRegion(db) let itemsAreIdentical = try itemsAreIdenticalFactory(db) @@ -166,7 +166,7 @@ public final class FetchedRecordsController { throws where Request: FetchRequest, Request.RowDecoder == Record { - self.request = ItemRequest(request) + self.request = AnyFetchRequest(request).asRequest(of: Item.self) (self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in let region = try request.databaseRegion(db) let itemsAreIdentical = try itemsAreIdenticalFactory(db) @@ -389,8 +389,7 @@ public final class FetchedRecordsController { private let itemsAreIdenticalFactory: ItemComparatorFactory /// The request - fileprivate typealias ItemRequest = AnyFetchRequest> - fileprivate var request: ItemRequest + fileprivate var request: AnyFetchRequest> /// The observed database region private var region: DatabaseRegion diff --git a/Tests/GRDBTests/DatabaseRegionTests.swift b/Tests/GRDBTests/DatabaseRegionTests.swift index 27fa04cbd..1ed336a7e 100644 --- a/Tests/GRDBTests/DatabaseRegionTests.swift +++ b/Tests/GRDBTests/DatabaseRegionTests.swift @@ -446,7 +446,7 @@ class DatabaseRegionTests : GRDBTestCase { try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1,2,3]") do { - let derivedRequest: AnyFetchRequest = AnyFetchRequest(request) + let derivedRequest = AnyFetchRequest(request) try XCTAssertEqual(derivedRequest.databaseRegion(db).description, "foo(a,id)[1,2,3]") } do { From 289394c7ac77a4645d6b9261cffacffc42bc6c82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 30 May 2020 13:52:39 +0200 Subject: [PATCH 10/28] Turn LockedBox and ReadWriteBox into property wrappers. Also fix an old concurrency bug in tests, regarding query recording --- GRDB/Core/Database.swift | 10 +- GRDB/Core/DatabasePool.swift | 4 +- GRDB/Record/PersistableRecord.swift | 12 +- GRDB/Utils/LockedBox.swift | 23 +- GRDB/Utils/Pool.swift | 12 +- GRDB/Utils/ReadWriteBox.swift | 26 +- Tests/GRDBTests/GRDBTestCase.swift | 9 +- ...RecordPersistenceConflictPolicyTests.swift | 30 +- Tests/GRDBTests/PoolTests.swift | 2 +- Tests/GRDBTests/TableDefinitionTests.swift | 358 +++++++++--------- 10 files changed, 245 insertions(+), 241 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 8fb6a6bf7..87484b242 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -144,7 +144,7 @@ public final class Database { var isInsideTransactionBlock = false /// Support for checkForSuspensionViolation(from:) - var isSuspended = LockedBox(value: false) + @LockedBox var isSuspended = false /// Support for checkForSuspensionViolation(from:) /// This cache is never cleared: we assume journal mode never changes. @@ -596,7 +596,7 @@ public final class Database { /// /// Suspension ends with resume(). func suspend() { - isSuspended.write { isSuspended in + $isSuspended.update { isSuspended in if isSuspended { return } @@ -623,9 +623,7 @@ public final class Database { /// /// See suspend(). func resume() { - isSuspended.write { isSuspended in - isSuspended = false - } + isSuspended = false } /// Support for checkForSuspensionViolation(from:) @@ -653,7 +651,7 @@ public final class Database { /// the database, in order to avoid the [`0xdead10cc` /// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html). func checkForSuspensionViolation(from statement: Statement) throws { - try isSuspended.read { isSuspended in + try $isSuspended.read { isSuspended in guard isSuspended else { return } diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 3f78a8913..b6b149e39 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -12,7 +12,7 @@ public final class DatabasePool: DatabaseWriter { private var collations = Set() private var tokenizerRegistrations: [(Database) -> Void] = [] - var databaseSnapshotCount = LockedBox(value: 0) + @LockedBox var databaseSnapshotCount = 0 // MARK: - Database Information @@ -1031,7 +1031,7 @@ extension DatabasePool { path: path, configuration: writer.configuration, defaultLabel: "GRDB.DatabasePool", - purpose: "snapshot.\(databaseSnapshotCount.increment())") + purpose: "snapshot.\($databaseSnapshotCount.increment())") snapshot.read { setupDatabase($0) } return snapshot } diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index 0d170a7e8..b3bb97aa7 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -975,9 +975,9 @@ private struct InsertQuery: Hashable { } extension InsertQuery { - static let sqlCache = ReadWriteBox(value: [InsertQuery: String]()) + @ReadWriteBox private static var sqlCache: [InsertQuery: String] = [:] var sql: String { - if let sql = InsertQuery.sqlCache.read({ $0[self] }) { + if let sql = Self.sqlCache[self] { return sql } let columnsSQL = insertedColumns.map(\.quotedDatabaseIdentifier).joined(separator: ", ") @@ -996,7 +996,7 @@ extension InsertQuery { VALUES (\(valuesSQL)) """ } - InsertQuery.sqlCache.write { $0[self] = sql } + Self.sqlCache[self] = sql return sql } } @@ -1012,9 +1012,9 @@ private struct UpdateQuery: Hashable { } extension UpdateQuery { - static let sqlCache = ReadWriteBox(value: [UpdateQuery: String]()) + @ReadWriteBox private static var sqlCache: [UpdateQuery: String] = [:] var sql: String { - if let sql = UpdateQuery.sqlCache.read({ $0[self] }) { + if let sql = Self.sqlCache[self] { return sql } let updateSQL = updatedColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: ", ") @@ -1034,7 +1034,7 @@ extension UpdateQuery { WHERE \(whereSQL) """ } - UpdateQuery.sqlCache.write { $0[self] = sql } + Self.sqlCache[self] = sql return sql } } diff --git a/GRDB/Utils/LockedBox.swift b/GRDB/Utils/LockedBox.swift index 0fd3f5b87..a1bd933d9 100644 --- a/GRDB/Utils/LockedBox.swift +++ b/GRDB/Utils/LockedBox.swift @@ -1,36 +1,39 @@ import Foundation /// A LockedBox protects a value with an NSLock. +@propertyWrapper final class LockedBox { - private var _value: T + private var _wrappedValue: T private var lock = NSLock() - var value: T { + var wrappedValue: T { get { read { $0 } } - set { write { $0 = newValue } } + set { update { $0 = newValue } } } - init(value: T) { - _value = value + var projectedValue: LockedBox { self } + + init(wrappedValue: T) { + _wrappedValue = wrappedValue } func read(_ block: (T) throws -> U) rethrows -> U { lock.lock() defer { lock.unlock() } - return try block(_value) + return try block(_wrappedValue) } - func write(_ block: (inout T) throws -> U) rethrows -> U { + func update(_ block: (inout T) throws -> U) rethrows -> U { lock.lock() defer { lock.unlock() } - return try block(&_value) + return try block(&_wrappedValue) } } extension LockedBox where T: Numeric { @discardableResult func increment() -> T { - write { n in + update { n in n += 1 return n } @@ -38,7 +41,7 @@ extension LockedBox where T: Numeric { @discardableResult func decrement() -> T { - write { n in + update { n in n -= 1 return n } diff --git a/GRDB/Utils/Pool.swift b/GRDB/Utils/Pool.swift index a76579912..c7b12c0de 100644 --- a/GRDB/Utils/Pool.swift +++ b/GRDB/Utils/Pool.swift @@ -47,7 +47,7 @@ final class Pool { } private let makeElement: () throws -> T - private var items: ReadWriteBox<[Item]> = ReadWriteBox(value: []) + @ReadWriteBox private var items: [Item] = [] private let itemsSemaphore: DispatchSemaphore // limits the number of elements private let itemsGroup: DispatchGroup // knows when no element is used private let barrierQueue: DispatchQueue @@ -67,7 +67,7 @@ final class Pool { itemsSemaphore.wait() itemsGroup.enter() do { - let item = try items.write { items -> Item in + let item = try $items.update { items -> Item in if let item = items.first(where: \.isAvailable) { item.isAvailable = false return item @@ -96,7 +96,7 @@ final class Pool { } private func release(_ item: Item) { - items.write { _ in + $items.update { _ in // This is why Item is a class, not a struct: so that we can // release it without having to find in it the items array. item.isAvailable = true @@ -108,7 +108,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 -> Void) rethrows { - try items.read { items in + try $items.read { items in for item in items { try body(item.element) } @@ -118,9 +118,7 @@ final class Pool { /// Removes all elements from the pool. /// Currently used elements won't be reused. func removeAll() { - items.write { - $0.removeAll() - } + items = [] } /// Blocks until no element is used, and runs the `barrier` function before diff --git a/GRDB/Utils/ReadWriteBox.swift b/GRDB/Utils/ReadWriteBox.swift index f540908c2..1037ef8b3 100644 --- a/GRDB/Utils/ReadWriteBox.swift +++ b/GRDB/Utils/ReadWriteBox.swift @@ -1,29 +1,33 @@ import Dispatch -/// A ReadWriteBox grants multiple readers and single-writer guarantees on a value. +/// A ReadWriteBox grants multiple readers and single-writer guarantees on a +/// value. It is backed by a concurrent DispatchQueue. +@propertyWrapper final class ReadWriteBox { - private var _value: T + private var _wrappedValue: T private var queue: DispatchQueue - var value: T { + var wrappedValue: T { get { read { $0 } } - set { write { $0 = newValue } } + set { update { $0 = newValue } } } - init(value: T) { - _value = value + var projectedValue: ReadWriteBox { self } + + init(wrappedValue: T) { + _wrappedValue = wrappedValue queue = DispatchQueue(label: "GRDB.ReadWriteBox", attributes: [.concurrent]) } func read(_ block: (T) throws -> U) rethrows -> U { try queue.sync { - try block(_value) + try block(_wrappedValue) } } - func write(_ block: (inout T) throws -> U) rethrows -> U { + func update(_ block: (inout T) throws -> U) rethrows -> U { try queue.sync(flags: [.barrier]) { - try block(&_value) + try block(&_wrappedValue) } } } @@ -31,7 +35,7 @@ final class ReadWriteBox { extension ReadWriteBox where T: Numeric { @discardableResult func increment() -> T { - write { n in + update { n in n += 1 return n } @@ -39,7 +43,7 @@ extension ReadWriteBox where T: Numeric { @discardableResult func decrement() -> T { - write { n in + update { n in n -= 1 return n } diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index 80ee052c8..1f27adbad 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -52,10 +52,10 @@ class GRDBTestCase: XCTestCase { private var dbDirectoryPath: String! // Populated by default configuration - var sqlQueries: [String]! // TODO: protect against concurrent accesses + @LockedBox var sqlQueries: [String] = [] // Populated by default configuration - var lastSQLQuery: String! { sqlQueries.last! } + var lastSQLQuery: String? { sqlQueries.last } override func setUp() { super.setUp() @@ -100,7 +100,6 @@ class GRDBTestCase: XCTestCase { } dbConfiguration.trace = { [unowned self] sql in - #warning("TODO: make it thread-safe") self.sqlQueries.append(sql) } @@ -147,7 +146,7 @@ class GRDBTestCase: XCTestCase { // Compare SQL strings (ignoring leading and trailing white space and semicolons. func assertEqualSQL(_ db: Database, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws { try request.makeStatement(db).makeCursor().next() - assertEqualSQL(lastSQLQuery, sql, file: file, line: line) + assertEqualSQL(lastSQLQuery!, sql, file: file, line: line) } // Compare SQL strings (ignoring leading and trailing white space and semicolons. @@ -160,7 +159,7 @@ class GRDBTestCase: XCTestCase { func sql(_ databaseReader: DatabaseReader, _ request: Request) -> String { try! databaseReader.unsafeRead { db in try request.makeStatement(db).makeCursor().next() - return lastSQLQuery + return lastSQLQuery! } } } diff --git a/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift b/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift index b108ab579..ddf471bb2 100644 --- a/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift @@ -125,13 +125,13 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase { // Insert var record = DefaultPolicy(id: nil) try record.insert(db) - XCTAssertTrue(self.lastSQLQuery.hasPrefix("INSERT INTO \"records\"")) + XCTAssertTrue(self.lastSQLQuery!.hasPrefix("INSERT INTO \"records\"")) XCTAssertEqual(record.id, 1) // Update record = DefaultPolicy(id: 1) try record.update(db) - XCTAssertTrue(self.lastSQLQuery.hasPrefix("UPDATE \"records\"")) + XCTAssertTrue(self.lastSQLQuery!.hasPrefix("UPDATE \"records\"")) } } @@ -145,13 +145,13 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase { // Insert var record = MixedPolicy(id: nil) try record.insert(db) - XCTAssertTrue(self.lastSQLQuery.hasPrefix("INSERT OR FAIL INTO \"records\"")) + XCTAssertTrue(self.lastSQLQuery!.hasPrefix("INSERT OR FAIL INTO \"records\"")) XCTAssertEqual(record.id, 1) // Update record = MixedPolicy(id: 1) try record.update(db) - XCTAssertTrue(self.lastSQLQuery.hasPrefix("UPDATE OR ROLLBACK \"records\"")) + XCTAssertTrue(self.lastSQLQuery!.hasPrefix("UPDATE OR ROLLBACK \"records\"")) } } @@ -190,7 +190,7 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase { // Insert var record = ReplacePolicy(id: nil, email: "arthur@example.com") try record.insert(db) - XCTAssertTrue(self.lastSQLQuery.hasPrefix("INSERT OR REPLACE INTO \"records\"")) + XCTAssertTrue(self.lastSQLQuery!.hasPrefix("INSERT OR REPLACE INTO \"records\"")) XCTAssertEqual(record.id, 1) XCTAssertEqual(observer.events.count, 1) XCTAssertEqual(observer.events[0].kind, .insert) @@ -199,7 +199,7 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase { // Insert record = ReplacePolicy(id: nil, email: "arthur@example.com") try record.insert(db) - XCTAssertTrue(self.lastSQLQuery.hasPrefix("INSERT OR REPLACE INTO \"records\"")) + XCTAssertTrue(self.lastSQLQuery!.hasPrefix("INSERT OR REPLACE INTO \"records\"")) XCTAssertEqual(record.id, 2) XCTAssertTrue(try ReplacePolicy.fetchCount(db) == 1) XCTAssertEqual(observer.events.count, 1) @@ -209,7 +209,7 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase { // Update record = ReplacePolicy(id: 2, email: "arthur@example.com") try record.update(db) - XCTAssertTrue(self.lastSQLQuery.hasPrefix("UPDATE OR REPLACE \"records\"")) + XCTAssertTrue(self.lastSQLQuery!.hasPrefix("UPDATE OR REPLACE \"records\"")) XCTAssertEqual(observer.events.count, 1) XCTAssertEqual(observer.events[0].kind, .update) XCTAssertEqual(observer.events[0].rowID, 2) @@ -241,13 +241,13 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase { // Insert var record = IgnorePolicy(id: nil) try record.insert(db) - XCTAssertTrue(self.lastSQLQuery.hasPrefix("INSERT OR IGNORE INTO \"records\"")) + XCTAssertTrue(self.lastSQLQuery!.hasPrefix("INSERT OR IGNORE INTO \"records\"")) XCTAssertTrue(record.id == nil) // Update record = IgnorePolicy(id: 1) try record.update(db) - XCTAssertTrue(self.lastSQLQuery.hasPrefix("UPDATE OR IGNORE \"records\"")) + XCTAssertTrue(self.lastSQLQuery!.hasPrefix("UPDATE OR IGNORE \"records\"")) } } @@ -261,13 +261,13 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase { // Insert var record = FailPolicy(id: nil) try record.insert(db) - XCTAssertTrue(self.lastSQLQuery.hasPrefix("INSERT OR FAIL INTO \"records\"")) + XCTAssertTrue(self.lastSQLQuery!.hasPrefix("INSERT OR FAIL INTO \"records\"")) XCTAssertEqual(record.id, 1) // Update record = FailPolicy(id: 1) try record.update(db) - XCTAssertTrue(self.lastSQLQuery.hasPrefix("UPDATE OR FAIL \"records\"")) + XCTAssertTrue(self.lastSQLQuery!.hasPrefix("UPDATE OR FAIL \"records\"")) } } @@ -281,13 +281,13 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase { // Insert var record = AbortPolicy(id: nil) try record.insert(db) - XCTAssertTrue(self.lastSQLQuery.hasPrefix("INSERT INTO \"records\"")) + XCTAssertTrue(self.lastSQLQuery!.hasPrefix("INSERT INTO \"records\"")) XCTAssertEqual(record.id, 1) // Update record = AbortPolicy(id: 1) try record.update(db) - XCTAssertTrue(self.lastSQLQuery.hasPrefix("UPDATE \"records\"")) + XCTAssertTrue(self.lastSQLQuery!.hasPrefix("UPDATE \"records\"")) } } @@ -301,13 +301,13 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase { // Insert var record = RollbackPolicy(id: nil) try record.insert(db) - XCTAssertTrue(self.lastSQLQuery.hasPrefix("INSERT OR ROLLBACK INTO \"records\"")) + XCTAssertTrue(self.lastSQLQuery!.hasPrefix("INSERT OR ROLLBACK INTO \"records\"")) XCTAssertEqual(record.id, 1) // Update record = RollbackPolicy(id: 1) try record.update(db) - XCTAssertTrue(self.lastSQLQuery.hasPrefix("UPDATE OR ROLLBACK \"records\"")) + XCTAssertTrue(self.lastSQLQuery!.hasPrefix("UPDATE OR ROLLBACK \"records\"")) } } } diff --git a/Tests/GRDBTests/PoolTests.swift b/Tests/GRDBTests/PoolTests.swift index e00d9cce1..7cb3b32a6 100644 --- a/Tests/GRDBTests/PoolTests.swift +++ b/Tests/GRDBTests/PoolTests.swift @@ -4,7 +4,7 @@ import XCTest class PoolTests: XCTestCase { /// Returns a Pool whose elements are incremented integers: 1, 2, 3... private func makeCounterPool(maximumCount: Int) -> Pool { - let count = ReadWriteBox(value: 0) + let count = ReadWriteBox(wrappedValue: 0) return Pool(maximumCount: maximumCount, makeElement: count.increment) } diff --git a/Tests/GRDBTests/TableDefinitionTests.swift b/Tests/GRDBTests/TableDefinitionTests.swift index 6d7f37921..8e86435cc 100644 --- a/Tests/GRDBTests/TableDefinitionTests.swift +++ b/Tests/GRDBTests/TableDefinitionTests.swift @@ -12,29 +12,29 @@ class TableDefinitionTests: GRDBTestCase { t.column("name", .text) } - assertEqualSQL( - lastSQLQuery, - ("CREATE TABLE \"test\" (" + - "\"id\" INTEGER PRIMARY KEY, " + - "\"name\" TEXT" + - ")") as String) + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "test" (\ + "id" INTEGER PRIMARY KEY, \ + "name" TEXT\ + ) + """) } } - + func testTableCreationOptions() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "test", temporary: true, ifNotExists: true, withoutRowID: true) { t in t.column("id", .integer).primaryKey() } - assertEqualSQL( - lastSQLQuery, - ("CREATE TEMPORARY TABLE IF NOT EXISTS \"test\" (" + - "\"id\" INTEGER PRIMARY KEY" + - ") WITHOUT ROWID") as String) + assertEqualSQL(lastSQLQuery!, """ + CREATE TEMPORARY TABLE IF NOT EXISTS "test" (\ + "id" INTEGER PRIMARY KEY\ + ) WITHOUT ROWID + """) } } - + func testUntypedColumn() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -44,7 +44,9 @@ class TableDefinitionTests: GRDBTestCase { t.column("b") } - assertEqualSQL(lastSQLQuery, "CREATE TABLE \"test\" (\"a\", \"b\")") + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "test" ("a", "b") + """) } } @@ -54,7 +56,7 @@ class TableDefinitionTests: GRDBTestCase { try db.create(table: "test") { t in t.autoIncrementedPrimaryKey("id") } - assertEqualSQL(lastSQLQuery, """ + assertEqualSQL(lastSQLQuery!, """ CREATE TABLE "test" (\ "id" INTEGER PRIMARY KEY AUTOINCREMENT\ ) @@ -65,7 +67,7 @@ class TableDefinitionTests: GRDBTestCase { try db.create(table: "test") { t in t.autoIncrementedPrimaryKey("id", onConflict: .fail) } - assertEqualSQL(lastSQLQuery, """ + assertEqualSQL(lastSQLQuery!, """ CREATE TABLE "test" (\ "id" INTEGER PRIMARY KEY ON CONFLICT FAIL AUTOINCREMENT\ ) @@ -73,33 +75,33 @@ class TableDefinitionTests: GRDBTestCase { return .rollback } } - + func testColumnPrimaryKeyOptions() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inTransaction { db in try db.create(table: "test") { t in t.column("id", .integer).primaryKey(onConflict: .fail) } - assertEqualSQL( - lastSQLQuery, - ("CREATE TABLE \"test\" (" + - "\"id\" INTEGER PRIMARY KEY ON CONFLICT FAIL" + - ")") as String) + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "test" (\ + "id" INTEGER PRIMARY KEY ON CONFLICT FAIL\ + ) + """) return .rollback } try dbQueue.inTransaction { db in try db.create(table: "test") { t in t.column("id", .integer).primaryKey(autoincrement: true) } - assertEqualSQL( - lastSQLQuery, - ("CREATE TABLE \"test\" (" + - "\"id\" INTEGER PRIMARY KEY AUTOINCREMENT" + - ")") as String) + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "test" (\ + "id" INTEGER PRIMARY KEY AUTOINCREMENT\ + ) + """) return .rollback } } - + func testColumnNotNull() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -111,19 +113,19 @@ class TableDefinitionTests: GRDBTestCase { t.column("e", .integer).notNull(onConflict: .ignore) t.column("f", .integer).notNull(onConflict: .replace) } - assertEqualSQL( - lastSQLQuery, - ("CREATE TABLE \"test\" (" + - "\"a\" INTEGER NOT NULL, " + - "\"b\" INTEGER NOT NULL, " + - "\"c\" INTEGER NOT NULL ON CONFLICT ROLLBACK, " + - "\"d\" INTEGER NOT NULL ON CONFLICT FAIL, " + - "\"e\" INTEGER NOT NULL ON CONFLICT IGNORE, " + - "\"f\" INTEGER NOT NULL ON CONFLICT REPLACE" + - ")") as String) + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "test" (\ + "a" INTEGER NOT NULL, \ + "b" INTEGER NOT NULL, \ + "c" INTEGER NOT NULL ON CONFLICT ROLLBACK, \ + "d" INTEGER NOT NULL ON CONFLICT FAIL, \ + "e" INTEGER NOT NULL ON CONFLICT IGNORE, \ + "f" INTEGER NOT NULL ON CONFLICT REPLACE\ + ) + """) } } - + func testColumnIndexed() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -149,19 +151,19 @@ class TableDefinitionTests: GRDBTestCase { t.column("e", .integer).unique(onConflict: .ignore) t.column("f", .integer).unique(onConflict: .replace) } - assertEqualSQL( - lastSQLQuery, - ("CREATE TABLE \"test\" (" + - "\"a\" INTEGER UNIQUE, " + - "\"b\" INTEGER UNIQUE, " + - "\"c\" INTEGER UNIQUE ON CONFLICT ROLLBACK, " + - "\"d\" INTEGER UNIQUE ON CONFLICT FAIL, " + - "\"e\" INTEGER UNIQUE ON CONFLICT IGNORE, " + - "\"f\" INTEGER UNIQUE ON CONFLICT REPLACE" + - ")") as String) + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "test" (\ + "a" INTEGER UNIQUE, \ + "b" INTEGER UNIQUE, \ + "c" INTEGER UNIQUE ON CONFLICT ROLLBACK, \ + "d" INTEGER UNIQUE ON CONFLICT FAIL, \ + "e" INTEGER UNIQUE ON CONFLICT IGNORE, \ + "f" INTEGER UNIQUE ON CONFLICT REPLACE\ + ) + """) } } - + func testColumnCheck() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -170,14 +172,14 @@ class TableDefinitionTests: GRDBTestCase { t.column("b", .integer).check(sql: "b <> 2") t.column("c", .integer).check { $0 > 0 }.check { $0 < 10 } } - assertEqualSQL( - lastSQLQuery, - ("CREATE TABLE \"test\" (" + - "\"a\" INTEGER CHECK (\"a\" > 0), " + - "\"b\" INTEGER CHECK (b <> 2), " + - "\"c\" INTEGER CHECK (\"c\" > 0) CHECK (\"c\" < 10)" + - ")") as String) - + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "test" (\ + "a" INTEGER CHECK ("a" > 0), \ + "b" INTEGER CHECK (b <> 2), \ + "c" INTEGER CHECK ("c" > 0) CHECK ("c" < 10)\ + ) + """) + // Sanity check try db.execute(sql: "INSERT INTO test (a, b, c) VALUES (1, 0, 1)") do { @@ -187,7 +189,7 @@ class TableDefinitionTests: GRDBTestCase { } } } - + func testColumnDefault() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -198,34 +200,34 @@ class TableDefinitionTests: GRDBTestCase { t.column("d", .integer).defaults(to: "foo".data(using: .utf8)!) t.column("e", .integer).defaults(sql: "NULL") } - assertEqualSQL( - lastSQLQuery, - ("CREATE TABLE \"test\" (" + - "\"a\" INTEGER DEFAULT 1, " + - "\"b\" INTEGER DEFAULT 1.0, " + - "\"c\" INTEGER DEFAULT '''fooéı👨👨🏿🇫🇷🇨🇮''', " + - "\"d\" INTEGER DEFAULT X'666F6F', " + - "\"e\" INTEGER DEFAULT NULL" + - ")") as String) - + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "test" (\ + "a" INTEGER DEFAULT 1, \ + "b" INTEGER DEFAULT 1.0, \ + "c" INTEGER DEFAULT '''fooéı👨👨🏿🇫🇷🇨🇮''', \ + "d" INTEGER DEFAULT X'666F6F', \ + "e" INTEGER DEFAULT NULL\ + ) + """) + // Sanity check try db.execute(sql: "INSERT INTO test DEFAULT VALUES") XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT a FROM test")!, 1) XCTAssertEqual(try String.fetchOne(db, sql: "SELECT c FROM test")!, "'fooéı👨👨🏿🇫🇷🇨🇮'") } } - + func testColumnCollation() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inTransaction { db in try db.create(table: "test") { t in t.column("name", .text).collate(.nocase) } - assertEqualSQL( - lastSQLQuery, - ("CREATE TABLE \"test\" (" + - "\"name\" TEXT COLLATE NOCASE" + - ")") as String) + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "test" (\ + "name" TEXT COLLATE NOCASE\ + ) + """) return .rollback } @@ -235,15 +237,15 @@ class TableDefinitionTests: GRDBTestCase { try db.create(table: "test") { t in t.column("name", .text).collate(collation) } - assertEqualSQL( - lastSQLQuery, - ("CREATE TABLE \"test\" (" + - "\"name\" TEXT COLLATE foo" + - ")") as String) + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "test" (\ + "name" TEXT COLLATE foo\ + ) + """) return .rollback } } - + func testColumnReference() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -260,17 +262,17 @@ class TableDefinitionTests: GRDBTestCase { t.column("weird", .text).references("parent", column: "name").references("parent", column: "email") t.column("pklessRowId", .text).references("pkless") } - assertEqualSQL( - lastSQLQuery, - ("CREATE TABLE \"child\" (" + - "\"parentName\" TEXT REFERENCES \"parent\"(\"name\") ON DELETE CASCADE ON UPDATE CASCADE, " + - "\"parentEmail\" TEXT REFERENCES \"parent\"(\"email\") ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED, " + - "\"weird\" TEXT REFERENCES \"parent\"(\"name\") REFERENCES \"parent\"(\"email\"), " + - "\"pklessRowId\" TEXT REFERENCES \"pkless\"(\"rowid\")" + - ")") as String) + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "child" (\ + "parentName" TEXT REFERENCES "parent"("name") ON DELETE CASCADE ON UPDATE CASCADE, \ + "parentEmail" TEXT REFERENCES "parent"("email") ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED, \ + "weird" TEXT REFERENCES "parent"("name") REFERENCES "parent"("email"), \ + "pklessRowId" TEXT REFERENCES "pkless"("rowid")\ + ) + """) } } - + func testTablePrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inTransaction { db in @@ -279,13 +281,13 @@ class TableDefinitionTests: GRDBTestCase { t.column("a", .text) t.column("b", .text) } - assertEqualSQL( - lastSQLQuery, - ("CREATE TABLE \"test\" (" + - "\"a\" TEXT, " + - "\"b\" TEXT, " + - "PRIMARY KEY (\"a\", \"b\")" + - ")") as String) + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "test" (\ + "a" TEXT, \ + "b" TEXT, \ + PRIMARY KEY ("a", "b")\ + ) + """) return .rollback } try dbQueue.inTransaction { db in @@ -294,17 +296,17 @@ class TableDefinitionTests: GRDBTestCase { t.column("a", .text) t.column("b", .text) } - assertEqualSQL( - lastSQLQuery, - ("CREATE TABLE \"test\" (" + - "\"a\" TEXT, " + - "\"b\" TEXT, " + - "PRIMARY KEY (\"a\", \"b\") ON CONFLICT FAIL" + - ")") as String) + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "test" (\ + "a" TEXT, \ + "b" TEXT, \ + PRIMARY KEY ("a", "b") ON CONFLICT FAIL\ + ) + """) return .rollback } } - + func testTableUniqueKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -315,18 +317,18 @@ class TableDefinitionTests: GRDBTestCase { t.column("b", .text) t.column("c", .text) } - assertEqualSQL( - lastSQLQuery, - ("CREATE TABLE \"test\" (" + - "\"a\" TEXT, " + - "\"b\" TEXT, " + - "\"c\" TEXT, " + - "UNIQUE (\"a\"), " + - "UNIQUE (\"b\", \"c\") ON CONFLICT FAIL" + - ")") as String) + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "test" (\ + "a" TEXT, \ + "b" TEXT, \ + "c" TEXT, \ + UNIQUE ("a"), \ + UNIQUE ("b", "c") ON CONFLICT FAIL\ + ) + """) } } - + func testTableForeignKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -342,18 +344,18 @@ class TableDefinitionTests: GRDBTestCase { t.column("d", .text) t.column("e", .text) } - assertEqualSQL( - lastSQLQuery, - ("CREATE TABLE \"child\" (" + - "\"c\" TEXT, " + - "\"d\" TEXT, " + - "\"e\" TEXT, " + - "FOREIGN KEY (\"c\", \"d\") REFERENCES \"parent\"(\"a\", \"b\") ON DELETE CASCADE ON UPDATE CASCADE, " + - "FOREIGN KEY (\"d\", \"e\") REFERENCES \"parent\"(\"b\", \"a\") ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED" + - ")") as String) + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "child" (\ + "c" TEXT, \ + "d" TEXT, \ + "e" TEXT, \ + FOREIGN KEY ("c", "d") REFERENCES "parent"("a", "b") ON DELETE CASCADE ON UPDATE CASCADE, \ + FOREIGN KEY ("d", "e") REFERENCES "parent"("b", "a") ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED\ + ) + """) } } - + func testTableCheck() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -363,14 +365,14 @@ class TableDefinitionTests: GRDBTestCase { t.column("a", .integer) t.column("b", .integer) } - assertEqualSQL( - lastSQLQuery, - ("CREATE TABLE \"test\" (" + - "\"a\" INTEGER, " + - "\"b\" INTEGER, " + - "CHECK ((\"a\" + \"b\") < 10), " + - "CHECK (a + b < 10)" + - ")") as String) + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "test" (\ + "a" INTEGER, \ + "b" INTEGER, \ + CHECK (("a" + "b") < 10), \ + CHECK (a + b < 10)\ + ) + """) // Sanity check try db.execute(sql: "INSERT INTO test (a, b) VALUES (1, 0)") @@ -381,7 +383,7 @@ class TableDefinitionTests: GRDBTestCase { } } } - + func testAutoReferences() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -389,25 +391,25 @@ class TableDefinitionTests: GRDBTestCase { t.column("id", .integer).primaryKey() t.column("id2", .integer).references("test1") } - assertEqualSQL( - lastSQLQuery, - ("CREATE TABLE \"test1\" (" + - "\"id\" INTEGER PRIMARY KEY, " + - "\"id2\" INTEGER REFERENCES \"test1\"(\"id\")" + - ")") as String) - + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "test1" (\ + "id" INTEGER PRIMARY KEY, \ + "id2" INTEGER REFERENCES "test1"("id")\ + ) + """) + try db.create(table: "test2") { t in t.column("id", .integer) t.column("id2", .integer).references("test2") t.primaryKey(["id"]) } - assertEqualSQL( - lastSQLQuery, - ("CREATE TABLE \"test2\" (" + - "\"id\" INTEGER, " + - "\"id2\" INTEGER REFERENCES \"test2\"(\"id\"), " + - "PRIMARY KEY (\"id\")" + - ")") as String) + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "test2" (\ + "id" INTEGER, \ + "id2" INTEGER REFERENCES "test2"("id"), \ + PRIMARY KEY ("id")\ + ) + """) try db.create(table: "test3") { t in t.column("a", .integer) @@ -417,28 +419,28 @@ class TableDefinitionTests: GRDBTestCase { t.foreignKey(["c", "d"], references: "test3") t.primaryKey(["a", "b"]) } - assertEqualSQL( - lastSQLQuery, - ("CREATE TABLE \"test3\" (" + - "\"a\" INTEGER, " + - "\"b\" INTEGER, " + - "\"c\" INTEGER, " + - "\"d\" INTEGER, " + - "PRIMARY KEY (\"a\", \"b\"), " + - "FOREIGN KEY (\"c\", \"d\") REFERENCES \"test3\"(\"a\", \"b\")" + - ")") as String) - + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "test3" (\ + "a" INTEGER, \ + "b" INTEGER, \ + "c" INTEGER, \ + "d" INTEGER, \ + PRIMARY KEY ("a", "b"), \ + FOREIGN KEY ("c", "d") REFERENCES "test3"("a", "b")\ + ) + """) + try db.create(table: "test4") { t in t.column("parent", .integer).references("test4") } assertEqualSQL( - lastSQLQuery, + lastSQLQuery!, ("CREATE TABLE \"test4\" (" + "\"parent\" INTEGER REFERENCES \"test4\"(\"rowid\")" + ")") as String) } } - + func testRenameTable() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -449,13 +451,13 @@ class TableDefinitionTests: GRDBTestCase { XCTAssertEqual(try db.columns(in: "test").count, 1) try db.rename(table: "test", to: "foo") - assertEqualSQL(lastSQLQuery, "ALTER TABLE \"test\" RENAME TO \"foo\"") + assertEqualSQL(lastSQLQuery!, "ALTER TABLE \"test\" RENAME TO \"foo\"") XCTAssertFalse(try db.tableExists("test")) XCTAssertTrue(try db.tableExists("foo")) XCTAssertEqual(try db.columns(in: "foo").count, 1) } } - + func testAlterTable() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -480,29 +482,29 @@ class TableDefinitionTests: GRDBTestCase { assertEqualSQL(sqlQueries[sqlQueries.count - 1], "ALTER TABLE \"test\" ADD COLUMN \"e\"") } } - + func testAlterTableRenameColumn() throws { guard sqlite3_libversion_number() >= 3025000 else { return } #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 13.0, tvOS 13.0, watchOS 6.0, *) else { - return - } + guard #available(iOS 13.0, tvOS 13.0, watchOS 6.0, *) else { + return + } #endif let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "test") { t in t.column("a", .text) } - + sqlQueries.removeAll() try db.alter(table: "test") { t in t.rename(column: "a", to: "b") t.add(column: "c") t.rename(column: "c", to: "d") } - + assertEqualSQL(sqlQueries[sqlQueries.count - 3], "ALTER TABLE \"test\" RENAME COLUMN \"a\" TO \"b\"") assertEqualSQL(sqlQueries[sqlQueries.count - 2], "ALTER TABLE \"test\" ADD COLUMN \"c\"") assertEqualSQL(sqlQueries[sqlQueries.count - 1], "ALTER TABLE \"test\" RENAME COLUMN \"c\" TO \"d\"") @@ -520,11 +522,11 @@ class TableDefinitionTests: GRDBTestCase { XCTAssertEqual(try db.columns(in: "test").count, 2) try db.drop(table: "test") - assertEqualSQL(lastSQLQuery, "DROP TABLE \"test\"") + assertEqualSQL(lastSQLQuery!, "DROP TABLE \"test\"") XCTAssertFalse(try db.tableExists("test")) } } - + func testCreateIndex() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -535,10 +537,10 @@ class TableDefinitionTests: GRDBTestCase { } try db.create(index: "test_on_a", on: "test", columns: ["a"]) - assertEqualSQL(lastSQLQuery, "CREATE INDEX \"test_on_a\" ON \"test\"(\"a\")") + assertEqualSQL(lastSQLQuery!, "CREATE INDEX \"test_on_a\" ON \"test\"(\"a\")") try db.create(index: "test_on_a_b", on: "test", columns: ["a", "b"], unique: true, ifNotExists: true) - assertEqualSQL(lastSQLQuery, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_b\" ON \"test\"(\"a\", \"b\")") + assertEqualSQL(lastSQLQuery!, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_b\" ON \"test\"(\"a\", \"b\")") // Sanity check XCTAssertEqual(try Set(db.indexes(on: "test").map(\.name)), ["test_on_a", "test_on_a_b"]) @@ -555,13 +557,13 @@ class TableDefinitionTests: GRDBTestCase { } try db.create(index: "test_on_a_b", on: "test", columns: ["a", "b"], unique: true, ifNotExists: true, condition: Column("a") == 1) - assertEqualSQL(lastSQLQuery, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_b\" ON \"test\"(\"a\", \"b\") WHERE \"a\" = 1") + assertEqualSQL(lastSQLQuery!, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_b\" ON \"test\"(\"a\", \"b\") WHERE \"a\" = 1") // Sanity check XCTAssertEqual(try Set(db.indexes(on: "test").map(\.name)), ["test_on_a_b"]) } } - + func testDropIndex() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -572,7 +574,7 @@ class TableDefinitionTests: GRDBTestCase { try db.create(index: "test_on_name", on: "test", columns: ["name"]) try db.drop(index: "test_on_name") - assertEqualSQL(lastSQLQuery, "DROP INDEX \"test_on_name\"") + assertEqualSQL(lastSQLQuery!, "DROP INDEX \"test_on_name\"") // Sanity check XCTAssertTrue(try db.indexes(on: "test").isEmpty) @@ -583,10 +585,10 @@ class TableDefinitionTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.reindex(collation: .binary) - assertEqualSQL(lastSQLQuery, "REINDEX BINARY") + assertEqualSQL(lastSQLQuery!, "REINDEX BINARY") try db.reindex(collation: .localizedCompare) - assertEqualSQL(lastSQLQuery, "REINDEX swiftLocalizedCompare") + assertEqualSQL(lastSQLQuery!, "REINDEX swiftLocalizedCompare") } } } From 00c2f6153552b2eff7fffd8c891d18428d324296 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 30 May 2020 13:54:45 +0200 Subject: [PATCH 11/28] TODO --- TODO.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/TODO.md b/TODO.md index 20a199f07..826aa8979 100644 --- a/TODO.md +++ b/TODO.md @@ -16,7 +16,7 @@ ## Features -- [ ] DatabaseMigrator.hasBeenSuperseded(): https://forums.swift.org/t/detect-future-database-migrations/36315/4 +- [ ] Access the database label from the tracing function - [ ] Subqueries: request.isEmpty / request.exists - [ ] Subqueries: request.count - [ ] Extract one row from a hasMany association (the one with the maximum date, the one with a flag set, etc.) https://stackoverflow.com/questions/43188771/sqlite-join-query-most-recent-posts-by-each-user (failed PR: https://github.com/groue/GRDB.swift/pull/767) @@ -42,7 +42,6 @@ - [ ] Decode NSDecimalNumber from text database values - [ ] Check https://sqlite.org/sqlar.html - [ ] FTS: prefix queries -- [ ] A way to stop a ValueObservation observer without waiting for deinit - [ ] More schema alterations - [ ] DatabasePool.databaseSchemaIsLocked = true (should forbid schema changes, and never reset dbPool readers' caches). Or can we invalidate reader's cache automatically from the writer connection? - [ ] Database.clearSchemaCache() is fine, but what about dbPool readers? Can we invalidate the cache for a whole pool? From 03a66af35e849b31eaf9035ea8ecef7ef3e20998 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 May 2020 13:22:27 +0200 Subject: [PATCH 12/28] Bump iOS requirement to iOS10+ iOS9 simulator is no longer available with the Xcode 11.4+ requirement. https://twitter.com/xenadu02/status/1140093901438689280 --- Documentation/GRDB5MigrationGuide.md | 2 +- GRDB.swift.podspec | 2 +- Package.swift | 2 +- README.md | 2 +- SQLiteCustom/GRDBDeploymentTarget.xcconfig | 2 +- Support/GRDBDeploymentTarget.xcconfig | 2 +- Tests/CocoaPods/GRDBiOS-framework/Podfile | 2 +- .../CocoaPods/GRDBiOS-framework/iOS.xcodeproj/project.pbxproj | 4 ++-- Tests/CocoaPods/GRDBiOS-static/Podfile | 2 +- Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.pbxproj | 4 ++-- 10 files changed, 12 insertions(+), 12 deletions(-) diff --git a/Documentation/GRDB5MigrationGuide.md b/Documentation/GRDB5MigrationGuide.md index 57781fe3a..f7ee7033a 100644 --- a/Documentation/GRDB5MigrationGuide.md +++ b/Documentation/GRDB5MigrationGuide.md @@ -24,7 +24,7 @@ GRDB requirements have been bumped: - **Swift 5.2+** (was Swift 4.2+) - **Xcode 11.4+** (was Xcode 10.0+) -- iOS 9.0+ (unchanged) +- **iOS 10.0+** (was iOS 9.0+) - **macOS 10.10+** (was macOS 10.9+) - tvOS 9.0+ (unchanged) - watchOS 2.0+ (unchanged) diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 82e9c5529..ac2b993b9 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -10,7 +10,7 @@ Pod::Spec.new do |s| s.module_name = 'GRDB' s.swift_versions = ['5.2'] - s.ios.deployment_target = '9.0' + s.ios.deployment_target = '10.0' s.osx.deployment_target = '10.10' s.watchos.deployment_target = '2.0' s.tvos.deployment_target = '9.0' diff --git a/Package.swift b/Package.swift index d100bc67a..940e4d848 100644 --- a/Package.swift +++ b/Package.swift @@ -6,7 +6,7 @@ import PackageDescription let package = Package( name: "GRDB", platforms: [ - .iOS("9.0"), + .iOS("10.0"), .macOS("10.10"), .tvOS("9.0"), .watchOS("2.0"), diff --git a/README.md b/README.md index c5d9ec4ef..38be75a0d 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ **Latest release**: May 11, 2020 • version 5.0.0-beta.2 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) -**Requirements**: iOS 9.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ • Swift 5.2+ / Xcode 11.4+ +**Requirements**: iOS 10.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ • Swift 5.2+ / Xcode 11.4+ | Swift version | GRDB version | | ------------- | ----------------------------------------------------------- | diff --git a/SQLiteCustom/GRDBDeploymentTarget.xcconfig b/SQLiteCustom/GRDBDeploymentTarget.xcconfig index da7166278..58994c0a3 100644 --- a/SQLiteCustom/GRDBDeploymentTarget.xcconfig +++ b/SQLiteCustom/GRDBDeploymentTarget.xcconfig @@ -1,4 +1,4 @@ -IPHONEOS_DEPLOYMENT_TARGET = 9.0 +IPHONEOS_DEPLOYMENT_TARGET = 10.0 MACOSX_DEPLOYMENT_TARGET = 10.10 TVOS_DEPLOYMENT_TARGET = 9.0 WATCHOS_DEPLOYMENT_TARGET = 2.0 diff --git a/Support/GRDBDeploymentTarget.xcconfig b/Support/GRDBDeploymentTarget.xcconfig index 6188f42d7..a88f9e56d 100644 --- a/Support/GRDBDeploymentTarget.xcconfig +++ b/Support/GRDBDeploymentTarget.xcconfig @@ -1,4 +1,4 @@ -IPHONEOS_DEPLOYMENT_TARGET = 9.0 +IPHONEOS_DEPLOYMENT_TARGET = 10.0 MACOSX_DEPLOYMENT_TARGET = 10.10 TVOS_DEPLOYMENT_TARGET = 9.0 WATCHOS_DEPLOYMENT_TARGET = 2.0 diff --git a/Tests/CocoaPods/GRDBiOS-framework/Podfile b/Tests/CocoaPods/GRDBiOS-framework/Podfile index 47db57c49..ea7d91e6c 100644 --- a/Tests/CocoaPods/GRDBiOS-framework/Podfile +++ b/Tests/CocoaPods/GRDBiOS-framework/Podfile @@ -1,6 +1,6 @@ use_frameworks! target 'iOS' -platform :ios, '9.0' +platform :ios, '10.0' pod 'GRDB.swift', :path => '../../..' post_install do |installer| diff --git a/Tests/CocoaPods/GRDBiOS-framework/iOS.xcodeproj/project.pbxproj b/Tests/CocoaPods/GRDBiOS-framework/iOS.xcodeproj/project.pbxproj index 598c55b17..a619c60fa 100644 --- a/Tests/CocoaPods/GRDBiOS-framework/iOS.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/GRDBiOS-framework/iOS.xcodeproj/project.pbxproj @@ -251,7 +251,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -301,7 +301,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SWIFT_COMPILATION_MODE = wholemodule; diff --git a/Tests/CocoaPods/GRDBiOS-static/Podfile b/Tests/CocoaPods/GRDBiOS-static/Podfile index 9335d2ec8..882142de1 100644 --- a/Tests/CocoaPods/GRDBiOS-static/Podfile +++ b/Tests/CocoaPods/GRDBiOS-static/Podfile @@ -1,5 +1,5 @@ target 'iOS' -platform :ios, '9.0' +platform :ios, '10.0' pod 'GRDB.swift', :path => '../../..' post_install do |installer| diff --git a/Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.pbxproj b/Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.pbxproj index e765c7056..a9994316e 100644 --- a/Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.pbxproj @@ -232,7 +232,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -282,7 +282,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SWIFT_COMPILATION_MODE = wholemodule; From 9ee3fd38b511bf2f23647dad439b17d2254ba54d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 May 2020 13:52:04 +0200 Subject: [PATCH 13/28] Remove mentions of unsupported iOS versions --- Documentation/FTS5Tokenizers.md | 2 +- Documentation/Migrations.md | 3 +-- GRDB/Core/Database.swift | 10 ++++++---- GRDB/Core/DatabasePool.swift | 2 +- GRDB/Core/DatabaseQueue.swift | 2 +- .../Core/Support/StandardLibrary/StandardLibrary.swift | 6 +++--- GRDB/Migration/Migration.swift | 5 +---- GRDB/QueryInterface/SQL/SQLFunctions.swift | 6 +++--- GRDB/Record/EncodableRecord+Encodable.swift | 4 ++-- GRDB/Record/EncodableRecord.swift | 2 +- GRDB/Record/FetchableRecord+Decodable.swift | 6 +++--- GRDB/Record/FetchableRecord.swift | 2 +- .../AssociationPrefetchingObservationTests.swift | 8 ++++---- .../GRDBTests/DatabaseDateDecodingStrategyTests.swift | 4 ++-- .../GRDBTests/DatabaseDateEncodingStrategyTests.swift | 4 ++-- Tests/GRDBTests/DatabaseErrorTests.swift | 2 -- Tests/GRDBTests/DatabaseFunctionTests.swift | 2 +- Tests/GRDBTests/DatabasePoolConcurrencyTests.swift | 4 ++-- Tests/GRDBTests/DatabaseQueueTests.swift | 4 ++-- Tests/GRDBTests/DatabaseRegionTests.swift | 6 ------ Tests/GRDBTests/FTS5WrapperTokenizerTests.swift | 2 +- Tests/GRDBTests/QueryInterfaceExpressionsTests.swift | 2 +- 22 files changed, 39 insertions(+), 49 deletions(-) diff --git a/Documentation/FTS5Tokenizers.md b/Documentation/FTS5Tokenizers.md index 12e5fdc77..7b380a4dc 100644 --- a/Documentation/FTS5Tokenizers.md +++ b/Documentation/FTS5Tokenizers.md @@ -371,7 +371,7 @@ final class LatinAsciiTokenizer : FTS5WrapperTokenizer { } ``` -> :point_up: **Note**: String.applyingTransform is not available before iOS 9.0 and macOS 10.11. Use the Core Foundation function [CFStringTransform](https://developer.apple.com/reference/corefoundation/1542411-cfstringtransform) instead. +> :point_up: **Note**: String.applyingTransform is not available before macOS 10.11. Use the Core Foundation function [CFStringTransform](https://developer.apple.com/reference/corefoundation/1542411-cfstringtransform) instead. Remember to register LatinAsciiTokenizer before using it: diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index 2b484a54d..d2b9d4ee6 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -31,8 +31,7 @@ migrator.registerMigration("v2") { db in **Each migration runs in a separate transaction.** Should one throw an error, its transaction is rollbacked, subsequent migrations do not run, and the error is eventually thrown by `migrator.migrate(dbQueue)`. -**Migrations run with deferred foreign key checks,** starting SQLite 3.7.16+ (iOS 9.0+ / -+ / tvOS 9.0+ / watchOS 2.0+ / [custom SQLite build] / [SQLCipher](../README.md#encryption)). This means that eventual foreign key violations are only checked at the end of the migration (and they make the migration fail). +**Migrations run with deferred foreign key checks.** This means that eventual foreign key violations are only checked at the end of the migration (and they make the migration fail). **The memory of applied migrations is stored in the database itself** (in a reserved table). diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 87484b242..982155c92 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -228,9 +228,9 @@ public final class Database { } // 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 + // It is available from macOS 10.12, tvOS 10.0, watchOS 3.0 // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - #if GRDBCUSTOMSQLITE || GRDBCIPHER + #if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS) let dbPointer = Unmanaged.passUnretained(self).toOpaque() sqlite3_trace_v2( sqliteConnection, @@ -242,7 +242,7 @@ public final class Database { #elseif os(Linux) setupTrace_v1() #else - if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { + if #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) { let dbPointer = Unmanaged.passUnretained(self).toOpaque() sqlite3_trace_v2( sqliteConnection, @@ -257,6 +257,7 @@ public final class Database { #endif } + #if !(GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)) // Precondition: configuration.trace != nil private func setupTrace_v1() { let dbPointer = Unmanaged.passUnretained(self).toOpaque() @@ -266,6 +267,7 @@ public final class Database { db.configuration.trace!(sql) }, dbPointer) } + #endif // Precondition: configuration.trace != nil private static func trace_v2( @@ -331,7 +333,7 @@ public final class Database { add(function: .lowercase) add(function: .uppercase) - if #available(iOS 9.0, OSX 10.11, watchOS 3.0, *) { + if #available(OSX 10.11, watchOS 3.0, *) { add(function: .localizedCapitalize) add(function: .localizedLowercase) add(function: .localizedUppercase) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index b6b149e39..fbe2ae7eb 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -139,7 +139,7 @@ public final class DatabasePool: DatabaseWriter { // Undo job done in setupMemoryManagement() // // https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error - // Explicit unregistration is required before iOS 9 and OS X 10.11. + // Explicit unregistration is required before OS X 10.11. NotificationCenter.default.removeObserver(self) // Close reader connections before the writer connection. diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index d072bf1e6..a3d269452 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -68,7 +68,7 @@ public final class DatabaseQueue: DatabaseWriter { // Undo job done in setupMemoryManagement() // // https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error - // Explicit unregistration is required before iOS 9 and OS X 10.11. + // Explicit unregistration is required before OS X 10.11. NotificationCenter.default.removeObserver(self) } } diff --git a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift index 5a06d066d..99a2597a3 100644 --- a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift +++ b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift @@ -554,7 +554,7 @@ extension DatabaseFunction { /// let nameColumn = Column("name") /// let request = Player.select(nameColumn.localizedCapitalized) /// let names = try String.fetchAll(dbQueue, request) // [String] - @available(iOS 9.0, OSX 10.11, watchOS 3.0, *) + @available(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 { @@ -575,7 +575,7 @@ extension DatabaseFunction { /// let nameColumn = Column("name") /// let request = Player.select(nameColumn.localizedLowercased) /// let names = try String.fetchAll(dbQueue, request) // [String] - @available(iOS 9.0, OSX 10.11, watchOS 3.0, *) + @available(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 { @@ -596,7 +596,7 @@ extension DatabaseFunction { /// let nameColumn = Column("name") /// let request = Player.select(nameColumn.localizedUppercased) /// let names = try String.fetchAll(dbQueue, request) // [String] - @available(iOS 9.0, OSX 10.11, watchOS 3.0, *) + @available(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 { diff --git a/GRDB/Migration/Migration.swift b/GRDB/Migration/Migration.swift index 7208b9f67..cc47a79c8 100644 --- a/GRDB/Migration/Migration.swift +++ b/GRDB/Migration/Migration.swift @@ -4,10 +4,7 @@ struct Migration { let migrate: (Database) throws -> Void func run(_ db: Database) throws { - // PRAGMA foreign_key_check and SQLITE_CONSTRAINT_FOREIGNKEY were - // introduced in SQLite 3.7.16 - // http://www.sqlite.org/changes.html#version_3_7_16 - if try sqlite3_libversion_number() >= 3007016 && (Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false) { + if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false { try runWithDeferredForeignKeysChecks(db) } else { try runWithoutDisabledForeignKeys(db) diff --git a/GRDB/QueryInterface/SQL/SQLFunctions.swift b/GRDB/QueryInterface/SQL/SQLFunctions.swift index 9178f6521..dcd2c3b05 100644 --- a/GRDB/QueryInterface/SQL/SQLFunctions.swift +++ b/GRDB/QueryInterface/SQL/SQLFunctions.swift @@ -187,7 +187,7 @@ extension SQLSpecificExpressible { /// let nameColumn = Column("name") /// let request = Player.select(nameColumn.localizedCapitalized) /// let names = try String.fetchAll(dbQueue, request) // [String] - @available(iOS 9.0, OSX 10.11, watchOS 3.0, *) + @available(OSX 10.11, watchOS 3.0, *) public var localizedCapitalized: SQLExpression { DatabaseFunction.localizedCapitalize(sqlExpression) } @@ -198,7 +198,7 @@ extension SQLSpecificExpressible { /// let nameColumn = Column("name") /// let request = Player.select(nameColumn.localizedLowercased) /// let names = try String.fetchAll(dbQueue, request) // [String] - @available(iOS 9.0, OSX 10.11, watchOS 3.0, *) + @available(OSX 10.11, watchOS 3.0, *) public var localizedLowercased: SQLExpression { DatabaseFunction.localizedLowercase(sqlExpression) } @@ -209,7 +209,7 @@ extension SQLSpecificExpressible { /// let nameColumn = Column("name") /// let request = Player.select(nameColumn.localizedUppercased) /// let names = try String.fetchAll(dbQueue, request) // [String] - @available(iOS 9.0, OSX 10.11, watchOS 3.0, *) + @available(OSX 10.11, watchOS 3.0, *) public var localizedUppercased: SQLExpression { DatabaseFunction.localizedUppercase(sqlExpression) } diff --git a/GRDB/Record/EncodableRecord+Encodable.swift b/GRDB/Record/EncodableRecord+Encodable.swift index 2708def6b..e50491e26 100644 --- a/GRDB/Record/EncodableRecord+Encodable.swift +++ b/GRDB/Record/EncodableRecord+Encodable.swift @@ -320,7 +320,7 @@ extension JSONRequiredEncoder: UnkeyedEncodingContainer { mutating func superEncoder() -> Encoder { self } } -@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) +@available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) private var iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime @@ -342,7 +342,7 @@ extension DatabaseDateEncodingStrategy { case .secondsSince1970: return Int64(floor(date.timeIntervalSince1970)) case .iso8601: - if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { + if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) { return iso8601Formatter.string(from: date) } else { fatalError("ISO8601DateFormatter is unavailable on this platform.") diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index d9cb84a9c..30b4454e3 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -348,7 +348,7 @@ public enum DatabaseDateEncodingStrategy { case millisecondsSince1970 /// Encodes dates according to the ISO 8601 and RFC 3339 standards - @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) + @available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) case iso8601 /// Encodes a String, according to the provided formatter diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index 2d33c9d4c..371768271 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -412,7 +412,7 @@ private struct MissingColumnError: Error { var column: String } -@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) +@available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) private var iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime @@ -461,7 +461,7 @@ extension DatabaseDateDecodingStrategy { let timeInterval = TimeInterval(sqliteStatement: sqliteStatement, index: index) return Date(timeIntervalSince1970: timeInterval / 1000.0) case .iso8601: - if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { + if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) { let string = String(sqliteStatement: sqliteStatement, index: index) guard let date = iso8601Formatter.date(from: string) else { fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index) @@ -540,7 +540,7 @@ extension DatabaseDateDecodingStrategy { .fromDatabaseValue(dbValue) .map { Date(timeIntervalSince1970: $0 / 1000.0) } case .iso8601: - if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { + if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) { return String .fromDatabaseValue(dbValue) .flatMap { iso8601Formatter.date(from: $0) } diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index b00b64cdc..c6f169fa9 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -497,7 +497,7 @@ public enum DatabaseDateDecodingStrategy { case millisecondsSince1970 /// Decodes dates according to the ISO 8601 standards - @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) + @available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) case iso8601 /// Decodes a String, according to the provided formatter diff --git a/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift b/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift index 3f0c28014..90a598b93 100644 --- a/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift @@ -231,8 +231,8 @@ class AssociationPrefetchingObservationTests: GRDBTestCase { try assertRequestRegionEqual( db, request, - "a(*),b(colb1,colb2,colb3),c(colc1,colc2)", // iOS 12 - "a(cola1,cola2),b(colb1,colb2,colb3),c(colc1,colc2)") // iOS 9 + "a(*),b(colb1,colb2,colb3),c(colc1,colc2)", + "a(cola1,cola2),b(colb1,colb2,colb3),c(colc1,colc2)") } // Request with filters @@ -283,8 +283,8 @@ class AssociationPrefetchingObservationTests: GRDBTestCase { try assertRequestRegionEqual( db, request, - "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 + "a(*),b(colb1,colb2,colb3),c(colc1,colc2),d(cold1,cold2,cold3)", + "a(cola1),b(colb1,colb2,colb3),c(colc1,colc2),d(cold1,cold2,cold3)") } } } diff --git a/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift index be0b9ffbd..30ccd6d47 100644 --- a/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift @@ -22,7 +22,7 @@ private enum StrategyMillisecondsSince1970: StrategyProvider { static let strategy: DatabaseDateDecodingStrategy = .millisecondsSince1970 } -@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) +@available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) private enum StrategyIso8601: StrategyProvider { static let strategy: DatabaseDateDecodingStrategy = .iso8601 } @@ -269,7 +269,7 @@ extension DatabaseDateDecodingStrategyTests { extension DatabaseDateDecodingStrategyTests { func testIso8601() throws { // check ISO8601DateFormatter availabiliity - if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { + if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) { try makeDatabaseQueue().read { db in var calendar = Calendar(identifier: .gregorian) calendar.timeZone = TimeZone(secondsFromGMT: 0)! diff --git a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift index b0604641d..df6452fb2 100644 --- a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift @@ -26,7 +26,7 @@ private enum StrategyMillisecondsSince1970: StrategyProvider { static let strategy: DatabaseDateEncodingStrategy = .millisecondsSince1970 } -@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) +@available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) private enum StrategyIso8601: StrategyProvider { static let strategy: DatabaseDateEncodingStrategy = .iso8601 } @@ -167,7 +167,7 @@ extension DatabaseDateEncodingStrategyTests { extension DatabaseDateEncodingStrategyTests { func testIso8601() { // check ISO8601DateFormatter availabiliity - if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { + if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) { testNullEncoding(strategy: StrategyIso8601.self) for (date, value) in zip(testedDates, [ diff --git a/Tests/GRDBTests/DatabaseErrorTests.swift b/Tests/GRDBTests/DatabaseErrorTests.swift index 7a0dff3ef..3087c3e0b 100644 --- a/Tests/GRDBTests/DatabaseErrorTests.swift +++ b/Tests/GRDBTests/DatabaseErrorTests.swift @@ -27,8 +27,6 @@ class DatabaseErrorTests: GRDBTestCase { XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version XCTAssertEqual(error.sql!, "INSERT INTO pets (masterId, name) VALUES (?, ?)") - // SQLITE_CONSTRAINT_FOREIGNKEY was added 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) XCTAssertEqual(error.description.lowercased(), "sqlite error 19 with statement `insert into pets (masterid, name) values (?, ?)` arguments [1, \"bobby\"]: foreign key constraint failed") XCTAssertEqual(sqlQueries.count, 2) diff --git a/Tests/GRDBTests/DatabaseFunctionTests.swift b/Tests/GRDBTests/DatabaseFunctionTests.swift index 07f2681c6..e7e9dd6ba 100644 --- a/Tests/GRDBTests/DatabaseFunctionTests.swift +++ b/Tests/GRDBTests/DatabaseFunctionTests.swift @@ -31,7 +31,7 @@ class DatabaseFunctionTests: GRDBTestCase { let uppercase = DatabaseFunction.uppercase XCTAssertEqual(try String.fetchOne(db, sql: "SELECT \(uppercase.name)('jérÔME')"), "JÉRÔME") - if #available(iOS 9.0, OSX 10.11, *) { + if #available(OSX 10.11, *) { // Locale-dependent tests. Are they fragile? let localizedCapitalize = DatabaseFunction.localizedCapitalize diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index 2f3979413..0520ed5ff 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -959,7 +959,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { func testTargetQueue() throws { // dispatchPrecondition(condition:) availability - if #available(OSX 10.12, iOS 10.0, tvOS 10.0, *) { + if #available(OSX 10.12, tvOS 10.0, *) { func test(targetQueue: DispatchQueue) throws { dbConfiguration.targetQueue = targetQueue let dbPool = try makeDatabasePool() @@ -986,7 +986,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { func testQoS() throws { // dispatchPrecondition(condition:) availability - if #available(OSX 10.12, iOS 10.0, tvOS 10.0, *) { + if #available(OSX 10.12, tvOS 10.0, *) { func test(qos: DispatchQoS) throws { // https://forums.swift.org/t/what-is-the-default-target-queue-for-a-serial-queue/18094/5 // diff --git a/Tests/GRDBTests/DatabaseQueueTests.swift b/Tests/GRDBTests/DatabaseQueueTests.swift index aa49309bd..b801dc79a 100644 --- a/Tests/GRDBTests/DatabaseQueueTests.swift +++ b/Tests/GRDBTests/DatabaseQueueTests.swift @@ -124,7 +124,7 @@ class DatabaseQueueTests: GRDBTestCase { func testTargetQueue() throws { // dispatchPrecondition(condition:) availability - if #available(OSX 10.12, iOS 10.0, tvOS 10.0, *) { + if #available(OSX 10.12, tvOS 10.0, *) { func test(targetQueue: DispatchQueue) throws { dbConfiguration.targetQueue = targetQueue let dbQueue = try makeDatabaseQueue() @@ -151,7 +151,7 @@ class DatabaseQueueTests: GRDBTestCase { func testQoS() throws { // dispatchPrecondition(condition:) availability - if #available(OSX 10.12, iOS 10.0, tvOS 10.0, *) { + if #available(OSX 10.12, tvOS 10.0, *) { func test(qos: DispatchQoS) throws { // https://forums.swift.org/t/what-is-the-default-target-queue-for-a-serial-queue/18094/5 // diff --git a/Tests/GRDBTests/DatabaseRegionTests.swift b/Tests/GRDBTests/DatabaseRegionTests.swift index 1ed336a7e..6d9be0adc 100644 --- a/Tests/GRDBTests/DatabaseRegionTests.swift +++ b/Tests/GRDBTests/DatabaseRegionTests.swift @@ -513,12 +513,6 @@ class DatabaseRegionTests : GRDBTestCase { // the rowid column, regardless of its name in the request (rowid, oid, _rowid_) // // See also testRowIdNameInSelectStatement - - guard sqlite3_libversion_number() > 3007013 else { - // This test fails on iOS 8.1 (SQLite 3.7.13) - // TODO: evaluate the consequences - return - } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE foo (name TEXT)") diff --git a/Tests/GRDBTests/FTS5WrapperTokenizerTests.swift b/Tests/GRDBTests/FTS5WrapperTokenizerTests.swift index b5fb9dde6..9145fa51b 100644 --- a/Tests/GRDBTests/FTS5WrapperTokenizerTests.swift +++ b/Tests/GRDBTests/FTS5WrapperTokenizerTests.swift @@ -37,7 +37,7 @@ private final class LatinAsciiTokenizer : FTS5WrapperTokenizer { func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws { // Convert token to Latin-ASCII and lowercase - if #available(iOS 9.0, OSX 10.11, *) { + if #available(OSX 10.11, *) { if let token = token.applyingTransform(StringTransform("Latin-ASCII; Lower"), reverse: false) { try tokenCallback(token, flags) } diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index 1eda4b9ac..6df8a77b9 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -927,7 +927,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { sql(dbQueue, tableRequest.select(Col.name.uppercased)), "SELECT swiftUppercaseString(\"name\") FROM \"readers\"") - if #available(iOS 9.0, OSX 10.11, *) { + if #available(OSX 10.11, *) { XCTAssertEqual( sql(dbQueue, tableRequest.select(Col.name.localizedCapitalized)), "SELECT swiftLocalizedCapitalizedString(\"name\") FROM \"readers\"") From 318564a13c3a86f203578e9fee7f5b3e7fe78bad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 May 2020 14:02:18 +0200 Subject: [PATCH 14/28] CHANGELOG --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 94e2d3194..e3f097f81 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -74,6 +74,10 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [#784](https://github.com/groue/GRDB.swift/pull/784): Fix observation of eager-loaded to-many associations +### Breaking Changes + +- [#790](https://github.com/groue/GRDB.swift/pull/790): Bump required iOS version to 10.0 + ## 5.0.0-beta.2 From 30f619ca2c230768103c1dbd38dd19e366b6b124 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 May 2020 19:08:08 +0200 Subject: [PATCH 15/28] Refactor database tracing - Make it possible to log the database label along with the executed SQL - Make it possible to avoid arguments expansion - Make it possible to profile statements --- .swiftlint.yml | 1 + GRDB/Core/Configuration.swift | 8 - GRDB/Core/Database.swift | 294 ++++++++++++++++++++++++++-------- GRDB/Fixit/GRDB-5.0.swift | 11 ++ 4 files changed, 238 insertions(+), 76 deletions(-) diff --git a/.swiftlint.yml b/.swiftlint.yml index e34e12f95..4a1fccef9 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -3,6 +3,7 @@ included: disabled_rules: - cyclomatic_complexity + - duplicate_enum_cases - file_length - force_cast - force_try diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index f92a06d7d..ace157781 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -63,11 +63,6 @@ public struct Configuration { /// The default label is nil. public var label: String? = nil - /// A function that is called on every statement executed by the database. - /// - /// Default: nil - public var trace: TraceFunction? - /// If false, SQLite from version 3.29.0 will not interpret a double-quoted /// string as a string literal if it does not match any valid identifier. /// @@ -219,6 +214,3 @@ public struct Configuration { } } } - -/// A tracing function that takes an SQL string. -public typealias TraceFunction = (String) -> Void diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 982155c92..ce5412c14 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -153,7 +153,7 @@ public final class Database { // MARK: - Private properties private var busyCallback: BusyCallback? - + private var trace: ((TraceEvent) -> Void)? private var functions = Set() private var collations = Set() private var _readOnlyDepth = 0 // Modify with beginReadOnly/endReadOnly @@ -200,8 +200,6 @@ public final class Database { /// This method must be called after database initialization func setup() throws { - // Setup trace first, so that setup queries are traced. - setupTrace() setupDoubleQuotedStringLiterals() try setupForeignKeys() setupBusyMode() @@ -222,71 +220,6 @@ public final class Database { configuration.SQLiteConnectionDidOpen?() } - private func setupTrace() { - 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 macOS 10.12, tvOS 10.0, watchOS 3.0 - // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - #if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS) - 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() - #else - if #available(OSX 10.12, tvOS 10.0, 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 - } - - #if !(GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)) - // Precondition: configuration.trace != nil - private func setupTrace_v1() { - let dbPointer = Unmanaged.passUnretained(self).toOpaque() - sqlite3_trace(sqliteConnection, { (dbPointer, sql) in - guard let sql = sql.map(String.init) else { return } - let db = Unmanaged.fromOpaque(dbPointer!).takeUnretainedValue() - db.configuration.trace!(sql) - }, dbPointer) - } - #endif - - // Precondition: configuration.trace != nil - private static func trace_v2( - _ mask: UInt32, - _ dbPointer: UnsafeMutableRawPointer?, - _ stmt: UnsafeMutableRawPointer?, - _ unexpandedSQL: UnsafeMutableRawPointer?, - _ sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer?) - -> Int32 - { - guard let stmt = stmt else { return SQLITE_OK } - guard let expandedSQLCString = sqlite3_expanded_sql(OpaquePointer(stmt)) else { return SQLITE_OK } - let sql = String(cString: expandedSQLCString) - sqlite3_free(expandedSQLCString) - let db = Unmanaged.fromOpaque(dbPointer!).takeUnretainedValue() - db.configuration.trace!(sql) - return SQLITE_OK - } - private func setupDoubleQuotedStringLiterals() { if configuration.acceptsDoubleQuotedStringLiterals { enableDoubleQuotedStringLiterals(sqliteConnection) @@ -555,6 +488,125 @@ public final class Database { return try block() } + // MARK: - Trace + + /// Registers a tracing function. + /// + /// For example: + /// + /// // Trace all SQL statements executed by the database + /// var configuration = Configuration() + /// configuration.prepareDatabase = { db in + /// db.trace(options: .statement) { event in + /// print("SQL: \(event)") + /// } + /// } + /// let dbQueue = try DatabaseQueue(path: "...", configuration: configuration) + /// + /// Pass an empty options set, or a nil tracing function in order to stop + /// database tracing. + /// + /// See https://www.sqlite.org/c3ref/trace_v2.html for more information. + /// + /// - parameter options: The set of desired event kinds. + /// - parameter trace: the tracing function. + public func trace(options: TracingOptions, _ trace: ((TraceEvent) -> Void)? = nil) { + SchedulingWatchdog.preconditionValidQueue(self) + self.trace = trace + + if options.isEmpty || trace == nil { + #if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS) + sqlite3_trace_v2(sqliteConnection, 0, nil, nil) + #elseif os(Linux) + sqlite3_trace(sqliteConnection, nil) + #else + if #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) { + sqlite3_trace_v2(sqliteConnection, 0, nil, nil) + } else { + sqlite3_trace(sqliteConnection, nil, nil) + } + #endif + 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 macOS 10.12, tvOS 10.0, watchOS 3.0 + // https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + #if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS) + let dbPointer = Unmanaged.passUnretained(self).toOpaque() + sqlite3_trace_v2(sqliteConnection, UInt32(bitPattern: options.rawValue), { (mask, dbPointer, p, x) in + let db = Unmanaged.fromOpaque(dbPointer!).takeUnretainedValue() + db.trace_v2(CInt(bitPattern: mask), p, x, sqlite3_expanded_sql) + return SQLITE_OK + }, dbPointer) + #elseif os(Linux) + setupTrace_v1() + #else + if #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) { + let dbPointer = Unmanaged.passUnretained(self).toOpaque() + sqlite3_trace_v2(sqliteConnection, UInt32(bitPattern: options.rawValue), { (mask, dbPointer, p, x) in + let db = Unmanaged.fromOpaque(dbPointer!).takeUnretainedValue() + db.trace_v2(CInt(bitPattern: mask), p, x, sqlite3_expanded_sql) + return SQLITE_OK + }, dbPointer) + } else { + setupTrace_v1() + } + #endif + } + + #if !(GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)) + private func setupTrace_v1() { + let dbPointer = Unmanaged.passUnretained(self).toOpaque() + sqlite3_trace(sqliteConnection, { (dbPointer, sql) in + guard let sql = sql.map(String.init(cString:)) else { return } + let db = Unmanaged.fromOpaque(dbPointer!).takeUnretainedValue() + db.trace?(Database.TraceEvent.statement(TraceEvent.Statement(impl: .trace_v1(sql)))) + }, dbPointer) + } + #endif + + // Precondition: configuration.trace != nil + private func trace_v2( + _ mask: CInt, + _ p: UnsafeMutableRawPointer?, + _ x: UnsafeMutableRawPointer?, + _ sqlite3_expanded_sql: @escaping @convention(c) (OpaquePointer?) -> UnsafeMutablePointer?) + { + guard let trace = trace else { return } + + switch mask { + case SQLITE_TRACE_STMT: + if let sqliteStatement = p, let unexpandedSQL = x { + let statement = TraceEvent.Statement(impl: .trace_v2( + sqliteStatement: OpaquePointer(sqliteStatement), + unexpandedSQL: UnsafePointer(unexpandedSQL.assumingMemoryBound(to: CChar.self)), + sqlite3_expanded_sql: sqlite3_expanded_sql)) + trace(TraceEvent.statement(statement)) + } + case SQLITE_TRACE_PROFILE: + if let sqliteStatement = p, let durationP = x?.assumingMemoryBound(to: Int64.self) { + let statement = TraceEvent.Statement(impl: .trace_v2( + sqliteStatement: OpaquePointer(sqliteStatement), + unexpandedSQL: nil, + sqlite3_expanded_sql: sqlite3_expanded_sql)) + let duration = TimeInterval(durationP.pointee) / 1.0e9 + + #if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS) + trace(TraceEvent.profile(statement: statement, duration: duration)) + #elseif os(Linux) + #else + if #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) { + trace(TraceEvent.profile(statement: statement, duration: duration)) + } + #endif + } + default: + break + } + } + // MARK: - Checkpoints func checkpoint(_ kind: Database.CheckpointMode) throws { @@ -1308,6 +1360,112 @@ extension Database { /// log function that takes an error message. public typealias LogErrorFunction = (_ resultCode: ResultCode, _ message: String) -> Void + /// An option for `Database.trace(options:_:)` + public struct TracingOptions: OptionSet { + public let rawValue: CInt + + public init(rawValue: CInt) { + self.rawValue = rawValue + } + + /// Reports executed statements + public static let statement = TracingOptions(rawValue: SQLITE_TRACE_STMT) + + #if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS) + /// Reports executed statements and the estimated duration that the + /// statement took to run. + public static let profile = TracingOptions(rawValue: SQLITE_TRACE_PROFILE) + #elseif os(Linux) + #else + /// Reports executed statements and the estimated duration that the + /// statement took to run. + @available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) + public static let profile = TracingOptions(rawValue: SQLITE_TRACE_PROFILE) + #endif + } + + /// An event reported by `Database.trace(options:_:)` + public enum TraceEvent: CustomStringConvertible { + + /// Information about a statement reported by `Database.trace(options:_:)` + public struct Statement { + enum Impl { + case trace_v1(String) + case trace_v2( + sqliteStatement: SQLiteStatement, + unexpandedSQL: UnsafePointer?, + sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer?) + } + let impl: Impl + + #if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS) + /// The executed SQL. + public var sql: String { _sql } + #elseif os(Linux) + #else + /// The executed SQL. + @available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) + public var sql: String { _sql } + #endif + + var _sql: String { + switch impl { + case .trace_v1: + // Likely a GRDB bug + fatalError("Not get statement SQL") + + case let .trace_v2(sqliteStatement, unexpandedSQL, _): + if let unexpandedSQL = unexpandedSQL { + return String(cString: unexpandedSQL) + .trimmingCharacters(in: .sqlStatementSeparators) + } else { + return String(cString: sqlite3_sql(sqliteStatement)) + .trimmingCharacters(in: .sqlStatementSeparators) + } + } + } + + /// The executed SQL, with bound parameters expanded. + public var expandedSQL: String { + switch impl { + case let .trace_v1(expandedSQL): + return expandedSQL + + case let .trace_v2(sqliteStatement, _, sqlite3_expanded_sql): + guard let cString = sqlite3_expanded_sql(sqliteStatement) else { + return "" + } + defer { sqlite3_free(cString) } + return String(cString: cString) + .trimmingCharacters(in: .sqlStatementSeparators) + } + } + } + + /// An event reported by `TracingOptions.statement`. + case statement(Statement) + + #if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS) + /// An event reported by `TracingOptions.profile`. + case profile(statement: Statement, duration: TimeInterval) + #elseif os(Linux) + #else + /// An event reported by `TracingOptions.profile`. + @available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) + case profile(statement: Statement, duration: TimeInterval) + #endif + + public var description: String { + switch self { + case let .statement(statement): + return statement.expandedSQL + case let .profile(statement: statement, duration: duration): + let durationString = String(format: "%.3f", duration) + return "\(durationString)s \(statement.expandedSQL)" + } + } + } + /// The end of a transaction: Commit, or Rollback public enum TransactionCompletion { case commit diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift index 0a39c5ea0..f240beeff 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -47,6 +47,14 @@ extension AssociationAggregate { { preconditionFailure() } } +extension Configuration { + @available(*, unavailable, message: "Use Database.trace(options:_:) in Configuration.prepareDatabase instead.") + public var trace: TraceFunction? { + get { preconditionFailure() } + set { preconditionFailure() } + } +} + extension DatabaseFunction { @available(*, unavailable, renamed: "callAsFunction(_:)") public func apply(_ arguments: SQLExpressible...) -> SQLExpression @@ -251,6 +259,9 @@ extension TableRecord where Self: FetchableRecord { { preconditionFailure() } } +@available(*, unavailable) +public typealias TraceFunction = (String) -> Void + extension ValueObservation { @available(*, unavailable, message: "ValueObservation now schedules its values asynchronously on the main queue by default. See ValueObservation.start() for possible configuration") var scheduling: ValueScheduling { From 81213f2649753c7f61e0d19dbeb73a44ffd3685c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 May 2020 19:08:42 +0200 Subject: [PATCH 16/28] Tests for Database.trace(options:_:) --- GRDB.xcodeproj/project.pbxproj | 8 + GRDBCustom.xcodeproj/project.pbxproj | 6 + .../GRDBTests.xcodeproj/project.pbxproj | 6 + .../GRDBTests.xcodeproj/project.pbxproj | 6 + Tests/GRDBTests/DatabaseTraceTests.swift | 163 ++++++++++++++++++ Tests/GRDBTests/FTS3RecordTests.swift | 28 ++- Tests/GRDBTests/FTS3TableBuilderTests.swift | 12 -- Tests/GRDBTests/FTS4RecordTests.swift | 28 ++- Tests/GRDBTests/FTS4TableBuilderTests.swift | 12 -- Tests/GRDBTests/GRDBTestCase.swift | 10 +- 10 files changed, 219 insertions(+), 60 deletions(-) create mode 100644 Tests/GRDBTests/DatabaseTraceTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index c0809a480..d222458ad 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -814,6 +814,9 @@ 56FC987B1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; }; 56FC987E1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; }; 56FDECE31BB32DFD009AD709 /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; }; + 56FEB8F8248403000081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */; }; + 56FEB8F9248403010081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */; }; + 56FEB8FA248403020081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */; }; 56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; 56FEE7FF1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; 56FF45441D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; }; @@ -1506,6 +1509,7 @@ 56FBFED82210731A00945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = ""; }; 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = ""; }; 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = ""; }; + 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseTraceTests.swift; sourceTree = ""; }; 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = ""; }; 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordDeleteTests.swift; sourceTree = ""; }; 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = ""; }; @@ -2053,6 +2057,7 @@ 566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */, 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */, 56A238131B9C74A90082EB20 /* DatabaseTests.swift */, + 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */, 564FCE5D20F7E11A00202B90 /* DatabaseValueConversionErrorTests.swift */, 56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */, 56A238191B9C74A90082EB20 /* DatabaseValueConvertible */, @@ -3115,6 +3120,7 @@ 56176C701EACCCC9000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, 56FEE7FF1F47253700D930EA /* TableRecordTests.swift in Sources */, 56057C562291B16A00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */, + 56FEB8F9248403010081AF83 /* DatabaseTraceTests.swift in Sources */, 56A2386A1B9C74A90082EB20 /* RecordSubClassTests.swift in Sources */, 56A2383E1B9C74A90082EB20 /* DatabaseValueTests.swift in Sources */, 567156181CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */, @@ -3322,6 +3328,7 @@ 5674A72A1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, 566A84402041914000E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 56057C552291B16A00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */, + 56FEB8F8248403000081AF83 /* DatabaseTraceTests.swift in Sources */, 56176C5E1EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, 56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */, 56D496641D81304E008276D7 /* FoundationUUIDTests.swift in Sources */, @@ -3659,6 +3666,7 @@ AAA4DD76230F262000C74B15 /* FTS5WrapperTokenizerTests.swift in Sources */, AAA4DD77230F262000C74B15 /* TableRecordTests.swift in Sources */, AAA4DD78230F262000C74B15 /* AssociationHasManyRowScopeTests.swift in Sources */, + 56FEB8FA248403020081AF83 /* DatabaseTraceTests.swift in Sources */, AAA4DD79230F262000C74B15 /* RecordSubClassTests.swift in Sources */, AAA4DD7A230F262000C74B15 /* DatabaseValueTests.swift in Sources */, AAA4DD7B230F262000C74B15 /* DatabaseQueueReadOnlyTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 663c45e4c..865cb54ee 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -470,6 +470,8 @@ 56F409292465C8F500A7A152 /* SQLRequestProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F409262465C8F500A7A152 /* SQLRequestProtocol.swift */; }; 56FBFED62210731100945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED52210731000945324 /* SQLRequest.swift */; }; 56FBFED72210731100945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED52210731000945324 /* SQLRequest.swift */; }; + 56FEB8FE248403270081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */; }; + 56FEB8FF248403270081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */; }; 56FEE7FE1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; 56FEE8021F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; 56FF45431D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; }; @@ -1039,6 +1041,7 @@ 56F409262465C8F500A7A152 /* SQLRequestProtocol.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestProtocol.swift; sourceTree = ""; }; 56FBFED52210731000945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = ""; }; 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = ""; }; + 56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTraceTests.swift; sourceTree = ""; }; 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = ""; }; 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordDeleteTests.swift; sourceTree = ""; }; 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = ""; }; @@ -1559,6 +1562,7 @@ 566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */, 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */, 56A238131B9C74A90082EB20 /* DatabaseTests.swift */, + 56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */, 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */, 56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */, 56A238191B9C74A90082EB20 /* DatabaseValueConvertible */, @@ -2393,6 +2397,7 @@ 567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 5674A7291F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, 56057C5A2291B18E00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */, + 56FEB8FF248403270081AF83 /* DatabaseTraceTests.swift in Sources */, 56FEE8021F47253700D930EA /* TableRecordTests.swift in Sources */, F3BA81211CFB3063003DC1BA /* RecordPrimaryKeyNoneTests.swift in Sources */, F3BA80F71CFB3021003DC1BA /* SelectStatementTests.swift in Sources */, @@ -2730,6 +2735,7 @@ F3BA80FA1CFB3021003DC1BA /* SelectStatementTests.swift in Sources */, 5674A7271F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, 56057C592291B18E00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */, + 56FEB8FE248403270081AF83 /* DatabaseTraceTests.swift in Sources */, 56FEE7FE1F47253700D930EA /* TableRecordTests.swift in Sources */, F3BA81191CFB305F003DC1BA /* QueryInterfaceRequestTests.swift in Sources */, F3BA812F1CFB3064003DC1BA /* RecordPrimaryKeyNoneTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index d61aa179f..637f8c431 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -403,6 +403,8 @@ 56DF002A228DE00900D611F3 /* AssociationPrefetchingRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0026228DE00900D611F3 /* AssociationPrefetchingRowTests.swift */; }; 56E4F7FF2392E6D200A611F6 /* DatabaseAbortedTransactionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E4F7FE2392E6D200A611F6 /* DatabaseAbortedTransactionTests.swift */; }; 56E4F8002392E6D200A611F6 /* DatabaseAbortedTransactionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E4F7FE2392E6D200A611F6 /* DatabaseAbortedTransactionTests.swift */; }; + 56FEB901248403460081AF83 /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB900248403440081AF83 /* DatabaseTests.swift */; }; + 56FEB902248403460081AF83 /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB900248403440081AF83 /* DatabaseTests.swift */; }; 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 */; }; @@ -613,6 +615,7 @@ 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 = ""; }; 56E4F7FE2392E6D200A611F6 /* DatabaseAbortedTransactionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAbortedTransactionTests.swift; sourceTree = ""; }; + 56FEB900248403440081AF83 /* DatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTests.swift; sourceTree = ""; }; 6A4788C0F815F6C5E4EBDE12 /* Pods-GRDBTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.debug.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.debug.xcconfig"; sourceTree = ""; }; 7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_GRDBTestsEncrypted.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 83BFB5733A86DAA3D0BEE684 /* Pods-GRDBTestsEncrypted.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTestsEncrypted.debug.xcconfig"; path = "Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted.debug.xcconfig"; sourceTree = ""; }; @@ -735,6 +738,7 @@ 564A1F79226B89D7001F64F1 /* DatabaseSavepointTests.swift */, 564A1F3F226B89D0001F64F1 /* DatabaseSnapshotTests.swift */, 564B3D77239BDC00007BF308 /* DatabaseSuspensionTests.swift */, + 56FEB900248403440081AF83 /* DatabaseTests.swift */, 564A1FC7226B89DF001F64F1 /* DatabaseTests.swift */, 564A1FAF226B89DC001F64F1 /* DatabaseTimestampTests.swift */, 564A1FD6226B89E0001F64F1 /* DatabaseUUIDEncodingStrategyTests.swift */, @@ -1220,6 +1224,7 @@ 564A2001226B89E1001F64F1 /* RecordPrimaryKeyNoneTests.swift in Sources */, 564A2051226B89E1001F64F1 /* RecordWithColumnNameManglingTests.swift in Sources */, 564A205B226B89E1001F64F1 /* RecordCopyTests.swift in Sources */, + 56FEB901248403460081AF83 /* DatabaseTests.swift in Sources */, 564A205F226B89E1001F64F1 /* SQLLiteralTests.swift in Sources */, 564A206C226B89E1001F64F1 /* FTS5CustomTokenizerTests.swift in Sources */, 564A2002226B89E1001F64F1 /* DerivableRequestTests.swift in Sources */, @@ -1424,6 +1429,7 @@ 564A211F226B8E18001F64F1 /* RecordPrimaryKeyNoneTests.swift in Sources */, 564A2120226B8E18001F64F1 /* RecordWithColumnNameManglingTests.swift in Sources */, 564A2121226B8E18001F64F1 /* RecordCopyTests.swift in Sources */, + 56FEB902248403460081AF83 /* DatabaseTests.swift in Sources */, 564A2122226B8E18001F64F1 /* SQLLiteralTests.swift in Sources */, 564A2123226B8E18001F64F1 /* FTS5CustomTokenizerTests.swift in Sources */, 564A2124226B8E18001F64F1 /* DerivableRequestTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index 5074166e3..5ada826b0 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -405,6 +405,8 @@ 56DF0024228DDFF000D611F3 /* AssociationPrefetchingCodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0020228DDFF000D611F3 /* AssociationPrefetchingCodableRecordTests.swift */; }; 56E4F7FC2392E6C400A611F6 /* DatabaseAbortedTransactionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E4F7FB2392E6C300A611F6 /* DatabaseAbortedTransactionTests.swift */; }; 56E4F7FD2392E6C400A611F6 /* DatabaseAbortedTransactionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E4F7FB2392E6C300A611F6 /* DatabaseAbortedTransactionTests.swift */; }; + 56FEB904248403510081AF83 /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB903248403510081AF83 /* DatabaseTests.swift */; }; + 56FEB905248403510081AF83 /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB903248403510081AF83 /* DatabaseTests.swift */; }; 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 */; }; @@ -616,6 +618,7 @@ 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 = ""; }; 56E4F7FB2392E6C300A611F6 /* DatabaseAbortedTransactionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAbortedTransactionTests.swift; sourceTree = ""; }; + 56FEB903248403510081AF83 /* DatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTests.swift; sourceTree = ""; }; 67377FE4CDAD675809F93AD4 /* Pods_GRDBTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_GRDBTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 6A4788C0F815F6C5E4EBDE12 /* Pods-GRDBTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.debug.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.debug.xcconfig"; sourceTree = ""; }; 7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_GRDBTestsEncrypted.framework; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -738,6 +741,7 @@ 564A1F79226B89D7001F64F1 /* DatabaseSavepointTests.swift */, 564A1F3F226B89D0001F64F1 /* DatabaseSnapshotTests.swift */, 564B3D74239BDBEC007BF308 /* DatabaseSuspensionTests.swift */, + 56FEB903248403510081AF83 /* DatabaseTests.swift */, 564A1FC7226B89DF001F64F1 /* DatabaseTests.swift */, 564A1FAF226B89DC001F64F1 /* DatabaseTimestampTests.swift */, 564A1FD6226B89E0001F64F1 /* DatabaseUUIDEncodingStrategyTests.swift */, @@ -1226,6 +1230,7 @@ 564A2051226B89E1001F64F1 /* RecordWithColumnNameManglingTests.swift in Sources */, 564A205B226B89E1001F64F1 /* RecordCopyTests.swift in Sources */, 564A205F226B89E1001F64F1 /* SQLLiteralTests.swift in Sources */, + 56FEB904248403510081AF83 /* DatabaseTests.swift in Sources */, 564A206C226B89E1001F64F1 /* FTS5CustomTokenizerTests.swift in Sources */, 564A2002226B89E1001F64F1 /* DerivableRequestTests.swift in Sources */, 56057C6B2291D0C000A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */, @@ -1430,6 +1435,7 @@ 564A2120226B8E18001F64F1 /* RecordWithColumnNameManglingTests.swift in Sources */, 564A2121226B8E18001F64F1 /* RecordCopyTests.swift in Sources */, 564A2122226B8E18001F64F1 /* SQLLiteralTests.swift in Sources */, + 56FEB905248403510081AF83 /* DatabaseTests.swift in Sources */, 564A2123226B8E18001F64F1 /* FTS5CustomTokenizerTests.swift in Sources */, 564A2124226B8E18001F64F1 /* DerivableRequestTests.swift in Sources */, 56057C6C2291D0C000A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */, diff --git a/Tests/GRDBTests/DatabaseTraceTests.swift b/Tests/GRDBTests/DatabaseTraceTests.swift new file mode 100644 index 000000000..7edebef23 --- /dev/null +++ b/Tests/GRDBTests/DatabaseTraceTests.swift @@ -0,0 +1,163 @@ +import XCTest +import GRDB + +class DatabaseTraceTests : GRDBTestCase { + func testTraceStatementExpandedSQL() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var lastExpandedSQL: String? + db.trace(options: .statement) { event in + switch event { + case let .statement(statement): + lastExpandedSQL = statement.expandedSQL + default: + XCTFail("Unexpected event") + } + } + try db.execute(sql: "CREATE table t(a);") + XCTAssertEqual(lastExpandedSQL, "CREATE table t(a)") + + try db.execute(sql: "INSERT INTO t (a) VALUES (?)", arguments: [1]) + XCTAssertEqual(lastExpandedSQL, "INSERT INTO t (a) VALUES (1)") + } + } + + func testTraceStatementSQL() throws { + guard #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) else { + return + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var lastSQL: String? + var lastDescription: String? + db.trace(options: .statement) { event in + lastDescription = event.description + switch event { + case let .statement(statement): + lastSQL = statement.sql + default: + XCTFail("Unexpected event") + } + } + try db.execute(sql: "CREATE table t(a);") + XCTAssertEqual(lastSQL, "CREATE table t(a)") + XCTAssertEqual(lastDescription, "CREATE table t(a)") + + try db.execute(sql: "INSERT INTO t (a) VALUES (?)", arguments: [1]) + XCTAssertEqual(lastSQL, "INSERT INTO t (a) VALUES (?)") + XCTAssertEqual(lastDescription, "INSERT INTO t (a) VALUES (1)") + } + } + + func testTraceProfile() throws { + guard #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) else { + return + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var lastSQL: String? + var lastExpandedSQL: String? + var lastDuration: TimeInterval? + var lastDescription: String? + db.trace(options: .profile) { event in + lastDescription = event.description + switch event { + case let .profile(statement: statement, duration: duration): + lastSQL = statement.sql + lastExpandedSQL = statement.expandedSQL + lastDuration = duration + default: + XCTFail("Unexpected event") + } + } + try db.execute(sql: "CREATE table t(a);") + XCTAssertEqual(lastSQL, "CREATE table t(a)") + XCTAssertEqual(lastExpandedSQL, "CREATE table t(a)") + XCTAssertTrue(lastDuration! > 0) + XCTAssert(lastDescription!.hasSuffix("s CREATE table t(a)")) + + try db.execute(sql: "INSERT INTO t (a) VALUES (?)", arguments: [1]) + XCTAssertEqual(lastSQL, "INSERT INTO t (a) VALUES (?)") + XCTAssertEqual(lastExpandedSQL, "INSERT INTO t (a) VALUES (1)") + XCTAssertTrue(lastDuration! > 0) + XCTAssert(lastDescription!.hasSuffix("s INSERT INTO t (a) VALUES (1)")) + + db.add(function: DatabaseFunction("wait", argumentCount: 1, pure: true, function: { dbValues in + if let delay = TimeInterval.fromDatabaseValue(dbValues[0]) { + Thread.sleep(forTimeInterval: delay) + } + return nil + })) + + try db.execute(sql: "SELECT wait(?)", arguments: [0.5]) + XCTAssertEqual(lastSQL, "SELECT wait(?)") + XCTAssertEqual(lastExpandedSQL, "SELECT wait(0.5)") + XCTAssertGreaterThan(lastDuration!, 0.4) + XCTAssertLessThan(lastDuration!, 0.6) + XCTAssert(lastDescription!.hasSuffix("s SELECT wait(0.5)")) + } + } + + func testTraceMultiple() throws { + guard #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) else { + return + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var events: [String] = [] + db.trace(options: [.statement, .profile]) { event in + events.append(event.description) + switch event { + case .statement: + break + case .profile: + break + default: + XCTFail("Unexpected event") + } + } + try db.execute(sql: "CREATE table t(a);") + XCTAssertEqual(events.count, 2) + } + } + + func testTraceFromConfiguration() throws { + var events: [String] = [] + var configuration = Configuration() + configuration.prepareDatabase = { db in + db.trace(options: .statement) { event in + events.append("SQL: \(event)") + } + } + let dbQueue = try makeDatabaseQueue(configuration: configuration) + try dbQueue.inDatabase { db in + try db.execute(sql: """ + CREATE table t(a); + INSERT INTO t (a) VALUES (?) + """, arguments: [1]) + XCTAssertEqual(events.suffix(2), [ + "SQL: CREATE table t(a)", + "SQL: INSERT INTO t (a) VALUES (1)"]) + } + } + + func testTraceReset() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + var events: [String] = [] + db.trace(options: .statement) { event in + events.append(event.description) + } + try db.execute(sql: "CREATE table t(a);") + XCTAssertEqual(events.last, "CREATE table t(a)") + + db.trace(options: []) + + try db.execute(sql: "INSERT INTO t (a) VALUES (?)", arguments: [1]) + XCTAssertEqual(events.last, "CREATE table t(a)") + } + } +} diff --git a/Tests/GRDBTests/FTS3RecordTests.swift b/Tests/GRDBTests/FTS3RecordTests.swift index 9dd37dbcb..21aade5a6 100644 --- a/Tests/GRDBTests/FTS3RecordTests.swift +++ b/Tests/GRDBTests/FTS3RecordTests.swift @@ -34,18 +34,6 @@ extension Book : MutablePersistableRecord { } class FTS3RecordTests: GRDBTestCase { - - override func setUp() { - super.setUp() - - dbConfiguration.trace = { [unowned self] sql in - // Ignore virtual table logs - if !sql.hasPrefix("--") { - self.sqlQueries.append(sql) - } - } - } - override func setup(_ dbWriter: DatabaseWriter) throws { try dbWriter.write { db in try db.create(virtualTable: "books", using: FTS3()) { t in @@ -113,12 +101,18 @@ class FTS3RecordTests: GRDBTestCase { try book.insert(db) } - let pattern = try FTS3Pattern(rawPattern: "Herman Melville") - XCTAssertEqual(try Book.matching(pattern).fetchCount(db), 1) - XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"books\" WHERE \"books\" MATCH 'Herman Melville'") + do { + sqlQueries = [] + let pattern = try FTS3Pattern(rawPattern: "Herman Melville") + XCTAssertEqual(try Book.matching(pattern).fetchCount(db), 1) + XCTAssertTrue(sqlQueries.contains("SELECT COUNT(*) FROM \"books\" WHERE \"books\" MATCH 'Herman Melville'")) + } - XCTAssertEqual(try Book.fetchCount(db), 1) - XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"books\"") + do { + sqlQueries = [] + XCTAssertEqual(try Book.fetchCount(db), 1) + XCTAssertTrue(sqlQueries.contains("SELECT COUNT(*) FROM \"books\"")) + } } } } diff --git a/Tests/GRDBTests/FTS3TableBuilderTests.swift b/Tests/GRDBTests/FTS3TableBuilderTests.swift index db878bd26..678f0f332 100644 --- a/Tests/GRDBTests/FTS3TableBuilderTests.swift +++ b/Tests/GRDBTests/FTS3TableBuilderTests.swift @@ -2,18 +2,6 @@ import XCTest import GRDB class FTS3TableBuilderTests: GRDBTestCase { - - override func setUp() { - super.setUp() - - dbConfiguration.trace = { [unowned self] sql in - // Ignore virtual table logs - if !sql.hasPrefix("--") { - self.sqlQueries.append(sql) - } - } - } - func testWithoutBody() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in diff --git a/Tests/GRDBTests/FTS4RecordTests.swift b/Tests/GRDBTests/FTS4RecordTests.swift index c5ccdfd9f..d6b00cda1 100644 --- a/Tests/GRDBTests/FTS4RecordTests.swift +++ b/Tests/GRDBTests/FTS4RecordTests.swift @@ -34,18 +34,6 @@ extension Book : MutablePersistableRecord { } class FTS4RecordTests: GRDBTestCase { - - override func setUp() { - super.setUp() - - dbConfiguration.trace = { [unowned self] sql in - // Ignore virtual table logs - if !sql.hasPrefix("--") { - self.sqlQueries.append(sql) - } - } - } - override func setup(_ dbWriter: DatabaseWriter) throws { try dbWriter.write { db in try db.create(virtualTable: "books", using: FTS4()) { t in @@ -113,12 +101,18 @@ class FTS4RecordTests: GRDBTestCase { try book.insert(db) } - let pattern = try FTS3Pattern(rawPattern: "Herman Melville") - XCTAssertEqual(try Book.matching(pattern).fetchCount(db), 1) - XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"books\" WHERE \"books\" MATCH 'Herman Melville'") + do { + sqlQueries = [] + let pattern = try FTS3Pattern(rawPattern: "Herman Melville") + XCTAssertEqual(try Book.matching(pattern).fetchCount(db), 1) + XCTAssertTrue(sqlQueries.contains("SELECT COUNT(*) FROM \"books\" WHERE \"books\" MATCH 'Herman Melville'")) + } - XCTAssertEqual(try Book.fetchCount(db), 1) - XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"books\"") + do { + sqlQueries = [] + XCTAssertEqual(try Book.fetchCount(db), 1) + XCTAssertTrue(sqlQueries.contains("SELECT COUNT(*) FROM \"books\"")) + } } } } diff --git a/Tests/GRDBTests/FTS4TableBuilderTests.swift b/Tests/GRDBTests/FTS4TableBuilderTests.swift index c6400958f..435eaea7c 100644 --- a/Tests/GRDBTests/FTS4TableBuilderTests.swift +++ b/Tests/GRDBTests/FTS4TableBuilderTests.swift @@ -2,18 +2,6 @@ import XCTest import GRDB class FTS4TableBuilderTests: GRDBTestCase { - - override func setUp() { - super.setUp() - - dbConfiguration.trace = { [unowned self] sql in - // Ignore virtual table logs - if !sql.hasPrefix("--") { - self.sqlQueries.append(sql) - } - } - } - func testWithoutBody() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index 1f27adbad..b28d29a75 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -99,8 +99,14 @@ class GRDBTestCase: XCTestCase { } } - dbConfiguration.trace = { [unowned self] sql in - self.sqlQueries.append(sql) + dbConfiguration.prepareDatabase = { db in + db.trace(options: .statement) { event in + self.sqlQueries.append(event.description) + } + + #if GRDBCIPHER_USE_ENCRYPTION + try db.usePassphrase("secret") + #endif } #if GRDBCIPHER_USE_ENCRYPTION From 2677cf8de814b8bc2abb693dd7517585e5d1c554 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 May 2020 19:16:23 +0200 Subject: [PATCH 17/28] Update documentation --- README.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 38be75a0d..80f8715f7 100644 --- a/README.md +++ b/README.md @@ -470,7 +470,6 @@ let newPlaceCount = try dbQueue.write { db -> Int in var config = Configuration() config.readonly = true config.foreignKeysEnabled = true // Default is already true -config.trace = { print($0) } // Prints all SQL statements config.label = "MyDatabase" // Useful when your app opens multiple databases let dbQueue = try DatabaseQueue( @@ -550,7 +549,6 @@ let newPlaceCount = try dbPool.write { db -> Int in var config = Configuration() config.readonly = true config.foreignKeysEnabled = true // Default is already true -config.trace = { print($0) } // Prints all SQL statements config.label = "MyDatabase" // Useful when your app opens multiple databases config.maximumReaderCount = 10 // The default is 5 @@ -7351,8 +7349,13 @@ try dbQueue.read { db in Another option is to setup a tracing function that prints out all SQL requests executed by your application. You provide the trace function when you connect to the database: ```swift +// Prints all SQL statements var config = Configuration() -config.trace = { print($0) } // Prints all SQL statements +config.prepareDatabase = { db in + try db.trace(options: .statement) { + print($0) + } +} let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) try dbQueue.read { db in From 3e25faabbac16283218b2e945572b8d0b3b3232d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 May 2020 19:16:35 +0200 Subject: [PATCH 18/28] Update the migration guide --- Documentation/GRDB5MigrationGuide.md | 34 ++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/Documentation/GRDB5MigrationGuide.md b/Documentation/GRDB5MigrationGuide.md index f7ee7033a..20c272d91 100644 --- a/Documentation/GRDB5MigrationGuide.md +++ b/Documentation/GRDB5MigrationGuide.md @@ -293,7 +293,23 @@ The changes can quite impact your application. We'll describe them below, as wel ## Other Changes -1. [Batch updates] used to rely of the `<-` operator. This operator has been removed. Use the `set(to:)` method instead: +1. The `Configuration.trace` property has been removed. You know use the `Database.trace(options:_:)` method instead: + + ```swift + // BEFORE: GRDB 4 + var config = Configuration() + config.trace = { print($0) } + let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) + + // NEW: GRDB 5 + var config = Configuration() + config.prepareDatabase = { db in + try db.trace(options: .statement) { print($0) } + } + let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) + ``` + +2. [Batch updates] used to rely of the `<-` operator. This operator has been removed. Use the `set(to:)` method instead: ```swift // BEFORE: GRDB 4 @@ -305,7 +321,7 @@ The changes can quite impact your application. We'll describe them below, as wel > :question: This change avoids conflicts with other libraries that define the same operator. -2. [SQL Interpolation] does no longer wrap subqueries in parenthesis: +3. [SQL Interpolation] does no longer wrap subqueries in parenthesis: ```swift // BEFORE: GRDB 4 @@ -320,7 +336,7 @@ The changes can quite impact your application. We'll describe them below, as wel > :question: This change makes it possible to concatenate subqueries with the UNION operator. -3. In order to extract raw SQL string from an [SQLLiteral], you now need a database connection: +4. In order to extract raw SQL string from an [SQLLiteral], you now need a database connection: ```swift let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)" @@ -335,7 +351,7 @@ The changes can quite impact your application. We'll describe them below, as wel print(arguments) // prints ["O'Brien", 42] ``` -4. In order to extract raw SQL string from a request ([SQLRequest] or [QueryInterfaceRequest]), you now need to call the `makePreparedRequest()` method: +5. In order to extract raw SQL string from a request ([SQLRequest] or [QueryInterfaceRequest]), you now need to call the `makePreparedRequest()` method: ```swift // BEFORE: GRDB 4 @@ -355,7 +371,7 @@ The changes can quite impact your application. We'll describe them below, as wel } ``` -5. The `TableRecord.selectionSQL()` method is no longer avaible. When you need to embed the columns selected by a record type in an SQL request, you now have to use [SQL Interpolation]: +6. The `TableRecord.selectionSQL()` method is no longer avaible. When you need to embed the columns selected by a record type in an SQL request, you now have to use [SQL Interpolation]: ```swift // BEFORE: GRDB 4 @@ -367,7 +383,7 @@ The changes can quite impact your application. We'll describe them below, as wel let players = try request.fetchAll(db) ``` -6. [Custom SQL functions] are now [callable values](https://github.com/apple/swift-evolution/blob/master/proposals/0253-callable.md): +7. [Custom SQL functions] are now [callable values](https://github.com/apple/swift-evolution/blob/master/proposals/0253-callable.md): ```swift // BEFORE: GRDB 4 @@ -377,13 +393,13 @@ The changes can quite impact your application. We'll describe them below, as wel Player.select(myFunction(Column("name"))) ``` -7. Defining custom `FetchRequest` types is now **discouraged**. +8. Defining custom `FetchRequest` types is now **discouraged**. A future GRDB version will remove the ability to define custom `FetchRequest` types. Our suggestion is to refactor your app so that your custom request type is no longer needed: [SQLRequest] and [QueryInterfaceRequest] are now supposed to fully address your needs. If it is not possible, then please [open an issue](https://github.com/groue/GRDB.swift/issues) and describe your particular use case. -8. The module name for [custom SQLite builds](CustomSQLiteBuilds.md) is now the plain `GRDB`: +9. The module name for [custom SQLite builds](CustomSQLiteBuilds.md) is now the plain `GRDB`: ```swift // BEFORE: GRDB 4 @@ -393,7 +409,7 @@ The changes can quite impact your application. We'll describe them below, as wel import GRDB ``` -9. Importing the `GRDB` module grants access to the [SQLite C interface](https://www.sqlite.org/c3ref/intro.html). You don't need any longer to import the underlying SQLite library: +10. Importing the `GRDB` module grants access to the [SQLite C interface](https://www.sqlite.org/c3ref/intro.html). You don't need any longer to import the underlying SQLite library: ```swift // BEFORE: GRDB 4 From b95d7cb6472538a903b068157cee4910083e6629 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 May 2020 20:13:45 +0200 Subject: [PATCH 19/28] More Tests for Database.trace(options:_:) --- Tests/GRDBTests/DatabaseTraceTests.swift | 8 ------ Tests/GRDBTests/FTS5RecordTests.swift | 28 ++++++++------------- Tests/GRDBTests/FTS5TableBuilderTests.swift | 12 --------- 3 files changed, 11 insertions(+), 37 deletions(-) diff --git a/Tests/GRDBTests/DatabaseTraceTests.swift b/Tests/GRDBTests/DatabaseTraceTests.swift index 7edebef23..c3203ca7d 100644 --- a/Tests/GRDBTests/DatabaseTraceTests.swift +++ b/Tests/GRDBTests/DatabaseTraceTests.swift @@ -110,14 +110,6 @@ class DatabaseTraceTests : GRDBTestCase { var events: [String] = [] db.trace(options: [.statement, .profile]) { event in events.append(event.description) - switch event { - case .statement: - break - case .profile: - break - default: - XCTFail("Unexpected event") - } } try db.execute(sql: "CREATE table t(a);") XCTAssertEqual(events.count, 2) diff --git a/Tests/GRDBTests/FTS5RecordTests.swift b/Tests/GRDBTests/FTS5RecordTests.swift index eecdea9a9..19c54c843 100644 --- a/Tests/GRDBTests/FTS5RecordTests.swift +++ b/Tests/GRDBTests/FTS5RecordTests.swift @@ -35,18 +35,6 @@ extension Book : MutablePersistableRecord { } class FTS5RecordTests: GRDBTestCase { - - override func setUp() { - super.setUp() - - dbConfiguration.trace = { [unowned self] sql in - // Ignore virtual table logs - if !sql.hasPrefix("--") { - self.sqlQueries.append(sql) - } - } - } - override func setup(_ dbWriter: DatabaseWriter) throws { try dbWriter.write { db in try db.create(virtualTable: "books", using: FTS5()) { t in @@ -109,12 +97,18 @@ class FTS5RecordTests: GRDBTestCase { try book.insert(db) } - let pattern = FTS5Pattern(matchingAllTokensIn: "Herman Melville")! - XCTAssertEqual(try Book.matching(pattern).fetchCount(db), 1) - XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"books\" WHERE \"books\" MATCH 'herman melville'") + do { + sqlQueries = [] + let pattern = FTS5Pattern(matchingAllTokensIn: "Herman Melville")! + XCTAssertEqual(try Book.matching(pattern).fetchCount(db), 1) + XCTAssertTrue(sqlQueries.contains("SELECT COUNT(*) FROM \"books\" WHERE \"books\" MATCH 'herman melville'")) + } - XCTAssertEqual(try Book.fetchCount(db), 1) - XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"books\"") + do { + sqlQueries = [] + XCTAssertEqual(try Book.fetchCount(db), 1) + XCTAssertTrue(sqlQueries.contains("SELECT COUNT(*) FROM \"books\"")) + } } } } diff --git a/Tests/GRDBTests/FTS5TableBuilderTests.swift b/Tests/GRDBTests/FTS5TableBuilderTests.swift index adf6a593e..10f879879 100644 --- a/Tests/GRDBTests/FTS5TableBuilderTests.swift +++ b/Tests/GRDBTests/FTS5TableBuilderTests.swift @@ -3,18 +3,6 @@ import XCTest import GRDB class FTS5TableBuilderTests: GRDBTestCase { - - override func setUp() { - super.setUp() - - dbConfiguration.trace = { [unowned self] sql in - // Ignore virtual table logs - if !sql.hasPrefix("--") { - self.sqlQueries.append(sql) - } - } - } - func testWithoutBody() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in From b80814a77eb0efecdfc1f75aa1055eca0035032f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 May 2020 20:16:00 +0200 Subject: [PATCH 20/28] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e3f097f81..0bc64ee15 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -77,6 +77,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ### Breaking Changes - [#790](https://github.com/groue/GRDB.swift/pull/790): Bump required iOS version to 10.0 +- [#791](https://github.com/groue/GRDB.swift/pull/791): Extend tracing of statement execution ## 5.0.0-beta.2 From 5f7a9de8a5a61b6e6361e704422f0769b1b99259 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 1 Jun 2020 06:28:46 +0200 Subject: [PATCH 21/28] Fix statement profiling test for slow setups --- Tests/GRDBTests/DatabaseTraceTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/GRDBTests/DatabaseTraceTests.swift b/Tests/GRDBTests/DatabaseTraceTests.swift index c3203ca7d..7b00d22f8 100644 --- a/Tests/GRDBTests/DatabaseTraceTests.swift +++ b/Tests/GRDBTests/DatabaseTraceTests.swift @@ -95,7 +95,7 @@ class DatabaseTraceTests : GRDBTestCase { XCTAssertEqual(lastSQL, "SELECT wait(?)") XCTAssertEqual(lastExpandedSQL, "SELECT wait(0.5)") XCTAssertGreaterThan(lastDuration!, 0.4) - XCTAssertLessThan(lastDuration!, 0.6) + XCTAssertLessThan(lastDuration!, 2) // Travis can be so slow XCTAssert(lastDescription!.hasSuffix("s SELECT wait(0.5)")) } } From b47680638dbbf8c13f66d25d5839622159bc5a59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 1 Jun 2020 07:16:48 +0200 Subject: [PATCH 22/28] Trace statements by default --- Documentation/GRDB5MigrationGuide.md | 2 +- GRDB/Core/Database.swift | 11 +++++++---- README.md | 4 +--- Tests/GRDBTests/DatabaseTraceTests.swift | 6 +++--- 4 files changed, 12 insertions(+), 11 deletions(-) diff --git a/Documentation/GRDB5MigrationGuide.md b/Documentation/GRDB5MigrationGuide.md index 20c272d91..e34b6116b 100644 --- a/Documentation/GRDB5MigrationGuide.md +++ b/Documentation/GRDB5MigrationGuide.md @@ -304,7 +304,7 @@ The changes can quite impact your application. We'll describe them below, as wel // NEW: GRDB 5 var config = Configuration() config.prepareDatabase = { db in - try db.trace(options: .statement) { print($0) } + try db.trace { print($0) } } let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) ``` diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index ce5412c14..b29b53bd0 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -503,14 +503,17 @@ public final class Database { /// } /// let dbQueue = try DatabaseQueue(path: "...", configuration: configuration) /// - /// Pass an empty options set, or a nil tracing function in order to stop - /// database tracing. + /// Pass an empty options set in order to stop database tracing: + /// + /// // Stop tracing + /// db.trace(options: []) /// /// See https://www.sqlite.org/c3ref/trace_v2.html for more information. /// - /// - parameter options: The set of desired event kinds. + /// - parameter options: The set of desired event kinds. Defaults to + /// `.statement`, which notifies all executed database statements. /// - parameter trace: the tracing function. - public func trace(options: TracingOptions, _ trace: ((TraceEvent) -> Void)? = nil) { + public func trace(options: TracingOptions = .statement, _ trace: ((TraceEvent) -> Void)? = nil) { SchedulingWatchdog.preconditionValidQueue(self) self.trace = trace diff --git a/README.md b/README.md index 80f8715f7..165b41201 100644 --- a/README.md +++ b/README.md @@ -7352,9 +7352,7 @@ Another option is to setup a tracing function that prints out all SQL requests e // Prints all SQL statements var config = Configuration() config.prepareDatabase = { db in - try db.trace(options: .statement) { - print($0) - } + try db.trace { print($0) } } let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) diff --git a/Tests/GRDBTests/DatabaseTraceTests.swift b/Tests/GRDBTests/DatabaseTraceTests.swift index 7b00d22f8..8ea4cf40c 100644 --- a/Tests/GRDBTests/DatabaseTraceTests.swift +++ b/Tests/GRDBTests/DatabaseTraceTests.swift @@ -116,11 +116,11 @@ class DatabaseTraceTests : GRDBTestCase { } } - func testTraceFromConfiguration() throws { + func testTraceFromConfigurationWithDefaultOptions() throws { var events: [String] = [] var configuration = Configuration() configuration.prepareDatabase = { db in - db.trace(options: .statement) { event in + db.trace { event in events.append("SQL: \(event)") } } @@ -136,7 +136,7 @@ class DatabaseTraceTests : GRDBTestCase { } } - func testTraceReset() throws { + func testStopTrace() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var events: [String] = [] From 9540df84cf6fed4346a57911d347ced8186bd666 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 1 Jun 2020 07:39:43 +0200 Subject: [PATCH 23/28] Documentation --- CHANGELOG.md | 5 +++++ README.md | 40 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0bc64ee15..17af488f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -70,6 +70,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## Next Release +### Documentation Diff + +- Updated FAQ: [How do I print a request as SQL?](README.md#how-do-i-print-a-request-as-sql) +- New FAQ: [How do I monitor the duration of database statements execution?](README.md#how-do-i-monitor-the-duration-of-database-statements-execution) + ### Fixed - [#784](https://github.com/groue/GRDB.swift/pull/784): Fix observation of eager-loaded to-many associations diff --git a/README.md b/README.md index 165b41201..62fe4ec8f 100644 --- a/README.md +++ b/README.md @@ -7277,6 +7277,7 @@ FAQ - [How do I open a database stored as a resource of my application?](#how-do-i-open-a-database-stored-as-a-resource-of-my-application) - [How do I close a database connection?](#how-do-i-close-a-database-connection) - [How do I print a request as SQL?](#how-do-i-print-a-request-as-sql) +- [How do I monitor the duration of database statements execution?](#how-do-i-monitor-the-duration-of-database-statements-execution) - [Generic parameter 'T' could not be inferred](#generic-parameter-t-could-not-be-inferred) - [SQLite error 10 "disk I/O error", SQLite error 23 "not authorized"](#sqlite-error-10-disk-io-error-sqlite-error-23-not-authorized) - [SQLite error 21 "wrong number of statement arguments" with LIKE queries](#sqlite-error-21-wrong-number-of-statement-arguments-with-like-queries) @@ -7346,7 +7347,7 @@ try dbQueue.read { db in } ``` -Another option is to setup a tracing function that prints out all SQL requests executed by your application. You provide the trace function when you connect to the database: +Another option is to setup a tracing function that prints out the executed SQL requests. For example, provide a tracing function when you connect to the database: ```swift // Prints all SQL statements @@ -7362,9 +7363,46 @@ try dbQueue.read { db in } ``` +If you want to hide values such as `'O''Brien'` from the logged statements, adapt the tracing function as below: + +```swift +try db.trace { event in + if case let .statement(statement) = event { + // Prints SELECT * FROM player WHERE name = ? + print(statement.sql) + } +} +``` + > :point_up: **Note**: the generated SQL may change between GRDB releases, without notice: don't have your application rely on any specific SQL output. +### How do I monitor the duration of database statements execution? + +Use the `trace(options:_:)` method, with the `.profile` option: + +```swift +var config = Configuration() +config.prepareDatabase = { db in + try db.trace(options: .profile) { event in + // Prints all SQL statements with their duration + print(event) + + // Access to detailed profiling information + if case let .profile(statement, duration) = event, duration > 0.5 { + print("Slow query: \(statement.sql)") + } + } +} +let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) + +try dbQueue.read { db in + let players = try Player.filter(Column("name") == "O'Brien").fetchAll(db) + // Prints "0.003s SELECT * FROM player WHERE name = 'O''Brien'" +} +``` + + ### Generic parameter 'T' could not be inferred You may get this error when using the `read` and `write` methods of database queues and pools: From 996c1c994f0798e2a253a79731bec3fdefe3085d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 1 Jun 2020 07:41:46 +0200 Subject: [PATCH 24/28] Documentation --- Documentation/GRDB5MigrationGuide.md | 2 +- README.md | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Documentation/GRDB5MigrationGuide.md b/Documentation/GRDB5MigrationGuide.md index e34b6116b..39ad4ab44 100644 --- a/Documentation/GRDB5MigrationGuide.md +++ b/Documentation/GRDB5MigrationGuide.md @@ -304,7 +304,7 @@ The changes can quite impact your application. We'll describe them below, as wel // NEW: GRDB 5 var config = Configuration() config.prepareDatabase = { db in - try db.trace { print($0) } + db.trace { print($0) } } let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) ``` diff --git a/README.md b/README.md index 62fe4ec8f..0a5149c9f 100644 --- a/README.md +++ b/README.md @@ -7353,7 +7353,7 @@ Another option is to setup a tracing function that prints out the executed SQL r // Prints all SQL statements var config = Configuration() config.prepareDatabase = { db in - try db.trace { print($0) } + db.trace { print($0) } } let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) @@ -7366,7 +7366,7 @@ try dbQueue.read { db in If you want to hide values such as `'O''Brien'` from the logged statements, adapt the tracing function as below: ```swift -try db.trace { event in +db.trace { event in if case let .statement(statement) = event { // Prints SELECT * FROM player WHERE name = ? print(statement.sql) @@ -7384,7 +7384,7 @@ Use the `trace(options:_:)` method, with the `.profile` option: ```swift var config = Configuration() config.prepareDatabase = { db in - try db.trace(options: .profile) { event in + db.trace(options: .profile) { event in // Prints all SQL statements with their duration print(event) From a2dce4a238d8c7340a75b62dcf8446cf117288dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 1 Jun 2020 09:02:25 +0200 Subject: [PATCH 25/28] Come on, Travis --- Tests/GRDBTests/ValueObservationRecorder.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/GRDBTests/ValueObservationRecorder.swift b/Tests/GRDBTests/ValueObservationRecorder.swift index 5c05e49a6..ef5304651 100644 --- a/Tests/GRDBTests/ValueObservationRecorder.swift +++ b/Tests/GRDBTests/ValueObservationRecorder.swift @@ -382,7 +382,7 @@ extension GRDBTestCase { // debug SQLite builds can be *very* slow let timeout: TimeInterval = 2 #else - let timeout: TimeInterval = 0.3 + let timeout: TimeInterval = 1 #endif func test( @@ -599,7 +599,7 @@ extension GRDBTestCase { // debug SQLite builds can be *very* slow let timeout: TimeInterval = 2 #else - let timeout: TimeInterval = 0.3 + let timeout: TimeInterval = 1 #endif func test( From 961e5e46c1f053aad8890f5ba102b92a5c3dfdb0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 1 Jun 2020 13:44:46 +0200 Subject: [PATCH 26/28] Fix SQLCipher tests --- .../SQLCipher3/GRDBTests.xcodeproj/project.pbxproj | 12 +----------- .../SQLCipher4/GRDBTests.xcodeproj/project.pbxproj | 6 ------ Tests/GRDBTests/GRDBTestCase.swift | 9 +-------- 3 files changed, 2 insertions(+), 25 deletions(-) diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index 637f8c431..a39754704 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -25,8 +25,6 @@ 561CFAB12376EFBE000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFAAD2376EFBE000C8BAA /* AssociationHasManyOrderingTests.swift */; }; 563DE4FB231A9212005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4FA231A9212005081B7 /* DatabaseConfigurationTests.swift */; }; 563DE4FC231A9212005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4FA231A9212005081B7 /* DatabaseConfigurationTests.swift */; }; - 563F4CBA242F801A0052E96C /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563F4CB9242F801A0052E96C /* ValueObservationRecordTests.swift */; }; - 563F4CBB242F801A0052E96C /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563F4CB9242F801A0052E96C /* ValueObservationRecordTests.swift */; }; 564A1FDE226B89E1001F64F1 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F27226B89CE001F64F1 /* MutablePersistableRecordDeleteTests.swift */; }; 564A1FDF226B89E1001F64F1 /* AssociationHasOneThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F28226B89CE001F64F1 /* AssociationHasOneThroughRowScopeTests.swift */; }; 564A1FE0226B89E1001F64F1 /* RowCopiedFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F29226B89CF001F64F1 /* RowCopiedFromStatementTests.swift */; }; @@ -403,8 +401,6 @@ 56DF002A228DE00900D611F3 /* AssociationPrefetchingRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0026228DE00900D611F3 /* AssociationPrefetchingRowTests.swift */; }; 56E4F7FF2392E6D200A611F6 /* DatabaseAbortedTransactionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E4F7FE2392E6D200A611F6 /* DatabaseAbortedTransactionTests.swift */; }; 56E4F8002392E6D200A611F6 /* DatabaseAbortedTransactionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E4F7FE2392E6D200A611F6 /* DatabaseAbortedTransactionTests.swift */; }; - 56FEB901248403460081AF83 /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB900248403440081AF83 /* DatabaseTests.swift */; }; - 56FEB902248403460081AF83 /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB900248403440081AF83 /* DatabaseTests.swift */; }; 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 */; }; @@ -615,7 +611,6 @@ 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 = ""; }; 56E4F7FE2392E6D200A611F6 /* DatabaseAbortedTransactionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAbortedTransactionTests.swift; sourceTree = ""; }; - 56FEB900248403440081AF83 /* DatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTests.swift; sourceTree = ""; }; 6A4788C0F815F6C5E4EBDE12 /* Pods-GRDBTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.debug.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.debug.xcconfig"; sourceTree = ""; }; 7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_GRDBTestsEncrypted.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 83BFB5733A86DAA3D0BEE684 /* Pods-GRDBTestsEncrypted.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTestsEncrypted.debug.xcconfig"; path = "Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted.debug.xcconfig"; sourceTree = ""; }; @@ -738,7 +733,6 @@ 564A1F79226B89D7001F64F1 /* DatabaseSavepointTests.swift */, 564A1F3F226B89D0001F64F1 /* DatabaseSnapshotTests.swift */, 564B3D77239BDC00007BF308 /* DatabaseSuspensionTests.swift */, - 56FEB900248403440081AF83 /* DatabaseTests.swift */, 564A1FC7226B89DF001F64F1 /* DatabaseTests.swift */, 564A1FAF226B89DC001F64F1 /* DatabaseTimestampTests.swift */, 564A1FD6226B89E0001F64F1 /* DatabaseUUIDEncodingStrategyTests.swift */, @@ -939,7 +933,7 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 1020; - LastUpgradeCheck = 1100; + LastUpgradeCheck = 1150; TargetAttributes = { 564A1F1C226B876D001F64F1 = { CreatedOnToolsVersion = 10.2.1; @@ -1134,7 +1128,6 @@ 564A202E226B89E1001F64F1 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 564A2078226B89E1001F64F1 /* ForeignKeyInfoTests.swift in Sources */, 564A2050226B89E1001F64F1 /* RecordPrimaryKeySingleTests.swift in Sources */, - 563F4CBA242F801A0052E96C /* ValueObservationRecordTests.swift in Sources */, 561017D22462968600317275 /* DatabasePoolTests.swift in Sources */, 564A2091226B89E1001F64F1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 5676FBB022F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, @@ -1224,7 +1217,6 @@ 564A2001226B89E1001F64F1 /* RecordPrimaryKeyNoneTests.swift in Sources */, 564A2051226B89E1001F64F1 /* RecordWithColumnNameManglingTests.swift in Sources */, 564A205B226B89E1001F64F1 /* RecordCopyTests.swift in Sources */, - 56FEB901248403460081AF83 /* DatabaseTests.swift in Sources */, 564A205F226B89E1001F64F1 /* SQLLiteralTests.swift in Sources */, 564A206C226B89E1001F64F1 /* FTS5CustomTokenizerTests.swift in Sources */, 564A2002226B89E1001F64F1 /* DerivableRequestTests.swift in Sources */, @@ -1339,7 +1331,6 @@ 564A20CD226B8E18001F64F1 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 564A20CE226B8E18001F64F1 /* ForeignKeyInfoTests.swift in Sources */, 564A20CF226B8E18001F64F1 /* RecordPrimaryKeySingleTests.swift in Sources */, - 563F4CBB242F801A0052E96C /* ValueObservationRecordTests.swift in Sources */, 561017D32462968600317275 /* DatabasePoolTests.swift in Sources */, 564A20D0226B8E18001F64F1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 5676FBB122F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, @@ -1429,7 +1420,6 @@ 564A211F226B8E18001F64F1 /* RecordPrimaryKeyNoneTests.swift in Sources */, 564A2120226B8E18001F64F1 /* RecordWithColumnNameManglingTests.swift in Sources */, 564A2121226B8E18001F64F1 /* RecordCopyTests.swift in Sources */, - 56FEB902248403460081AF83 /* DatabaseTests.swift in Sources */, 564A2122226B8E18001F64F1 /* SQLLiteralTests.swift in Sources */, 564A2123226B8E18001F64F1 /* FTS5CustomTokenizerTests.swift in Sources */, 564A2124226B8E18001F64F1 /* DerivableRequestTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index 5ada826b0..5074166e3 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -405,8 +405,6 @@ 56DF0024228DDFF000D611F3 /* AssociationPrefetchingCodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0020228DDFF000D611F3 /* AssociationPrefetchingCodableRecordTests.swift */; }; 56E4F7FC2392E6C400A611F6 /* DatabaseAbortedTransactionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E4F7FB2392E6C300A611F6 /* DatabaseAbortedTransactionTests.swift */; }; 56E4F7FD2392E6C400A611F6 /* DatabaseAbortedTransactionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E4F7FB2392E6C300A611F6 /* DatabaseAbortedTransactionTests.swift */; }; - 56FEB904248403510081AF83 /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB903248403510081AF83 /* DatabaseTests.swift */; }; - 56FEB905248403510081AF83 /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB903248403510081AF83 /* DatabaseTests.swift */; }; 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 */; }; @@ -618,7 +616,6 @@ 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 = ""; }; 56E4F7FB2392E6C300A611F6 /* DatabaseAbortedTransactionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAbortedTransactionTests.swift; sourceTree = ""; }; - 56FEB903248403510081AF83 /* DatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTests.swift; sourceTree = ""; }; 67377FE4CDAD675809F93AD4 /* Pods_GRDBTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_GRDBTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 6A4788C0F815F6C5E4EBDE12 /* Pods-GRDBTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.debug.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.debug.xcconfig"; sourceTree = ""; }; 7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_GRDBTestsEncrypted.framework; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -741,7 +738,6 @@ 564A1F79226B89D7001F64F1 /* DatabaseSavepointTests.swift */, 564A1F3F226B89D0001F64F1 /* DatabaseSnapshotTests.swift */, 564B3D74239BDBEC007BF308 /* DatabaseSuspensionTests.swift */, - 56FEB903248403510081AF83 /* DatabaseTests.swift */, 564A1FC7226B89DF001F64F1 /* DatabaseTests.swift */, 564A1FAF226B89DC001F64F1 /* DatabaseTimestampTests.swift */, 564A1FD6226B89E0001F64F1 /* DatabaseUUIDEncodingStrategyTests.swift */, @@ -1230,7 +1226,6 @@ 564A2051226B89E1001F64F1 /* RecordWithColumnNameManglingTests.swift in Sources */, 564A205B226B89E1001F64F1 /* RecordCopyTests.swift in Sources */, 564A205F226B89E1001F64F1 /* SQLLiteralTests.swift in Sources */, - 56FEB904248403510081AF83 /* DatabaseTests.swift in Sources */, 564A206C226B89E1001F64F1 /* FTS5CustomTokenizerTests.swift in Sources */, 564A2002226B89E1001F64F1 /* DerivableRequestTests.swift in Sources */, 56057C6B2291D0C000A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */, @@ -1435,7 +1430,6 @@ 564A2120226B8E18001F64F1 /* RecordWithColumnNameManglingTests.swift in Sources */, 564A2121226B8E18001F64F1 /* RecordCopyTests.swift in Sources */, 564A2122226B8E18001F64F1 /* SQLLiteralTests.swift in Sources */, - 56FEB905248403510081AF83 /* DatabaseTests.swift in Sources */, 564A2123226B8E18001F64F1 /* FTS5CustomTokenizerTests.swift in Sources */, 564A2124226B8E18001F64F1 /* DerivableRequestTests.swift in Sources */, 56057C6C2291D0C000A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */, diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index b28d29a75..39aa57ef4 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -100,7 +100,7 @@ class GRDBTestCase: XCTestCase { } dbConfiguration.prepareDatabase = { db in - db.trace(options: .statement) { event in + db.trace { event in self.sqlQueries.append(event.description) } @@ -109,13 +109,6 @@ class GRDBTestCase: XCTestCase { #endif } - #if GRDBCIPHER_USE_ENCRYPTION - // Encrypt all databases by default. - dbConfiguration.prepareDatabase = { db in - try db.usePassphrase("secret") - } - #endif - sqlQueries = [] } From 7333b1a0806856ddea0a3747384923d00878f9a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 1 Jun 2020 18:20:02 +0200 Subject: [PATCH 27/28] Travis: no more stages --- .travis.yml | 104 ++++++++++------------------------------------------ 1 file changed, 19 insertions(+), 85 deletions(-) diff --git a/.travis.yml b/.travis.yml index b18f5d14c..5334c8f9c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -30,179 +30,113 @@ jobs: ########################################### ## Test GRDB Xcode 11.4 - - stage: Test GRDB Xcode 11.4 + - name: "Test GRDB Xcode 11.4 - GRDBOSX" gemfile: .ci/gemfiles/Gemfile.travis osx_image: xcode11.4 - env: - - TID=GRDBOSX (Swift 5.2, macOS) script: make test_framework_GRDBOSX_maxSwift - # - stage: Test GRDB Xcode 11.4 - # gemfile: .ci/gemfiles/Gemfile.travis - # osx_image: xcode11.4 - # env: - # - TID=GRDBOSX (Swift 5.2, macOS) - # script: make test_framework_GRDBOSX_minSwift - - - stage: Test GRDB Xcode 11.4 + - name: "Test GRDB Xcode 11.4 - GRDBWatchOS" gemfile: .ci/gemfiles/Gemfile.travis osx_image: xcode11.4 - env: - - TID=GRDBWatchOS (watchOS) script: make test_framework_GRDBWatchOS - - stage: Test GRDB Xcode 11.4 + - name: "Test GRDB Xcode 11.4 - GRDBiOS iOS maxTarget" gemfile: .ci/gemfiles/Gemfile.travis osx_image: xcode11.4 - env: - - TID=GRDBiOS (Swift 5.2, iOS ) script: make test_framework_GRDBiOS_maxTarget_maxSwift - # - stage: Test GRDB Xcode 11.4 - # gemfile: .ci/gemfiles/Gemfile.travis - # osx_image: xcode11.4 - # env: - # - TID=GRDBiOS (Swift 5.2, iOS ) - # script: make test_framework_GRDBiOS_maxTarget_minSwift - - - stage: Test GRDB Xcode 11.4 + - name: "Test GRDB Xcode 11.4 - GRDBiOS iOS minTarget" gemfile: .ci/gemfiles/Gemfile.travis osx_image: xcode11.4 - env: - - TID=GRDBiOS (Swift 5.2, iOS ) script: make test_framework_GRDBiOS_minTarget - - stage: Test GRDB Xcode 11.4 + - name: "Test GRDB Xcode 11.4 - GRDBtvOS maxTarget" gemfile: .ci/gemfiles/Gemfile.travis osx_image: xcode11.4 - env: - - TID=GRDBtvOS (Swift 5.2, tvOS ) script: make test_framework_GRDBtvOS_maxTarget_maxSwift - # - stage: Test GRDB Xcode 11.4 - # gemfile: .ci/gemfiles/Gemfile.travis - # osx_image: xcode11.4 - # env: - # - TID=GRDBtvOS (Swift 5.2, tvOS ) - # script: make test_framework_GRDBtvOS_maxTarget_minSwift - - - stage: Test GRDB Xcode 11.4 + - name: "Test GRDB Xcode 11.4 - GRDBtvOS minTarget" gemfile: .ci/gemfiles/Gemfile.travis osx_image: xcode11.4 - env: - - TID=GRDBtvOS (Swift 5.2, tvOS ) script: make test_framework_GRDBtvOS_minTarget - - stage: Test GRDB Xcode 11.4 + - name: "Test GRDB Xcode 11.4 - SPM" gemfile: .ci/gemfiles/Gemfile.travis osx_image: xcode11.4 - env: - - TID=GRDB [SPM] (macOS) script: make test_SPM ########################################### ## Test GRDBCustom Xcode 11.4 - - stage: Test GRDBCustom Xcode 11.4 + - name: "Test GRDBCustom Xcode 11.4 - GRDBOSX" gemfile: .ci/gemfiles/Gemfile.travis osx_image: xcode11.4 - env: - - TID=GRDBOSX (Swift 5.2, macOS) script: make test_framework_GRDBCustomSQLiteOSX - - stage: Test GRDBCustom Xcode 11.4 + - name: "Test GRDBCustom Xcode 11.4 - GRDBiOS maxTarget" gemfile: .ci/gemfiles/Gemfile.travis osx_image: xcode11.4 - env: - - TID=GRDBiOS (Swift 5.2, iOS ) script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift - # - stage: Test GRDBCustom Xcode 11.4 - # gemfile: .ci/gemfiles/Gemfile.travis - # osx_image: xcode11.4 - # env: - # - TID=GRDBiOS (Swift 5.2, iOS ) - # script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_minSwift - - - stage: Test GRDBCustom Xcode 11.4 + - name: "Test GRDBCustom Xcode 11.4 - GRDBiOS minTarget" gemfile: .ci/gemfiles/Gemfile.travis osx_image: xcode11.4 - env: - - TID=GRDBiOS (Swift 5.2, iOS ) script: make test_framework_GRDBCustomSQLiteiOS_minTarget ########################################### ## Test SQLCipher Xcode 11.4 - - stage: Test SQLCipher Xcode 11.4 + - name: "Test SQLCipher Xcode 11.4 - SQLCipher 3" gemfile: .ci/gemfiles/Gemfile.travis osx_image: xcode11.4 - env: - - TID=SQLCipher 3 script: make test_framework_SQLCipher3 - - stage: Test SQLCipher Xcode 11.4 + - name: "Test SQLCipher Xcode 11.4 - SQLCipher 4" gemfile: .ci/gemfiles/Gemfile.travis osx_image: xcode11.4 - env: - - TID=SQLCipher 4 script: make test_framework_SQLCipher4 ########################################### ## Test Installation Xcode 11.4 # Manual Install - - stage: Test Installation Xcode 11.4 + - name: "Test Installation Xcode 11.4 - Manual Install" gemfile: .ci/gemfiles/Gemfile.travis osx_image: xcode11.4 - env: - - TID=Manual Install script: make test_install_manual # CocoaPods Lint - - stage: Test Installation Xcode 11.4 + - name: "Test Installation Xcode 11.4 - CocoaPods Lint" gemfile: .ci/gemfiles/Gemfile.travis osx_image: xcode11.4 - env: - - TID=CocoaPods Lint script: make test_CocoaPodsLint_GRDB # CocoaPods Install GRDB - - stage: Test Installation Xcode 11.4 + - name: "Test Installation Xcode 11.4 - CocoaPods Framework" gemfile: .ci/gemfiles/Gemfile.travis osx_image: xcode11.4 - env: - - TID=CocoaPods GRDB (framework) script: make test_install_GRDB_CocoaPods_framework # CocoaPods Install GRDB - - stage: Test Installation Xcode 11.4 + - name: "Test Installation Xcode 11.4 - CocoaPods Static" gemfile: .ci/gemfiles/Gemfile.travis osx_image: xcode11.4 - env: - - TID=CocoaPods GRDB (static) script: make test_install_GRDB_CocoaPods_static # SPM Install - - stage: Test Installation Xcode 11.4 + - name: "Test Installation Xcode 11.4 - SPM Package" gemfile: .ci/gemfiles/Gemfile.travis osx_image: xcode11.4 - env: - - TID=SPM Package script: make test_install_SPM_Package # SPM Install - - stage: Test Installation Xcode 11.4 + - name: "Test Installation Xcode 11.4 - SPM Package in Xcode Project" gemfile: .ci/gemfiles/Gemfile.travis osx_image: xcode11.4 - env: - - TID=SPM Package in Xcode Project script: make test_install_SPM_Project # Custom SQLite Install - - stage: Test Installation Xcode 11.4 + - name: "Test Installation Xcode 11.4 - Custom SQLite" gemfile: .ci/gemfiles/Gemfile.travis osx_image: xcode11.4 - env: - - TID=Custom SQLite script: make test_install_customSQLite From a8b58cb7e71921cd34ced2daa4e307e2c4f90e77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 1 Jun 2020 20:20:52 +0200 Subject: [PATCH 28/28] v5.0.0-beta.3 --- CHANGELOG.md | 10 ++++++++- Documentation/FullTextSearch.md | 4 ++-- Documentation/Migrations.md | 2 +- GRDB.swift.podspec | 2 +- Makefile | 6 ++--- README.md | 40 ++++++++++++++++----------------- Support/Info.plist | 2 +- 7 files changed, 37 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 17af488f6..5cd4d6919 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,11 +5,13 @@ All notable changes to this project will be documented in this file. GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library. + #### 5.x Releases -- `5.0.0` Betas - [5.0.0-beta](#500-beta) | [5.0.0-beta.2](#500-beta2) +- `5.0.0` Betas - [5.0.0-beta](#500-beta) | [5.0.0-beta.2](#500-beta2) | [5.0.0-beta.3](#500-beta3) #### 4.x Releases @@ -68,7 +70,13 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [0.110.0](#01100), ... + + +## 5.0.0-beta.3 + +Released June 1, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta.2...v5.0.0-beta.3) ### Documentation Diff diff --git a/Documentation/FullTextSearch.md b/Documentation/FullTextSearch.md index 6f49812eb..ce185bc19 100644 --- a/Documentation/FullTextSearch.md +++ b/Documentation/FullTextSearch.md @@ -280,7 +280,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Structs/StatementArguments.html): +FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.3/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, @@ -529,7 +529,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Structs/StatementArguments.html): +FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.3/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index d2b9d4ee6..b3210b49b 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -68,7 +68,7 @@ try dbQueue.read { db in } ``` -See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Structs/DatabaseMigrator.html) for more migrator methods. +See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.3/Structs/DatabaseMigrator.html) for more migrator methods. ## The `eraseDatabaseOnSchemaChange` Option diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index ac2b993b9..bf485e9fb 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '5.0.0-beta.2' + s.version = '5.0.0-beta.3' 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 e6a1df55d..401d528fc 100644 --- a/Makefile +++ b/Makefile @@ -387,10 +387,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/v5.0.0-beta.2 \ - --module-version 5.0.0-beta.2 \ + --github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.0.0-beta.3 \ + --module-version 5.0.0-beta.3 \ --module GRDB \ - --root-url http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/ \ + --root-url http://groue.github.io/GRDB.swift/docs/5.0.0-beta.3/ \ --output Documentation/Reference \ --xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS else diff --git a/README.md b/README.md index 0a5149c9f..4cec98ae9 100644 --- a/README.md +++ b/README.md @@ -11,13 +11,13 @@ --- -**Latest release**: May 11, 2020 • version 5.0.0-beta.2 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) +**Latest release**: June 1, 2020 • version 5.0.0-beta.3 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) **Requirements**: iOS 10.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ • Swift 5.2+ / Xcode 11.4+ | Swift version | GRDB version | | ------------- | ----------------------------------------------------------- | -| **Swift 5.2** | **v5.0.0-beta.2**, [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0)| +| **Swift 5.2** | **v5.0.0-beta.3**, [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0)| | Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | | Swift 5 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | | Swift 4.2 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | @@ -264,7 +264,7 @@ Documentation #### Reference -- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) +- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.3/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) #### Getting Started @@ -477,7 +477,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.3/Structs/Configuration.html) for more details. ## Database Pools @@ -557,7 +557,7 @@ let dbPool = try DatabasePool( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.3/Structs/Configuration.html) for more details. Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information. @@ -617,7 +617,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/5.0.0-beta.2/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/5.0.0-beta.3/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. You can also embed query arguments right into your SQL queries, with the `literal` argument label, as in the example below. See [SQL Interpolation] for more details. @@ -815,7 +815,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/5.0.0-beta.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`: +- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.3/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 @@ -897,7 +897,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/5.0.0-beta.2/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/5.0.0-beta.3/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: @@ -1180,7 +1180,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/5.0.0-beta.2/Structs/StatementArguments.html): +Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.3/Structs/StatementArguments.html): ```swift let url: URL = ... @@ -1587,7 +1587,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/5.0.0-beta.2/Structs/Configuration.html) configuration flag: +Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.3/Structs/Configuration.html) configuration flag: ```swift // fatal error: A transaction has been left opened at the end of a database access @@ -1701,7 +1701,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/5.0.0-beta.2/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/5.0.0-beta.3/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). ```swift updateStatement.arguments = ["name": "Arthur", "score": 1000] @@ -1960,7 +1960,7 @@ row["consumed"] // "Hello" row["produced"] // nil ``` -Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.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. +Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.3/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). @@ -2415,7 +2415,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/5.0.0-beta.2/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/5.0.0-beta.3/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()`. @@ -2794,7 +2794,7 @@ protocol EncodableRecord { } ``` -See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. +See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.3/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.3/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.3/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). @@ -4179,7 +4179,7 @@ Player // SELECT * FROM player ``` -Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Structs/StatementArguments.html): +Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.3/Structs/StatementArguments.html): ```swift // SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate) @@ -4780,7 +4780,7 @@ try Player.customRequest().fetchAll(db) // [Player] **To build custom requests**, you can use one of the built-in requests or derive requests from other requests. -- [SQLRequest](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example: +- [SQLRequest](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.3/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example: ```swift extension Player { @@ -4823,7 +4823,7 @@ try Player.customRequest().fetchAll(db) // [Player] - 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/5.0.0-beta.2/Structs/AnyFetchRequest.html): a type-erased request. +- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.3/Structs/AnyFetchRequest.html): a type-erased request. ## Joined Queries Support @@ -5930,7 +5930,7 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan ### DatabaseRegion -**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/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/5.0.0-beta.3/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. @@ -5940,7 +5940,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/5.0.0-beta.2/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). +For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.3/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). #### The DatabaseRegionConvertible Protocol @@ -7037,7 +7037,7 @@ try snapshot2.read { db in ### DatabaseWriter and DatabaseReader Protocols -Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only. +Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.3/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.3/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only. These protocols provide a unified API that let you write generic code that targets all concurrency modes. They fuel, for example: diff --git a/Support/Info.plist b/Support/Info.plist index bcd0a5dec..b6bcd6824 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 5.0.0-beta.2 + 5.0.0-beta.3 CFBundleSignature ???? CFBundleVersion