From b715206502decb7acc46203762587c363306051f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 Dec 2020 16:05:12 +0100 Subject: [PATCH 01/20] Row values --- GRDB.xcodeproj/project.pbxproj | 10 +++++++ .../SQL/SQLExpressionVisitor.swift | 2 ++ GRDB/QueryInterface/SQL/SQLRowValue.swift | 28 +++++++++++++++++++ .../SQLExpressionGenerator.swift | 7 +++++ .../SQLGeneration/SQLOrderingGenerator.swift | 6 +++- .../SQLGeneration/SQLQueryGenerator.swift | 24 ++++++++++++++++ .../SQLSelectableCountGenerator.swift | 4 +++ .../SQLSelectableResultColumnGenerator.swift | 4 +++ GRDBCustom.xcodeproj/project.pbxproj | 6 ++++ 9 files changed, 90 insertions(+), 1 deletion(-) create mode 100644 GRDB/QueryInterface/SQL/SQLRowValue.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index a141298f8..143118fa3 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -821,6 +821,10 @@ 56D51D001EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; 56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; 56D51D061EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; + 56D8B3FF257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */; }; + 56D8B400257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */; }; + 56D8B401257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */; }; + 56D8B402257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */; }; 56D91AA22205E03700770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA12205E03700770D8D /* SQLRelation.swift */; }; 56D91AA32205E03700770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA12205E03700770D8D /* SQLRelation.swift */; }; 56D91AA42205E03700770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA12205E03700770D8D /* SQLRelation.swift */; }; @@ -1621,6 +1625,7 @@ 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectable.swift; sourceTree = ""; }; 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = ""; }; + 56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRowValue.swift; sourceTree = ""; }; 56D91AA12205E03700770D8D /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = ""; }; 56D91AA82205F2F000770D8D /* DatabasePromise.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePromise.swift; sourceTree = ""; }; 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQuery.swift; sourceTree = ""; }; @@ -2125,6 +2130,7 @@ 56F34FE024B0E915007513FC /* SQLOrderingTermVisitor.swift */, 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */, 56D91AA12205E03700770D8D /* SQLRelation.swift */, + 56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */, 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */, 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */, 56F34FC824B0DD6A007513FC /* SQLSelectableVisitor.swift */, @@ -3063,6 +3069,7 @@ 565490D61D5AE252005622CB /* StandardLibrary.swift in Sources */, 565490B81D5AE236005622CB /* DatabaseError.swift in Sources */, 56DAA2E11DE9C827006E10C8 /* Cursor.swift in Sources */, + 56D8B401257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */, 5653EB0520944C7C00F46237 /* BelongsToAssociation.swift in Sources */, 5644DE6F20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */, 56A2FA3C24424F4800E97D23 /* Export.swift in Sources */, @@ -3210,6 +3217,7 @@ 5653EB0D20944C7C00F46237 /* HasManyAssociation.swift in Sources */, 567ECE502222E431009245CA /* GRDB-5.0.swift in Sources */, 566AD8B51D5318F4002EC1A8 /* TableDefinition.swift in Sources */, + 56D8B400257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */, 5698AD241DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 56FBFED92210731A00945324 /* SQLRequest.swift in Sources */, 5644DE6E20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */, @@ -3808,6 +3816,7 @@ AAA4DCD2230F1E0600C74B15 /* HasManyAssociation.swift in Sources */, AAA4DCD3230F1E0600C74B15 /* GRDB-5.0.swift in Sources */, AAA4DCD4230F1E0600C74B15 /* TableDefinition.swift in Sources */, + 56D8B402257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */, AAA4DCD5230F1E0600C74B15 /* FTS5WrapperTokenizer.swift in Sources */, AAA4DCD6230F1E0600C74B15 /* SQLRequest.swift in Sources */, AAA4DCD7230F1E0600C74B15 /* DatabaseValueConversion.swift in Sources */, @@ -4180,6 +4189,7 @@ 56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, 56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */, 563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */, + 56D8B3FF257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */, 564CE43121AA901800652B19 /* ValueObserver.swift in Sources */, 5605F1651C672E4000235C62 /* NSNull.swift in Sources */, 56CEB5191EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, diff --git a/GRDB/QueryInterface/SQL/SQLExpressionVisitor.swift b/GRDB/QueryInterface/SQL/SQLExpressionVisitor.swift index 6101369be..24d99821a 100644 --- a/GRDB/QueryInterface/SQL/SQLExpressionVisitor.swift +++ b/GRDB/QueryInterface/SQL/SQLExpressionVisitor.swift @@ -3,6 +3,8 @@ public protocol _SQLExpressionVisitor: _FetchRequestVisitor { mutating func visit(_ dbValue: DatabaseValue) throws mutating func visit(_ column: Column) throws mutating func visit(_ column: _SQLQualifiedColumn) throws + /// - precondition: expr.expressions.count > 1 + mutating func visit(_ expr: _SQLRowValue) throws mutating func visit(_ expr: _SQLExpressionBetween) throws mutating func visit(_ expr: _SQLExpressionBinary) throws /// - precondition: expr.expressions.count > 1 diff --git a/GRDB/QueryInterface/SQL/SQLRowValue.swift b/GRDB/QueryInterface/SQL/SQLRowValue.swift new file mode 100644 index 000000000..b386f3a2c --- /dev/null +++ b/GRDB/QueryInterface/SQL/SQLRowValue.swift @@ -0,0 +1,28 @@ +/// A [row value](https://www.sqlite.org/rowvalue.html). +/// +/// :nodoc: +public struct _SQLRowValue: SQLExpression { + let expressions: [SQLExpression] + + /// SQLite row values were shipped in SQLite 3.15: + /// https://www.sqlite.org/releaselog/3_15_0.html + public /* public for tests */ static let isAvailable = (sqlite3_libversion_number() >= 3015000) + + /// - precondition: `expressions` is not empty + init(_ expressions: [SQLExpression]) { + assert(!expressions.isEmpty) + self.expressions = expressions + } + + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + _SQLRowValue(expressions.map { $0._qualifiedExpression(with: alias) }) + } + + public func _accept(_ visitor: inout Visitor) throws { + if let expression = expressions.first, expressions.count == 1 { + try expression._accept(&visitor) + } else { + try visitor.visit(self) + } + } +} diff --git a/GRDB/QueryInterface/SQLGeneration/SQLExpressionGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLExpressionGenerator.swift index f9f1b09c4..0321cb9ae 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLExpressionGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLExpressionGenerator.swift @@ -41,6 +41,13 @@ private struct SQLExpressionGenerator: _SQLExpressionVisitor { resultSQL += column.name.quotedDatabaseIdentifier } + mutating func visit(_ expr: _SQLRowValue) throws { + let values = try expr + .expressions + .map { try $0.expressionSQL(context, wrappedInParenthesis: false) } + resultSQL = "(\(values.joined(separator: ", ")))" + } + mutating func visit(_ expr: _SQLExpressionBetween) throws { resultSQL = try """ \(expr.expression.expressionSQL(context, wrappedInParenthesis: true)) \ diff --git a/GRDB/QueryInterface/SQLGeneration/SQLOrderingGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLOrderingGenerator.swift index cf161f103..75efa42d1 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLOrderingGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLOrderingGenerator.swift @@ -36,7 +36,7 @@ private struct SQLOrderingGenerator: _SQLOrderingTermVisitor { mutating func visit(_ ordering: _SQLOrderingLiteral) throws { resultSQL = try ordering.sqlLiteral.sql(context) } - + // MARK: - _SQLExpressionVisitor mutating func visit(_ expr: DatabaseValue) throws { @@ -51,6 +51,10 @@ private struct SQLOrderingGenerator: _SQLOrderingTermVisitor { resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) } + mutating func visit(_ expr: _SQLRowValue) throws { + resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) + } + mutating func visit(_ expr: _SQLExpressionBetween) throws { resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 501ae3ad5..7631a9217 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -870,6 +870,10 @@ private struct SQLExpressionIsTrue: _SQLExpressionVisitor { try setFalse() } + mutating func visit(_ expr: _SQLRowValue) throws { + try setFalse() + } + mutating func visit(_ expr: _SQLExpressionBetween) throws { try setFalse() } @@ -995,6 +999,12 @@ private struct SQLExpressionIsConstantInRequest: _SQLExpressionVisitor { try setNotConstant() } + mutating func visit(_ expr: _SQLRowValue) throws { + for expression in expr.expressions { + try expression._accept(&self) + } + } + mutating func visit(_ expr: _SQLExpressionBetween) throws { try expr.expression._accept(&self) try expr.lowerBound._accept(&self) @@ -1139,6 +1149,8 @@ private struct SQLTableColumnVisitor: _SQLExpressionVisitor { } } + mutating func visit(_ expr: _SQLRowValue) throws { } + mutating func visit(_ expr: _SQLExpressionBetween) throws { } mutating func visit(_ expr: _SQLExpressionBinary) throws { @@ -1243,6 +1255,7 @@ extension SQLExpression { } } +#warning("TODO: what should we do with _SQLRowValue? (a, b) == (1, 2) for example?") /// Support for `SQLExpression.identifyingColums(_:for:)` private struct SQLIdentifyingColumns: _SQLExpressionVisitor { struct BreakError: Error { } @@ -1256,6 +1269,8 @@ private struct SQLIdentifyingColumns: _SQLExpressionVisitor { mutating func visit(_ column: _SQLQualifiedColumn) throws { } + mutating func visit(_ expr: _SQLRowValue) throws { } + mutating func visit(_ expr: _SQLExpressionBetween) throws { } mutating func visit(_ expr: _SQLExpressionBinary) throws { } @@ -1353,6 +1368,7 @@ extension SQLExpression { } } +#warning("TODO: what should we do with _SQLRowValue? (a, b) == (1, 2) for example?") /// Support for `SQLExpression.identifyingRowIDs(_:for:)` private struct SQLIdentifyingRowIDs: _SQLExpressionVisitor { let db: Database @@ -1369,6 +1385,8 @@ private struct SQLIdentifyingRowIDs: _SQLExpressionVisitor { mutating func visit(_ column: _SQLQualifiedColumn) throws { } + mutating func visit(_ expr: _SQLRowValue) throws { } + mutating func visit(_ expr: _SQLExpressionBetween) throws { } mutating func visit(_ expr: _SQLExpressionBinary) throws { } @@ -1525,6 +1543,12 @@ private struct SQLSelectableIsAggregate: _SQLSelectableVisitor { mutating func visit(_ selectable: _SQLQualifiedAllColumns) throws { } + mutating func visit(_ expr: _SQLRowValue) throws { + for expression in expr.expressions { + try expression._accept(&self) + } + } + mutating func visit(_ selectable: _SQLSelectionLiteral) throws { // Don't know - assume not an aggregate } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLSelectableCountGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLSelectableCountGenerator.swift index a4c1e7bb3..18c82f09d 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLSelectableCountGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLSelectableCountGenerator.swift @@ -60,6 +60,10 @@ private struct SQLSelectableCountGenerator: _SQLSelectableVisitor { resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) } + mutating func visit(_ expr: _SQLRowValue) throws { + resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) + } + mutating func visit(_ expr: _SQLExpressionBetween) throws { resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLSelectableResultColumnGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLSelectableResultColumnGenerator.swift index 2a5c330d6..1b9d0d2a1 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLSelectableResultColumnGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLSelectableResultColumnGenerator.swift @@ -59,6 +59,10 @@ private struct SQLSelectableResultColumnGenerator: _SQLSelectableVisitor { resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) } + mutating func visit(_ expr: _SQLRowValue) throws { + resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) + } + mutating func visit(_ expr: _SQLExpressionBetween) throws { resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) } diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index b5295f03f..44755329d 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -487,6 +487,8 @@ 56D507651F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; 56D51D021EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; 56D51D051EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; + 56D8B40D257D0FBE008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B40B257D0FBE008AA1F7 /* SQLRowValue.swift */; }; + 56D8B40E257D0FBE008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B40B257D0FBE008AA1F7 /* SQLRowValue.swift */; }; 56DAA2D51DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D91DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2DD1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; }; @@ -1105,6 +1107,7 @@ 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS4.swift; sourceTree = ""; }; 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = ""; }; + 56D8B40B257D0FBE008AA1F7 /* SQLRowValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRowValue.swift; sourceTree = ""; }; 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCursorTests.swift; sourceTree = ""; }; 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Cursor.swift; sourceTree = ""; }; 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = ""; }; @@ -1604,6 +1607,7 @@ 56F34FE524B0E94C007513FC /* SQLOrderingTermVisitor.swift */, 5656A8502295BD56001FF3FF /* SQLQuery.swift */, 5656A84E2295BD56001FF3FF /* SQLRelation.swift */, + 56D8B40B257D0FBE008AA1F7 /* SQLRowValue.swift */, 5656A8492295BD56001FF3FF /* SQLSelectable.swift */, 5656A84F2295BD56001FF3FF /* SQLSelectable+QueryInterface.swift */, 56F34FCD24B0DE0B007513FC /* SQLSelectableVisitor.swift */, @@ -2415,6 +2419,7 @@ F3BA80331CFB28A4003DC1BA /* PersistableRecord.swift in Sources */, 5656A8802295BD56001FF3FF /* SQLForeignKeyRequest.swift in Sources */, 56B964BE1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, + 56D8B40E257D0FBE008AA1F7 /* SQLRowValue.swift in Sources */, 561408A1221596A100DAD589 /* GRDB-5.0.swift in Sources */, F3BA80211CFB288C003DC1BA /* NSNull.swift in Sources */, 56FBFED72210731100945324 /* SQLRequest.swift in Sources */, @@ -2787,6 +2792,7 @@ F3BA808F1CFB2E7A003DC1BA /* PersistableRecord.swift in Sources */, 5656A87F2295BD56001FF3FF /* SQLForeignKeyRequest.swift in Sources */, 56B964BB1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, + 56D8B40D257D0FBE008AA1F7 /* SQLRowValue.swift in Sources */, 561408A0221596A100DAD589 /* GRDB-5.0.swift in Sources */, F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */, 56FBFED62210731100945324 /* SQLRequest.swift in Sources */, From b70f85d94b06d46f3f2678206fcaf40472c1aa1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 Dec 2020 16:39:46 +0100 Subject: [PATCH 02/20] Fix #871 --- GRDB/QueryInterface/SQL/SQLAssociation.swift | 7 +- GRDB/QueryInterface/SQL/SQLRelation.swift | 9 ++ .../SQLPreparedRequestGenerator.swift | 147 +++++++++++++----- .../AssociationPrefetchingRowTests.swift | 49 ++++++ .../AssociationPrefetchingSQLTests.swift | 8 +- 5 files changed, 176 insertions(+), 44 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLAssociation.swift b/GRDB/QueryInterface/SQL/SQLAssociation.swift index ac10c45df..0e135682c 100644 --- a/GRDB/QueryInterface/SQL/SQLAssociation.swift +++ b/GRDB/QueryInterface/SQL/SQLAssociation.swift @@ -123,12 +123,7 @@ public struct _SQLAssociation { // children are useless: let relation = step.relation .selectOnly([]) - .filteringChildren({ - switch $0.kind { - case .allPrefetched, .allNotPrefetched: return false - case .oneRequired, .oneOptional: return true - } - }) + .removingChildrenForPrefetchedAssociations() // Don't interfere with user-defined keys that could be added later let key = step.key.map(\.baseName) { "grdb_\($0)" } diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 6f260e99e..8516de8a1 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -365,6 +365,15 @@ extension SQLRelation { func filteringChildren(_ included: (Child) throws -> Bool) rethrows -> Self { try map(\.children) { try $0.filter { try included($1) } } } + + func removingChildrenForPrefetchedAssociations() -> Self { + filteringChildren { + switch $0.kind { + case .allPrefetched, .allNotPrefetched: return false + case .oneRequired, .oneOptional: return true + } + } + } } extension SQLRelation: _JoinableRequest { diff --git a/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift index e17c486bb..4c83d51d7 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift @@ -87,7 +87,7 @@ private struct SQLPreparedRequestGenerator: _FetchRequestVisitor { if associations.isEmpty == false { // Eager loading of prefetched associations preparedRequest = preparedRequest.with(\.supplementaryFetch) { db, rows in - try prefetch(db, associations: associations, in: rows) + try prefetch(db, associations: associations, into: rows, from: request) } } self.preparedRequest = preparedRequest @@ -135,8 +135,23 @@ private struct SQLRequestCounter: _FetchRequestVisitor { // MARK: - Eager loading of hasMany associations // CAUTION: Keep this code in sync with prefetchedRegion(_:_:) -/// Append rows from prefetched associations into the argument rows. -private func prefetch(_ db: Database, associations: [_SQLAssociation], in rows: [Row]) throws { +/// Append rows from prefetched associations into the `rows` argument. +/// +/// - parameter db: A database connection. +/// - parameter associations: Prefetched associations. +/// - parameter baseRows: The rows that need to be extended with prefetched rows. +/// - parameter query: The query that was used to fetch `rows`. +private func prefetch( + _ db: Database, + associations: [_SQLAssociation], + into baseRows: [Row], + from baseRequest: QueryInterfaceRequest) throws +{ + guard let firstBaseRow = baseRows.first else { + // No rows -> no prefetch + return + } + for association in associations { switch association.pivot.condition { case .expression: @@ -148,24 +163,104 @@ private func prefetch(_ db: Database, associations: [_SQLAssociation], in rows: let pivotMapping = try foreignKeyRequest .fetchForeignKeyMapping(db) .joinMapping(originIsLeft: originIsLeft) - try prefetch(db, association: association, pivotMapping: pivotMapping, in: rows) + let pivotColumns = pivotMapping.map(\.right) + let leftColumns = pivotMapping.map(\.left) + + // We want to avoid the "Expression tree is too large" SQLite error + // when there are many base rows: + // https://github.com/groue/GRDB.swift/issues/871 + // + // To this end, we do not inject any value from the base rows in + // the prefetch request. Instead, we directly inject the base + // request as a common table expression (CTE). + // + // This is only useful for compound foreign keys. And we need + // row values (https://www.sqlite.org/rowvalue.html). So we have + // a backup plan which does not uses any CTE. + let usesCommonTableExpression = pivotMapping.count > 1 && _SQLRowValue.isAvailable + + let prefetchRequest: QueryInterfaceRequest + if usesCommonTableExpression { + // HasMany: Author.including(all: Author.books) + // + // WITH grdb_base AS (SELECT a, b FROM author) + // SELECT book.*, book.authorId AS grdb_authorId + // FROM book + // WHERE (book.a, book.b) IN (SELECT * FROM grdb_base) + // + // HasManyThrough: Citizen.including(all: Citizen.countries) + // + // WITH grdb_base AS (SELECT a, b FROM citizen) + // SELECT country.*, passport.citizenId AS grdb_citizenId + // FROM country + // JOIN passport ON passport.countryCode = country.code + // AND (passport.a, passport.b) IN (SELECT * FROM grdb_base) + let baseRequest = baseRequest.map(\.query.relation) { baseRelation in + // Ordering and including(all:) children are + // useless, and we only need pivoting columns: + baseRelation + .unordered() + .removingChildrenForPrefetchedAssociations() + .selectOnly(leftColumns.map(Column.init)) + } + let baseCTE = CommonTableExpression( + named: "grdb_base", + request: baseRequest) + let pivotFilter = baseCTE.all().contains(_SQLRowValue(pivotColumns.map(Column.init))) + + prefetchRequest = makePrefetchRequest( + for: association, + filteringPivotWith: pivotFilter, + annotatedWith: pivotColumns) + .with(baseCTE) + } else { + // HasMany: Author.including(all: Author.books) + // + // SELECT *, authorId AS grdb_authorId + // FROM book + // WHERE authorId IN (1, 2, 3) + // + // HasManyThrough: Citizen.including(all: Citizen.countries) + // + // SELECT country.*, passport.citizenId AS grdb_citizenId + // FROM country + // JOIN passport ON passport.countryCode = country.code + // AND passport.citizenId IN (1, 2, 3) + let pivotFilter = pivotMapping.joinExpression(leftRows: baseRows) + + prefetchRequest = makePrefetchRequest( + for: association, + filteringPivotWith: pivotFilter, + annotatedWith: pivotColumns) + } + + let prefetchedRows = try prefetchRequest.fetchAll(db) + let prefetchedGroups = prefetchedRows.grouped(byDatabaseValuesOnColumns: pivotColumns.map { "grdb_\($0)" }) + let groupingIndexes = firstBaseRow.indexes(forColumns: leftColumns) + + for row in baseRows { + let groupingKey = groupingIndexes.map { row.impl.databaseValue(atUncheckedIndex: $0) } + let prefetchedRows = prefetchedGroups[groupingKey, default: []] + row.prefetchedRows.setRows(prefetchedRows, forKeyPath: association.keyPath) + } } } } -// CAUTION: Keep this code in sync with prefetchedRegion(_:_:) -private func prefetch( - _ db: Database, - association: _SQLAssociation, - pivotMapping: JoinMapping, - in rows: [Row]) throws +/// Returns a request for prefetched rows. +/// +/// - parameter assocciation: The prefetched association. +/// - parameter pivotFilter: The expression that filters the pivot of +/// the association. +/// - parameter pivotColumns: The pivot columns that annotate the +/// returned request. +func makePrefetchRequest( + for association: _SQLAssociation, + filteringPivotWith pivotFilter: SQLExpression, + annotatedWith pivotColumns: [String]) +-> QueryInterfaceRequest { - guard let firstRow = rows.first else { - // No rows -> no prefetch - return - } - - // Annotate prefetched rows with pivot columns, so that we can + // We annotate prefetched rows with pivot columns, so that we can // group them. // // Those pivot columns are necessary when we prefetch @@ -186,32 +281,14 @@ private func prefetch( // // FROM book // // WHERE authorId IN (1, 2, 3) // Author.including(all: Author.books) - - let pivotFilter = pivotMapping.joinExpression(leftRows: rows) - - let pivotColumns = pivotMapping.map(\.right) - let pivotAlias = TableAlias() let prefetchRelation = association .map(\.pivot.relation, { $0.qualified(with: pivotAlias).filter(pivotFilter) }) .destinationRelation() - // Annotate with the pivot columns that allow grouping .annotated(with: pivotColumns.map { pivotAlias[$0].forKey("grdb_\($0)") }) - let prefetchRequest = QueryInterfaceRequest(relation: prefetchRelation) - - let prefetchedRows = try prefetchRequest.fetchAll(db) - - let prefetchedGroups = prefetchedRows.grouped(byDatabaseValuesOnColumns: pivotColumns.map { "grdb_\($0)" }) - - let groupingIndexes = firstRow.indexes(forColumns: pivotMapping.map(\.left)) - - for row in rows { - let groupingKey = groupingIndexes.map { row.impl.databaseValue(atUncheckedIndex: $0) } - let prefetchedRows = prefetchedGroups[groupingKey, default: []] - row.prefetchedRows.setRows(prefetchedRows, forKeyPath: association.keyPath) - } + return QueryInterfaceRequest(relation: prefetchRelation) } // CAUTION: Keep this code in sync with prefetch(_:associations:in:) diff --git a/Tests/GRDBTests/AssociationPrefetchingRowTests.swift b/Tests/GRDBTests/AssociationPrefetchingRowTests.swift index ea1c82a20..5cab99c6d 100644 --- a/Tests/GRDBTests/AssociationPrefetchingRowTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingRowTests.swift @@ -1138,4 +1138,53 @@ class AssociationPrefetchingRowTests: GRDBTestCase { XCTAssertEqual(row3.prefetchedRows["bs"], []) } } + + // Regression test for https://github.com/groue/GRDB.swift/issues/871 + func testCompoundColumnLimit() throws { + struct Parent: Encodable, PersistableRecord { + let a: Int + let b: Int + static let children = hasMany(Child.self) + } + + struct Child: Encodable, PersistableRecord { + let a: Int + let b: Int + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parent") { t in + t.column("a", .integer).notNull() + t.column("b", .integer).notNull() + t.primaryKey(["a", "b"]) + } + + try db.create(table: "child") { t in + t.column("a", .integer).notNull() + t.column("b", .integer).notNull() + t.foreignKey(["a", "b"], references: "parent") + } + + let count = Int(sqlite3_limit(db.sqliteConnection, SQLITE_LIMIT_EXPR_DEPTH, -1)) + for index in 0.. Date: Sun, 6 Dec 2020 18:00:29 +0100 Subject: [PATCH 03/20] Document TODOs with row values --- GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 7631a9217..35e82c10c 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -1242,6 +1242,10 @@ extension SQLExpression { /// WHERE a = 1 OR a = 2 -- [] /// WHERE a > 1 -- [] /// + /// TODO: deal with row values: + /// WHERE (a, b) = (1, 2) -- ["a", "b"] + /// WHERE (a, b) IN (SELECT ...) -- ["a", "b"] + /// /// Support for `SQLQueryGenerator.expectsSingleResult()` func identifyingColums(_ db: Database, for alias: TableAlias) throws -> Set { var visitor = SQLIdentifyingColumns(db: db, alias: alias) @@ -1255,7 +1259,6 @@ extension SQLExpression { } } -#warning("TODO: what should we do with _SQLRowValue? (a, b) == (1, 2) for example?") /// Support for `SQLExpression.identifyingColums(_:for:)` private struct SQLIdentifyingColumns: _SQLExpressionVisitor { struct BreakError: Error { } @@ -1360,6 +1363,8 @@ extension SQLExpression { /// WHERE id IN (1, 2) OR rowid IN (2, 3) -- [1, 2, 3] /// WHERE id > 1 -- nil /// + /// TODO: deal with row values: + /// WHERE (id, a) = (1, 2) -- 1 /// Support for `SQLQueryGenerator.optimizedSelectedRegion()` func identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set? { var visitor = SQLIdentifyingRowIDs(db: db, alias: alias) @@ -1368,7 +1373,6 @@ extension SQLExpression { } } -#warning("TODO: what should we do with _SQLRowValue? (a, b) == (1, 2) for example?") /// Support for `SQLExpression.identifyingRowIDs(_:for:)` private struct SQLIdentifyingRowIDs: _SQLExpressionVisitor { let db: Database From fcd6a453f0ad41f163ecbde0d0cfaba319204923 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 Dec 2020 18:25:26 +0100 Subject: [PATCH 04/20] Replace CTE request with its table name --- .../SQLGeneration/SQLPreparedRequestGenerator.swift | 7 ++++--- Tests/GRDBTests/AssociationPrefetchingSQLTests.swift | 4 ++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift index 4c83d51d7..c0bfa8086 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift @@ -186,7 +186,7 @@ private func prefetch( // WITH grdb_base AS (SELECT a, b FROM author) // SELECT book.*, book.authorId AS grdb_authorId // FROM book - // WHERE (book.a, book.b) IN (SELECT * FROM grdb_base) + // WHERE (book.a, book.b) IN grdb_base // // HasManyThrough: Citizen.including(all: Citizen.countries) // @@ -194,7 +194,7 @@ private func prefetch( // SELECT country.*, passport.citizenId AS grdb_citizenId // FROM country // JOIN passport ON passport.countryCode = country.code - // AND (passport.a, passport.b) IN (SELECT * FROM grdb_base) + // AND (passport.a, passport.b) IN grdb_base let baseRequest = baseRequest.map(\.query.relation) { baseRelation in // Ordering and including(all:) children are // useless, and we only need pivoting columns: @@ -206,7 +206,8 @@ private func prefetch( let baseCTE = CommonTableExpression( named: "grdb_base", request: baseRequest) - let pivotFilter = baseCTE.all().contains(_SQLRowValue(pivotColumns.map(Column.init))) + let pivotRowValue = _SQLRowValue(pivotColumns.map(Column.init)) + let pivotFilter = SQLLiteral("\(pivotRowValue) IN grdb_base").sqlExpression prefetchRequest = makePrefetchRequest( for: association, diff --git a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift index 278420f70..4955e6cb0 100644 --- a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift @@ -200,7 +200,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { """ WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent") \ SELECT *, "parentA" AS "grdb_parentA", "parentB" AS "grdb_parentB" \ - FROM "child" WHERE ("parentA", "parentB") IN (SELECT * FROM "grdb_base") + FROM "child" WHERE ("parentA", "parentB") IN grdb_base """]) } @@ -243,7 +243,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent" WHERE "parentA" = 'foo') \ SELECT *, "parentA" AS "grdb_parentA", "parentB" AS "grdb_parentB" \ FROM "child" \ - WHERE ("name" = 'foo') AND (("parentA", "parentB") IN (SELECT * FROM "grdb_base")) + WHERE ("name" = 'foo') AND (("parentA", "parentB") IN grdb_base) """]) } } From f1196bf924214fc8057099b4dbd9c983278883df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 Dec 2020 18:37:27 +0100 Subject: [PATCH 05/20] Limit availability of _SQLRowValue.isAvailable --- GRDB/QueryInterface/SQL/SQLRowValue.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/QueryInterface/SQL/SQLRowValue.swift b/GRDB/QueryInterface/SQL/SQLRowValue.swift index b386f3a2c..763cb70f6 100644 --- a/GRDB/QueryInterface/SQL/SQLRowValue.swift +++ b/GRDB/QueryInterface/SQL/SQLRowValue.swift @@ -6,7 +6,7 @@ public struct _SQLRowValue: SQLExpression { /// SQLite row values were shipped in SQLite 3.15: /// https://www.sqlite.org/releaselog/3_15_0.html - public /* public for tests */ static let isAvailable = (sqlite3_libversion_number() >= 3015000) + static let isAvailable = (sqlite3_libversion_number() >= 3015000) /// - precondition: `expressions` is not empty init(_ expressions: [SQLExpression]) { From 732ec36b674a9a10fff7975ab2f90e55b7bbb406 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 Dec 2020 18:39:01 +0100 Subject: [PATCH 06/20] Documentation --- .../SQLGeneration/SQLPreparedRequestGenerator.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift index c0bfa8086..0da21f2c9 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift @@ -135,12 +135,12 @@ private struct SQLRequestCounter: _FetchRequestVisitor { // MARK: - Eager loading of hasMany associations // CAUTION: Keep this code in sync with prefetchedRegion(_:_:) -/// Append rows from prefetched associations into the `rows` argument. +/// Append rows from prefetched associations into the `baseRows` argument. /// /// - parameter db: A database connection. /// - parameter associations: Prefetched associations. /// - parameter baseRows: The rows that need to be extended with prefetched rows. -/// - parameter query: The query that was used to fetch `rows`. +/// - parameter query: The query that was used to fetch `baseRows`. private func prefetch( _ db: Database, associations: [_SQLAssociation], @@ -176,7 +176,7 @@ private func prefetch( // // This is only useful for compound foreign keys. And we need // row values (https://www.sqlite.org/rowvalue.html). So we have - // a backup plan which does not uses any CTE. + // a backup plan which does not use any CTE. let usesCommonTableExpression = pivotMapping.count > 1 && _SQLRowValue.isAvailable let prefetchRequest: QueryInterfaceRequest From 23c93eebdfb64755e035290b9b972b1216e52e85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 Dec 2020 19:08:06 +0100 Subject: [PATCH 07/20] Remove fixed caveat from documentation --- Documentation/AssociationsBasics.md | 22 ---------------------- 1 file changed, 22 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 28ba7538c..40b6bce8d 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -941,24 +941,6 @@ The pattern is always the same: you start from a base request, that you extend w Finally, readers who speak SQL may compare `optional` with left joins, and `required` with inner joins. -> :warning: **Warning**: You will get a database error with code [`SQLITE_ERROR`](https://www.sqlite.org/rescode.html#error) (1) "Expression tree is too large", when the following conditions are met: -> -> - You use the `including(all:)` method (say: `Parent.including(all: children)`). -> - The association is based on a compound foreign key (made of two columns or more). -> - The request fetches a lot of parent records. The exact threshold depends on [SQLITE_LIMIT_EXPR_DEPTH](https://www.sqlite.org/limits.html). It is around 1000 parents in recent iOS and macOS systems. To get an exact figure, run: -> -> ```swift -> let limit = try dbQueue.read { db in -> sqlite3_limit(db.sqliteConnection, SQLITE_LIMIT_EXPR_DEPTH, -1) -> } -> ``` -> -> Possible workarounds are: -> -> - Refactor the database schema so that you do not depend on a compound foreign key. -> - Prefetch children with your own code, without using `including(all:)`. -> -> For more information about this caveat, see [issue #871](https://github.com/groue/GRDB.swift/issues/871). ## Combining Associations @@ -2395,10 +2377,6 @@ See [Good Practices for Designing Record Types] for more information. .including(all: Country.passports .including(required: Passport.citizen)) ``` - -- **The `including(all:)` method may fail with a database error of code [`SQLITE_ERROR`](https://www.sqlite.org/rescode.html#error) (1) "Expression tree is too large" when you use a compound foreign key and there are a lot of parent records.** - - See [Joining And Prefetching Associated Records] for more information about this error. Come [discuss](http://twitter.com/groue) for more information, or if you wish to help turning those missing features into reality. From aabf6e624716167122c6dc0be9602eb264e8bc0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 Dec 2020 19:29:32 +0100 Subject: [PATCH 08/20] Prefer CommonTableExpression.contains(_:) --- .../SQLGeneration/SQLPreparedRequestGenerator.swift | 3 +-- Tests/GRDBTests/AssociationPrefetchingSQLTests.swift | 4 ++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift index 0da21f2c9..08477018a 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift @@ -206,8 +206,7 @@ private func prefetch( let baseCTE = CommonTableExpression( named: "grdb_base", request: baseRequest) - let pivotRowValue = _SQLRowValue(pivotColumns.map(Column.init)) - let pivotFilter = SQLLiteral("\(pivotRowValue) IN grdb_base").sqlExpression + let pivotFilter = baseCTE.contains(_SQLRowValue(pivotColumns.map(Column.init))) prefetchRequest = makePrefetchRequest( for: association, diff --git a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift index 4955e6cb0..da5a35d73 100644 --- a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift @@ -200,7 +200,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { """ WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent") \ SELECT *, "parentA" AS "grdb_parentA", "parentB" AS "grdb_parentB" \ - FROM "child" WHERE ("parentA", "parentB") IN grdb_base + FROM "child" WHERE ("parentA", "parentB") IN "grdb_base" """]) } @@ -243,7 +243,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent" WHERE "parentA" = 'foo') \ SELECT *, "parentA" AS "grdb_parentA", "parentB" AS "grdb_parentB" \ FROM "child" \ - WHERE ("name" = 'foo') AND (("parentA", "parentB") IN grdb_base) + WHERE ("name" = 'foo') AND (("parentA", "parentB") IN "grdb_base") """]) } } From 5eff2448bba6ca8ee4768ee2b72f0fb1eef2c732 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 7 Dec 2020 06:01:13 +0100 Subject: [PATCH 09/20] Documentation --- .../SQLGeneration/SQLPreparedRequestGenerator.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift index 08477018a..eef798b14 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift @@ -140,7 +140,7 @@ private struct SQLRequestCounter: _FetchRequestVisitor { /// - parameter db: A database connection. /// - parameter associations: Prefetched associations. /// - parameter baseRows: The rows that need to be extended with prefetched rows. -/// - parameter query: The query that was used to fetch `baseRows`. +/// - parameter baseRequest: The request that was used to fetch `baseRows`. private func prefetch( _ db: Database, associations: [_SQLAssociation], From 2cb4cf51c329f4a966fa70ae2c5ba6fa4206aa46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 8 Dec 2020 18:32:08 +0100 Subject: [PATCH 10/20] TODO --- Tests/GRDBTests/AssociationPrefetchingSQLTests.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift index da5a35d73..84bdeaf3d 100644 --- a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift @@ -157,6 +157,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { } } + #warning("TODO: test two levels of include(all:) with compound foreign keys") func testIncludingAllHasManyWithCompoundForeignKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in From cad788e59e4508bdcd58342c185b1294836f7daf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 8 Dec 2020 18:38:01 +0100 Subject: [PATCH 11/20] Revert "Prefer CommonTableExpression.contains(_:)" This reverts commit 87a0921586e319ccd4ee02e991ec555c6a915c13. --- .../SQLGeneration/SQLPreparedRequestGenerator.swift | 3 ++- Tests/GRDBTests/AssociationPrefetchingSQLTests.swift | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift index eef798b14..4431c6ba0 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift @@ -206,7 +206,8 @@ private func prefetch( let baseCTE = CommonTableExpression( named: "grdb_base", request: baseRequest) - let pivotFilter = baseCTE.contains(_SQLRowValue(pivotColumns.map(Column.init))) + let pivotRowValue = _SQLRowValue(pivotColumns.map(Column.init)) + let pivotFilter = SQLLiteral("\(pivotRowValue) IN grdb_base").sqlExpression prefetchRequest = makePrefetchRequest( for: association, diff --git a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift index 84bdeaf3d..b9c189fa0 100644 --- a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift @@ -201,7 +201,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { """ WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent") \ SELECT *, "parentA" AS "grdb_parentA", "parentB" AS "grdb_parentB" \ - FROM "child" WHERE ("parentA", "parentB") IN "grdb_base" + FROM "child" WHERE ("parentA", "parentB") IN grdb_base """]) } @@ -244,7 +244,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent" WHERE "parentA" = 'foo') \ SELECT *, "parentA" AS "grdb_parentA", "parentB" AS "grdb_parentB" \ FROM "child" \ - WHERE ("name" = 'foo') AND (("parentA", "parentB") IN "grdb_base") + WHERE ("name" = 'foo') AND (("parentA", "parentB") IN grdb_base) """]) } } From 472b5bc604f94809a37301956c4b1d7a1d840b6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 8 Dec 2020 19:28:07 +0100 Subject: [PATCH 12/20] Test two levels of include(all:) with compound foreign keys --- .../AssociationPrefetchingSQLTests.swift | 149 +++++++++++++++++- 1 file changed, 148 insertions(+), 1 deletion(-) diff --git a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift index b9c189fa0..1c2bf55f6 100644 --- a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift @@ -157,7 +157,6 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { } } - #warning("TODO: test two levels of include(all:) with compound foreign keys") func testIncludingAllHasManyWithCompoundForeignKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in @@ -401,6 +400,154 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { } } + func testIncludingAllHasManyIncludingAllHasManyWithCompoundForeignKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "parent") { t in + t.column("parentA", .text) + t.column("parentB", .text) + t.column("name", .text) + t.primaryKey(["parentA", "parentB"]) + } + try db.create(table: "child") { t in + t.column("childA", .text) + t.column("childB", .text) + t.column("parentA", .text) + t.column("parentB", .text) + t.column("name", .text) + t.primaryKey(["childA", "childB"]) + t.foreignKey(["parentA", "parentB"], references: "parent") + } + try db.create(table: "grandchild") { t in + t.column("childA", .text) + t.column("childB", .text) + t.column("name", .text) + t.foreignKey(["childA", "childB"], references: "child") + } + try db.execute(sql: """ + INSERT INTO parent (parentA, parentB, name) VALUES ('foo', 'bar', 'foo'); + INSERT INTO parent (parentA, parentB, name) VALUES ('baz', 'qux', 'foo'); + INSERT INTO child (childA, childB, parentA, parentB, name) VALUES ('a', 'b', 'foo', 'bar', 'blue'); + INSERT INTO child (childA, childB, parentA, parentB, name) VALUES ('c', 'd', 'foo', 'bar', 'pink'); + INSERT INTO child (childA, childB, parentA, parentB, name) VALUES ('e', 'f', 'baz', 'qux', 'blue'); + INSERT INTO grandchild (childA, childB, name) VALUES ('a', 'b', 'dog'); + INSERT INTO grandchild (childA, childB, name) VALUES ('a', 'b', 'cat'); + INSERT INTO grandchild (childA, childB, name) VALUES ('c', 'd', 'cat'); + INSERT INTO grandchild (childA, childB, name) VALUES ('e', 'f', 'dog'); + """) + + struct Parent: TableRecord { } + struct Child: TableRecord { } + struct GrandChild: TableRecord { } + + // Plain request + do { + let request = Parent + .including(all: Parent.hasMany(Child.self) + .including(all: Child.hasMany(GrandChild.self))) + .orderByPrimaryKey() + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter(isSelectQuery) + XCTAssertEqual(selectQueries, [ + """ + SELECT * FROM "parent" ORDER BY "parentA", "parentB" + """, + """ + WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent") \ + SELECT *, "parentA" AS "grdb_parentA", "parentB" AS "grdb_parentB" \ + FROM "child" WHERE ("parentA", "parentB") IN grdb_base + """, + """ + WITH "grdb_base" AS (\ + WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent") \ + SELECT "childA", "childB" FROM "child" \ + WHERE ("parentA", "parentB") IN grdb_base\ + ) \ + SELECT *, "childA" AS "grdb_childA", "childB" AS "grdb_childB" \ + FROM "grandChild" WHERE ("childA", "childB") IN grdb_base + """]) + } + + // Request with avoided prefetch + do { + let request = Parent + .none() + .including(all: Parent.hasMany(Child.self) + .including(all: Child.hasMany(GrandChild.self))) + .orderByPrimaryKey() + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter(isSelectQuery) + XCTAssertEqual(selectQueries, [ + """ + SELECT * FROM "parent" WHERE 0 ORDER BY "parentA", "parentB" + """]) + } + do { + let request = Parent + .including(all: Parent.hasMany(Child.self) + .none() + .including(all: Child.hasMany(GrandChild.self))) + .orderByPrimaryKey() + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter(isSelectQuery) + XCTAssertEqual(selectQueries, [ + """ + SELECT * FROM "parent" ORDER BY "parentA", "parentB" + """, + """ + WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent") \ + SELECT *, "parentA" AS "grdb_parentA", "parentB" AS "grdb_parentB" \ + FROM "child" \ + WHERE 0 AND (("parentA", "parentB") IN grdb_base) + """]) + } + + // Request with filters + do { + let request = Parent + .including(all: Parent.hasMany(Child.self) + .including(all: Child.hasMany(GrandChild.self) + .filter(Column("name") == "dog")) + .filter(Column("name") == "blue")) + .filter(Column("name") == "foo") + .orderByPrimaryKey() + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter(isSelectQuery) + XCTAssertEqual(selectQueries, [ + """ + SELECT * FROM "parent" WHERE "name" = 'foo' ORDER BY "parentA", "parentB" + """, + """ + WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent" WHERE "name" = 'foo') \ + SELECT *, "parentA" AS "grdb_parentA", "parentB" AS "grdb_parentB" \ + FROM "child" WHERE ("name" = 'blue') AND (("parentA", "parentB") IN grdb_base) + """, + """ + WITH "grdb_base" AS (\ + WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent" WHERE "name" = 'foo') \ + SELECT "childA", "childB" FROM "child" \ + WHERE ("name" = 'blue') AND (("parentA", "parentB") IN grdb_base)\ + ) \ + SELECT *, "childA" AS "grdb_childA", "childB" AS "grdb_childB" \ + FROM "grandChild" \ + WHERE ("name" = 'dog') AND (("childA", "childB") IN grdb_base) + """]) + } + } + } + func testIncludingAllHasManyIncludingRequiredOrOptionalHasMany() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in From 4e8d129162d72ebbacec2848b84bee2f4e9dc94f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 8 Dec 2020 20:47:21 +0100 Subject: [PATCH 13/20] Only use the CTE technique if foreign key columns are not null --- GRDB/Core/Database+Schema.swift | 10 +++++ .../SQLPreparedRequestGenerator.swift | 41 +++++++++++++++---- 2 files changed, 43 insertions(+), 8 deletions(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 3cd5fc7c9..05641e969 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -245,6 +245,16 @@ extension Database { try columnsForUniqueKey(Array(columns), in: tableName) != nil } + // Internal onvenience. Not robust enough for public use. + func table(_ tableName: String, hasNotNullConstraintOnColumns columnNames: [String]) throws -> Bool { + let columnNames = columnNames.map { $0.lowercased() } + let columns = try self + .columns(in: tableName) + .filter { columnNames.contains($0.name.lowercased()) } + assert(columns.count == columnNames.count, "columns not found") + return columns.allSatisfy(\.isNotNull) + } + /// The foreign keys defined on table named `tableName`. public func foreignKeys(on tableName: String) throws -> [ForeignKeyInfo] { if let foreignKeys = schemaCache.foreignKeys(on: tableName) { diff --git a/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift index 4431c6ba0..bec6a9036 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift @@ -167,17 +167,42 @@ private func prefetch( let leftColumns = pivotMapping.map(\.left) // We want to avoid the "Expression tree is too large" SQLite error - // when there are many base rows: + // when the foreign key contains several columns, and there are many + // base rows that overflow SQLITE_LIMIT_EXPR_DEPTH: // https://github.com/groue/GRDB.swift/issues/871 // - // To this end, we do not inject any value from the base rows in - // the prefetch request. Instead, we directly inject the base - // request as a common table expression (CTE). + // -- May be too complex for the SQLite engine + // SELECT * FROM child + // WHERE (a = ? AND b = ?) + // OR (a = ? AND b = ?) + // OR ... // - // This is only useful for compound foreign keys. And we need - // row values (https://www.sqlite.org/rowvalue.html). So we have - // a backup plan which does not use any CTE. - let usesCommonTableExpression = pivotMapping.count > 1 && _SQLRowValue.isAvailable + // Instead, we do not inject any value from the base rows in + // the prefetch request. Instead, we directly inject the base + // request as a common table expression (CTE): + // + // WITH grdb_base AS (SELECT a, b FROM parent) + // SELECT * FROM child + // WHERE (a, b) IN grdb_base + // + // This technique works well, but there are two preconditions: + // + // 1. Row values must be available (https://www.sqlite.org/rowvalue.html) + // This is the case of almost all our target platforms. + // + // 2. There must be no null values in the foreign key. That is + // because the `WHERE (a, b) IN grdb_base` snippet does not find + // foreign keys that contain a null value, when we do want to + // find them. We thus look for NOT NULL constraints, and reward + // database schemas that define "proper" foreign keys. + // + // If any of those precondition is not met, we fallback to the + // `(a = ? AND b = ?) OR ...` condition (the one that may fail if + // there are too many base rows). + let usesCommonTableExpression = try pivotMapping.count > 1 + && _SQLRowValue.isAvailable + && (db.table(baseRequest.query.relation.source.tableName, hasNotNullConstraintOnColumns: leftColumns) + || db.table(association.pivot.relation.source.tableName, hasNotNullConstraintOnColumns: pivotColumns)) let prefetchRequest: QueryInterfaceRequest if usesCommonTableExpression { From 6082fc4e543599b040ba5ff8c96273e00fd74fdc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 8 Dec 2020 20:47:57 +0100 Subject: [PATCH 14/20] Tests for nullable compound foreign keys --- .../AssociationPrefetchingSQLTests.swift | 178 +++++++++++++----- 1 file changed, 136 insertions(+), 42 deletions(-) diff --git a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift index 1c2bf55f6..781920b84 100644 --- a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift @@ -157,26 +157,27 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { } } - func testIncludingAllHasManyWithCompoundForeignKey() throws { + func testIncludingAllHasManyWithNotNullCompoundForeignKey() throws { + // We can use the CTE technique let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "parent") { t in - t.column("parentA", .text) - t.column("parentB", .text) + t.column("parentA", .text).notNull() // <- NOT NULL: important + t.column("parentB", .text).notNull() // <- NOT NULL: important t.primaryKey(["parentA", "parentB"]) } try db.create(table: "child") { t in - t.column("parentA", .text) - t.column("parentB", .text) + t.column("pA", .text) + t.column("pB", .text) t.column("name", .text) - t.foreignKey(["parentA", "parentB"], references: "parent") + t.foreignKey(["pA", "pB"], references: "parent") } try db.execute(sql: """ INSERT INTO parent (parentA, parentB) VALUES ('foo', 'bar'); INSERT INTO parent (parentA, parentB) VALUES ('baz', 'qux'); - INSERT INTO child (parentA, parentB, name) VALUES ('foo', 'bar', 'foobar1'); - INSERT INTO child (parentA, parentB, name) VALUES ('foo', 'bar', 'foobar2'); - INSERT INTO child (parentA, parentB, name) VALUES ('baz', 'qux', 'bazqux1'); + INSERT INTO child (pA, pB, name) VALUES ('foo', 'bar', 'foobar1'); + INSERT INTO child (pA, pB, name) VALUES ('foo', 'bar', 'foobar2'); + INSERT INTO child (pA, pB, name) VALUES ('baz', 'qux', 'bazqux1'); """) struct Parent: TableRecord { } @@ -199,8 +200,8 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { """, """ WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent") \ - SELECT *, "parentA" AS "grdb_parentA", "parentB" AS "grdb_parentB" \ - FROM "child" WHERE ("parentA", "parentB") IN grdb_base + SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB" \ + FROM "child" WHERE ("pA", "pB") IN grdb_base """]) } @@ -241,9 +242,102 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { """, """ WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent" WHERE "parentA" = 'foo') \ - SELECT *, "parentA" AS "grdb_parentA", "parentB" AS "grdb_parentB" \ + SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB" \ FROM "child" \ - WHERE ("name" = 'foo') AND (("parentA", "parentB") IN grdb_base) + WHERE ("name" = 'foo') AND (("pA", "pB") IN grdb_base) + """]) + } + } + } + + func testIncludingAllHasManyWithNullableCompoundForeignKey() throws { + // We can NOT use the CTE technique + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "parent") { t in + t.column("parentA", .text) // <- Nullable: important + t.column("parentB", .text) // <- Nullable: important + t.primaryKey(["parentA", "parentB"]) + } + try db.create(table: "child") { t in + t.column("pA", .text) // <- Nullable: important + t.column("pB", .text) // <- Nullable: important + t.column("name", .text) + t.foreignKey(["pA", "pB"], references: "parent") + } + try db.execute(sql: """ + INSERT INTO parent (parentA, parentB) VALUES ('foo', 'bar'); + INSERT INTO parent (parentA, parentB) VALUES ('baz', 'qux'); + INSERT INTO child (pA, pB, name) VALUES ('foo', 'bar', 'foobar1'); + INSERT INTO child (pA, pB, name) VALUES ('foo', 'bar', 'foobar2'); + INSERT INTO child (pA, pB, name) VALUES ('baz', 'qux', 'bazqux1'); + """) + + struct Parent: TableRecord { } + struct Child: TableRecord { } + + // Plain request + do { + let request = Parent + .including(all: Parent + .hasMany(Child.self)) + .orderByPrimaryKey() + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter(isSelectQuery) + XCTAssertEqual(selectQueries, [ + """ + SELECT * FROM "parent" ORDER BY "parentA", "parentB" + """, + """ + SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB" \ + FROM "child" \ + WHERE (("pA" = 'baz') AND ("pB" = 'qux')) \ + OR (("pA" = 'foo') AND ("pB" = 'bar')) + """]) + } + + // Request with avoided prefetch + do { + let request = Parent + .none() + .including(all: Parent + .hasMany(Child.self)) + .orderByPrimaryKey() + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter(isSelectQuery) + XCTAssertEqual(selectQueries, [ + """ + SELECT * FROM "parent" WHERE 0 ORDER BY "parentA", "parentB" + """]) + } + + // Request with filters + do { + let request = Parent + .including(all: Parent + .hasMany(Child.self) + .filter(Column("name") == "foo")) + .filter(Column("parentA") == "foo") + .orderByPrimaryKey() + + sqlQueries.removeAll() + _ = try Row.fetchAll(db, request) + + let selectQueries = sqlQueries.filter(isSelectQuery) + XCTAssertEqual(selectQueries, [ + """ + SELECT * FROM "parent" WHERE "parentA" = 'foo' ORDER BY "parentA", "parentB" + """, + """ + SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB" \ + FROM "child" \ + WHERE ("name" = 'foo') AND (("pA" = 'foo') AND ("pB" = 'bar')) """]) } } @@ -404,36 +498,36 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "parent") { t in - t.column("parentA", .text) - t.column("parentB", .text) + t.column("parentA", .text).notNull() + t.column("parentB", .text).notNull() t.column("name", .text) t.primaryKey(["parentA", "parentB"]) } try db.create(table: "child") { t in - t.column("childA", .text) - t.column("childB", .text) - t.column("parentA", .text) - t.column("parentB", .text) + t.column("childA", .text).notNull() + t.column("childB", .text).notNull() + t.column("pA", .text) + t.column("pB", .text) t.column("name", .text) t.primaryKey(["childA", "childB"]) - t.foreignKey(["parentA", "parentB"], references: "parent") + t.foreignKey(["pA", "pB"], references: "parent") } try db.create(table: "grandchild") { t in - t.column("childA", .text) - t.column("childB", .text) + t.column("cA", .text) + t.column("cB", .text) t.column("name", .text) - t.foreignKey(["childA", "childB"], references: "child") + t.foreignKey(["cA", "cB"], references: "child") } try db.execute(sql: """ INSERT INTO parent (parentA, parentB, name) VALUES ('foo', 'bar', 'foo'); INSERT INTO parent (parentA, parentB, name) VALUES ('baz', 'qux', 'foo'); - INSERT INTO child (childA, childB, parentA, parentB, name) VALUES ('a', 'b', 'foo', 'bar', 'blue'); - INSERT INTO child (childA, childB, parentA, parentB, name) VALUES ('c', 'd', 'foo', 'bar', 'pink'); - INSERT INTO child (childA, childB, parentA, parentB, name) VALUES ('e', 'f', 'baz', 'qux', 'blue'); - INSERT INTO grandchild (childA, childB, name) VALUES ('a', 'b', 'dog'); - INSERT INTO grandchild (childA, childB, name) VALUES ('a', 'b', 'cat'); - INSERT INTO grandchild (childA, childB, name) VALUES ('c', 'd', 'cat'); - INSERT INTO grandchild (childA, childB, name) VALUES ('e', 'f', 'dog'); + INSERT INTO child (childA, childB, pA, pB, name) VALUES ('a', 'b', 'foo', 'bar', 'blue'); + INSERT INTO child (childA, childB, pA, pB, name) VALUES ('c', 'd', 'foo', 'bar', 'pink'); + INSERT INTO child (childA, childB, pA, pB, name) VALUES ('e', 'f', 'baz', 'qux', 'blue'); + INSERT INTO grandchild (cA, cB, name) VALUES ('a', 'b', 'dog'); + INSERT INTO grandchild (cA, cB, name) VALUES ('a', 'b', 'cat'); + INSERT INTO grandchild (cA, cB, name) VALUES ('c', 'd', 'cat'); + INSERT INTO grandchild (cA, cB, name) VALUES ('e', 'f', 'dog'); """) struct Parent: TableRecord { } @@ -457,17 +551,17 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { """, """ WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent") \ - SELECT *, "parentA" AS "grdb_parentA", "parentB" AS "grdb_parentB" \ - FROM "child" WHERE ("parentA", "parentB") IN grdb_base + SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB" \ + FROM "child" WHERE ("pA", "pB") IN grdb_base """, """ WITH "grdb_base" AS (\ WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent") \ SELECT "childA", "childB" FROM "child" \ - WHERE ("parentA", "parentB") IN grdb_base\ + WHERE ("pA", "pB") IN grdb_base\ ) \ - SELECT *, "childA" AS "grdb_childA", "childB" AS "grdb_childB" \ - FROM "grandChild" WHERE ("childA", "childB") IN grdb_base + SELECT *, "cA" AS "grdb_cA", "cB" AS "grdb_cB" \ + FROM "grandChild" WHERE ("cA", "cB") IN grdb_base """]) } @@ -505,9 +599,9 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { """, """ WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent") \ - SELECT *, "parentA" AS "grdb_parentA", "parentB" AS "grdb_parentB" \ + SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB" \ FROM "child" \ - WHERE 0 AND (("parentA", "parentB") IN grdb_base) + WHERE 0 AND (("pA", "pB") IN grdb_base) """]) } @@ -531,18 +625,18 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { """, """ WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent" WHERE "name" = 'foo') \ - SELECT *, "parentA" AS "grdb_parentA", "parentB" AS "grdb_parentB" \ - FROM "child" WHERE ("name" = 'blue') AND (("parentA", "parentB") IN grdb_base) + SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB" \ + FROM "child" WHERE ("name" = 'blue') AND (("pA", "pB") IN grdb_base) """, """ WITH "grdb_base" AS (\ WITH "grdb_base" AS (SELECT "parentA", "parentB" FROM "parent" WHERE "name" = 'foo') \ SELECT "childA", "childB" FROM "child" \ - WHERE ("name" = 'blue') AND (("parentA", "parentB") IN grdb_base)\ + WHERE ("name" = 'blue') AND (("pA", "pB") IN grdb_base)\ ) \ - SELECT *, "childA" AS "grdb_childA", "childB" AS "grdb_childB" \ + SELECT *, "cA" AS "grdb_cA", "cB" AS "grdb_cB" \ FROM "grandChild" \ - WHERE ("name" = 'dog') AND (("childA", "childB") IN grdb_base) + WHERE ("name" = 'dog') AND (("cA", "cB") IN grdb_base) """]) } } From 4a6a2c54951e8f5f680b9e4c13a2eb2d4ab49e61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 8 Dec 2020 21:12:14 +0100 Subject: [PATCH 15/20] Fix typo --- GRDB/Core/Database+Schema.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 05641e969..45af896a7 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -245,7 +245,7 @@ extension Database { try columnsForUniqueKey(Array(columns), in: tableName) != nil } - // Internal onvenience. Not robust enough for public use. + // Internal convenience. Not robust enough for public use. func table(_ tableName: String, hasNotNullConstraintOnColumns columnNames: [String]) throws -> Bool { let columnNames = columnNames.map { $0.lowercased() } let columns = try self From 618be9b5e4198bd218160f01718038977c804a56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 9 Dec 2020 08:16:07 +0100 Subject: [PATCH 16/20] Do not support null in foreign keys more than SQLite itself --- Documentation/AssociationsBasics.md | 6 +- GRDB/Core/Database+Schema.swift | 10 -- .../SQLPreparedRequestGenerator.swift | 24 ++-- .../AssociationPrefetchingSQLTests.swift | 109 ++---------------- 4 files changed, 19 insertions(+), 130 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 40b6bce8d..3b1727b65 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -697,7 +697,7 @@ See [Foreign Keys] for more information. **Associations can automatically infer the foreign keys that define how two database tables are linked together.** -In the example below, the `book.authorId` column is automatically used to link a book to its author: +In the example below, the `book.authorId` column is automatically used to link a book to its author, because the database schema defines a foreign key between the book and author database tables (see [Convention for the BelongsTo Association]). ![BelongsToSchema](https://cdn.rawgit.com/groue/GRDB.swift/master/Documentation/Images/Associations2/BelongsToSchema.svg) @@ -711,7 +711,9 @@ struct Author: TableRecord { } ``` -But this requires the database schema to define a foreign key between the book and author database tables (see [Convention for the BelongsTo Association]). +> :point_up: **Note**: Generally speaking, all foreign keys are supported, including composite keys that span several columns. +> +> :warning: **Warning**: SQLite voids foreign key constraints when one or more of a foreign key column is NULL (see [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html)). GRDB behavior is undefined when a foreign key involves a NULL value. It is recommended that your database schema sets NOT NULL constraints where appropriate. Sometimes the database schema does not define any foreign key. And sometimes, there are *several* foreign keys from a table to another. diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 45af896a7..3cd5fc7c9 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -245,16 +245,6 @@ extension Database { try columnsForUniqueKey(Array(columns), in: tableName) != nil } - // Internal convenience. Not robust enough for public use. - func table(_ tableName: String, hasNotNullConstraintOnColumns columnNames: [String]) throws -> Bool { - let columnNames = columnNames.map { $0.lowercased() } - let columns = try self - .columns(in: tableName) - .filter { columnNames.contains($0.name.lowercased()) } - assert(columns.count == columnNames.count, "columns not found") - return columns.allSatisfy(\.isNotNull) - } - /// The foreign keys defined on table named `tableName`. public func foreignKeys(on tableName: String) throws -> [ForeignKeyInfo] { if let foreignKeys = schemaCache.foreignKeys(on: tableName) { diff --git a/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift index bec6a9036..8bcdb9e94 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift @@ -185,24 +185,14 @@ private func prefetch( // SELECT * FROM child // WHERE (a, b) IN grdb_base // - // This technique works well, but there are two preconditions: + // This technique works well, but there is one precondition: row + // values must be available (https://www.sqlite.org/rowvalue.html). + // This is the case of almost all our target platforms. // - // 1. Row values must be available (https://www.sqlite.org/rowvalue.html) - // This is the case of almost all our target platforms. - // - // 2. There must be no null values in the foreign key. That is - // because the `WHERE (a, b) IN grdb_base` snippet does not find - // foreign keys that contain a null value, when we do want to - // find them. We thus look for NOT NULL constraints, and reward - // database schemas that define "proper" foreign keys. - // - // If any of those precondition is not met, we fallback to the - // `(a = ? AND b = ?) OR ...` condition (the one that may fail if - // there are too many base rows). - let usesCommonTableExpression = try pivotMapping.count > 1 - && _SQLRowValue.isAvailable - && (db.table(baseRequest.query.relation.source.tableName, hasNotNullConstraintOnColumns: leftColumns) - || db.table(association.pivot.relation.source.tableName, hasNotNullConstraintOnColumns: pivotColumns)) + // Otherwise, we fallback to the `(a = ? AND b = ?) OR ...` + // condition (the one that may fail if there are too many + // base rows). + let usesCommonTableExpression = pivotMapping.count > 1 && _SQLRowValue.isAvailable let prefetchRequest: QueryInterfaceRequest if usesCommonTableExpression { diff --git a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift index 781920b84..87e6c7c23 100644 --- a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift @@ -157,13 +157,13 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { } } - func testIncludingAllHasManyWithNotNullCompoundForeignKey() throws { + func testIncludingAllHasManyWithCompoundForeignKey() throws { // We can use the CTE technique let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "parent") { t in - t.column("parentA", .text).notNull() // <- NOT NULL: important - t.column("parentB", .text).notNull() // <- NOT NULL: important + t.column("parentA", .text) + t.column("parentB", .text) t.primaryKey(["parentA", "parentB"]) } try db.create(table: "child") { t in @@ -249,100 +249,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { } } } - - func testIncludingAllHasManyWithNullableCompoundForeignKey() throws { - // We can NOT use the CTE technique - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { db in - try db.create(table: "parent") { t in - t.column("parentA", .text) // <- Nullable: important - t.column("parentB", .text) // <- Nullable: important - t.primaryKey(["parentA", "parentB"]) - } - try db.create(table: "child") { t in - t.column("pA", .text) // <- Nullable: important - t.column("pB", .text) // <- Nullable: important - t.column("name", .text) - t.foreignKey(["pA", "pB"], references: "parent") - } - try db.execute(sql: """ - INSERT INTO parent (parentA, parentB) VALUES ('foo', 'bar'); - INSERT INTO parent (parentA, parentB) VALUES ('baz', 'qux'); - INSERT INTO child (pA, pB, name) VALUES ('foo', 'bar', 'foobar1'); - INSERT INTO child (pA, pB, name) VALUES ('foo', 'bar', 'foobar2'); - INSERT INTO child (pA, pB, name) VALUES ('baz', 'qux', 'bazqux1'); - """) - - struct Parent: TableRecord { } - struct Child: TableRecord { } - - // Plain request - do { - let request = Parent - .including(all: Parent - .hasMany(Child.self)) - .orderByPrimaryKey() - - sqlQueries.removeAll() - _ = try Row.fetchAll(db, request) - - let selectQueries = sqlQueries.filter(isSelectQuery) - XCTAssertEqual(selectQueries, [ - """ - SELECT * FROM "parent" ORDER BY "parentA", "parentB" - """, - """ - SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB" \ - FROM "child" \ - WHERE (("pA" = 'baz') AND ("pB" = 'qux')) \ - OR (("pA" = 'foo') AND ("pB" = 'bar')) - """]) - } - - // Request with avoided prefetch - do { - let request = Parent - .none() - .including(all: Parent - .hasMany(Child.self)) - .orderByPrimaryKey() - - sqlQueries.removeAll() - _ = try Row.fetchAll(db, request) - - let selectQueries = sqlQueries.filter(isSelectQuery) - XCTAssertEqual(selectQueries, [ - """ - SELECT * FROM "parent" WHERE 0 ORDER BY "parentA", "parentB" - """]) - } - - // Request with filters - do { - let request = Parent - .including(all: Parent - .hasMany(Child.self) - .filter(Column("name") == "foo")) - .filter(Column("parentA") == "foo") - .orderByPrimaryKey() - - sqlQueries.removeAll() - _ = try Row.fetchAll(db, request) - - let selectQueries = sqlQueries.filter(isSelectQuery) - XCTAssertEqual(selectQueries, [ - """ - SELECT * FROM "parent" WHERE "parentA" = 'foo' ORDER BY "parentA", "parentB" - """, - """ - SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB" \ - FROM "child" \ - WHERE ("name" = 'foo') AND (("pA" = 'foo') AND ("pB" = 'bar')) - """]) - } - } - } - + func testIncludingAllHasManyIncludingAllHasMany() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in @@ -498,14 +405,14 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "parent") { t in - t.column("parentA", .text).notNull() - t.column("parentB", .text).notNull() + t.column("parentA", .text) + t.column("parentB", .text) t.column("name", .text) t.primaryKey(["parentA", "parentB"]) } try db.create(table: "child") { t in - t.column("childA", .text).notNull() - t.column("childB", .text).notNull() + t.column("childA", .text) + t.column("childB", .text) t.column("pA", .text) t.column("pB", .text) t.column("name", .text) From 6a68e31903a41ce513a901c196184731b31cb8d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 9 Dec 2020 19:01:29 +0100 Subject: [PATCH 17/20] Clarify handling of NULL in foreign keys --- Documentation/AssociationsBasics.md | 2 +- GRDB/QueryInterface/SQL/SQLRelation.swift | 25 ++++++++----------- .../SQLPreparedRequestGenerator.swift | 8 +++--- 3 files changed, 15 insertions(+), 20 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 3b1727b65..8fabff33e 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -713,7 +713,7 @@ struct Author: TableRecord { > :point_up: **Note**: Generally speaking, all foreign keys are supported, including composite keys that span several columns. > -> :warning: **Warning**: SQLite voids foreign key constraints when one or more of a foreign key column is NULL (see [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html)). GRDB behavior is undefined when a foreign key involves a NULL value. It is recommended that your database schema sets NOT NULL constraints where appropriate. +> :warning: **Warning**: SQLite voids foreign key constraints when one or more of a foreign key column is NULL (see [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html)). GRDB does not match foreign keys that involve a NULL value either. It is recommended that your database schema sets NOT NULL constraints where appropriate. Sometimes the database schema does not define any foreign key. And sometimes, there are *several* foreign keys from a table to another. diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 8516de8a1..91392e76f 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -597,7 +597,7 @@ extension JoinMapping { // We could return `false.sqlExpression`. // // But we need to take care of database observation, and generate - // SQL that involves all used columns. Consider using a `NullRow`. + // SQL that involves all used columns. Consider using a `DummyRow`. fatalError("Provide at least one left row, or this method can't generate SQL that can be observed.") } @@ -618,16 +618,10 @@ extension JoinMapping { // Unique database values and filter out NULL: let leftIndex = mapping.leftIndex var dbValues = Set(leftRows.map { $0.databaseValue(at: leftIndex) }) - dbValues.remove(.null) - - if dbValues.isEmpty { - // null was removed from dbValues - return mapping.rightColumn == nil - } else { - // table.a IN (1, 2, 3, ...) - // Sort database values for nicer output. - return dbValues.sorted(by: <).contains(mapping.rightColumn) - } + dbValues.remove(.null) // SQLite doesn't match foreign keys on NULL + // table.a IN (1, 2, 3, ...) + // Sort database values for nicer output. + return dbValues.sorted(by: <).contains(mapping.rightColumn) } else { // Join on a multiple columns. // ((table.a = 1) AND (table.b = 2)) OR ((table.a = 3) AND (table.b = 4)) ... @@ -637,7 +631,8 @@ extension JoinMapping { mappings .map({ mapping -> SQLExpression in let leftValue = leftRow.databaseValue(at: mapping.leftIndex) - return mapping.rightColumn == leftValue + // Force `=` operator, because SQLite doesn't match foreign keys on NULL + return _SQLExpressionEqual(.equal, mapping.rightColumn, leftValue) }) .joined(operator: .and) }) @@ -669,12 +664,12 @@ protocol ColumnAddressable { func databaseValue(at index: ColumnIndex) -> DatabaseValue } -/// A "row" that contains null values for all columns -struct NullRow: ColumnAddressable { +/// A "row" that contains a dummy value for all columns +struct DummyRow: ColumnAddressable { struct DummyIndex { } func index(forColumn column: String) -> DummyIndex? { DummyIndex() } @inline(__always) - func databaseValue(at index: DummyIndex) -> DatabaseValue { .null } + func databaseValue(at index: DummyIndex) -> DatabaseValue { DatabaseValue(storage: .int64(1)) } } /// Row has columns diff --git a/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift index 8bcdb9e94..32f3c261e 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift @@ -334,12 +334,12 @@ func prefetchedRegion( pivotMapping: JoinMapping) throws -> DatabaseRegion { - // Filter the pivot on a `NullRow` in order to make sure all join + // Filter the pivot on a `DummyRow` 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 - let pivotFilter = pivotMapping.joinExpression(leftRows: [NullRow()]) + // ... JOIN right ON right.leftId = ? + // ^ content of the DummyRow + let pivotFilter = pivotMapping.joinExpression(leftRows: [DummyRow()]) let prefetchRelation = association .map(\.pivot.relation) { $0.filter(pivotFilter) } From 13946f1d8d715f01406c79090479ab4e8697820a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 12 Dec 2020 12:20:55 +0100 Subject: [PATCH 18/20] Remove unclear recommentation --- Documentation/AssociationsBasics.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 8fabff33e..15a156fc2 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -713,7 +713,7 @@ struct Author: TableRecord { > :point_up: **Note**: Generally speaking, all foreign keys are supported, including composite keys that span several columns. > -> :warning: **Warning**: SQLite voids foreign key constraints when one or more of a foreign key column is NULL (see [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html)). GRDB does not match foreign keys that involve a NULL value either. It is recommended that your database schema sets NOT NULL constraints where appropriate. +> :warning: **Warning**: SQLite voids foreign key constraints when one or more of a foreign key column is NULL (see [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html)). GRDB does not match foreign keys that involve a NULL value either. Sometimes the database schema does not define any foreign key. And sometimes, there are *several* foreign keys from a table to another. From 1ff825c861fdbaa68c7ca3b6195641b140534aa3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 12 Dec 2020 12:32:21 +0100 Subject: [PATCH 19/20] CHANGELOG --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a0850690..aeb0033c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -73,7 +73,10 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **New**: [#880](https://github.com/groue/GRDB.swift/pull/880): Common Table Expressions - **Fixed**: [#881](https://github.com/groue/GRDB.swift/pull/881) by [@felixscheinost](https://github.com/felixscheinost) and [#883](https://github.com/groue/GRDB.swift/pull/883) by [@professordeng](https://github.com/professordeng): Documentation improvements +- **Fixed**: [#885](https://github.com/groue/GRDB.swift/pull/885): Robustness of eager loading of to-many associations based on compound foreign keys - **Documentation update**: A new guide: [Common Table Expressions](https://github.com/groue/GRDB.swift/blob/master/Documentation/CommonTableExpressions.md) +- **Documentation update**: The [Foreign Keys](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md#foreign-keys) chapter of the Associations Guide clarifies the behavior of SQLite and GRDB regarding the presence of NULL if compound foreign keys. + ## 5.2.0 From c8818c1d44e8c22a5d8b96e695a8dac76c456d42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 12 Dec 2020 12:47:44 +0100 Subject: [PATCH 20/20] CTEs are experimental --- Documentation/CommonTableExpressions.md | 4 ++++ Documentation/SharingADatabase.md | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/Documentation/CommonTableExpressions.md b/Documentation/CommonTableExpressions.md index 16e21518d..37fd28c47 100644 --- a/Documentation/CommonTableExpressions.md +++ b/Documentation/CommonTableExpressions.md @@ -1,6 +1,10 @@ Common Table Expressions ======================== +[**:fire: EXPERIMENTAL**](../README.md#what-are-experimental-features) + +--- + **Common table expressions** (CTEs) can generally be seen as *SQL views that you define on the fly*. A certain level of familiarity with SQL databases is helpful before you dive into this guide. The starting point is obviously the [SQLite documentation](https://sqlite.org/lang_with.html). Many CTE tutorials exist online as well, including [this good one](https://blog.expensify.com/2015/09/25/the-simplest-sqlite-common-table-expression-tutorial/). diff --git a/Documentation/SharingADatabase.md b/Documentation/SharingADatabase.md index 5ebe48b2b..ba1bff409 100644 --- a/Documentation/SharingADatabase.md +++ b/Documentation/SharingADatabase.md @@ -188,7 +188,7 @@ See https://developer.apple.com/library/archive/technotes/tn2151/_index.html for This will avoid https://github.com/sqlcipher/sqlcipher/issues/255. -2. [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features) In each process that wants to write in the database: +2. [**:fire: EXPERIMENTAL**](../README.md#what-are-experimental-features) In each process that wants to write in the database: Set the `observesSuspensionNotifications` configuration flag: