From 86b9616dd7fa6ae99713b92cb23fcfc40e561e85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 24 Jul 2020 18:32:24 +0200 Subject: [PATCH 01/10] DatabasePool readers don't invalidate their database schema cache until schema is actually changed. --- CHANGELOG.md | 5 +- GRDB/Core/Database+Schema.swift | 10 +++ GRDB/Core/Database.swift | 50 +------------ GRDB/Core/DatabasePool.swift | 72 ++++++++++++++----- GRDB/Core/DatabaseSnapshot.swift | 9 ++- .../DatabasePoolConcurrencyTests.swift | 7 +- .../DatabasePoolSchemaCacheTests.swift | 24 +++++-- Tests/GRDBTests/DatabaseSnapshotTests.swift | 55 ++++++++++++++ 8 files changed, 154 insertions(+), 78 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ce64bf565..0799e3e53 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,10 +68,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [0.110.0](#01100), ... - +- **New**: DatabasePool readers don't invalidate their database schema cache until schema is actually changed. ## 5.0.0-beta.9 diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 175610bec..25de4e0eb 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -18,6 +18,16 @@ extension Database { publicStatementCache.clear() } + /// Clears the database schema cache if the database schema has changed + /// since this method was last called. + func clearSchemaCacheIfNeeded() throws { + let schemaVersion = try Int32.fetchOne(internalCachedSelectStatement(sql: "PRAGMA schema_version")) + if _lastSchemaVersion != schemaVersion { + _lastSchemaVersion = schemaVersion + clearSchemaCache() + } + } + /// Returns whether a table exists. public func tableExists(_ name: String) throws -> Bool { try exists(type: .table, name: name) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 8f9d57a38..1f1b4736b 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -125,6 +125,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // MARK: - Internal properties // Caches + var _lastSchemaVersion: Int32? // Support for clearSchemaCacheIfNeeded() var schemaCache: DatabaseSchemaCache // internal so that it can be tested lazy var internalStatementCache = StatementCache(database: self) lazy var publicStatementCache = StatementCache(database: self) @@ -1072,55 +1073,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib assert(isInsideTransaction) } - /// Begins a database transaction and take a snapshot of the last committed - /// database state. - func beginSnapshotTransaction() throws { - // https://www.sqlite.org/isolation.html - // - // > In WAL mode, SQLite exhibits "snapshot isolation". When a read - // > transaction starts, that reader continues to see an unchanging - // > "snapshot" of the database file as it existed at the moment in time - // > when the read transaction started. Any write transactions that - // > commit while the read transaction is active are still invisible to - // > the read transaction, because the reader is seeing a snapshot of - // > database file from a prior moment in time. - // - // That's exactly what we need. But what does "when read transaction - // starts" mean? - // - // http://www.sqlite.org/lang_transaction.html - // - // > Deferred [transaction] means that no locks are acquired on the - // > database until the database is first accessed. [...] Locks are not - // > acquired until the first read or write operation. [...] Because the - // > acquisition of locks is deferred until they are needed, it is - // > possible that another thread or process could create a separate - // > transaction and write to the database after the BEGIN on the - // > current thread has executed. - // - // Now that's precise enough: SQLite defers "snapshot isolation" until - // the first SELECT: - // - // Reader Writer - // BEGIN DEFERRED TRANSACTION - // UPDATE ... (1) - // Here the change (1) is visible - // SELECT ... - // UPDATE ... (2) - // Here the change (2) is not visible - // - // We thus have to perform a select that establishes the - // snapshot isolation before we release the writer queue: - // - // Reader Writer - // BEGIN DEFERRED TRANSACTION - // SELECT anything - // UPDATE ... - // Here the change is not visible by GRDB user - try beginTransaction(.deferred) - try internalCachedSelectStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next() - } - /// Rollbacks a database transaction. public func rollback() throws { // The SQLite documentation contains two related but distinct techniques diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 022ffc985..fc88caf81 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -322,8 +322,7 @@ extension DatabasePool: DatabaseReader { // The block isolation comes from the DEFERRED transaction. // See DatabasePoolTests.testReadMethodIsolationOfBlock(). try db.inTransaction(.deferred) { - // Reset the schema cache before running user code in snapshot isolation - db.clearSchemaCache() + try db.clearSchemaCacheIfNeeded() result = try block(db) return .commit } @@ -369,9 +368,7 @@ extension DatabasePool: DatabaseReader { do { // The block isolation comes from the DEFERRED transaction. try db.beginTransaction(.deferred) - - // Reset the schema cache before running user code in snapshot isolation - db.clearSchemaCache() + try db.clearSchemaCacheIfNeeded() block(.success(db)) } catch { block(.failure(error)) @@ -416,9 +413,7 @@ extension DatabasePool: DatabaseReader { do { // The block isolation comes from the DEFERRED transaction. try db.beginTransaction(.deferred) - - // Reset the schema cache before running user code in snapshot isolation - db.clearSchemaCache() + try db.clearSchemaCacheIfNeeded() block(.success(db)) } catch { block(.failure(error)) @@ -460,8 +455,7 @@ extension DatabasePool: DatabaseReader { GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.") return try readerPool.get { reader in try reader.sync { db in - // Reset the schema cache - db.clearSchemaCache() + try db.clearSchemaCacheIfNeeded() return try block(db) } } @@ -500,8 +494,7 @@ extension DatabasePool: DatabaseReader { } else { return try readerPool.get { reader in try reader.sync { db in - // Reset the schema cache - db.clearSchemaCache() + try db.clearSchemaCacheIfNeeded() return try block(db) } } @@ -592,19 +585,64 @@ extension DatabasePool: DatabaseReader { releaseReader() } do { - try db.beginSnapshotTransaction() + // https://www.sqlite.org/isolation.html + // + // > In WAL mode, SQLite exhibits "snapshot isolation". When + // > a read transaction starts, that reader continues to see + // > an unchanging "snapshot" of the database file as it + // > existed at the moment in time when the read transaction + // > started. Any write transactions that commit while the + // > read transaction is active are still invisible to the + // > read transaction, because the reader is seeing a + // > snapshot of database file from a prior moment in time. + // + // That's exactly what we need. But what does "when read + // transaction starts" mean? + // + // http://www.sqlite.org/lang_transaction.html + // + // > Deferred [transaction] means that no locks are acquired + // > on the database until the database is first accessed. + // > [...] Locks are not acquired until the first read or + // > write operation. [...] Because the acquisition of locks + // > is deferred until they are needed, it is possible that + // > another thread or process could create a separate + // > transaction and write to the database after the BEGIN + // > on the current thread has executed. + // + // Now that's precise enough: SQLite defers snapshot + // isolation until the first SELECT: + // + // Reader Writer + // BEGIN DEFERRED TRANSACTION + // UPDATE ... (1) + // Here the change (1) is visible from the reader + // SELECT ... + // UPDATE ... (2) + // Here the change (2) is not visible from the reader + // + // We thus have to perform a select that establishes the + // snapshot isolation before we release the writer queue: + // + // Reader Writer + // BEGIN DEFERRED TRANSACTION + // SELECT anything + // UPDATE ... (1) + // Here the change (1) is not visible from the reader + // + // Since any select goes, use `PRAGMA schema_version`. + try db.beginTransaction(.deferred) + try db.clearSchemaCacheIfNeeded() } catch { isolationSemaphore.signal() block(.failure(error)) return } - // Release the writer queue + // Now that we have an isolated snapshot of the last commit, we + // can release the writer queue. isolationSemaphore.signal() - // Reset the schema cache before running user code in snapshot isolation - db.clearSchemaCache() - block(.success(db)) } } catch { diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index edd3edbeb..a865fdeb1 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -57,7 +57,14 @@ public class DatabaseSnapshot: DatabaseReader { guard journalMode == "wal" else { throw DatabaseError(message: "WAL mode is not activated at path: \(path)") } - try db.beginSnapshotTransaction() + + // Open transaction + try db.beginTransaction(.deferred) + + // Acquire snapshot isolation + try db.internalCachedSelectStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next() + + // Support for ValueObservation in DatabasePool version = try? db.takeVersionSnapshot() } } diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index 73a26c40a..ccf171093 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -480,10 +480,13 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { try! dbPool.read { db in s1.signal() _ = s2.wait(timeout: .distantFuture) - XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1) // Not a bug. The writer did not start a transaction. + // We read 0 due to snaphot isolation: the reader has checked + // the schema version before `s1` could let the writer insert + // an item. + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 0) s3.signal() _ = s4.wait(timeout: .distantFuture) - XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1) + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 0) } } let block2 = { () in diff --git a/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift b/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift index cfe20e1ca..850404c98 100644 --- a/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift +++ b/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift @@ -31,7 +31,14 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase { _ = try db.columns(in: "items") _ = try db.indexes(on: "items") - // Assert that reader cache is warmed + // Assert that reader cache is warm + XCTAssertTrue(db.schemaCache.primaryKey("items") != nil) + XCTAssertTrue(db.schemaCache.columns(in: "items") != nil) + XCTAssertTrue(db.schemaCache.indexes(on: "items") != nil) + } + + try dbPool.read { db in + // Assert that reader cache is still warm XCTAssertTrue(db.schemaCache.primaryKey("items") != nil) XCTAssertTrue(db.schemaCache.columns(in: "items") != nil) XCTAssertTrue(db.schemaCache.indexes(on: "items") != nil) @@ -43,24 +50,31 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase { _ = try db.columns(in: "items") _ = try db.indexes(on: "items") - // Assert that writer cache is warmed + // Assert that writer cache is warm XCTAssertTrue(db.schemaCache.primaryKey("items") != nil) XCTAssertTrue(db.schemaCache.columns(in: "items") != nil) XCTAssertTrue(db.schemaCache.indexes(on: "items") != nil) } try dbPool.write { db in - // Empty cache after schema change + // Assert that writer cache is still warm + XCTAssertTrue(db.schemaCache.primaryKey("items") != nil) + XCTAssertTrue(db.schemaCache.columns(in: "items") != nil) + XCTAssertTrue(db.schemaCache.indexes(on: "items") != nil) + } + + try dbPool.write { db in + // Change schema try db.execute(sql: "DROP TABLE items") - // Assert that the writer cache is empty + // Assert that the writer cache is cleared XCTAssertTrue(db.schemaCache.primaryKey("items") == nil) XCTAssertTrue(db.schemaCache.columns(in: "items") == nil) XCTAssertTrue(db.schemaCache.indexes(on: "items") == nil) } try dbPool.read { db in - // Assert that a reader cache is empty + // Assert that reader cache is cleared XCTAssertTrue(db.schemaCache.primaryKey("items") == nil) XCTAssertTrue(db.schemaCache.columns(in: "items") == nil) XCTAssertTrue(db.schemaCache.indexes(on: "items") == nil) diff --git a/Tests/GRDBTests/DatabaseSnapshotTests.swift b/Tests/GRDBTests/DatabaseSnapshotTests.swift index df3c8cb4a..432099d0a 100644 --- a/Tests/GRDBTests/DatabaseSnapshotTests.swift +++ b/Tests/GRDBTests/DatabaseSnapshotTests.swift @@ -195,6 +195,61 @@ class DatabaseSnapshotTests: GRDBTestCase { // MARK: - Concurrency + func testReadBlockIsolationStartingWithRead() throws { + let dbPool = try makeDatabasePool() + try dbPool.write { db in + try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") + } + + // Block 1 Block 2 + // dbSnapshot.read { + // > + let s1 = DispatchSemaphore(value: 0) + // INSERT INTO items (id) VALUES (NULL) + // < + let s2 = DispatchSemaphore(value: 0) + // SELECT COUNT(*) FROM items -> 0 + // > + let s3 = DispatchSemaphore(value: 0) + // INSERT INTO items (id) VALUES (NULL) + // < + let s4 = DispatchSemaphore(value: 0) + // SELECT COUNT(*) FROM items -> 0 + // } + + let block1 = { () in + let snapshot = try! dbPool.makeSnapshot() + try! snapshot.read { db in + s1.signal() + _ = s2.wait(timeout: .distantFuture) + // We read 0 due to snaphot isolation which was acquired before + // `s1` could let the writer insert an item. + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 0) + s3.signal() + _ = s4.wait(timeout: .distantFuture) + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 0) + } + } + let block2 = { () in + do { + _ = s1.wait(timeout: .distantFuture) + try dbPool.writeWithoutTransaction { db in + try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)") + s2.signal() + _ = s3.wait(timeout: .distantFuture) + try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)") + s4.signal() + } + } catch { + XCTFail("error: \(error)") + } + } + let blocks = [block1, block2] + DispatchQueue.concurrentPerform(iterations: blocks.count) { index in + blocks[index]() + } + } + func testDefaultLabel() throws { let dbPool = try makeDatabasePool() From bf1d6038e1ddcad7b35e0f7b5626cd528fbc7088 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 26 Jul 2020 13:33:35 +0200 Subject: [PATCH 02/10] Failing tests for #816 --- .../QueryInterfaceExpressionsTests.swift | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index 9ea55cc2a..013123b0e 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -463,16 +463,16 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.age == true)), - "SELECT * FROM \"readers\" WHERE \"age\"") + "SELECT * FROM \"readers\" WHERE \"age\" = 1") XCTAssertEqual( sql(dbQueue, tableRequest.filter(true == Col.age)), - "SELECT * FROM \"readers\" WHERE \"age\"") + "SELECT * FROM \"readers\" WHERE \"age\" = 1") XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.age == false)), - "SELECT * FROM \"readers\" WHERE NOT \"age\"") + "SELECT * FROM \"readers\" WHERE \"age\" = 0") XCTAssertEqual( sql(dbQueue, tableRequest.filter(false == Col.age)), - "SELECT * FROM \"readers\" WHERE NOT \"age\"") + "SELECT * FROM \"readers\" WHERE \"age\" = 0") XCTAssertEqual( sql(dbQueue, tableRequest.filter(true == true)), "SELECT * FROM \"readers\" WHERE 1") @@ -615,16 +615,16 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.age != true)), - "SELECT * FROM \"readers\" WHERE NOT \"age\"") + "SELECT * FROM \"readers\" WHERE \"age\" <> 1") XCTAssertEqual( sql(dbQueue, tableRequest.filter(true != Col.age)), - "SELECT * FROM \"readers\" WHERE NOT \"age\"") + "SELECT * FROM \"readers\" WHERE \"age\" <> 1") XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.age != false)), - "SELECT * FROM \"readers\" WHERE \"age\"") + "SELECT * FROM \"readers\" WHERE \"age\" <> 0") XCTAssertEqual( sql(dbQueue, tableRequest.filter(false != Col.age)), - "SELECT * FROM \"readers\" WHERE \"age\"") + "SELECT * FROM \"readers\" WHERE \"age\" <> 0") XCTAssertEqual( sql(dbQueue, tableRequest.filter(true != true)), "SELECT * FROM \"readers\" WHERE 0") From c532b8709c77f542804df6dd2d79243750b6721e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 26 Jul 2020 14:19:31 +0200 Subject: [PATCH 03/10] Refactor boolean tests (fix #816) --- GRDB/Core/DatabaseValue.swift | 40 +++--- .../SQL/SQLExpression+QueryInterface.swift | 124 ++++++++++++------ GRDB/QueryInterface/SQL/SQLExpression.swift | 67 ++++++++-- GRDB/QueryInterface/SQL/SQLOperators.swift | 46 +++---- 4 files changed, 182 insertions(+), 95 deletions(-) diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index d23325b5d..0b47a837b 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -221,30 +221,30 @@ extension DatabaseValue { // SQLExpression extension DatabaseValue { + // Specific boolean checks for null, true, and false /// :nodoc: - public var _negated: SQLExpression { + public func _is(_ test: _SQLBooleanTest) -> SQLExpression { switch storage { case .null: - // SELECT NOT NULL -- NULL return DatabaseValue.null - case .int64(let int64): - return (int64 == 0).sqlExpression - case .double(let double): - return (double == 0.0).sqlExpression - case .string: - // We can't assume all strings are true, and return false: - // - // SELECT NOT '1' -- 0 (because '1' is turned into the integer 1, which is negated into 0) - // SELECT NOT '0' -- 1 (because '0' is turned into the integer 0, which is negated into 1) - return _SQLExpressionNot(self) - case .blob: - // We can't assume all blobs are true, and return false: - // - // SELECT NOT X'31' -- 0 (because X'31' is turned into the string '1', - // then into integer 1, which is negated into 0) - // SELECT NOT X'30' -- 1 (because X'30' is turned into the string '0', - // then into integer 0, which is negated into 1) - return _SQLExpressionNot(self) + + case .int64(let int64) where int64 == 0 || int64 == 1: + switch test { + case .true: + return (int64 == 1).sqlExpression + case .false, .falsey: + return (int64 == 0).sqlExpression + } + + default: + switch test { + case .true: + return _SQLExpressionEqual(.equal, self, true.sqlExpression) + case .false: + return _SQLExpressionEqual(.equal, self, false.sqlExpression) + case .falsey: + return _SQLExpressionNot(self) + } } } diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift index bc6aad488..df9f4582a 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -12,18 +12,6 @@ extension SQLExpression { // MARK: - _SQLExpressionNot -extension SQLExpression { - /// The default implementation returns the expression prefixed by `NOT`. - /// - /// let column = Column("favorite") - /// column.negated // NOT favorite - /// - /// :nodoc: - public var _negated: SQLExpression { - _SQLExpressionNot(self) - } -} - /// :nodoc: public struct _SQLExpressionNot: SQLExpression { let expression: SQLExpression @@ -32,6 +20,22 @@ public struct _SQLExpressionNot: SQLExpression { self.expression = expression } + /// :nodoc: + public func _is(_ test: _SQLBooleanTest) -> SQLExpression { + switch test { + case .true: + return self + + case .false: + // `(NOT expression) == 0` is equivalent to `expression` + return expression + + case .falsey: + // Support `NOT (NOT expression)` as a technique to build 0 or 1 + return _SQLExpressionNot(self) + } + } + /// :nodoc: public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { _SQLExpressionNot(expression._qualifiedExpression(with: alias)) @@ -99,13 +103,17 @@ struct SQLBinaryOperator: Hashable { /// The SQL for the negated operator, if any let negatedSQL: String? + /// Does the operator output a boolean value? + let isBoolean: Bool + /// Creates a binary operator /// - /// SQLBinaryOperator("-") - /// SQLBinaryOperator("IS", negated: "IS NOT") - init(_ sql: String, negated: String? = nil) { + /// SQLBinaryOperator("-", isBoolean: false) + /// SQLBinaryOperator("LIKE", negated: "NOT LIKE", isBoolean: true) + init(_ sql: String, negated: String? = nil, isBoolean: Bool) { self.sql = sql self.negatedSQL = negated + self.isBoolean = isBoolean } /// Returns the negated binary operator, if any @@ -116,32 +124,32 @@ struct SQLBinaryOperator: Hashable { guard let negatedSQL = negatedSQL else { return nil } - return SQLBinaryOperator(negatedSQL, negated: sql) + return SQLBinaryOperator(negatedSQL, negated: sql, isBoolean: isBoolean) } /// The `<` binary operator - static let lessThan = SQLBinaryOperator("<") + static let lessThan = SQLBinaryOperator("<", isBoolean: true) /// The `<=` binary operator - static let lessThanOrEqual = SQLBinaryOperator("<=") + static let lessThanOrEqual = SQLBinaryOperator("<=", isBoolean: true) /// The `>` binary operator - static let greaterThan = SQLBinaryOperator(">") + static let greaterThan = SQLBinaryOperator(">", isBoolean: true) /// The `>=` binary operator - static let greaterThanOrEqual = SQLBinaryOperator(">=") + static let greaterThanOrEqual = SQLBinaryOperator(">=", isBoolean: true) /// The `-` binary operator - static let subtract = SQLBinaryOperator("-") + static let subtract = SQLBinaryOperator("-", isBoolean: false) /// The `/` binary operator - static let divide = SQLBinaryOperator("/") + static let divide = SQLBinaryOperator("/", isBoolean: false) /// The `LIKE` binary operator - static let like = SQLBinaryOperator("LIKE") + static let like = SQLBinaryOperator("LIKE", negated: "NOT LIKE", isBoolean: true) /// The `MATCH` binary operator - static let match = SQLBinaryOperator("MATCH") + static let match = SQLBinaryOperator("MATCH", isBoolean: true) } /// _SQLExpressionBinary is an expression made of two expressions joined with a @@ -167,11 +175,28 @@ public struct _SQLExpressionBinary: SQLExpression { } /// :nodoc: - public var _negated: SQLExpression { - if let negatedOp = op.negated { - return _SQLExpressionBinary(negatedOp, lhs, rhs) - } else { - return _SQLExpressionNot(self) + public func _is(_ test: _SQLBooleanTest) -> SQLExpression { + switch test { + case .true: + if op.isBoolean { + return self + } else { + return _SQLExpressionEqual(.equal, self, true.sqlExpression) + } + case .false: + if let negatedOp = op.negated { + return _SQLExpressionBinary(negatedOp, lhs, rhs) + } else if op.isBoolean { + return _SQLExpressionNot(self) + } else { + return _SQLExpressionEqual(.equal, self, false.sqlExpression) + } + case .falsey: + if let negatedOp = op.negated { + return _SQLExpressionBinary(negatedOp, lhs, rhs) + } else { + return _SQLExpressionNot(self) + } } } @@ -380,8 +405,13 @@ public struct _SQLExpressionEqual: SQLExpression { } /// :nodoc: - public var _negated: SQLExpression { - _SQLExpressionEqual(op.negated, lhs, rhs) + public func _is(_ test: _SQLBooleanTest) -> SQLExpression { + switch test { + case .true: + return self + case .false, .falsey: + return _SQLExpressionEqual(op.negated, lhs, rhs) + } } /// :nodoc: @@ -416,8 +446,13 @@ public struct _SQLExpressionContains: SQLExpression { } /// :nodoc: - public var _negated: SQLExpression { - _SQLExpressionContains(expression, collection, negated: !isNegated) + public func _is(_ test: _SQLBooleanTest) -> SQLExpression { + switch test { + case .true: + return self + case .false, .falsey: + return _SQLExpressionContains(expression, collection, negated: !isNegated) + } } /// :nodoc: @@ -457,8 +492,13 @@ public struct _SQLExpressionBetween: SQLExpression { } /// :nodoc: - public var _negated: SQLExpression { - _SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated) + public func _is(_ test: _SQLBooleanTest) -> SQLExpression { + switch test { + case .true: + return self + case .false, .falsey: + return _SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated) + } } /// :nodoc: @@ -574,8 +614,13 @@ public struct _SQLExpressionIsEmpty: SQLExpression { } /// :nodoc: - public var _negated: SQLExpression { - _SQLExpressionIsEmpty(countExpression, isEmpty: !isEmpty) + public func _is(_ test: _SQLBooleanTest) -> SQLExpression { + switch test { + case .true: + return self + case .false, .falsey: + return _SQLExpressionIsEmpty(countExpression, isEmpty: !isEmpty) + } } /// :nodoc: @@ -626,6 +671,11 @@ public struct _SQLExpressionCollate: SQLExpression { self.collationName = collationName } + /// :nodoc: + public func _is(_ test: _SQLBooleanTest) -> SQLExpression { + _SQLExpressionCollate(expression._is(test), collationName: collationName) + } + /// :nodoc: public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { _SQLExpressionCollate(expression._qualifiedExpression(with: alias), collationName: collationName) diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 41a7540a0..b46110a4a 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -4,19 +4,34 @@ /// /// :nodoc: public protocol _SQLExpression { - /// Returns the expression, negated. This property fuels the `!` operator. + /// Performs a boolean test. /// - /// The default implementation returns the expression prefixed by `NOT`. + /// We generally distinguish four boolean values: /// - /// let column = Column("favorite") - /// column.negated // NOT favorite + /// 1. truthy: `filter(expression)` + /// 2. falsey: `filter(!expression)` + /// 3. true: `filter(expression == true)` + /// 4. false: `filter(expression == false)` /// - /// Some expressions may provide a custom implementation that returns a - /// more natural SQL expression. + /// They generally produce the following SQL: /// - /// let expression = [1,2,3].contains(Column("id")) // id IN (1,2,3) - /// expression.negated // id NOT IN (1,2,3) - var _negated: SQLExpression { get } + /// 1. truthy: `WHERE expression` + /// 2. falsey: `WHERE NOT expression` + /// 3. true: `WHERE expression = 1` + /// 4. false: `WHERE expression = 0` + /// + /// The "true" and "false" tests allow the SQLite query planner to + /// optimize indexed boolean columns. This is why it is important that the + /// user can explicitly use them. See https://github.com/groue/GRDB.swift/issues/816 + /// + /// This method is a customization point, so that some specific expressions + /// can produce idiomatic SQL. For example: + /// + /// - `column.like(pattern` -> `column LIKE pattern` + /// - `!(column.like(pattern)` -> `column NOT LIKE pattern` + /// - `(column.like(pattern) == true` -> `column LIKE pattern` + /// - `(column.like(pattern) == false` -> `column NOT LIKE pattern` + func _is(_ test: _SQLBooleanTest) -> SQLExpression /// Returns a qualified expression func _qualifiedExpression(with alias: TableAlias) -> SQLExpression @@ -29,6 +44,40 @@ public protocol _SQLExpression { /// described at https://www.sqlite.org/lang_expr.html public protocol SQLExpression: _SQLExpression, SQLSpecificExpressible, SQLSelectable, SQLOrderingTerm { } +/// `_SQLBooleanTest` supports boolean tests. +/// +/// See `SQLExpression._is(_:)` +/// +/// :nodoc: +public enum _SQLBooleanTest { + /// Fuels `expression == true` + case `true` + + /// Fuels `expression == false` + case `false` + + /// Fuels `!expression` + case falsey +} + +extension SQLExpression { + /// The default implementation of boolean tests. + /// + /// :nodoc: + public func _is(_ test: _SQLBooleanTest) -> SQLExpression { + switch test { + case .true: + return _SQLExpressionEqual(.equal, self, true.sqlExpression) + + case .false: + return _SQLExpressionEqual(.equal, self, false.sqlExpression) + + case .falsey: + return _SQLExpressionNot(self) + } + } +} + extension SQLExpression { /// :nodoc: public func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { diff --git a/GRDB/QueryInterface/SQL/SQLOperators.swift b/GRDB/QueryInterface/SQL/SQLOperators.swift index d6dbda147..475deee30 100644 --- a/GRDB/QueryInterface/SQL/SQLOperators.swift +++ b/GRDB/QueryInterface/SQL/SQLOperators.swift @@ -59,9 +59,9 @@ public func == (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpressi /// Column("validated") == false public func == (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression { if rhs { - return lhs.sqlExpression + return lhs.sqlExpression._is(.true) } else { - return lhs.sqlExpression._negated + return lhs.sqlExpression._is(.false) } } @@ -102,9 +102,9 @@ public func == (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpressi /// false == Column("validated") public func == (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression { if lhs { - return rhs.sqlExpression + return rhs.sqlExpression._is(.true) } else { - return rhs.sqlExpression._negated + return rhs.sqlExpression._is(.false) } } @@ -126,7 +126,7 @@ public func == (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// // name IS NOT NULL /// Column("name") != nil public func != (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { - isEqual(lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null)._negated + !(lhs == rhs) } /// An SQL expression that compares two expressions with the `<>` SQL operator. @@ -139,7 +139,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpress /// // name IS NOT NULL /// Column("name").collating(.nocase) != nil public func != (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpression { - _SQLExpressionCollate(lhs.expression != rhs, collationName: lhs.collationName) + !(lhs == rhs) } /// An SQL expression that checks the boolean value of an expression. @@ -152,11 +152,7 @@ public func != (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpressi /// // validated /// Column("validated") != false public func != (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression { - if rhs { - return lhs.sqlExpression._negated - } else { - return lhs.sqlExpression - } + !(lhs == rhs) } /// An SQL expression that compares two expressions with the `<>` SQL operator. @@ -169,7 +165,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression { /// // name IS NOT NULL /// nil != Column("name") public func != (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { - isEqual(lhs?.sqlExpression ?? DatabaseValue.null, rhs.sqlExpression)._negated + !(lhs == rhs) } /// An SQL expression that compares two expressions with the `<>` SQL operator. @@ -182,7 +178,7 @@ public func != (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpress /// // name IS NOT NULL /// nil != Column("name").collating(.nocase) public func != (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression { - _SQLExpressionCollate(lhs != rhs.expression, collationName: rhs.collationName) + !(lhs == rhs) } /// An SQL expression that checks the boolean value of an expression. @@ -195,11 +191,7 @@ public func != (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpressi /// // validated /// false != Column("validated") public func != (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression { - if lhs { - return rhs.sqlExpression._negated - } else { - return rhs.sqlExpression - } + !(lhs == rhs) } /// An SQL expression that compares two expressions with the `<>` SQL operator. @@ -207,7 +199,7 @@ public func != (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression { /// // email <> login /// Column("email") != Column("login") public func != (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - isEqual(lhs.sqlExpression, rhs.sqlExpression)._negated + !(lhs == rhs) } /// An SQL expression that compares two expressions with the `IS` SQL operator. @@ -259,7 +251,7 @@ public func === (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQ /// // name IS NOT 'Arthur' /// Column("name") !== "Arthur" public func !== (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { - _SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null) + !(lhs === rhs) } /// An SQL expression that compares two expressions with the `IS NOT` SQL operator. @@ -267,7 +259,7 @@ public func !== (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpres /// // name IS NOT 'Arthur' COLLATE NOCASE /// Column("name").collating(.nocase) !== "Arthur" public func !== (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpression { - _SQLExpressionCollate(lhs.expression !== rhs, collationName: lhs.collationName) + !(lhs === rhs) } /// An SQL expression that compares two expressions with the `IS NOT` SQL operator. @@ -275,11 +267,7 @@ public func !== (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpress /// // name IS NOT 'Arthur' /// "Arthur" !== Column("name") public func !== (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { - if let lhs = lhs { - return _SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs.sqlExpression) - } else { - return _SQLExpressionEqual(.isNot, rhs.sqlExpression, DatabaseValue.null) - } + !(lhs === rhs) } /// An SQL expression that compares two expressions with the `IS NOT` SQL operator. @@ -287,7 +275,7 @@ public func !== (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpres /// // name IS NOT 'Arthur' COLLATE NOCASE /// "Arthur" !== Column("name").collating(.nocase) public func !== (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression { - _SQLExpressionCollate(lhs !== rhs.expression, collationName: rhs.collationName) + !(lhs === rhs) } /// An SQL expression that compares two expressions with the `IS NOT` SQL operator. @@ -295,7 +283,7 @@ public func !== (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpress /// // email IS NOT login /// Column("email") !== Column("login") public func !== (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs.sqlExpression) + !(lhs === rhs) } // MARK: - Comparison Operators (<, >, <=, >=) @@ -726,7 +714,7 @@ public func || (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// // id NOT BETWEEN 1 AND 10 /// !((1...10).contains(Column("id"))) public prefix func ! (value: SQLSpecificExpressible) -> SQLExpression { - value.sqlExpression._negated + value.sqlExpression._is(.falsey) } // MARK: - Like Operator From 454b9d5546b8c02266b269f3579d56ab3dd64396 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 26 Jul 2020 14:19:46 +0200 Subject: [PATCH 04/10] More tests for boolean tests --- .../QueryInterfaceExpressionsTests.swift | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index 013123b0e..10ccc1c35 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -584,6 +584,25 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { sql(dbQueue, tableRequest.filter(Col.age != Col.age)), "SELECT * FROM \"readers\" WHERE \"age\" <> \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Col.age == 10))), + "SELECT * FROM \"readers\" WHERE \"age\" <> 10") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Col.age == (10 as Int?)))), + "SELECT * FROM \"readers\" WHERE \"age\" <> 10") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(10 == Col.age))), + "SELECT * FROM \"readers\" WHERE 10 <> \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!((10 as Int?) == Col.age))), + "SELECT * FROM \"readers\" WHERE 10 <> \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(10 == 10))), + "SELECT * FROM \"readers\" WHERE 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Col.age == Col.age))), + "SELECT * FROM \"readers\" WHERE \"age\" <> \"age\"") + XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.age != nil)), "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") @@ -600,6 +619,22 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { sql(dbQueue, tableRequest.filter(Col.age != Col.age)), "SELECT * FROM \"readers\" WHERE \"age\" <> \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Col.age == nil))), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Col.age == DatabaseValue.null))), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(nil == Col.age))), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(DatabaseValue.null == Col.age))), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Col.age == Col.age))), + "SELECT * FROM \"readers\" WHERE \"age\" <> \"age\"") + XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.name != "B")), "SELECT * FROM \"readers\" WHERE \"name\" <> 'B'") @@ -613,6 +648,19 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { sql(dbQueue, tableRequest.filter(Col.name != Col.name)), "SELECT * FROM \"readers\" WHERE \"name\" <> \"name\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Col.name == "B"))), + "SELECT * FROM \"readers\" WHERE \"name\" <> 'B'") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!("B" == Col.name))), + "SELECT * FROM \"readers\" WHERE 'B' <> \"name\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!("B" == "B"))), + "SELECT * FROM \"readers\" WHERE 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Col.name == Col.name))), + "SELECT * FROM \"readers\" WHERE \"name\" <> \"name\"") + XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.age != true)), "SELECT * FROM \"readers\" WHERE \"age\" <> 1") @@ -634,6 +682,28 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { XCTAssertEqual( sql(dbQueue, tableRequest.filter(true != false)), "SELECT * FROM \"readers\" WHERE 1") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Col.age == true))), + "SELECT * FROM \"readers\" WHERE \"age\" <> 1") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(true == Col.age))), + "SELECT * FROM \"readers\" WHERE \"age\" <> 1") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Col.age == false))), + "SELECT * FROM \"readers\" WHERE \"age\" <> 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(false == Col.age))), + "SELECT * FROM \"readers\" WHERE \"age\" <> 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(true == true))), + "SELECT * FROM \"readers\" WHERE 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(false == false))), + "SELECT * FROM \"readers\" WHERE 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(true == false))), + "SELECT * FROM \"readers\" WHERE 1") } func testNotEqualWithCollation() throws { @@ -1217,6 +1287,18 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.name.like("%foo"))), "SELECT * FROM \"readers\" WHERE \"name\" LIKE '%foo'") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!Col.name.like("%foo"))), + "SELECT * FROM \"readers\" WHERE \"name\" NOT LIKE '%foo'") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Col.name.like("%foo") == true)), + "SELECT * FROM \"readers\" WHERE \"name\" LIKE '%foo'") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Col.name.like("%foo") == false)), + "SELECT * FROM \"readers\" WHERE \"name\" NOT LIKE '%foo'") } From 843624044cb2e2b45170af2aed000988b753ad2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 26 Jul 2020 15:08:21 +0200 Subject: [PATCH 05/10] CHANGELOG --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0799e3e53..9412bf1cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -71,6 +71,8 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## Next Release - **New**: DatabasePool readers don't invalidate their database schema cache until schema is actually changed. +- **Breaking Change**: [#817](https://github.com/groue/GRDB.swift/pull/817): Allow query planner to optimize some boolean tests + ## 5.0.0-beta.9 From 474c2c3a766cbd096b10f70e01def520aacd09d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 26 Jul 2020 15:09:43 +0200 Subject: [PATCH 06/10] Thank you notice --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 993952f97..10279bbbe 100644 --- a/README.md +++ b/README.md @@ -7822,7 +7822,7 @@ Sample Code **Thanks** - [Pierlis](http://pierlis.com), where we write great software. -- [@alextrob](https://github.com/alextrob), [@bellebethcooper](https://github.com/bellebethcooper), [@bfad](https://github.com/bfad), [@cfilipov](https://github.com/cfilipov), [@charlesmchen-signal](https://github.com/charlesmchen-signal), [@Chiliec](https://github.com/Chiliec), [@chrisballinger](https://github.com/chrisballinger), [@darrenclark](https://github.com/darrenclark), [@davidkraus](https://github.com/davidkraus), [@fpillet](http://github.com/fpillet), [@GetToSet](https://github.com/GetToSet), [@gjeck](https://github.com/gjeck), [@gusrota](https://github.com/gusrota), [@haikusw](https://github.com/haikusw), [@hartbit](https://github.com/hartbit), [@kdubb](https://github.com/kdubb), [@kluufger](https://github.com/kluufger), [@KyleLeneau](https://github.com/KyleLeneau), [@Marus](https://github.com/Marus), [@MaxDesiatov](https://github.com/MaxDesiatov), [@michaelkirk-signal](https://github.com/michaelkirk-signal), [@mtancock](https://github.com/mtancock), [@pakko972](https://github.com/pakko972), [@peter-ss](https://github.com/peter-ss), [@pierlo](https://github.com/pierlo), [@pocketpixels](https://github.com/pocketpixels), [@robcas3](https://github.com/robcas3), [@runhum](https://github.com/runhum), [@schveiguy](https://github.com/schveiguy), [@SD10](https://github.com/SD10), [@sobri909](https://github.com/sobri909), [@sroddy](https://github.com/sroddy), [@swiftlyfalling](https://github.com/swiftlyfalling), [@Timac](https://github.com/Timac), [@valexa](https://github.com/valexa), and [@zmeyc](https://github.com/zmeyc) for their contributions, help, and feedback on GRDB. +- [@alextrob](https://github.com/alextrob), [@bellebethcooper](https://github.com/bellebethcooper), [@bfad](https://github.com/bfad), [@cfilipov](https://github.com/cfilipov), [@charlesmchen-signal](https://github.com/charlesmchen-signal), [@Chiliec](https://github.com/Chiliec), [@chrisballinger](https://github.com/chrisballinger), [@darrenclark](https://github.com/darrenclark), [@davidkraus](https://github.com/davidkraus), [@fpillet](http://github.com/fpillet), [@GetToSet](https://github.com/GetToSet), [@gjeck](https://github.com/gjeck), [@gusrota](https://github.com/gusrota), [@haikusw](https://github.com/haikusw), [@hartbit](https://github.com/hartbit), [@kdubb](https://github.com/kdubb), [@kluufger](https://github.com/kluufger), [@KyleLeneau](https://github.com/KyleLeneau), [@mallman](https://github.com/mallman), [@Marus](https://github.com/Marus), [@MaxDesiatov](https://github.com/MaxDesiatov), [@michaelkirk-signal](https://github.com/michaelkirk-signal), [@mtancock](https://github.com/mtancock), [@pakko972](https://github.com/pakko972), [@peter-ss](https://github.com/peter-ss), [@pierlo](https://github.com/pierlo), [@pocketpixels](https://github.com/pocketpixels), [@robcas3](https://github.com/robcas3), [@runhum](https://github.com/runhum), [@schveiguy](https://github.com/schveiguy), [@SD10](https://github.com/SD10), [@sobri909](https://github.com/sobri909), [@sroddy](https://github.com/sroddy), [@swiftlyfalling](https://github.com/swiftlyfalling), [@Timac](https://github.com/Timac), [@valexa](https://github.com/valexa), and [@zmeyc](https://github.com/zmeyc) for their contributions, help, and feedback on GRDB. - [@aymerick](https://github.com/aymerick) and [@kali](https://github.com/kali) because SQL. - [ccgus/fmdb](https://github.com/ccgus/fmdb) for its excellency. From 8cc82ae2b7d10003b60081bd3193a4734cb2ddc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 26 Jul 2020 15:16:19 +0200 Subject: [PATCH 07/10] Update migration guide --- Documentation/GRDB5MigrationGuide.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/Documentation/GRDB5MigrationGuide.md b/Documentation/GRDB5MigrationGuide.md index 5825ba706..563c2a281 100644 --- a/Documentation/GRDB5MigrationGuide.md +++ b/Documentation/GRDB5MigrationGuide.md @@ -461,6 +461,26 @@ let publisher = observation 13. Many types and methods that support the query builder used to be publicly exposed and flagged as experimental. They are now private, or renamed with an underscore prefix, which means they are not for public use. +14. Explicit boolean tests `expression == true` and `expression == false` generate different SQL: + + ```swift + // GRDB 4: SELECT * FROM player WHERE isActive + // GRDB 5: SELECT * FROM player WHERE isActive = 1 + Player.filter(Column("isActive") == true) + + // GRDB 4: SELECT * FROM player WHERE NOT isActive + // GRDB 5: SELECT * FROM player WHERE isActive = 0 + Player.filter(Column("isActive") == false) + + // GRDB 4 & 5: SELECT * FROM player WHERE isActive + Player.filter(Column("isActive")) + + // GRDB 4 & 5: SELECT * FROM player WHERE NOT isActive + Player.filter(!Column("isActive")) + ``` + + This change is innocuous for database boolean values that are `0`, `1`, or `NULL`. However, it is a breaking change for all other database values. + [ValueObservation]: ../README.md#valueobservation [DatabaseRegionObservation]: ../README.md#databaseregionobservation From 6ee7db48c8a0bbaa4988d4cb7fd8ac3673db3dca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 26 Jul 2020 16:04:02 +0200 Subject: [PATCH 08/10] Take care of indexes on expressions as well sqlite> create table t(a,b); sqlite> create index i on t(a like '%a', a, b); sqlite> explain query plan select * from t where a like '%a'; QUERY PLAN `--SCAN TABLE t sqlite> explain query plan select * from t where a not like '%a'; QUERY PLAN `--SCAN TABLE t sqlite> explain query plan select * from t where (a like '%a') = 1; QUERY PLAN `--SEARCH TABLE t USING COVERING INDEX i (=?) sqlite> explain query plan select * from t where (a like '%a') = 0; QUERY PLAN `--SEARCH TABLE t USING COVERING INDEX i (=?) --- .../SQL/SQLExpression+QueryInterface.swift | 75 +++++++++---------- .../QueryInterfaceExpressionsTests.swift | 4 +- 2 files changed, 39 insertions(+), 40 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift index df9f4582a..61be23e42 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -24,12 +24,11 @@ public struct _SQLExpressionNot: SQLExpression { public func _is(_ test: _SQLBooleanTest) -> SQLExpression { switch test { case .true: - return self + return _SQLExpressionEqual(.equal, self, true.sqlExpression) case .false: - // `(NOT expression) == 0` is equivalent to `expression` - return expression - + return _SQLExpressionEqual(.equal, self, false.sqlExpression) + case .falsey: // Support `NOT (NOT expression)` as a technique to build 0 or 1 return _SQLExpressionNot(self) @@ -103,17 +102,13 @@ struct SQLBinaryOperator: Hashable { /// The SQL for the negated operator, if any let negatedSQL: String? - /// Does the operator output a boolean value? - let isBoolean: Bool - /// Creates a binary operator /// - /// SQLBinaryOperator("-", isBoolean: false) - /// SQLBinaryOperator("LIKE", negated: "NOT LIKE", isBoolean: true) - init(_ sql: String, negated: String? = nil, isBoolean: Bool) { + /// SQLBinaryOperator("-") + /// SQLBinaryOperator("LIKE", negated: "NOT LIKE") + init(_ sql: String, negated: String? = nil) { self.sql = sql self.negatedSQL = negated - self.isBoolean = isBoolean } /// Returns the negated binary operator, if any @@ -124,32 +119,32 @@ struct SQLBinaryOperator: Hashable { guard let negatedSQL = negatedSQL else { return nil } - return SQLBinaryOperator(negatedSQL, negated: sql, isBoolean: isBoolean) + return SQLBinaryOperator(negatedSQL, negated: sql) } /// The `<` binary operator - static let lessThan = SQLBinaryOperator("<", isBoolean: true) + static let lessThan = SQLBinaryOperator("<") /// The `<=` binary operator - static let lessThanOrEqual = SQLBinaryOperator("<=", isBoolean: true) + static let lessThanOrEqual = SQLBinaryOperator("<=") /// The `>` binary operator - static let greaterThan = SQLBinaryOperator(">", isBoolean: true) + static let greaterThan = SQLBinaryOperator(">") /// The `>=` binary operator - static let greaterThanOrEqual = SQLBinaryOperator(">=", isBoolean: true) + static let greaterThanOrEqual = SQLBinaryOperator(">=") /// The `-` binary operator - static let subtract = SQLBinaryOperator("-", isBoolean: false) + static let subtract = SQLBinaryOperator("-") /// The `/` binary operator - static let divide = SQLBinaryOperator("/", isBoolean: false) + static let divide = SQLBinaryOperator("/") /// The `LIKE` binary operator - static let like = SQLBinaryOperator("LIKE", negated: "NOT LIKE", isBoolean: true) + static let like = SQLBinaryOperator("LIKE", negated: "NOT LIKE") /// The `MATCH` binary operator - static let match = SQLBinaryOperator("MATCH", isBoolean: true) + static let match = SQLBinaryOperator("MATCH") } /// _SQLExpressionBinary is an expression made of two expressions joined with a @@ -178,19 +173,11 @@ public struct _SQLExpressionBinary: SQLExpression { public func _is(_ test: _SQLBooleanTest) -> SQLExpression { switch test { case .true: - if op.isBoolean { - return self - } else { - return _SQLExpressionEqual(.equal, self, true.sqlExpression) - } + return _SQLExpressionEqual(.equal, self, true.sqlExpression) + case .false: - if let negatedOp = op.negated { - return _SQLExpressionBinary(negatedOp, lhs, rhs) - } else if op.isBoolean { - return _SQLExpressionNot(self) - } else { - return _SQLExpressionEqual(.equal, self, false.sqlExpression) - } + return _SQLExpressionEqual(.equal, self, false.sqlExpression) + case .falsey: if let negatedOp = op.negated { return _SQLExpressionBinary(negatedOp, lhs, rhs) @@ -408,8 +395,12 @@ public struct _SQLExpressionEqual: SQLExpression { public func _is(_ test: _SQLBooleanTest) -> SQLExpression { switch test { case .true: - return self - case .false, .falsey: + return _SQLExpressionEqual(.equal, self, true.sqlExpression) + + case .false: + return _SQLExpressionEqual(.equal, self, false.sqlExpression) + + case .falsey: return _SQLExpressionEqual(op.negated, lhs, rhs) } } @@ -449,8 +440,12 @@ public struct _SQLExpressionContains: SQLExpression { public func _is(_ test: _SQLBooleanTest) -> SQLExpression { switch test { case .true: - return self - case .false, .falsey: + return _SQLExpressionEqual(.equal, self, true.sqlExpression) + + case .false: + return _SQLExpressionEqual(.equal, self, false.sqlExpression) + + case .falsey: return _SQLExpressionContains(expression, collection, negated: !isNegated) } } @@ -495,8 +490,12 @@ public struct _SQLExpressionBetween: SQLExpression { public func _is(_ test: _SQLBooleanTest) -> SQLExpression { switch test { case .true: - return self - case .false, .falsey: + return _SQLExpressionEqual(.equal, self, true.sqlExpression) + + case .false: + return _SQLExpressionEqual(.equal, self, false.sqlExpression) + + case .falsey: return _SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated) } } diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index 10ccc1c35..e4e56d594 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -1294,11 +1294,11 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.name.like("%foo") == true)), - "SELECT * FROM \"readers\" WHERE \"name\" LIKE '%foo'") + "SELECT * FROM \"readers\" WHERE (\"name\" LIKE '%foo') = 1") XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.name.like("%foo") == false)), - "SELECT * FROM \"readers\" WHERE \"name\" NOT LIKE '%foo'") + "SELECT * FROM \"readers\" WHERE (\"name\" LIKE '%foo') = 0") } From 9529939262d713027bce810d83a89fa45ee6385b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 27 Jul 2020 06:40:18 +0200 Subject: [PATCH 09/10] Documentation --- GRDB/QueryInterface/SQL/SQLExpression.swift | 25 ++++++++++++++------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index b46110a4a..c89490b20 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -20,17 +20,26 @@ public protocol _SQLExpression { /// 3. true: `WHERE expression = 1` /// 4. false: `WHERE expression = 0` /// - /// The "true" and "false" tests allow the SQLite query planner to - /// optimize indexed boolean columns. This is why it is important that the - /// user can explicitly use them. See https://github.com/groue/GRDB.swift/issues/816 + /// The `= 1` and `= 0` tests allow the SQLite query planner to + /// optimize queries with indices on boolean columns and expressions. + /// See https://github.com/groue/GRDB.swift/issues/816 /// /// This method is a customization point, so that some specific expressions - /// can produce idiomatic SQL. For example: + /// can produce idiomatic SQL. /// - /// - `column.like(pattern` -> `column LIKE pattern` - /// - `!(column.like(pattern)` -> `column NOT LIKE pattern` - /// - `(column.like(pattern) == true` -> `column LIKE pattern` - /// - `(column.like(pattern) == false` -> `column NOT LIKE pattern` + /// For example, the `like(_)` expression: + /// + /// - `column.like(pattern)` -> `column LIKE pattern` + /// - `!(column.like(pattern))` -> `column NOT LIKE pattern` + /// - `column.like(pattern) == true` -> `(column LIKE pattern) = 1` + /// - `column.like(pattern) == false` -> `(column LIKE pattern) = 0` + /// + /// Another example, the `isEmpty` association aggregate: + /// + /// - `association.isEmpty` -> `COUNT(child.id) = 0` + /// - `!association.isEmpty` -> `COUNT(child.id) > 0` + /// - `association.isEmpty == true` -> `COUNT(child.id) = 0` + /// - `association.isEmpty == false` -> `COUNT(child.id) > 0` func _is(_ test: _SQLBooleanTest) -> SQLExpression /// Returns a qualified expression From 7b788e39882314a45cf493467997247ef71211b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 30 Jul 2020 08:29:27 +0200 Subject: [PATCH 10/10] v5.0.0-beta.10 --- CHANGELOG.md | 10 ++++++++- Documentation/FullTextSearch.md | 4 ++-- Documentation/Migrations.md | 2 +- GRDB.swift.podspec | 2 +- Makefile | 6 +++--- README.md | 38 ++++++++++++++++----------------- Support/Info.plist | 2 +- 7 files changed, 36 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9412bf1cf..39bf91b70 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-beta.3](#500-beta3) | [5.0.0-beta.4](#500-beta4) | [5.0.0-beta.5](#500-beta5) | [5.0.0-beta.6](#500-beta6) | [5.0.0-beta.7](#500-beta7) | [5.0.0-beta.8](#500-beta8) | [5.0.0-beta.9](#500-beta9) +- `5.0.0` Betas - [5.0.0-beta](#500-beta) | [5.0.0-beta.2](#500-beta2) | [5.0.0-beta.3](#500-beta3) | [5.0.0-beta.4](#500-beta4) | [5.0.0-beta.5](#500-beta5) | [5.0.0-beta.6](#500-beta6) | [5.0.0-beta.7](#500-beta7) | [5.0.0-beta.8](#500-beta8) | [5.0.0-beta.9](#500-beta9) | [5.0.0-beta.10](#500-beta10) #### 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.10 + +Released July 30, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta.9...v5.0.0-beta.10) - **New**: DatabasePool readers don't invalidate their database schema cache until schema is actually changed. - **Breaking Change**: [#817](https://github.com/groue/GRDB.swift/pull/817): Allow query planner to optimize some boolean tests diff --git a/Documentation/FullTextSearch.md b/Documentation/FullTextSearch.md index fcd577ebf..411f66cfa 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.9/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.10/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.9/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.10/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index 0c74aeff9..abfb12f85 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.9/Structs/DatabaseMigrator.html) for more migrator methods. +See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.10/Structs/DatabaseMigrator.html) for more migrator methods. ## The `eraseDatabaseOnSchemaChange` Option diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 3a6711b7f..a9c0ea198 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.9' + s.version = '5.0.0-beta.10' 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 f2c52f236..cc08a5c96 100644 --- a/Makefile +++ b/Makefile @@ -408,10 +408,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.9 \ - --module-version 5.0.0-beta.9 \ + --github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.0.0-beta.10 \ + --module-version 5.0.0-beta.10 \ --module GRDB \ - --root-url http://groue.github.io/GRDB.swift/docs/5.0.0-beta.9/ \ + --root-url http://groue.github.io/GRDB.swift/docs/5.0.0-beta.10/ \ --output Documentation/Reference \ --xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS else diff --git a/README.md b/README.md index 10279bbbe..0f9c8648b 100644 --- a/README.md +++ b/README.md @@ -11,13 +11,13 @@ --- -**Latest release**: July 23, 2020 • version 5.0.0-beta.9 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) +**Latest release**: July 30, 2020 • version 5.0.0-beta.10 • [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.9**, [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0)| +| **Swift 5.2** | **v5.0.0-beta.10**, [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) | @@ -278,7 +278,7 @@ Documentation #### Reference -- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.9/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) +- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.10/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) #### Getting Started @@ -480,7 +480,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.9/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.10/Structs/Configuration.html) for more details. ## Database Pools @@ -560,7 +560,7 @@ let dbPool = try DatabasePool( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.9/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.10/Structs/Configuration.html) for more details. Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information. @@ -620,7 +620,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.9/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.10/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. @@ -823,7 +823,7 @@ try dbQueue.read { db in - **Cursors are granted with direct access to SQLite,** unlike arrays and sets that have to take the time to copy database values. If you look after extra performance, you may prefer cursors. -- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.9/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.10/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: ```swift // Prints all Github links @@ -906,7 +906,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.9/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.10/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: @@ -1191,7 +1191,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.9/Structs/StatementArguments.html): +Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.10/Structs/StatementArguments.html): ```swift let url: URL = ... @@ -1598,7 +1598,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.9/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.10/Structs/Configuration.html) configuration flag: ```swift // fatal error: A transaction has been left opened at the end of a database access @@ -1712,7 +1712,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.9/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.10/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). ```swift updateStatement.arguments = ["name": "Arthur", "score": 1000] @@ -2476,7 +2476,7 @@ try Place.fetchSet(db, sql: "SELECT ...", arguments:...) // Set try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place? ``` -See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.9/Structs/StatementArguments.html) for more information about the query arguments. +See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.10/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()`. @@ -2857,7 +2857,7 @@ protocol EncodableRecord { } ``` -See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.9/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.9/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.9/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. +See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.10/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.10/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.10/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). @@ -4255,7 +4255,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.9/Structs/StatementArguments.html): +Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.10/Structs/StatementArguments.html): ```swift // SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate) @@ -4911,7 +4911,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.9/Structs/AnyFetchRequest.html): a type-erased request. +- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.10/Structs/AnyFetchRequest.html): a type-erased request. ## Joined Queries Support @@ -6071,7 +6071,7 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan ### DatabaseRegion -**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.9/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.10/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. @@ -6081,7 +6081,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.9/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). +For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.10/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). #### The DatabaseRegionConvertible Protocol @@ -7178,7 +7178,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.9/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.9/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.10/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.10/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: @@ -7909,4 +7909,4 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv [Sharing a Database]: Documentation/SharingADatabase.md [FAQ]: #faq [Database Observation]: #database-changes-observation -[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.0.0-beta.9/Structs/SQLRequest.html +[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.0.0-beta.10/Structs/SQLRequest.html diff --git a/Support/Info.plist b/Support/Info.plist index 9dd0315ef..b91f94ad0 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 5.0.0-beta.9 + 5.0.0-beta.10 CFBundleSignature ???? CFBundleVersion