diff --git a/.swiftlint.yml b/.swiftlint.yml index d179972e8..3afb2e518 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -2,6 +2,7 @@ included: - GRDB disabled_rules: + - comment_spacing - cyclomatic_complexity - duplicate_enum_cases - file_length diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 143118fa3..ee12d8d95 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -871,66 +871,18 @@ 56EB0AB31BCD787300A3DC55 /* DataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */; }; 56F0B9921B6001C600A2F135 /* FoundationNSDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */; }; 56F26C1C1CEE3F32007969C4 /* RowAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* RowAdapterTests.swift */; }; - 56F34F9924AE78DE007513FC /* SQLExpressionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34F9824AE78DE007513FC /* SQLExpressionVisitor.swift */; }; - 56F34F9A24AE78DE007513FC /* SQLExpressionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34F9824AE78DE007513FC /* SQLExpressionVisitor.swift */; }; - 56F34F9B24AE78DE007513FC /* SQLExpressionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34F9824AE78DE007513FC /* SQLExpressionVisitor.swift */; }; - 56F34F9C24AE78DE007513FC /* SQLExpressionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34F9824AE78DE007513FC /* SQLExpressionVisitor.swift */; }; - 56F34FA424B06A3B007513FC /* SQLExpressionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FA324B06A3B007513FC /* SQLExpressionGenerator.swift */; }; - 56F34FA524B06A3B007513FC /* SQLExpressionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FA324B06A3B007513FC /* SQLExpressionGenerator.swift */; }; - 56F34FA624B06A3B007513FC /* SQLExpressionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FA324B06A3B007513FC /* SQLExpressionGenerator.swift */; }; - 56F34FA724B06A3B007513FC /* SQLExpressionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FA324B06A3B007513FC /* SQLExpressionGenerator.swift */; }; 56F34FBA24B094B6007513FC /* SQLExpressionIsConstantTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */; }; 56F34FBB24B094B6007513FC /* SQLExpressionIsConstantTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */; }; 56F34FBC24B094B6007513FC /* SQLExpressionIsConstantTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */; }; 56F34FC224B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */; }; 56F34FC324B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */; }; 56F34FC424B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */; }; - 56F34FC924B0DD6A007513FC /* SQLSelectableVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC824B0DD6A007513FC /* SQLSelectableVisitor.swift */; }; - 56F34FCA24B0DD6A007513FC /* SQLSelectableVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC824B0DD6A007513FC /* SQLSelectableVisitor.swift */; }; - 56F34FCB24B0DD6B007513FC /* SQLSelectableVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC824B0DD6A007513FC /* SQLSelectableVisitor.swift */; }; - 56F34FCC24B0DD6B007513FC /* SQLSelectableVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC824B0DD6A007513FC /* SQLSelectableVisitor.swift */; }; - 56F34FD124B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FD024B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift */; }; - 56F34FD224B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FD024B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift */; }; - 56F34FD324B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FD024B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift */; }; - 56F34FD424B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FD024B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift */; }; - 56F34FD624B0E533007513FC /* SQLSelectableCountGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FD524B0E532007513FC /* SQLSelectableCountGenerator.swift */; }; - 56F34FD724B0E533007513FC /* SQLSelectableCountGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FD524B0E532007513FC /* SQLSelectableCountGenerator.swift */; }; - 56F34FD824B0E533007513FC /* SQLSelectableCountGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FD524B0E532007513FC /* SQLSelectableCountGenerator.swift */; }; - 56F34FD924B0E533007513FC /* SQLSelectableCountGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FD524B0E532007513FC /* SQLSelectableCountGenerator.swift */; }; - 56F34FE124B0E915007513FC /* SQLOrderingTermVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE024B0E915007513FC /* SQLOrderingTermVisitor.swift */; }; - 56F34FE224B0E915007513FC /* SQLOrderingTermVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE024B0E915007513FC /* SQLOrderingTermVisitor.swift */; }; - 56F34FE324B0E915007513FC /* SQLOrderingTermVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE024B0E915007513FC /* SQLOrderingTermVisitor.swift */; }; - 56F34FE424B0E915007513FC /* SQLOrderingTermVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE024B0E915007513FC /* SQLOrderingTermVisitor.swift */; }; - 56F34FE924B0EE9C007513FC /* SQLOrderingGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE824B0EE9C007513FC /* SQLOrderingGenerator.swift */; }; - 56F34FEA24B0EE9C007513FC /* SQLOrderingGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE824B0EE9C007513FC /* SQLOrderingGenerator.swift */; }; - 56F34FEB24B0EE9C007513FC /* SQLOrderingGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE824B0EE9C007513FC /* SQLOrderingGenerator.swift */; }; - 56F34FEC24B0EE9C007513FC /* SQLOrderingGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE824B0EE9C007513FC /* SQLOrderingGenerator.swift */; }; - 56F34FF424B0F83E007513FC /* SQLCollectionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FF324B0F83D007513FC /* SQLCollectionVisitor.swift */; }; - 56F34FF524B0F83E007513FC /* SQLCollectionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FF324B0F83D007513FC /* SQLCollectionVisitor.swift */; }; - 56F34FF624B0F83E007513FC /* SQLCollectionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FF324B0F83D007513FC /* SQLCollectionVisitor.swift */; }; - 56F34FF724B0F83E007513FC /* SQLCollectionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FF324B0F83D007513FC /* SQLCollectionVisitor.swift */; }; - 56F34FFF24B0FB69007513FC /* SQLCollectionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FFE24B0FB69007513FC /* SQLCollectionGenerator.swift */; }; - 56F3500024B0FB69007513FC /* SQLCollectionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FFE24B0FB69007513FC /* SQLCollectionGenerator.swift */; }; - 56F3500124B0FB69007513FC /* SQLCollectionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FFE24B0FB69007513FC /* SQLCollectionGenerator.swift */; }; - 56F3500224B0FB69007513FC /* SQLCollectionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FFE24B0FB69007513FC /* SQLCollectionGenerator.swift */; }; 56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; }; 56F3E74D1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; }; 56F5ABD91D814330001F60CB /* Data.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C33F1D23E82A00E59934 /* Data.swift */; }; 56F5ABDA1D814330001F60CB /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 56F5ABDC1D814330001F60CB /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; }; 56F5ABDD1D814330001F60CB /* UUID.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C22F1D1914540096E9D4 /* UUID.swift */; }; - 56F896AA24B9DEA7005FB062 /* FetchRequestVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896A924B9DEA7005FB062 /* FetchRequestVisitor.swift */; }; - 56F896AB24B9DEA7005FB062 /* FetchRequestVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896A924B9DEA7005FB062 /* FetchRequestVisitor.swift */; }; - 56F896AC24B9DEA7005FB062 /* FetchRequestVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896A924B9DEA7005FB062 /* FetchRequestVisitor.swift */; }; - 56F896AD24B9DEA7005FB062 /* FetchRequestVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896A924B9DEA7005FB062 /* FetchRequestVisitor.swift */; }; - 56F896B624B9E68D005FB062 /* SQLRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896B524B9E68D005FB062 /* SQLRequestGenerator.swift */; }; - 56F896B724B9E68D005FB062 /* SQLRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896B524B9E68D005FB062 /* SQLRequestGenerator.swift */; }; - 56F896B824B9E68D005FB062 /* SQLRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896B524B9E68D005FB062 /* SQLRequestGenerator.swift */; }; - 56F896B924B9E68D005FB062 /* SQLRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896B524B9E68D005FB062 /* SQLRequestGenerator.swift */; }; - 56F896BB24B9E730005FB062 /* SQLPreparedRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896BA24B9E730005FB062 /* SQLPreparedRequestGenerator.swift */; }; - 56F896BC24B9E730005FB062 /* SQLPreparedRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896BA24B9E730005FB062 /* SQLPreparedRequestGenerator.swift */; }; - 56F896BD24B9E730005FB062 /* SQLPreparedRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896BA24B9E730005FB062 /* SQLPreparedRequestGenerator.swift */; }; - 56F896BE24B9E730005FB062 /* SQLPreparedRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896BA24B9E730005FB062 /* SQLPreparedRequestGenerator.swift */; }; 56FBFED92210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; }; 56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; }; 56FBFEDB2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; }; @@ -1648,21 +1600,9 @@ 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataMemoryTests.swift; sourceTree = ""; }; 56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizerTests.swift; sourceTree = ""; }; 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDateTests.swift; sourceTree = ""; }; - 56F34F9824AE78DE007513FC /* SQLExpressionVisitor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpressionVisitor.swift; sourceTree = ""; }; - 56F34FA324B06A3B007513FC /* SQLExpressionGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpressionGenerator.swift; sourceTree = ""; }; 56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLExpressionIsConstantTests.swift; sourceTree = ""; }; 56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLIdentifyingColumnsTests.swift; sourceTree = ""; }; - 56F34FC824B0DD6A007513FC /* SQLSelectableVisitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelectableVisitor.swift; sourceTree = ""; }; - 56F34FD024B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelectableResultColumnGenerator.swift; sourceTree = ""; }; - 56F34FD524B0E532007513FC /* SQLSelectableCountGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectableCountGenerator.swift; sourceTree = ""; }; - 56F34FE024B0E915007513FC /* SQLOrderingTermVisitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLOrderingTermVisitor.swift; sourceTree = ""; }; - 56F34FE824B0EE9C007513FC /* SQLOrderingGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOrderingGenerator.swift; sourceTree = ""; }; - 56F34FF324B0F83D007513FC /* SQLCollectionVisitor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollectionVisitor.swift; sourceTree = ""; }; - 56F34FFE24B0FB69007513FC /* SQLCollectionGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollectionGenerator.swift; sourceTree = ""; }; 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = ""; }; - 56F896A924B9DEA7005FB062 /* FetchRequestVisitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchRequestVisitor.swift; sourceTree = ""; }; - 56F896B524B9E68D005FB062 /* SQLRequestGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestGenerator.swift; sourceTree = ""; }; - 56F896BA24B9E730005FB062 /* SQLPreparedRequestGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLPreparedRequestGenerator.swift; sourceTree = ""; }; 56FBFED82210731A00945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = ""; }; 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = ""; }; 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = ""; }; @@ -2097,15 +2037,8 @@ 5656A8162295AFD6001FF3FF /* SQLGeneration */ = { isa = PBXGroup; children = ( - 56F34FFE24B0FB69007513FC /* SQLCollectionGenerator.swift */, - 56F34FA324B06A3B007513FC /* SQLExpressionGenerator.swift */, 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */, - 56F34FE824B0EE9C007513FC /* SQLOrderingGenerator.swift */, - 56F896BA24B9E730005FB062 /* SQLPreparedRequestGenerator.swift */, 568D13182207213E00674B58 /* SQLQueryGenerator.swift */, - 56F896B524B9E68D005FB062 /* SQLRequestGenerator.swift */, - 56F34FD524B0E532007513FC /* SQLSelectableCountGenerator.swift */, - 56F34FD024B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift */, ); path = SQLGeneration; sourceTree = ""; @@ -2118,22 +2051,18 @@ 5656A81D2295B12F001FF3FF /* SQLAssociation.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, - 56F34FF324B0F83D007513FC /* SQLCollectionVisitor.swift */, 56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */, 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */, 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */, - 56F34F9824AE78DE007513FC /* SQLExpressionVisitor.swift */, 5653EAF920944C7B00F46237 /* SQLForeignKeyRequest.swift */, 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */, 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */, 56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */, - 56F34FE024B0E915007513FC /* SQLOrderingTermVisitor.swift */, 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */, 56D91AA12205E03700770D8D /* SQLRelation.swift */, 56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */, 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */, 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */, - 56F34FC824B0DD6A007513FC /* SQLSelectableVisitor.swift */, 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */, ); path = SQL; @@ -2375,7 +2304,6 @@ 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */, 563363C31C942C37000BE133 /* DatabaseWriter.swift */, 5636E9BB1D22574100B9B05F /* FetchRequest.swift */, - 56F896A924B9DEA7005FB062 /* FetchRequestVisitor.swift */, 56A238761B9C75030082EB20 /* Row.swift */, 567404871CEF84C8003ED5CC /* RowAdapter.swift */, 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */, @@ -2942,12 +2870,10 @@ files = ( 5616AAF3207CD45E00AC3664 /* RequestProtocols.swift in Sources */, 56B964BF1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, - 56F34FCB24B0DD6B007513FC /* SQLSelectableVisitor.swift in Sources */, 56D51D061EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 565490CE1D5AE252005622CB /* NSNull.swift in Sources */, 5656A8202295B12F001FF3FF /* SQLAssociation.swift in Sources */, 565490E41D5AE252005622CB /* TableRecord.swift in Sources */, - 56F3500124B0FB69007513FC /* SQLCollectionGenerator.swift in Sources */, 564CE5AE21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */, 565490CF1D5AE252005622CB /* NSNumber.swift in Sources */, 566475C01D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, @@ -2970,7 +2896,6 @@ 56172950223533F40006E219 /* EncodableRecord.swift in Sources */, 56AE64142229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */, 5613ED3721A95A5C00DC7A68 /* Map.swift in Sources */, - 56F34FD324B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */, 5659F48E1EA8D94E004A4992 /* Utils.swift in Sources */, 564CE43321AA901800652B19 /* ValueObserver.swift in Sources */, 56CEB5671EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, @@ -2987,7 +2912,6 @@ 565490D91D5AE252005622CB /* Migration.swift in Sources */, 56CEB5001EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD271DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, - 56F896BD24B9E730005FB062 /* SQLPreparedRequestGenerator.swift in Sources */, C96C0F2D2084A45A006B2981 /* SQLiteDateParser.swift in Sources */, 56012BB1257404E100B4925B /* CommonTableExpression.swift in Sources */, 566A841C2041146100E50BFD /* DatabaseSnapshot.swift in Sources */, @@ -3018,14 +2942,12 @@ 565490DA1D5AE252005622CB /* QueryInterfaceRequest.swift in Sources */, 563B8FAE24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */, 565490CA1D5AE252005622CB /* DatabaseDateComponents.swift in Sources */, - 56F896AC24B9DEA7005FB062 /* FetchRequestVisitor.swift in Sources */, 565490D01D5AE252005622CB /* NSString.swift in Sources */, 565490DF1D5AE252005622CB /* TableDefinition.swift in Sources */, 565490B71D5AE236005622CB /* Database.swift in Sources */, 5674A6E81F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, 56E9FACD221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */, 5653EB2320944C7C00F46237 /* HasOneAssociation.swift in Sources */, - 56F34F9B24AE78DE007513FC /* SQLExpressionVisitor.swift in Sources */, 565490C01D5AE236005622CB /* DatabaseWriter.swift in Sources */, 565490C41D5AE236005622CB /* SchedulingWatchdog.swift in Sources */, 566B91311FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, @@ -3045,12 +2967,10 @@ 56FBFEDB2210731A00945324 /* SQLRequest.swift in Sources */, 56F5ABD91D814330001F60CB /* Data.swift in Sources */, 565490D41D5AE252005622CB /* (null) in Sources */, - 56F34FA624B06A3B007513FC /* SQLExpressionGenerator.swift in Sources */, 566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, 565490B61D5AE236005622CB /* Configuration.swift in Sources */, 565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */, 56FC987E1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, - 56F896B824B9E68D005FB062 /* SQLRequestGenerator.swift in Sources */, 569BBA50229170FA00478429 /* Inflections+English.swift in Sources */, 563B8FB724A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */, 566B91391FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, @@ -3076,12 +2996,8 @@ 565490BC1D5AE236005622CB /* DatabaseSchemaCache.swift in Sources */, 563EF42F2161180D007DAACD /* AssociationAggregate.swift in Sources */, 565490BA1D5AE236005622CB /* DatabaseQueue.swift in Sources */, - 56F34FEB24B0EE9C007513FC /* SQLOrderingGenerator.swift in Sources */, 56781B0D243F86E600650A83 /* Refinable.swift in Sources */, 565490CD1D5AE252005622CB /* Date.swift in Sources */, - 56F34FD824B0E533007513FC /* SQLSelectableCountGenerator.swift in Sources */, - 56F34FE324B0E915007513FC /* SQLOrderingTermVisitor.swift in Sources */, - 56F34FF624B0F83E007513FC /* SQLCollectionVisitor.swift in Sources */, 5653EB0820944C7C00F46237 /* SQLForeignKeyRequest.swift in Sources */, 565490BE1D5AE236005622CB /* DatabaseValue.swift in Sources */, ); @@ -3111,8 +3027,6 @@ 5636E9BF1D22574100B9B05F /* FetchRequest.swift in Sources */, 563EF42E2161180D007DAACD /* AssociationAggregate.swift in Sources */, 56BB6EAC1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, - 56F34FEA24B0EE9C007513FC /* SQLOrderingGenerator.swift in Sources */, - 56F34FD724B0E533007513FC /* SQLSelectableCountGenerator.swift in Sources */, 563B8FC624A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */, 56300B791C53F592005A543B /* QueryInterfaceRequest.swift in Sources */, 5656A8B12295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */, @@ -3128,7 +3042,6 @@ 5605F15A1C672E4000235C62 /* CGFloat.swift in Sources */, 56CEB5481EAA359A00BFAF62 /* Column.swift in Sources */, 5653EB262094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */, - 56F896AB24B9DEA7005FB062 /* FetchRequestVisitor.swift in Sources */, 5605F1641C672E4000235C62 /* Date.swift in Sources */, 566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 564CE43221AA901800652B19 /* ValueObserver.swift in Sources */, @@ -3144,7 +3057,6 @@ 5664759D1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 568D13202207213E00674B58 /* SQLQueryGenerator.swift in Sources */, 5674048A1CEF84C8003ED5CC /* RowAdapter.swift in Sources */, - 56F34FE224B0E915007513FC /* SQLOrderingTermVisitor.swift in Sources */, 563EF416215F87EB007DAACD /* OrderedDictionary.swift in Sources */, 563363C51C942C37000BE133 /* DatabaseWriter.swift in Sources */, 5698AD1B1DAAD17D0056AF8C /* FTS5Tokenizer.swift in Sources */, @@ -3152,7 +3064,6 @@ 56B964B41DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, 563B8FB624A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */, 560A37A81C8FF6E500949E71 /* SerializedDatabase.swift in Sources */, - 56F34FD224B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */, 566A841B2041146100E50BFD /* DatabaseSnapshot.swift in Sources */, 56CEB54F1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 56A238941B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */, @@ -3161,7 +3072,6 @@ 56A8C2331D1914540096E9D4 /* UUID.swift in Sources */, 560D92411C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */, 566475BD1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, - 56F3500024B0FB69007513FC /* SQLCollectionGenerator.swift in Sources */, 56A238A51B9C753B0082EB20 /* Record.swift in Sources */, 5671FC231DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, @@ -3176,7 +3086,6 @@ 5657AB121D10899D006283EF /* URL.swift in Sources */, 5616AAF2207CD45E00AC3664 /* RequestProtocols.swift in Sources */, 5659F48B1EA8D94E004A4992 /* Utils.swift in Sources */, - 56F34FA524B06A3B007513FC /* SQLExpressionGenerator.swift in Sources */, 56A2387C1B9C75030082EB20 /* Configuration.swift in Sources */, 56DAA2DE1DE9C827006E10C8 /* Cursor.swift in Sources */, 560A37A51C8F625000949E71 /* DatabasePool.swift in Sources */, @@ -3185,14 +3094,10 @@ 56A2388C1B9C75030082EB20 /* Statement.swift in Sources */, 5659F4931EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 56D91AB12205F8AC00770D8D /* SQLQuery.swift in Sources */, - 56F896BC24B9E730005FB062 /* SQLPreparedRequestGenerator.swift in Sources */, 56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */, - 56F896B724B9E68D005FB062 /* SQLRequestGenerator.swift in Sources */, 5690C3431D23E82A00E59934 /* Data.swift in Sources */, 5674A7001F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, 5674A6E91F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, - 56F34FF524B0F83E007513FC /* SQLCollectionVisitor.swift in Sources */, - 56F34F9A24AE78DE007513FC /* SQLExpressionVisitor.swift in Sources */, 566B91161FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 56FC987B1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, 56A238881B9C75030082EB20 /* Row.swift in Sources */, @@ -3245,7 +3150,6 @@ 56D91AA32205E03700770D8D /* SQLRelation.swift in Sources */, 564F9C311F07611600877A00 /* DatabaseFunction.swift in Sources */, 564CE59E21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */, - 56F34FCA24B0DD6A007513FC /* SQLSelectableVisitor.swift in Sources */, 56B964A01DA51B4C0002DA19 /* FTS5.swift in Sources */, 5674A6F01F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, ); @@ -3710,8 +3614,6 @@ AAA4DC77230F1E0600C74B15 /* FetchRequest.swift in Sources */, AAA4DC78230F1E0600C74B15 /* AssociationAggregate.swift in Sources */, AAA4DC79230F1E0600C74B15 /* SchedulingWatchdog.swift in Sources */, - 56F34FEC24B0EE9C007513FC /* SQLOrderingGenerator.swift in Sources */, - 56F34FD924B0E533007513FC /* SQLSelectableCountGenerator.swift in Sources */, 563B8FC824A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */, AAA4DC7A230F1E0600C74B15 /* QueryInterfaceRequest.swift in Sources */, AAA4DC7B230F1E0600C74B15 /* TableRecord+QueryInterfaceRequest.swift in Sources */, @@ -3727,7 +3629,6 @@ AAA4DC84230F1E0600C74B15 /* CGFloat.swift in Sources */, AAA4DC85230F1E0600C74B15 /* Column.swift in Sources */, AAA4DC86230F1E0600C74B15 /* QueryInterfaceRequest+Association.swift in Sources */, - 56F896AD24B9DEA7005FB062 /* FetchRequestVisitor.swift in Sources */, AAA4DC87230F1E0600C74B15 /* Date.swift in Sources */, AAA4DC89230F1E0600C74B15 /* TransactionObserver.swift in Sources */, AAA4DC8A230F1E0600C74B15 /* ValueObserver.swift in Sources */, @@ -3743,7 +3644,6 @@ AAA4DC93230F1E0600C74B15 /* SQLCollection.swift in Sources */, AAA4DC94230F1E0600C74B15 /* SQLQueryGenerator.swift in Sources */, AAA4DC95230F1E0600C74B15 /* RowAdapter.swift in Sources */, - 56F34FE424B0E915007513FC /* SQLOrderingTermVisitor.swift in Sources */, AAA4DC96230F1E0600C74B15 /* OrderedDictionary.swift in Sources */, AAA4DC97230F1E0600C74B15 /* DatabaseWriter.swift in Sources */, AAA4DC98230F1E0600C74B15 /* FTS5Tokenizer.swift in Sources */, @@ -3751,7 +3651,6 @@ AAA4DC9A230F1E0600C74B15 /* FTS5TokenizerDescriptor.swift in Sources */, 563B8FB824A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */, AAA4DC9B230F1E0600C74B15 /* SerializedDatabase.swift in Sources */, - 56F34FD424B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */, AAA4DC9C230F1E0600C74B15 /* DatabaseSnapshot.swift in Sources */, AAA4DC9D230F1E0600C74B15 /* SQLExpressible.swift in Sources */, AAA4DC9E230F1E0600C74B15 /* DatabaseMigrator.swift in Sources */, @@ -3760,7 +3659,6 @@ AAA4DCA1230F1E0600C74B15 /* UUID.swift in Sources */, AAA4DCA2230F1E0600C74B15 /* DatabaseValueConvertible.swift in Sources */, AAA4DCA3230F1E0600C74B15 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, - 56F3500224B0FB69007513FC /* SQLCollectionGenerator.swift in Sources */, AAA4DCA4230F1E0600C74B15 /* Record.swift in Sources */, AAA4DCA5230F1E0600C74B15 /* FTS3TokenizerDescriptor.swift in Sources */, AAA4DCA6230F1E0600C74B15 /* FetchableRecord+TableRecord.swift in Sources */, @@ -3775,7 +3673,6 @@ AAA4DCAD230F1E0600C74B15 /* URL.swift in Sources */, AAA4DCAE230F1E0600C74B15 /* RequestProtocols.swift in Sources */, AAA4DCAF230F1E0600C74B15 /* Utils.swift in Sources */, - 56F34FA724B06A3B007513FC /* SQLExpressionGenerator.swift in Sources */, AAA4DCB0230F1E0600C74B15 /* Configuration.swift in Sources */, AAA4DCB1230F1E0600C74B15 /* Cursor.swift in Sources */, AAA4DCB2230F1E0600C74B15 /* DatabasePool.swift in Sources */, @@ -3784,14 +3681,10 @@ AAA4DCB5230F1E0600C74B15 /* Statement.swift in Sources */, AAA4DCB6230F1E0600C74B15 /* ReadWriteBox.swift in Sources */, AAA4DCB7230F1E0600C74B15 /* SQLQuery.swift in Sources */, - 56F896BE24B9E730005FB062 /* SQLPreparedRequestGenerator.swift in Sources */, AAA4DCB8230F1E0600C74B15 /* Migration.swift in Sources */, - 56F896B924B9E68D005FB062 /* SQLRequestGenerator.swift in Sources */, AAA4DCB9230F1E0600C74B15 /* Data.swift in Sources */, AAA4DCBA230F1E0600C74B15 /* FetchableRecord+Decodable.swift in Sources */, AAA4DCBB230F1E0600C74B15 /* DatabaseValueConvertible+Decodable.swift in Sources */, - 56F34FF724B0F83E007513FC /* SQLCollectionVisitor.swift in Sources */, - 56F34F9C24AE78DE007513FC /* SQLExpressionVisitor.swift in Sources */, AAA4DCBC230F1E0600C74B15 /* DatabaseCollation.swift in Sources */, AAA4DCBD230F1E0600C74B15 /* SQLExpression+QueryInterface.swift in Sources */, AAA4DCBE230F1E0600C74B15 /* Row.swift in Sources */, @@ -3844,7 +3737,6 @@ AAA4DCEF230F1E0600C74B15 /* SQLRelation.swift in Sources */, AAA4DCF0230F1E0600C74B15 /* DatabaseFunction.swift in Sources */, AAA4DCF1230F1E0600C74B15 /* RemoveDuplicates.swift in Sources */, - 56F34FCC24B0DD6B007513FC /* SQLSelectableVisitor.swift in Sources */, AAA4DCF2230F1E0600C74B15 /* FTS5.swift in Sources */, AAA4DCF3230F1E0600C74B15 /* DatabaseValueConvertible+Encodable.swift in Sources */, ); @@ -4083,8 +3975,6 @@ 563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */, 56D91AB02205F8AC00770D8D /* SQLQuery.swift in Sources */, 5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */, - 56F34FE924B0EE9C007513FC /* SQLOrderingGenerator.swift in Sources */, - 56F34FD624B0E533007513FC /* SQLSelectableCountGenerator.swift in Sources */, 563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */, 5656A8B02295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */, 5613ED4421A95B2C00DC7A68 /* ValueReducer.swift in Sources */, @@ -4100,7 +3990,6 @@ 566A841A2041146100E50BFD /* DatabaseSnapshot.swift in Sources */, 569EF0E2200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */, 56CEB4F11EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, - 56F896AA24B9DEA7005FB062 /* FetchRequestVisitor.swift in Sources */, 56D91AA22205E03700770D8D /* SQLRelation.swift in Sources */, 56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */, 56AACAA822ACED7100A40F2A /* Fetch.swift in Sources */, @@ -4116,7 +4005,6 @@ 5605F1591C672E4000235C62 /* CGFloat.swift in Sources */, 5674A7031F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, 5605F1631C672E4000235C62 /* Date.swift in Sources */, - 56F34FE124B0E915007513FC /* SQLOrderingTermVisitor.swift in Sources */, 5605F1711C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */, 566475CC1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, @@ -4124,7 +4012,6 @@ 563EF415215F87EB007DAACD /* OrderedDictionary.swift in Sources */, 563B8FB524A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */, 564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */, - 56F34FD124B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */, 564CE5AC21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */, 5659F4981EA8D989004A4992 /* Pool.swift in Sources */, 56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */, @@ -4133,7 +4020,6 @@ 5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 567404881CEF84C8003ED5CC /* RowAdapter.swift in Sources */, 5653EB0320944C7C00F46237 /* BelongsToAssociation.swift in Sources */, - 56F34FFF24B0FB69007513FC /* SQLCollectionGenerator.swift in Sources */, 563363C41C942C37000BE133 /* DatabaseWriter.swift in Sources */, 569BBA4E229170F800478429 /* Inflections+English.swift in Sources */, 5656A81E2295B12F001FF3FF /* SQLAssociation.swift in Sources */, @@ -4148,7 +4034,6 @@ 560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */, 56A8C2301D1914540096E9D4 /* UUID.swift in Sources */, 56CEB5011EAA2F4D00BFAF62 /* FTS4.swift in Sources */, - 56F34FA424B06A3B007513FC /* SQLExpressionGenerator.swift in Sources */, 56AE64122229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */, 56CEB55A1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, 56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */, @@ -4157,14 +4042,10 @@ 5653EB0920944C7C00F46237 /* Association.swift in Sources */, 56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */, 5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, - 56F896BB24B9E730005FB062 /* SQLPreparedRequestGenerator.swift in Sources */, 56A238A41B9C753B0082EB20 /* Record.swift in Sources */, - 56F896B624B9E68D005FB062 /* SQLRequestGenerator.swift in Sources */, 56CEB5451EAA359A00BFAF62 /* Column.swift in Sources */, 5657AB0F1D10899D006283EF /* URL.swift in Sources */, 560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */, - 56F34FF424B0F83E007513FC /* SQLCollectionVisitor.swift in Sources */, - 56F34F9924AE78DE007513FC /* SQLExpressionVisitor.swift in Sources */, 56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */, 5674A6EB1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 56D91AA92205F2F100770D8D /* DatabasePromise.swift in Sources */, @@ -4217,7 +4098,6 @@ 5644DE6D20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */, 5657AAB91D107001006283EF /* NSData.swift in Sources */, 560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */, - 56F34FC924B0DD6A007513FC /* SQLSelectableVisitor.swift in Sources */, 56CEB5531EAA359A00BFAF62 /* SQLExpression.swift in Sources */, 56B9649D1DA51B4C0002DA19 /* FTS5.swift in Sources */, ); diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index 0b47a837b..47b7552bd 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -137,6 +137,69 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon fatalError("Unexpected SQLite column type: \(type)") } } + + // MARK: SQLExpression + + /// :nodoc: + public func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { + if isNull { + // fast path for NULL + return "NULL" + } else if context.append(arguments: [self]) { + // Use statement arguments + return "?" + } else { + // Quoting needed: just use SQLite, which knows better. + return try String.fetchOne(context.db, sql: "SELECT QUOTE(?)", arguments: [self])! + } + } + + /// :nodoc: + public func _identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set? { + if isNull || self == false.databaseValue { + // Those requests select no row: + // - WHERE NULL + // - WHERE 0 + return [] + } + return nil + } + + // Specific boolean checks for null, true, and false + /// :nodoc: + public func _is(_ test: _SQLBooleanTest) -> SQLExpression { + switch storage { + case .null: + return DatabaseValue.null + + 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) + } + } + } + + /// :nodoc: + public var _isConstantInRequest: Bool { true } + + /// :nodoc: + public var _isTrue: Bool { self == true.databaseValue } + + /// :nodoc: + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { self } } // MARK: - Hashable & Equatable @@ -219,46 +282,6 @@ extension DatabaseValue { } } -// SQLExpression -extension DatabaseValue { - // Specific boolean checks for null, true, and false - /// :nodoc: - public func _is(_ test: _SQLBooleanTest) -> SQLExpression { - switch storage { - case .null: - return DatabaseValue.null - - 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) - } - } - } - - /// :nodoc: - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - self - } - - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) - } -} - // CustomStringConvertible extension DatabaseValue { /// :nodoc: diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index 1f182b198..6605ea5c4 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -4,8 +4,17 @@ /// /// :nodoc: public protocol _FetchRequest { - /// Accepts a visitor - func _accept(_ visitor: inout Visitor) throws + /// The number of columns selected by the request. + func _selectedColumnCount(_ db: Database) throws -> Int + + /// Returns the request SQL. + /// + /// - parameter context: An SQL generation context. + /// - parameter singleResult: A hint that a single result row will be + /// consumed. Implementations can optionally use it to optimize the + /// generated SQL, for example by adding a `LIMIT 1` SQL clause. + /// - returns: An SQL string. + func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String } /// The protocol for all requests that fetch database rows, and tell how those @@ -21,25 +30,96 @@ public protocol _FetchRequest { public protocol FetchRequest: _FetchRequest, DatabaseRegionConvertible, SQLExpression, SQLCollection { /// The type that tells how fetched database rows should be interpreted. associatedtype RowDecoder + + /// Returns a PreparedRequest that is ready to be executed. + /// + /// - parameter db: A database connection. + /// - parameter singleResult: A hint that a single result row will be + /// consumed. Implementations can optionally use it to optimize the + /// prepared statement, for example by adding a `LIMIT 1` SQL clause. + /// + /// // Calls makePreparedRequest(db, forSingleResult: true) + /// try request.fetchOne(db) + /// + /// // Calls makePreparedRequest(db, forSingleResult: false) + /// try request.fetchAll(db) + /// - returns: A prepared request. + func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest + + /// Returns the number of rows fetched by the request. + /// + /// - parameter db: A database connection. + func fetchCount(_ db: Database) throws -> Int } extension FetchRequest { - /// :nodoc: - public func _qualifiedCollection(with alias: TableAlias) -> SQLCollection { - self + // MARK: DatabaseRegionConvertible + + /// Returns the database region that the request feeds from. + /// + /// - parameter db: A database connection. + public func databaseRegion(_ db: Database) throws -> DatabaseRegion { + try makePreparedRequest(db, forSingleResult: false).statement.databaseRegion } + // MARK: SQLCollection + /// :nodoc: - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - self + public var _collectionExpressions: [SQLExpression]? { nil } + + /// :nodoc: + public func _collectionSQL(_ context: SQLGenerationContext) throws -> String { + try "(" + + _requestSQL(context, forSingleResult: false) + + ")" } - /// Returns an expression which applies the `IN` SQL operator. public func contains(_ value: SQLExpressible) -> SQLExpression { - _SQLExpressionContains(value, self) + SQLExpressionContains(value, self) + } + + /// :nodoc: + public func _qualifiedCollection(with alias: TableAlias) -> SQLCollection { self } + + // MARK: SQLExpression + + /// :nodoc: + public func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { + try "(" + + _requestSQL(context, forSingleResult: false) + + ")" + } + + /// :nodoc: + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { self } +} + +// MARK: - PreparedRequest + +/// A PreparedRequest is a request that is ready to be executed. +public struct PreparedRequest { + /// A prepared statement + public var statement: SelectStatement + + /// An eventual adapter for rows fetched by the select statement + public var adapter: RowAdapter? + + /// Support for eager loading of hasMany associations. + var supplementaryFetch: ((Database, [Row]) throws -> Void)? + + init( + statement: SelectStatement, + adapter: RowAdapter?, + supplementaryFetch: ((Database, [Row]) throws -> Void)? = nil) + { + self.statement = statement + self.adapter = adapter + self.supplementaryFetch = supplementaryFetch } } +extension PreparedRequest: Refinable { } + // MARK: - AdaptedFetchRequest extension FetchRequest { @@ -63,9 +143,30 @@ public struct AdaptedFetchRequest: FetchRequest { self.adapter = adapter } + public func fetchCount(_ db: Database) throws -> Int { + try base.fetchCount(db) + } + + public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { + var preparedRequest = try base.makePreparedRequest(db, forSingleResult: singleResult) + + if let baseAdapter = preparedRequest.adapter { + preparedRequest.adapter = try ChainedAdapter(first: baseAdapter, second: adapter(db)) + } else { + preparedRequest.adapter = try adapter(db) + } + + return preparedRequest + } + /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) + public func _selectedColumnCount(_ db: Database) throws -> Int { + try base._selectedColumnCount(db) + } + + /// :nodoc: + public func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { + try base._requestSQL(context, forSingleResult: singleResult) } } @@ -87,8 +188,21 @@ public struct AnyFetchRequest: FetchRequest { } /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try request._accept(&visitor) + public func _selectedColumnCount(_ db: Database) throws -> Int { + try request._selectedColumnCount(db) + } + + public func fetchCount(_ db: Database) throws -> Int { + try request.fetchCount(db) + } + + public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { + try request.makePreparedRequest(db, forSingleResult: singleResult) + } + + /// :nodoc: + public func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { + try request._requestSQL(context, forSingleResult: singleResult) } } @@ -101,13 +215,24 @@ extension AnyFetchRequest { } } -// Class-based type erasure, so that we preserve full type information in -// the generic `_accept(_:)` +// Class-based type erasure, so that we preserve full type information. private class FetchRequestEraser: FetchRequest { typealias RowDecoder = Void - func _accept(_ visitor: inout Visitor) throws { - fatalError("Abstract Method") + func _selectedColumnCount(_ db: Database) throws -> Int { + fatalError("subclass must override") + } + + func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { + fatalError("subclass must override") + } + + func fetchCount(_ db: Database) throws -> Int { + fatalError("subclass must override") + } + + func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { + fatalError("subclass must override") } } @@ -118,7 +243,19 @@ private final class ConcreteFetchRequestEraser: FetchRequ self.request = request } - override func _accept(_ visitor: inout Visitor) throws { - try request._accept(&visitor) + override func _selectedColumnCount(_ db: Database) throws -> Int { + try request._selectedColumnCount(db) + } + + override func fetchCount(_ db: Database) throws -> Int { + try request.fetchCount(db) + } + + override func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { + try request.makePreparedRequest(db, forSingleResult: singleResult) + } + + override func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { + try request._requestSQL(context, forSingleResult: singleResult) } } diff --git a/GRDB/Core/FetchRequestVisitor.swift b/GRDB/Core/FetchRequestVisitor.swift deleted file mode 100644 index 17a3fb48a..000000000 --- a/GRDB/Core/FetchRequestVisitor.swift +++ /dev/null @@ -1,6 +0,0 @@ -/// :nodoc: -public protocol _FetchRequestVisitor { - mutating func visit(_ request: AdaptedFetchRequest) throws - mutating func visit(_ request: QueryInterfaceRequest) throws - mutating func visit(_ request: SQLRequest) throws -} diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index 95213258c..4e4b4f1d4 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -41,13 +41,13 @@ public struct SQLLiteral { } return sql case let .subquery(requestPromise): - return try requestPromise.resolve(context.db).requestSQL(context, forSingleResult: false) + return try requestPromise.resolve(context.db)._requestSQL(context, forSingleResult: false) case let .expression(expression): - return try expression.expressionSQL(context, wrappedInParenthesis: false) + return try expression._expressionSQL(context, wrappedInParenthesis: false) case let .selectable(selectable): - return try selectable.resultColumnSQL(context) + return try selectable._resultColumnSQL(context) case let .orderingTerm(orderingTerm): - return try orderingTerm.orderingTermSQL(context) + return try orderingTerm._orderingTermSQL(context) } } @@ -119,7 +119,7 @@ public struct SQLLiteral { try elements.map { try $0.sql(context) }.joined() } - fileprivate func qualified(with alias: TableAlias) -> SQLLiteral { + func qualified(with alias: TableAlias) -> SQLLiteral { SQLLiteral(elements: elements.map { $0.qualified(with: alias) }) } } @@ -172,15 +172,15 @@ extension SQLLiteral { /// SQLLiteral(sql: "? + ?", arguments: [1, 2]).sqlExpression /// SQLLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]).sqlExpression public var sqlExpression: SQLExpression { - _SQLExpressionLiteral(sqlLiteral: self) + SQLExpressionLiteral(sqlLiteral: self) } var sqlSelectable: SQLSelectable { - _SQLSelectionLiteral(sqlLiteral: self) + SQLSelectionLiteral(sqlLiteral: self) } var sqlOrderingTerm: SQLOrderingTerm { - _SQLOrderingLiteral(sqlLiteral: self) + SQLOrderingLiteral(sqlLiteral: self) } } @@ -246,19 +246,40 @@ extension SQLLiteral: ExpressibleByStringInterpolation { } } -// MARK: - _SQLExpressionLiteral +// MARK: - SQLExpressionLiteral -/// SQLExpressionLiteral is an expression built from a raw SQL snippet. +// TODO: remove public qualifier when GRDB5 fixits are removed. +/// `SQLExpressionLiteral` is an expression built from a raw SQL snippet. /// -/// SQLExpressionLiteral(sql: "1 + 2") +/// To build one, use the `SQLiteral.sqlExpression` property: /// -/// The SQL literal may contain `?` and colon-prefixed arguments: +/// let name = "O'Brien" +/// let column = Column("name") +/// let literal: SQLLiteral = "\(column) = \(name)" +/// let expression = literal.sqlExpression /// -/// SQLExpressionLiteral(sql: "? + ?", arguments: [1, 2]) -/// SQLExpressionLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]) +/// Such expressions can feed query interface requests: +/// +/// try dbQueue.read { db in +/// // SELECT * FROM player WHERE name = 'O''Brien' +/// let players = try Player +/// .filter(expression) +/// .fetchAll(db) +/// +/// // SELECT player.*, team.* +/// // FROM player +/// // JOIN team WHERE team.id = player.teamID +/// // WHERE player.name = 'O''Brien' +/// let players = try Player +/// .including(required: Player.team) +/// .filter(expression) +/// .fetchAll(db) +/// } +/// +/// See SQLLiteral for more information. /// /// :nodoc: -public struct _SQLExpressionLiteral: SQLExpression { +public struct SQLExpressionLiteral: SQLExpression { let sqlLiteral: SQLLiteral // Prefer SQLLiteral.sqlExpression @@ -267,20 +288,25 @@ public struct _SQLExpressionLiteral: SQLExpression { } /// :nodoc: - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - sqlLiteral.qualified(with: alias).sqlExpression + public func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { + var resultSQL = try sqlLiteral.sql(context) + + if wrappedInParenthesis { + resultSQL = "(\(resultSQL))" + } + + return resultSQL } /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + sqlLiteral.qualified(with: alias).sqlExpression } } -// MARK: - _SQLSelectionLiteral +// MARK: - SQLSelectionLiteral -/// :nodoc: -public struct _SQLSelectionLiteral: SQLSelectable { +struct SQLSelectionLiteral: SQLSelectable { let sqlLiteral: SQLLiteral // Prefer SQLLiteral.sqlSelectable @@ -288,11 +314,7 @@ public struct _SQLSelectionLiteral: SQLSelectable { self.sqlLiteral = sqlLiteral } - /// :nodoc: - public func _count(distinct: Bool) -> _SQLCount? { nil } - - /// :nodoc: - public func _columnCount(_ db: Database) throws -> Int { + func _columnCount(_ db: Database) throws -> Int { fatalError(""" Selection literals don't known how many columns they contain. \ To resolve this error, select one or several literal expressions instead. \ @@ -300,21 +322,28 @@ public struct _SQLSelectionLiteral: SQLSelectable { """) } - /// :nodoc: - public func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { + func _count(distinct: Bool) -> _SQLCount? { nil } + + func _countedSQL(_ context: SQLGenerationContext) throws -> String { + fatalError(""" + Selection literals can't be counted. \ + To resolve this error, select one or several literal expressions instead. \ + See SQLLiteral.sqlExpression. + """) + } + + func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { sqlLiteral.qualified(with: alias).sqlSelectable } - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) + func _resultColumnSQL(_ context: SQLGenerationContext) throws -> String { + try sqlLiteral.sql(context) } } -// MARK: - _SQLOrderingLiteral +// MARK: - SQLOrderingLiteral -/// :nodoc: -public struct _SQLOrderingLiteral: SQLOrderingTerm { +struct SQLOrderingLiteral: SQLOrderingTerm { let sqlLiteral: SQLLiteral // Prefer SQLLiteral.sqlOrderingTerm @@ -322,21 +351,18 @@ public struct _SQLOrderingLiteral: SQLOrderingTerm { self.sqlLiteral = sqlLiteral } - /// :nodoc: - public var _reversed: SQLOrderingTerm { + func _orderingTermSQL(_ context: SQLGenerationContext) throws -> String { + try sqlLiteral.sql(context) + } + + func _qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { + sqlLiteral.qualified(with: alias).sqlOrderingTerm + } + + var _reversed: SQLOrderingTerm { fatalError(""" Ordering literals can't be reversed. \ To resolve this error, order by expression literals instead. """) } - - /// :nodoc: - public func _qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { - sqlLiteral.qualified(with: alias).sqlOrderingTerm - } - - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) - } } diff --git a/GRDB/Core/SQLRequest.swift b/GRDB/Core/SQLRequest.swift index f1517d23b..a1a7a4934 100644 --- a/GRDB/Core/SQLRequest.swift +++ b/GRDB/Core/SQLRequest.swift @@ -102,9 +102,39 @@ public struct SQLRequest { } extension SQLRequest: FetchRequest { + public func fetchCount(_ db: Database) throws -> Int { + try SQLRequest("SELECT COUNT(*) FROM (\(self))").fetchOne(db)! + } + + public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { + let context = SQLGenerationContext(db) + let sql = try sqlLiteral.sql(context) + let statement: SelectStatement + switch cache { + case .none: + statement = try db.makeSelectStatement(sql: sql) + case .public?: + statement = try db.cachedSelectStatement(sql: sql) + case .internal?: + statement = try db.internalCachedSelectStatement(sql: sql) + } + try statement.setArguments(context.arguments) + return PreparedRequest(statement: statement, adapter: adapter) + } + + /// :nodoc + public func _selectedColumnCount(_ db: Database) throws -> Int { + // Compile request. We can freely use the statement cache because we + // do not execute the statement or modify its arguments. + let context = SQLGenerationContext(db) + let sql = try _requestSQL(context, forSingleResult: false) + let statement = try db.cachedSelectStatement(sql: sql) + return statement.columnCount + } + /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) + public func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { + try sqlLiteral.sql(context) } } diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift index 915c56217..fab55f69c 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -194,22 +194,21 @@ extension FilteredRequest { { preconditionFailure() } } -@available(*, unavailable, message: "Build literal expressions with SQLLiteral.sqlExpression instead.") -public struct SQLExpressionLiteral: SQLExpression { +/// :nodoc: +extension SQLExpressionLiteral { + @available(*, unavailable, message: "Build literal expressions with SQLLiteral.sqlExpression instead.") public var sql: String { preconditionFailure() } + + @available(*, unavailable, message: "Build literal expressions with SQLLiteral.sqlExpression instead.") public var arguments: StatementArguments { preconditionFailure() } + @available(*, unavailable, message: "Build literal expressions with SQLLiteral.sqlExpression instead.") public init(sql: String, arguments: StatementArguments = StatementArguments()) { preconditionFailure() } + @available(*, unavailable, message: "Build literal expressions with SQLLiteral.sqlExpression instead.") public init(literal sqlLiteral: SQLLiteral) { preconditionFailure() } - - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression - { preconditionFailure() } - - public func _accept(_ visitor: inout Visitor) - { preconditionFailure() } } extension SQLLiteral { diff --git a/GRDB/QueryInterface/FTS3+QueryInterface.swift b/GRDB/QueryInterface/FTS3+QueryInterface.swift index 8974ce7c0..036133800 100644 --- a/GRDB/QueryInterface/FTS3+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS3+QueryInterface.swift @@ -16,7 +16,7 @@ extension TableRequest where Self: FilteredRequest { return none() } let alias = TableAlias() - let matchExpression = _SQLExpressionTableMatch(alias: alias, pattern: pattern.databaseValue) + let matchExpression = SQLExpressionTableMatch(alias: alias, pattern: pattern.databaseValue) return self.aliased(alias).filter(matchExpression) } } @@ -50,6 +50,6 @@ extension ColumnExpression { /// If the search pattern is nil, SQLite will evaluate the expression /// to false. public func match(_ pattern: FTS3Pattern?) -> SQLExpression { - _SQLExpressionBinary(.match, self, pattern ?? DatabaseValue.null) + SQLExpressionBinary(.match, self, pattern ?? DatabaseValue.null) } } diff --git a/GRDB/QueryInterface/FTS5+QueryInterface.swift b/GRDB/QueryInterface/FTS5+QueryInterface.swift index 6e66e3806..c0c69e771 100644 --- a/GRDB/QueryInterface/FTS5+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS5+QueryInterface.swift @@ -21,7 +21,7 @@ extension TableRequest where Self: FilteredRequest { return none() } let alias = TableAlias() - let matchExpression = _SQLExpressionTableMatch(alias: alias, pattern: pattern.databaseValue) + let matchExpression = SQLExpressionTableMatch(alias: alias, pattern: pattern.databaseValue) return self.aliased(alias).filter(matchExpression) } } diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index 41194075e..af082227d 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -38,7 +38,7 @@ extension AssociationToMany { /// /// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db) public var count: AssociationAggregate { - let expression = _SQLExpressionCountDistinct(_SQLExpressionFastPrimaryKey()) + let expression = SQLExpressionCountDistinct(SQLExpressionFastPrimaryKey()) return makeAggregate(expression).forKey("\(key.singularizedName)Count") } @@ -58,7 +58,7 @@ extension AssociationToMany { /// let teams: [Team] = try Team.having(!Team.players.isEmpty()) /// let teams: [Team] = try Team.having(Team.players.isEmpty() == false) public var isEmpty: AssociationAggregate { - let expression = _SQLExpressionIsEmpty(_SQLExpressionCountDistinct(_SQLExpressionFastPrimaryKey())) + let expression = SQLExpressionIsEmpty(SQLExpressionCountDistinct(SQLExpressionFastPrimaryKey())) return makeAggregate(expression).forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)") } @@ -80,7 +80,7 @@ extension AssociationToMany { /// /// let teams: [Team] = try Team.having(Team.players.average(Column("score")) > 100).fetchAll(db) public func average(_ expression: SQLExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(_SQLExpressionFunction("AVG", arguments: expression)) + let aggregate = makeAggregate(SQLExpressionFunction("AVG", arguments: expression)) if let column = expression as? ColumnExpression { let name = key.singularizedName return aggregate.forKey("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") @@ -107,7 +107,7 @@ extension AssociationToMany { /// /// let teams: [Team] = try Team.having(Team.players.max(Column("score")) < 100).fetchAll(db) public func max(_ expression: SQLExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(_SQLExpressionFunction("MAX", arguments: expression)) + let aggregate = makeAggregate(SQLExpressionFunction("MAX", arguments: expression)) if let column = expression as? ColumnExpression { let name = key.singularizedName return aggregate.forKey("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") @@ -134,7 +134,7 @@ extension AssociationToMany { /// /// let teams: [Team] = try Team.having(Team.players.min(Column("score")) > 100).fetchAll(db) public func min(_ expression: SQLExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(_SQLExpressionFunction("MIN", arguments: expression)) + let aggregate = makeAggregate(SQLExpressionFunction("MIN", arguments: expression)) if let column = expression as? ColumnExpression { let name = key.singularizedName return aggregate.forKey("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") @@ -161,7 +161,7 @@ extension AssociationToMany { /// /// let teams: [Team] = try Team.having(Team.players.sum(Column("score")) > 100).fetchAll(db) public func sum(_ expression: SQLExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(_SQLExpressionFunction("SUM", arguments: expression)) + let aggregate = makeAggregate(SQLExpressionFunction("SUM", arguments: expression)) if let column = expression as? ColumnExpression { let name = key.singularizedName return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum") diff --git a/GRDB/QueryInterface/Request/CommonTableExpression.swift b/GRDB/QueryInterface/Request/CommonTableExpression.swift index 510662d44..2fb7cf61d 100644 --- a/GRDB/QueryInterface/Request/CommonTableExpression.swift +++ b/GRDB/QueryInterface/Request/CommonTableExpression.swift @@ -159,7 +159,7 @@ extension CommonTableExpression { /// // name IN playerName /// playerNameCTE.contains(Column("name")) public func contains(_ element: SQLExpressible) -> SQLExpression { - _SQLTableCollection.tableName(tableName).contains(element) + SQLTableCollection.tableName(tableName).contains(element) } } @@ -195,9 +195,7 @@ struct SQLCTE { return columns.count } - var counter = SelectedColumnsCounter(db: db) - try requestPromise.resolve(db)._accept(&counter) - return counter.columnCount + return try requestPromise.resolve(db)._selectedColumnCount(db) } } diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index ef7dfaf1c..6ea60d15c 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -41,14 +41,31 @@ extension QueryInterfaceRequest { extension QueryInterfaceRequest: Refinable { } extension QueryInterfaceRequest: FetchRequest { - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) + public func fetchCount(_ db: Database) throws -> Int { + try query.fetchCount(db) + } + + public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { + let generator = SQLQueryGenerator(query: query, forSingleResult: singleResult) + var preparedRequest = try generator.makePreparedRequest(db) + let associations = query.relation.prefetchedAssociations + if associations.isEmpty == false { + // Eager loading of prefetched associations + preparedRequest = preparedRequest.with(\.supplementaryFetch) { db, rows in + try prefetch(db, associations: associations, into: rows, from: self) + } + } + return preparedRequest } /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) + public func _selectedColumnCount(_ db: Database) throws -> Int { + try SQLQueryGenerator(query: query).columnsCount(db) + } + + /// :nodoc: + public func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { + try SQLQueryGenerator(query: query, forSingleResult: singleResult).requestSQL(context) } } @@ -431,9 +448,9 @@ public struct ColumnAssignment { var value: SQLExpressible func sql(_ context: SQLGenerationContext) throws -> String { - try column.expressionSQL(context, wrappedInParenthesis: false) + - " = " + - value.sqlExpression.expressionSQL(context, wrappedInParenthesis: false) + try column._expressionSQL(context, wrappedInParenthesis: false) + + " = " + + value.sqlExpression._expressionSQL(context, wrappedInParenthesis: false) } } @@ -505,3 +522,248 @@ public func *= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssign public func /= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssignment { column.set(to: column / value) } + +// MARK: - Eager loading of hasMany associations + +// CAUTION: Keep this code in sync with prefetchedRegion(_:_:) +/// 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 baseRequest: The request that was used to fetch `baseRows`. +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: + // Likely a GRDB bug: such condition only exist for CTEs, which + // are not prefetched with including(all:) + fatalError("Not implemented: prefetch association without any foreign key") + + case let .foreignKey(request: foreignKeyRequest, originIsLeft: originIsLeft): + let pivotMapping = try foreignKeyRequest + .fetchForeignKeyMapping(db) + .joinMapping(originIsLeft: originIsLeft) + let pivotColumns = pivotMapping.map(\.right) + let leftColumns = pivotMapping.map(\.left) + + // We want to avoid the "Expression tree is too large" SQLite error + // 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 + // + // -- May be too complex for the SQLite engine + // SELECT * FROM child + // WHERE (a = ? AND b = ?) + // OR (a = ? AND b = ?) + // OR ... + // + // 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 is one precondition: row + // values must be available (https://www.sqlite.org/rowvalue.html). + // This is the case of almost all our target platforms. + // + // 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 { + // 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 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 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.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) + } + } + } +} + +/// 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 +{ + // We annotate prefetched rows with pivot columns, so that we can + // group them. + // + // Those pivot columns are necessary when we prefetch + // indirect associations: + // + // // SELECT country.*, passport.citizenId AS grdb_citizenId + // // -- ^ the necessary pivot column + // // FROM country + // // JOIN passport ON passport.countryCode = country.code + // // AND passport.citizenId IN (1, 2, 3) + // Citizen.including(all: Citizen.countries) + // + // Those pivot columns are redundant when we prefetch direct + // associations (maybe we'll remove this redundancy later): + // + // // SELECT *, authorId AS grdb_authorId + // // -- ^ the redundant pivot column + // // FROM book + // // WHERE authorId IN (1, 2, 3) + // Author.including(all: Author.books) + let pivotAlias = TableAlias() + + let prefetchRelation = association + .map(\.pivot.relation, { $0.qualified(with: pivotAlias).filter(pivotFilter) }) + .destinationRelation() + .annotated(with: pivotColumns.map { pivotAlias[$0].forKey("grdb_\($0)") }) + + return QueryInterfaceRequest(relation: prefetchRelation) +} + +// CAUTION: Keep this code in sync with prefetch(_:associations:in:) +/// Returns the region of prefetched associations +func prefetchedRegion(_ db: Database, associations: [_SQLAssociation]) throws -> DatabaseRegion { + try associations.reduce(into: DatabaseRegion()) { (region, association) in + switch association.pivot.condition { + case .expression: + // Likely a GRDB bug: such condition only exist for CTEs, which + // are not prefetched with including(all:) + fatalError("Not implemented: prefetch association without any foreign key") + + case let .foreignKey(request: foreignKeyRequest, originIsLeft: originIsLeft): + let pivotMapping = try foreignKeyRequest + .fetchForeignKeyMapping(db) + .joinMapping(originIsLeft: originIsLeft) + let prefetchRegion = try prefetchedRegion(db, association: association, pivotMapping: pivotMapping) + region.formUnion(prefetchRegion) + } + } +} + +// CAUTION: Keep this code in sync with prefetch(_:associations:in:) +func prefetchedRegion( + _ db: Database, + association: _SQLAssociation, + pivotMapping: JoinMapping) +throws -> DatabaseRegion +{ + // 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 = ? + // ^ content of the DummyRow + let pivotFilter = pivotMapping.joinExpression(leftRows: [DummyRow()]) + + let prefetchRelation = association + .map(\.pivot.relation) { $0.filter(pivotFilter) } + .destinationRelation() + + let prefetchQuery = SQLQuery(relation: prefetchRelation) + + return try SQLQueryGenerator(query: prefetchQuery) + .makeSelectStatement(db) + .databaseRegion // contains region of nested associations +} + +extension Array where Element == Row { + /// - precondition: Columns all exist in all rows. All rows have the same + /// columnns, in the same order. + fileprivate func grouped(byDatabaseValuesOnColumns columns: [String]) -> [[DatabaseValue]: [Row]] { + guard let firstRow = first else { + return [:] + } + let indexes = firstRow.indexes(forColumns: columns) + return Dictionary(grouping: self, by: { row in + indexes.map { row.impl.databaseValue(atUncheckedIndex: $0) } + }) + } +} + +extension Row { + /// - precondition: Columns all exist in the row. + fileprivate func indexes(forColumns columns: [String]) -> [Int] { + columns.map { column -> Int in + guard let index = index(forColumn: column) else { + fatalError("Column \(column) is not selected") + } + return index + } + } +} diff --git a/GRDB/QueryInterface/SQL/Column.swift b/GRDB/QueryInterface/SQL/Column.swift index 59bcdd445..36e887501 100644 --- a/GRDB/QueryInterface/SQL/Column.swift +++ b/GRDB/QueryInterface/SQL/Column.swift @@ -26,13 +26,13 @@ public protocol ColumnExpression: SQLExpression { extension ColumnExpression { /// :nodoc: - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - _SQLQualifiedColumn(name, alias: alias) + public func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { + name.quotedDatabaseIdentifier } /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + SQLQualifiedColumn(name, alias: alias) } } @@ -63,8 +63,8 @@ public struct Column: ColumnExpression, Equatable { /// A qualified column in the database, as in `SELECT t.a FROM t` /// /// :nodoc: -public struct _SQLQualifiedColumn: ColumnExpression { - public var name: String +struct SQLQualifiedColumn: ColumnExpression { + var name: String let alias: TableAlias /// Creates a column given its name. @@ -73,15 +73,26 @@ public struct _SQLQualifiedColumn: ColumnExpression { self.alias = alias } - /// :nodoc: - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - // Never requalify - self + func _column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool) throws -> String? { + if alias == self.alias { + return name + } else { + return nil + } } - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) + func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { + if let qualifier = context.qualifier(for: alias) { + return qualifier.quotedDatabaseIdentifier + + "." + + name.quotedDatabaseIdentifier + } + return name.quotedDatabaseIdentifier + } + + func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + // Never requalify + self } } diff --git a/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift b/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift index 780538677..531bcc21f 100644 --- a/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift @@ -7,7 +7,7 @@ /// /// // SELECT * FROM player WHERE email = 'arthur@example.com' COLLATE NOCASE /// Player.filter(email == "arthur@example.com") -public struct SQLCollatedExpression { +public struct SQLCollatedExpression: SQLOrderingTerm { /// The tainted expression public let expression: SQLExpression @@ -23,7 +23,7 @@ public struct SQLCollatedExpression { /// /// See https://github.com/groue/GRDB.swift/#the-query-interface public var asc: SQLOrderingTerm { - _SQLOrdering.asc(sqlExpression) + SQLOrdering.asc(sqlExpression) } /// Returns an ordering suitable for QueryInterfaceRequest.order() @@ -35,7 +35,7 @@ public struct SQLCollatedExpression { /// /// See https://github.com/groue/GRDB.swift/#the-query-interface public var desc: SQLOrderingTerm { - _SQLOrdering.desc(sqlExpression) + SQLOrdering.desc(sqlExpression) } #if GRDBCUSTOMSQLITE @@ -48,7 +48,7 @@ public struct SQLCollatedExpression { /// /// See https://github.com/groue/GRDB.swift/#the-query-interface public var ascNullsLast: SQLOrderingTerm { - _SQLOrdering.ascNullsLast(sqlExpression) + SQLOrdering.ascNullsLast(sqlExpression) } /// Returns an ordering suitable for QueryInterfaceRequest.order() @@ -60,7 +60,7 @@ public struct SQLCollatedExpression { /// /// See https://github.com/groue/GRDB.swift/#the-query-interface public var descNullsFirst: SQLOrderingTerm { - _SQLOrdering.descNullsFirst(sqlExpression) + SQLOrdering.descNullsFirst(sqlExpression) } #elseif !GRDBCIPHER /// Returns an ordering suitable for QueryInterfaceRequest.order() @@ -73,7 +73,7 @@ public struct SQLCollatedExpression { /// See https://github.com/groue/GRDB.swift/#the-query-interface @available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) public var ascNullsLast: SQLOrderingTerm { - _SQLOrdering.ascNullsLast(sqlExpression) + SQLOrdering.ascNullsLast(sqlExpression) } /// Returns an ordering suitable for QueryInterfaceRequest.order() @@ -86,7 +86,7 @@ public struct SQLCollatedExpression { /// See https://github.com/groue/GRDB.swift/#the-query-interface @available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) public var descNullsFirst: SQLOrderingTerm { - _SQLOrdering.descNullsFirst(sqlExpression) + SQLOrdering.descNullsFirst(sqlExpression) } #endif @@ -96,15 +96,14 @@ public struct SQLCollatedExpression { } var sqlExpression: SQLExpression { - _SQLExpressionCollate(expression, collationName: collationName) + SQLExpressionCollate(expression, collationName: collationName) } -} - -/// :nodoc: -extension SQLCollatedExpression: SQLOrderingTerm { + + // MARK: SQLOrderingTerm + /// :nodoc: - public var _reversed: SQLOrderingTerm { - desc + public func _orderingTermSQL(_ context: SQLGenerationContext) throws -> String { + try sqlExpression._orderingTermSQL(context) } /// :nodoc: @@ -113,7 +112,5 @@ extension SQLCollatedExpression: SQLOrderingTerm { } /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) - } + public var _reversed: SQLOrderingTerm { desc } } diff --git a/GRDB/QueryInterface/SQL/SQLCollection.swift b/GRDB/QueryInterface/SQL/SQLCollection.swift index 2bfe6a4d8..8f3712dc6 100644 --- a/GRDB/QueryInterface/SQL/SQLCollection.swift +++ b/GRDB/QueryInterface/SQL/SQLCollection.swift @@ -1,14 +1,21 @@ // MARK: - SQLCollection -/// Implementation details of `SQLCollection`. -/// -/// :nodoc: public protocol _SQLCollection { - /// Returns a qualified collection + /// Returns a qualified collection. + /// + /// :nodoc: func _qualifiedCollection(with alias: TableAlias) -> SQLCollection - /// Accepts a visitor - func _accept(_ visitor: inout Visitor) throws + /// The expressions in the collection, if known. + /// + /// :nodoc: + var _collectionExpressions: [SQLExpression]? { get } + + /// Returns an SQL string that represents the collection. + /// + /// - parameter context: An SQL generation context which accepts + /// statement arguments. + func _collectionSQL(_ context: SQLGenerationContext) throws -> String } /// SQLCollection is the protocol for types that can be checked for inclusion. @@ -18,17 +25,27 @@ public protocol SQLCollection: _SQLCollection { func contains(_ value: SQLExpressible) -> SQLExpression } -// MARK: - _SQLExpressionsArray +// MARK: - SQLExpressionsArray -/// _SQLExpressionsArray wraps an array of expressions +/// SQLExpressionsArray wraps an array of expressions /// -/// _SQLExpressionsArray([1, 2, 3]) +/// SQLExpressionsArray([1, 2, 3]) /// /// :nodoc: -public struct _SQLExpressionsArray: SQLCollection { +struct SQLExpressionsArray: SQLCollection { let expressions: [SQLExpression] - public func contains(_ value: SQLExpressible) -> SQLExpression { + var _collectionExpressions: [SQLExpression]? { expressions } + + func _collectionSQL(_ context: SQLGenerationContext) throws -> String { + try "(" + + expressions + .map { try $0._expressionSQL(context, wrappedInParenthesis: false) } + .joined(separator: ", ") + + ")" + } + + func contains(_ value: SQLExpressible) -> SQLExpression { guard let expression = expressions.first else { return false.databaseValue } @@ -41,72 +58,37 @@ public struct _SQLExpressionsArray: SQLCollection { if expressions.count == 1 { // Output `expr = value` instead of `expr IN (value)`, because it // looks nicer. And make sure we do not produce 'expr IS NULL'. - return _SQLExpressionEqual(.equal, value.sqlExpression, expression) + return SQLExpressionEqual(.equal, value.sqlExpression, expression) } - return _SQLExpressionContains(value, self) + return SQLExpressionContains(value, self) } - /// :nodoc: - public func _qualifiedCollection(with alias: TableAlias) -> SQLCollection { - _SQLExpressionsArray(expressions: expressions.map { $0._qualifiedExpression(with: alias) }) - } - - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) + func _qualifiedCollection(with alias: TableAlias) -> SQLCollection { + SQLExpressionsArray(expressions: expressions.map { $0._qualifiedExpression(with: alias) }) } } -// MARK: - _SQLTableCollection +// MARK: - SQLTableCollection -/// _SQLTableCollection aims at generating `value IN table` expressions. +/// SQLTableCollection aims at generating `value IN table` expressions. /// /// :nodoc: -public enum _SQLTableCollection: SQLCollection { +enum SQLTableCollection: SQLCollection { case tableName(String) - public func contains(_ value: SQLExpressible) -> SQLExpression { - return _SQLExpressionContains(value, self) + var _collectionExpressions: [SQLExpression]? { nil } + + func _collectionSQL(_ context: SQLGenerationContext) throws -> String { + switch self { + case let .tableName(tableName): + return tableName.quotedDatabaseIdentifier + } } - /// :nodoc: - public func _qualifiedCollection(with alias: TableAlias) -> SQLCollection { - self + func contains(_ value: SQLExpressible) -> SQLExpression { + return SQLExpressionContains(value, self) } - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws where Visitor: _SQLCollectionVisitor { - try visitor.visit(self) - } -} - -// MARK: - SQLCollectionExpressions - -extension SQLCollection { - /// The expressions in the collection, if possible - func expressions() -> [SQLExpression]? { - var visitor = SQLCollectionExpressions() - try! _accept(&visitor) - return visitor.expressions - } -} - -/// Support for SQLCollection.expressions -private struct SQLCollectionExpressions: _SQLCollectionVisitor { - var expressions: [SQLExpression]? - - mutating func visit(_ collection: _SQLExpressionsArray) throws { - expressions = collection.expressions - } - - mutating func visit(_ collection: _SQLTableCollection) throws { } - - // MARK: _FetchRequestVisitor - - mutating func visit(_ request: AdaptedFetchRequest) throws { } - - mutating func visit(_ request: QueryInterfaceRequest) throws { } - - mutating func visit(_ request: SQLRequest) throws { } + func _qualifiedCollection(with alias: TableAlias) -> SQLCollection { self } } diff --git a/GRDB/QueryInterface/SQL/SQLCollectionVisitor.swift b/GRDB/QueryInterface/SQL/SQLCollectionVisitor.swift deleted file mode 100644 index 7ea8109d3..000000000 --- a/GRDB/QueryInterface/SQL/SQLCollectionVisitor.swift +++ /dev/null @@ -1,5 +0,0 @@ -/// :nodoc: -public protocol _SQLCollectionVisitor: _FetchRequestVisitor { - mutating func visit(_ collection: _SQLExpressionsArray) throws - mutating func visit(_ collection: _SQLTableCollection) throws -} diff --git a/GRDB/QueryInterface/SQL/SQLExpressible.swift b/GRDB/QueryInterface/SQL/SQLExpressible.swift index 3bfad3c0a..a2e0d19ed 100644 --- a/GRDB/QueryInterface/SQL/SQLExpressible.swift +++ b/GRDB/QueryInterface/SQL/SQLExpressible.swift @@ -44,26 +44,3 @@ public protocol SQLSpecificExpressible: SQLExpressible { // - ==(SQLSpecificExpressible, SQLExpressible) // - ==(SQLSpecificExpressible, SQLSpecificExpressible) } - -// MARK: - SQLExpressible & SQLOrderingTerm - -extension SQLExpressible where Self: SQLOrderingTerm { - /// :nodoc: - public var _reversed: SQLOrderingTerm { - _SQLOrdering.desc(sqlExpression) - } -} - -// MARK: - SQLExpressible & SQLSelectable - -extension SQLExpressible where Self: SQLSelectable { - /// :nodoc: - public func _count(distinct: Bool) -> _SQLCount? { - sqlExpression._count(distinct: distinct) - } - - /// :nodoc: - public func _columnCount(_ db: Database) throws -> Int { - 1 - } -} diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift index 61be23e42..42307942a 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -6,47 +6,58 @@ extension SQLExpression { /// try "foo'bar".databaseValue.quotedSQL(db) // "'foo''bar'"" func quotedSQL(_ db: Database) throws -> String { let context = SQLGenerationContext(db, argumentsSink: .forRawSQL) - return try expressionSQL(context, wrappedInParenthesis: false) + return try _expressionSQL(context, wrappedInParenthesis: false) } } -// MARK: - _SQLExpressionNot +// MARK: - SQLExpressionNot /// :nodoc: -public struct _SQLExpressionNot: SQLExpression { +struct SQLExpressionNot: SQLExpression { let expression: SQLExpression init(_ expression: SQLExpression) { self.expression = expression } - /// :nodoc: - public func _is(_ test: _SQLBooleanTest) -> SQLExpression { + // MARK: SQLExpression + + func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { + var resultSQL = try "NOT \(expression._expressionSQL(context, wrappedInParenthesis: true))" + + if wrappedInParenthesis { + resultSQL = "(\(resultSQL))" + } + + return resultSQL + } + + func _is(_ test: _SQLBooleanTest) -> SQLExpression { switch test { case .true: - return _SQLExpressionEqual(.equal, self, true.sqlExpression) + return SQLExpressionEqual(.equal, self, true.sqlExpression) case .false: - return _SQLExpressionEqual(.equal, self, false.sqlExpression) + return SQLExpressionEqual(.equal, self, false.sqlExpression) case .falsey: // Support `NOT (NOT expression)` as a technique to build 0 or 1 - return _SQLExpressionNot(self) + return SQLExpressionNot(self) } } - /// :nodoc: - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - _SQLExpressionNot(expression._qualifiedExpression(with: alias)) + var _isConstantInRequest: Bool { expression._isConstantInRequest } + + func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + SQLExpressionNot(expression._qualifiedExpression(with: alias)) } - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) - } + // MARK: SQLSelectable + + var _isAggregate: Bool { expression._isAggregate } } -// MARK: - _SQLExpressionUnary +// MARK: - SQLExpressionUnary /// SQLUnaryOperator is a SQLite unary operator. struct SQLUnaryOperator: Hashable { @@ -68,11 +79,11 @@ struct SQLUnaryOperator: Hashable { static let minus = SQLUnaryOperator("-", needsRightSpace: false) } -/// _SQLExpressionUnary is an expression made of an unary operator and +/// SQLExpressionUnary is an expression made of an unary operator and /// an operand expression. /// /// :nodoc: -public struct _SQLExpressionUnary: SQLExpression { +struct SQLExpressionUnary: SQLExpression { let op: SQLUnaryOperator let expression: SQLExpression @@ -81,18 +92,40 @@ public struct _SQLExpressionUnary: SQLExpression { self.expression = value.sqlExpression } - /// :nodoc: - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - _SQLExpressionUnary(op, expression._qualifiedExpression(with: alias)) + // MARK: SQLExpression + + func _column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool) throws -> String? { + if acceptsBijection && op == .minus { + return try expression._column(db, for: alias, acceptsBijection: acceptsBijection) + } + + return nil } - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) + func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { + var resultSQL = try op.sql + + (op.needsRightSpace ? " " : "") + + expression._expressionSQL(context, wrappedInParenthesis: true) + + if wrappedInParenthesis { + resultSQL = "(\(resultSQL))" + } + + return resultSQL } + + var _isConstantInRequest: Bool { expression._isConstantInRequest } + + func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + SQLExpressionUnary(op, expression._qualifiedExpression(with: alias)) + } + + // MARK: SQLSelectable + + var _isAggregate: Bool { expression._isAggregate } } -// MARK: - _SQLExpressionBinary +// MARK: - SQLExpressionBinary /// SQLBinaryOperator is an SQLite binary operator, such as >, =, etc. struct SQLBinaryOperator: Hashable { @@ -147,13 +180,13 @@ struct SQLBinaryOperator: Hashable { static let match = SQLBinaryOperator("MATCH") } -/// _SQLExpressionBinary is an expression made of two expressions joined with a +/// SQLExpressionBinary is an expression made of two expressions joined with a /// binary operator. /// -/// _SQLExpressionBinary(.multiply, Column("length"), Column("width")) +/// SQLExpressionBinary(.multiply, Column("length"), Column("width")) /// /// :nodoc: -public struct _SQLExpressionBinary: SQLExpression { +struct SQLExpressionBinary: SQLExpression { let lhs: SQLExpression let op: SQLBinaryOperator let rhs: SQLExpression @@ -162,43 +195,76 @@ public struct _SQLExpressionBinary: SQLExpression { /// binary operator. /// /// // length * width - /// _SQLExpressionBinary(.subtract, Column("score"), Column("malus")) + /// SQLExpressionBinary(.subtract, Column("score"), Column("malus")) init(_ op: SQLBinaryOperator, _ lhs: SQLExpressible, _ rhs: SQLExpressible) { self.lhs = lhs.sqlExpression self.op = op self.rhs = rhs.sqlExpression } - /// :nodoc: - public func _is(_ test: _SQLBooleanTest) -> SQLExpression { + // MARK: SQLExpression + + func _column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool) throws -> String? { + guard acceptsBijection && op == .subtract else { + return nil + } + + if lhs._isConstantInRequest { + return try rhs._column(db, for: alias, acceptsBijection: acceptsBijection) + } else if rhs._isConstantInRequest { + return try lhs._column(db, for: alias, acceptsBijection: acceptsBijection) + } else { + return nil + } + } + + func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { + var resultSQL = try """ + \(lhs._expressionSQL(context, wrappedInParenthesis: true)) \ + \(op.sql) \ + \(rhs._expressionSQL(context, wrappedInParenthesis: true)) + """ + + if wrappedInParenthesis { + resultSQL = "(\(resultSQL))" + } + + return resultSQL + } + + func _is(_ test: _SQLBooleanTest) -> SQLExpression { switch test { case .true: - return _SQLExpressionEqual(.equal, self, true.sqlExpression) + return SQLExpressionEqual(.equal, self, true.sqlExpression) case .false: - return _SQLExpressionEqual(.equal, self, false.sqlExpression) + return SQLExpressionEqual(.equal, self, false.sqlExpression) case .falsey: if let negatedOp = op.negated { - return _SQLExpressionBinary(negatedOp, lhs, rhs) + return SQLExpressionBinary(negatedOp, lhs, rhs) } else { - return _SQLExpressionNot(self) + return SQLExpressionNot(self) } } } - /// :nodoc: - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - _SQLExpressionBinary(op, lhs._qualifiedExpression(with: alias), rhs._qualifiedExpression(with: alias)) + var _isConstantInRequest: Bool { + lhs._isConstantInRequest && rhs._isConstantInRequest } - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) + func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + SQLExpressionBinary(op, lhs._qualifiedExpression(with: alias), rhs._qualifiedExpression(with: alias)) + } + + // MARK: SQLSelectable + + var _isAggregate: Bool { + lhs._isAggregate || rhs._isAggregate } } -// MARK: - _SQLExpressionAssociativeBinary +// MARK: - SQLExpressionAssociativeBinary /// SQLAssociativeBinaryOperator is an SQLite associative binary operator, such /// as `+`, `*`, `AND`, etc. @@ -218,19 +284,28 @@ public struct SQLAssociativeBinaryOperator: Hashable { /// The neutral value let neutralValue: DatabaseValue - /// if true, (a • b) • c is strictly equal to a • (b • c). + /// If true, (a • b) • c is strictly equal to a • (b • c). /// /// `AND`, `OR`, `||` (concat) are stricly associative. /// /// `+` and `*` are not stricly associative when applied to floating /// point values. - let strictlyAssociative: Bool + let isStrictlyAssociative: Bool + + /// If true, (a • b) is a bijective function of a, and a bijective + /// function of b. + /// + /// `+` and `||` (concat) are bijective. + /// + /// `AND`, `OR` and `*` are not. + let isBijective: Bool /// Creates a binary operator - init(sql: String, neutralValue: DatabaseValue, strictlyAssociative: Bool) { + init(sql: String, neutralValue: DatabaseValue, strictlyAssociative: Bool, bijective: Bool) { self.sql = sql self.neutralValue = neutralValue - self.strictlyAssociative = strictlyAssociative + self.isStrictlyAssociative = strictlyAssociative + self.isBijective = bijective } /// The `+` binary operator @@ -242,7 +317,8 @@ public struct SQLAssociativeBinaryOperator: Hashable { public static let add = SQLAssociativeBinaryOperator( sql: "+", neutralValue: 0.databaseValue, - strictlyAssociative: false) + strictlyAssociative: false, + bijective: true) /// The `*` binary operator /// @@ -253,7 +329,8 @@ public struct SQLAssociativeBinaryOperator: Hashable { public static let multiply = SQLAssociativeBinaryOperator( sql: "*", neutralValue: 1.databaseValue, - strictlyAssociative: false) + strictlyAssociative: false, + bijective: false) /// The `AND` binary operator /// @@ -264,7 +341,8 @@ public struct SQLAssociativeBinaryOperator: Hashable { public static let and = SQLAssociativeBinaryOperator( sql: "AND", neutralValue: true.databaseValue, - strictlyAssociative: true) + strictlyAssociative: true, + bijective: false) /// The `OR` binary operator /// @@ -275,7 +353,8 @@ public struct SQLAssociativeBinaryOperator: Hashable { public static let or = SQLAssociativeBinaryOperator( sql: "OR", neutralValue: false.databaseValue, - strictlyAssociative: true) + strictlyAssociative: true, + bijective: false) /// The `||` string concatenation operator /// @@ -286,14 +365,15 @@ public struct SQLAssociativeBinaryOperator: Hashable { public static let concat = SQLAssociativeBinaryOperator( sql: "||", neutralValue: "".databaseValue, - strictlyAssociative: true) + strictlyAssociative: true, + bijective: true) } -/// `_SQLExpressionAssociativeBinary` is an expression made of several +/// `SQLExpressionAssociativeBinary` is an expression made of several /// expressions joined with an associative binary operator. /// /// :nodoc: -public struct _SQLExpressionAssociativeBinary: SQLExpression { +struct SQLExpressionAssociativeBinary: SQLExpression { let expressions: [SQLExpression] let op: SQLAssociativeBinaryOperator @@ -301,14 +381,14 @@ public struct _SQLExpressionAssociativeBinary: SQLExpression { /// binary operator. /// /// // length * width - /// _SQLExpressionAssociativeBinary(.multiply, [Column("length"), Column("width")]) + /// SQLExpressionAssociativeBinary(.multiply, [Column("length"), Column("width")]) init(_ op: SQLAssociativeBinaryOperator, _ expressions: [SQLExpression]) { self.op = op // flatten when possible: a • (b • c) = a • b • c - if op.strictlyAssociative { + if op.isStrictlyAssociative { self.expressions = expressions.flatMap { expression -> [SQLExpression] in - if let reduce = expression as? _SQLExpressionAssociativeBinary, reduce.op == op { + if let reduce = expression as? SQLExpressionAssociativeBinary, reduce.op == op { return reduce.expressions } else { return [expression] @@ -319,20 +399,138 @@ public struct _SQLExpressionAssociativeBinary: SQLExpression { } } - /// :nodoc: - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - _SQLExpressionAssociativeBinary(op, expressions.map { $0._qualifiedExpression(with: alias) }) - } + // MARK: SQLExpression - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { + func _column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool) throws -> String? { switch expressions.count { case 0: - try op.neutralValue._accept(&visitor) + return try op.neutralValue._column(db, for: alias, acceptsBijection: acceptsBijection) case 1: - try expressions[0]._accept(&visitor) + return try expressions[0]._column(db, for: alias, acceptsBijection: acceptsBijection) default: - try visitor.visit(self) + guard acceptsBijection && op.isBijective else { + return nil + } + + let nonConstants = expressions.filter { $0._isConstantInRequest == false } + if nonConstants.count == 1 { + return try nonConstants[0]._column(db, for: alias, acceptsBijection: acceptsBijection) + } + + return nil + } + } + + func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { + switch expressions.count { + case 0: + return try op.neutralValue._expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis) + case 1: + return try expressions[0]._expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis) + default: + let expressionSQLs = try expressions.map { + try $0._expressionSQL(context, wrappedInParenthesis: true) + } + let joiner = " \(op.sql) " + var resultSQL = expressionSQLs.joined(separator: joiner) + + if wrappedInParenthesis { + resultSQL = "(\(resultSQL))" + } + + return resultSQL + } + } + + func _identifyingColums(_ db: Database, for alias: TableAlias) throws -> Set { + switch expressions.count { + case 0: + return try op.neutralValue._identifyingColums(db, for: alias) + case 1: + return try expressions[0]._identifyingColums(db, for: alias) + default: + if op == .and { + return try expressions.reduce(into: []) { try $0.formUnion($1._identifyingColums(db, for: alias)) } + } else if op == .or { + return [] + } else { + return [] + } + } + } + + func _identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set? { + switch expressions.count { + case 0: + return try op.neutralValue._identifyingRowIDs(db, for: alias) + case 1: + return try expressions[0]._identifyingRowIDs(db, for: alias) + default: + if op == .and { + var result: Set? = nil + for expression in expressions { + if let expressionRowIDs = try expression._identifyingRowIDs(db, for: alias) { + if var rowIDs = result { + rowIDs.formIntersection(expressionRowIDs) + result = rowIDs + if rowIDs.isEmpty { + break + } + } else { + result = expressionRowIDs + } + } + } + return result + } else if op == .or { + var result: Set = [] + for expression in expressions { + if let expressionRowIDs = try expression._identifyingRowIDs(db, for: alias) { + result.formUnion(expressionRowIDs) + } else { + return nil + } + } + return result + } else { + return nil + } + } + } + + var _isConstantInRequest: Bool { + switch expressions.count { + case 0: + return op.neutralValue._isConstantInRequest + default: + return expressions.allSatisfy(\._isConstantInRequest) + } + } + + var _isTrue: Bool { + switch expressions.count { + case 0: + return op.neutralValue._isTrue + case 1: + return expressions[0]._isTrue + default: + // Could do better (1 OR x, for example) + return false + } + } + + func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + SQLExpressionAssociativeBinary(op, expressions.map { $0._qualifiedExpression(with: alias) }) + } + + // MARK: SQLSelectable + + var _isAggregate: Bool { + switch expressions.count { + case 0: + return op.neutralValue._isAggregate + default: + return expressions.contains(where: \._isAggregate) } } } @@ -357,14 +555,14 @@ extension Sequence where Element == SQLExpression { /// value of the operator. It is 0 (zero) for `.add`, 1 for ‘.multiply`, /// false for `.or`, and true for `.and`. public func joined(operator: SQLAssociativeBinaryOperator) -> SQLExpression { - _SQLExpressionAssociativeBinary(`operator`, Array(self)) + SQLExpressionAssociativeBinary(`operator`, Array(self)) } } -// MARK: - _SQLExpressionEqual +// MARK: - SQLExpressionEqual /// :nodoc: -public struct _SQLExpressionEqual: SQLExpression { +struct SQLExpressionEqual: SQLExpression { var lhs: SQLExpression var rhs: SQLExpression var op: Operator @@ -391,41 +589,116 @@ public struct _SQLExpressionEqual: SQLExpression { } } - /// :nodoc: - public func _is(_ test: _SQLBooleanTest) -> SQLExpression { - switch test { - case .true: - return _SQLExpressionEqual(.equal, self, true.sqlExpression) + // MARK: SQLExpression + + func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { + var resultSQL = try """ + \(lhs._expressionSQL(context, wrappedInParenthesis: true)) \ + \(op.rawValue) \ + \(rhs._expressionSQL(context, wrappedInParenthesis: true)) + """ + + if wrappedInParenthesis { + resultSQL = "(\(resultSQL))" + } + + return resultSQL + } + + func _identifyingColums(_ db: Database, for alias: TableAlias) throws -> Set { + switch op { + case .equal, .is: + if let column = try lhs._column(db, for: alias, acceptsBijection: true), + rhs._isConstantInRequest + { + return [column] + } - case .false: - return _SQLExpressionEqual(.equal, self, false.sqlExpression) + if let column = try rhs._column(db, for: alias, acceptsBijection: true), + lhs._isConstantInRequest + { + return [column] + } - case .falsey: - return _SQLExpressionEqual(op.negated, lhs, rhs) + return [] + + case .notEqual, .isNot: + return [] } } - /// :nodoc: - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - _SQLExpressionEqual(op, lhs._qualifiedExpression(with: alias), rhs._qualifiedExpression(with: alias)) + func _identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set? { + switch op { + case .equal, .is: + if let column = try lhs._column(db, for: alias), + try db.columnIsRowID(column, of: alias.tableName), + let dbValue = rhs as? DatabaseValue + { + if let rowID = Int64.fromDatabaseValue(dbValue) { + return [rowID] + } else { + // We miss `rowid = '1'` here, because SQLite would interpret the '1' string as a number + return [] + } + } + + if let column = try rhs._column(db, for: alias), + try db.columnIsRowID(column, of: alias.tableName), + let dbValue = lhs as? DatabaseValue + { + if let rowID = Int64.fromDatabaseValue(dbValue) { + return [rowID] + } else { + // We miss `rowid = '1'` here, because SQLite would interpret the '1' string as a number + return [] + } + } + + return nil + + case .notEqual, .isNot: + return nil + } } - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) + 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 SQLExpressionEqual(op.negated, lhs, rhs) + } + } + + var _isConstantInRequest: Bool { + lhs._isConstantInRequest && rhs._isConstantInRequest + } + + func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + SQLExpressionEqual(op, lhs._qualifiedExpression(with: alias), rhs._qualifiedExpression(with: alias)) + } + + // MARK: SQLSelectable + + var _isAggregate: Bool { + lhs._isAggregate || rhs._isAggregate } } -// MARK: - _SQLExpressionContains +// MARK: - SQLExpressionContains -/// _SQLExpressionContains is an expression that checks the inclusion of a +/// SQLExpressionContains is an expression that checks the inclusion of a /// value in a collection with the `IN` operator. /// /// // id IN (1,2,3) -/// _SQLExpressionContains(Column("id"), _SQLExpressionsArray([1,2,3])) +/// SQLExpressionContains(Column("id"), _SQLExpressionsArray([1,2,3])) /// /// :nodoc: -public struct _SQLExpressionContains: SQLExpression { +struct SQLExpressionContains: SQLExpression { let expression: SQLExpression let collection: SQLCollection let isNegated: Bool @@ -436,44 +709,93 @@ public struct _SQLExpressionContains: SQLExpression { self.isNegated = negated } - /// :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 _SQLExpressionContains(expression, collection, negated: !isNegated) + // MARK: SQLExpression + + func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { + var resultSQL = try """ + \(expression._expressionSQL(context, wrappedInParenthesis: true)) \ + \(isNegated ? "NOT IN" : "IN") \ + \(collection._collectionSQL(context)) + """ + + if wrappedInParenthesis { + resultSQL = "(\(resultSQL))" + } + + return resultSQL + } + + func _identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set? { + if + let expressions = collection._collectionExpressions, + let column = try expression._column(db, for: alias), + try db.columnIsRowID(column, of: alias.tableName) + { + return Set(expressions.compactMap { + ($0 as? DatabaseValue).flatMap { Int64.fromDatabaseValue($0) } + }) + } else { + return nil } } - /// :nodoc: - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - _SQLExpressionContains( + 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 SQLExpressionContains(expression, collection, negated: !isNegated) + } + } + + var _isConstantInRequest: Bool { + guard let expressions = collection._collectionExpressions else { + return false + } + + return expression._isConstantInRequest && expressions.allSatisfy(\._isConstantInRequest) + } + + func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + SQLExpressionContains( expression._qualifiedExpression(with: alias), collection._qualifiedCollection(with: alias), negated: isNegated) } - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) + // MARK: SQLSelectable + + var _isAggregate: Bool { + if expression._isAggregate { + // SELECT aggregate IN (...) + return true + } + + if let expressions = collection._collectionExpressions, + expressions.contains(where: \._isAggregate) + { + // SELECT expr IN (aggregate, ...) + return true + } + + return false } } -// MARK: - _SQLExpressionBetween +// MARK: - SQLExpressionBetween -/// _SQLExpressionBetween is an expression that checks if a values is included +/// SQLExpressionBetween is an expression that checks if a values is included /// in a range with the `BETWEEN` operator. /// /// // id BETWEEN 1 AND 3 -/// _SQLExpressionBetween(Column("id"), 1.databaseValue, 3.databaseValue) +/// SQLExpressionBetween(Column("id"), 1.databaseValue, 3.databaseValue) /// /// :nodoc: -public struct _SQLExpressionBetween: SQLExpression { +struct SQLExpressionBetween: SQLExpression { let expression: SQLExpression let lowerBound: SQLExpression let upperBound: SQLExpression @@ -486,39 +808,62 @@ public struct _SQLExpressionBetween: SQLExpression { self.isNegated = negated } - /// :nodoc: - public func _is(_ test: _SQLBooleanTest) -> SQLExpression { + // MARK: SQLExpression + + func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { + var resultSQL = try """ + \(expression._expressionSQL(context, wrappedInParenthesis: true)) \ + \(isNegated ? "NOT BETWEEN" : "BETWEEN") \ + \(lowerBound._expressionSQL(context, wrappedInParenthesis: true)) \ + AND \ + \(upperBound._expressionSQL(context, wrappedInParenthesis: true)) + """ + + if wrappedInParenthesis { + resultSQL = "(\(resultSQL))" + } + + return resultSQL + } + + func _is(_ test: _SQLBooleanTest) -> SQLExpression { switch test { case .true: - return _SQLExpressionEqual(.equal, self, true.sqlExpression) + return SQLExpressionEqual(.equal, self, true.sqlExpression) case .false: - return _SQLExpressionEqual(.equal, self, false.sqlExpression) + return SQLExpressionEqual(.equal, self, false.sqlExpression) case .falsey: - return _SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated) + return SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated) } } - /// :nodoc: - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - _SQLExpressionBetween( + var _isConstantInRequest: Bool { + expression._isConstantInRequest + && lowerBound._isConstantInRequest + && upperBound._isConstantInRequest + } + + func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + SQLExpressionBetween( expression._qualifiedExpression(with: alias), lowerBound._qualifiedExpression(with: alias), upperBound._qualifiedExpression(with: alias), negated: isNegated) } - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) + // MARK: SQLSelectable + + var _isAggregate: Bool { + expression._isAggregate } } -// MARK: - _SQLExpressionFunction +// MARK: - SQLExpressionFunction /// :nodoc: -public struct _SQLExpressionFunction: SQLExpression { +struct SQLExpressionFunction: SQLExpression { let function: String let arguments: [SQLExpression] @@ -531,26 +876,83 @@ public struct _SQLExpressionFunction: SQLExpression { self.init(function, arguments: arguments.map(\.sqlExpression)) } - /// :nodoc: - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - _SQLExpressionFunction(function, arguments: arguments.map { $0._qualifiedExpression(with: alias) }) + // MARK: SQLExpression + + func _column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool) throws -> String? { + guard acceptsBijection else { + return nil + } + let function = self.function.uppercased() + if ["HEX", "QUOTE"].contains(function) && arguments.count == 1 { + return try arguments[0]._column(db, for: alias, acceptsBijection: acceptsBijection) + } else if function == "IFNULL" && arguments.count == 2 && arguments[1]._isConstantInRequest { + return try arguments[0]._column(db, for: alias, acceptsBijection: acceptsBijection) + } else { + return nil + } } - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) + func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { + try function + + "(" + + arguments + .map { try $0._expressionSQL(context, wrappedInParenthesis: false) } + .joined(separator: ", ") + + ")" + } + + private static let knownPureFunctions = [ + "ABS", "CHAR", "COALESCE", "GLOB", "HEX", "IFNULL", + "IIF", "INSTR", "LENGTH", "LIKE", "LIKELIHOOD", + "LIKELY", "LOAD_EXTENSION", "LOWER", "LTRIM", + "NULLIF", "PRINTF", "QUOTE", "REPLACE", "ROUND", + "RTRIM", "SOUNDEX", "SQLITE_COMPILEOPTION_GET", + "SQLITE_COMPILEOPTION_USED", "SQLITE_SOURCE_ID", + "SQLITE_VERSION", "SUBSTR", "TRIM", "TRIM", + "TYPEOF", "UNICODE", "UNLIKELY", "UPPER", "ZEROBLOB", + ] + + var _isConstantInRequest: Bool { + let function = self.function.uppercased() + guard + ((function == "MAX" || function == "MIN") && arguments.count > 1) + || Self.knownPureFunctions.contains(function) + else { + return false // Don't know - assume not constant + } + + return arguments.allSatisfy(\._isConstantInRequest) + } + + func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + SQLExpressionFunction(function, arguments: arguments.map { $0._qualifiedExpression(with: alias) }) + } + + // MARK: SQLSelectable + + var _isAggregate: Bool { + let function = self.function.uppercased() + if ["MIN", "MAX"].contains(function) && arguments.count == 1 { + return true + } else if ["AVG", "COUNT", "SUM", "TOTAL"].contains(function) && arguments.count == 1 { + return true + } else if function == "GROUP_CONCAT" && (arguments.count == 1 || arguments.count == 2) { + return true + } else { + return false + } } } -// MARK: - _SQLExpressionCount +// MARK: - SQLExpressionCount -/// _SQLExpressionCount is a call to the SQL `COUNT` function. +/// SQLExpressionCount is a call to the SQL `COUNT` function. /// /// // COUNT(name) -/// _SQLExpressionCount(Column("name")) +/// SQLExpressionCount(Column("name")) /// /// :nodoc: -public struct _SQLExpressionCount: SQLExpression { +struct SQLExpressionCount: SQLExpression { /// The counted value let counted: SQLSelectable @@ -558,51 +960,59 @@ public struct _SQLExpressionCount: SQLExpression { self.counted = counted } - /// :nodoc: - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - _SQLExpressionCount(counted._qualifiedSelectable(with: alias)) + // MARK: SQLExpression + + func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { + try "COUNT(\(counted._countedSQL(context)))" } - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) + func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + SQLExpressionCount(counted._qualifiedSelectable(with: alias)) } + + // MARK: SQLSelectable + + var _isAggregate: Bool { true } } -// MARK: - _SQLExpressionCountDistinct +// MARK: - SQLExpressionCountDistinct -/// _SQLExpressionCountDistinct is a call to the SQL `COUNT(DISTINCT ...)` function. +/// SQLExpressionCountDistinct is a call to the SQL `COUNT(DISTINCT ...)` function. /// /// // COUNT(DISTINCT name) -/// _SQLExpressionCountDistinct(Column("name")) +/// SQLExpressionCountDistinct(Column("name")) /// /// :nodoc: -public struct _SQLExpressionCountDistinct: SQLExpression { +struct SQLExpressionCountDistinct: SQLExpression { let counted: SQLExpression init(_ counted: SQLExpression) { self.counted = counted } - /// :nodoc: - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - _SQLExpressionCountDistinct(counted._qualifiedExpression(with: alias)) + // MARK: SQLExpression + + func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { + try "COUNT(DISTINCT \(counted._countedSQL(context)))" } - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) + func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + SQLExpressionCountDistinct(counted._qualifiedExpression(with: alias)) } + + // MARK: SQLSelectable + + var _isAggregate: Bool { true } } -// MARK: - _SQLExpressionIsEmpty +// MARK: - SQLExpressionIsEmpty /// This one helps generating `COUNT(...) = 0` or `COUNT(...) > 0` while letting /// the user using the not `!` logical operator, or comparisons with booleans /// such as `== true` or `== false`. /// /// :nodoc: -public struct _SQLExpressionIsEmpty: SQLExpression { +struct SQLExpressionIsEmpty: SQLExpression { var countExpression: SQLExpression var isEmpty: Bool @@ -612,56 +1022,78 @@ public struct _SQLExpressionIsEmpty: SQLExpression { self.isEmpty = isEmpty } - /// :nodoc: - public func _is(_ test: _SQLBooleanTest) -> SQLExpression { + // MARK: SQLExpression + + func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { + var resultSQL = try """ + \(countExpression._expressionSQL(context, wrappedInParenthesis: true)) \ + \(isEmpty ? "= 0" : "> 0") + """ + + if wrappedInParenthesis { + resultSQL = "(\(resultSQL))" + } + + return resultSQL + } + + func _is(_ test: _SQLBooleanTest) -> SQLExpression { switch test { case .true: return self case .false, .falsey: - return _SQLExpressionIsEmpty(countExpression, isEmpty: !isEmpty) + return SQLExpressionIsEmpty(countExpression, isEmpty: !isEmpty) } } - /// :nodoc: - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - _SQLExpressionIsEmpty(countExpression._qualifiedExpression(with: alias), isEmpty: isEmpty) + var _isConstantInRequest: Bool { countExpression._isConstantInRequest } + + func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + SQLExpressionIsEmpty(countExpression._qualifiedExpression(with: alias), isEmpty: isEmpty) } - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) - } + // MARK: SQLSelectable + + var _isAggregate: Bool { countExpression._isAggregate } } -// MARK: - _SQLExpressionTableMatch +// MARK: - SQLExpressionTableMatch /// :nodoc: -public struct _SQLExpressionTableMatch: SQLExpression { +struct SQLExpressionTableMatch: SQLExpression { var alias: TableAlias var pattern: SQLExpression - /// :nodoc: - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - _SQLExpressionTableMatch( + func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { + var resultSQL = try """ + \(context.resolvedName(for: alias).quotedDatabaseIdentifier) \ + MATCH \ + \(pattern._expressionSQL(context, wrappedInParenthesis: true)) + """ + + if wrappedInParenthesis { + resultSQL = "(\(resultSQL))" + } + + return resultSQL + } + + func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + SQLExpressionTableMatch( alias: self.alias, pattern: pattern._qualifiedExpression(with: alias)) } - - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) - } } -// MARK: - _SQLExpressionCollate +// MARK: - SQLExpressionCollate -/// _SQLExpressionCollate is an expression tainted by an SQLite collation. +/// SQLExpressionCollate is an expression tainted by an SQLite collation. /// /// // email = 'arthur@example.com' COLLATE NOCASE -/// _SQLExpressionCollate(Column("email") == "arthur@example.com", "NOCASE") +/// SQLExpressionCollate(Column("email") == "arthur@example.com", "NOCASE") /// /// :nodoc: -public struct _SQLExpressionCollate: SQLExpression { +struct SQLExpressionCollate: SQLExpression { let expression: SQLExpression let collationName: Database.CollationName @@ -670,58 +1102,77 @@ public struct _SQLExpressionCollate: SQLExpression { self.collationName = collationName } - /// :nodoc: - public func _is(_ test: _SQLBooleanTest) -> SQLExpression { - _SQLExpressionCollate(expression._is(test), collationName: collationName) + // MARK: SQLExpression + + func _column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool) throws -> String? { + try expression._column(db, for: alias, acceptsBijection: acceptsBijection) } - /// :nodoc: - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - _SQLExpressionCollate(expression._qualifiedExpression(with: alias), collationName: collationName) + func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { + var resultSQL = try """ + \(expression._expressionSQL(context, wrappedInParenthesis: false)) \ + COLLATE \ + \(collationName.rawValue) + """ + + if wrappedInParenthesis { + resultSQL = "(\(resultSQL))" + } + + return resultSQL } - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) + func _identifyingColums(_ db: Database, for alias: TableAlias) throws -> Set { + try expression._identifyingColums(db, for: alias) } + + func _identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set? { + try expression._identifyingRowIDs(db, for: alias) + } + + func _is(_ test: _SQLBooleanTest) -> SQLExpression { + SQLExpressionCollate(expression._is(test), collationName: collationName) + } + + var _isConstantInRequest: Bool { expression._isConstantInRequest } + + var _isTrue: Bool { expression._isTrue } + + func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + SQLExpressionCollate(expression._qualifiedExpression(with: alias), collationName: collationName) + } + + // MARK: SQLSelectable + + var _isAggregate: Bool { expression._isAggregate } + } -// MARK: - _SQLExpressionFastPrimaryKey +// MARK: - SQLExpressionFastPrimaryKey -/// _SQLExpressionFastPrimaryKey is an expression that picks the fastest available +/// SQLExpressionFastPrimaryKey is an expression that picks the fastest available /// primary key. /// /// It crashes for WITHOUT ROWID table with a multi-columns primary key. /// Future versions of GRDB may use [row values](https://www.sqlite.org/rowvalue.html). /// /// :nodoc: -public struct _SQLExpressionFastPrimaryKey: SQLExpression { - /// :nodoc: - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - _SQLExpressionQualifiedFastPrimaryKey(alias: alias) +struct SQLExpressionFastPrimaryKey: SQLExpression { + func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { + // Likely a GRDB bug: how comes this expression is used before it + // has been qualified? + fatalError("SQLExpressionFastPrimaryKey is not qualified.") } - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) + func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + SQLExpressionQualifiedFastPrimaryKey(alias: alias) } } /// :nodoc: -public struct _SQLExpressionQualifiedFastPrimaryKey: SQLExpression { +struct SQLExpressionQualifiedFastPrimaryKey: SQLExpression { let alias: TableAlias - /// :nodoc: - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - // Never requalify - self - } - - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) - } - /// Return the name of the fast primary key column func columnName(_ db: Database) throws -> String { let primaryKey = try db.primaryKey(alias.tableName) @@ -738,4 +1189,21 @@ public struct _SQLExpressionQualifiedFastPrimaryKey: SQLExpression { fatalError("Not implemented: WITHOUT ROWID table with a multi-columns primary key") } } + + func _column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool) throws -> String? { + if alias == self.alias { + return try columnName(db) + } + return nil + } + + func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { + try SQLQualifiedColumn(columnName(context.db), alias: alias) + ._expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis) + } + + func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + // Never requalify + self + } } diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index c89490b20..e1447e426 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -1,9 +1,66 @@ -// MARK: - SQLExpression - /// Implementation details of `SQLExpression`. /// /// :nodoc: public protocol _SQLExpression { + /// If this expression is a table colum, returns the name of this column. + /// + /// When in doubt, returns nil. + /// + /// - parameter acceptsBijection: If true, expressions that define a + /// bijection on a column return this column. For example: `-score` + /// returns `score`. + func _column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool) throws -> String? + + /// Returns an SQL string that represents the expression. + /// + /// - parameter context: An SQL generation context which accepts + /// statement arguments. + /// - parameter wrappedInParenthesis: If true, the returned SQL should be + /// wrapped inside parenthesis. + func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String + + /// Returns the columns that identify a unique row in the request + /// + /// When in doubt, returns an empty set. + /// + /// WHERE 0 -- [] + /// WHERE a -- [] + /// WHERE a = b -- [] + /// WHERE a = 1 -- ["a"] + /// WHERE a = 1 AND b = 2 -- ["a", "b"] + /// WHERE a = 1 AND b = 2 AND c > 0 -- ["a", "b"] + /// 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 + + /// Returns the rowIds that identify rows in the request. A nil result means + /// an unbounded list. + /// + /// When in doubt, returns nil. + /// + /// WHERE 1 -- nil + /// WHERE 0 -- [] + /// WHERE NULL -- [] + /// WHERE id IS NULL -- [] + /// WHERE id = 1 -- [1] + /// WHERE id = 1 AND b = 2 -- [1] + /// WHERE id = 1 OR id = 2 -- [1, 2] + /// WHERE id IN (1, 2, 3) -- [1, 2, 3] + /// 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? + /// Performs a boolean test. /// /// We generally distinguish four boolean values: @@ -42,11 +99,36 @@ public protocol _SQLExpression { /// - `association.isEmpty == false` -> `COUNT(child.id) > 0` func _is(_ test: _SQLBooleanTest) -> SQLExpression + /// Returns true if the expression has a unique value when SQLite runs + /// a request. + /// + /// When in doubt, returns false. + /// + /// 1 -- true + /// 1 + 2 -- true + /// score -- false + /// + /// This property supports `_identifyingColums(_:for:)` + var _isConstantInRequest: Bool { get } + + /// Returns true iff the expression is trivially true. + /// + /// When in doubt, returns false. + /// + /// This property helps clearing up the ON clause. + var _isTrue: Bool { get } + /// Returns a qualified expression func _qualifiedExpression(with alias: TableAlias) -> SQLExpression - - /// Accepts a visitor - func _accept(_ visitor: inout Visitor) throws +} + +extension _SQLExpression { + /// If this expression is a table colum, returns the name of this column. + /// + /// When in doubt, returns nil. + func _column(_ db: Database, for alias: TableAlias) throws -> String? { + try _column(db, for: alias, acceptsBijection: false) + } } /// SQLExpression is the protocol for types that represent an SQL expression, as @@ -70,47 +152,66 @@ public enum _SQLBooleanTest { } extension SQLExpression { - /// The default implementation of boolean tests. - /// + /// Returns self + public var sqlExpression: SQLExpression { self } + + // MARK: _SQLExpression + + /// :nodoc: + public func _column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool) throws -> String? { + nil + } + + /// :nodoc: + public func _identifyingColums(_ db: Database, for alias: TableAlias) throws -> Set { + [] + } + + /// :nodoc: + public func _identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set? { + nil + } + /// :nodoc: public func _is(_ test: _SQLBooleanTest) -> SQLExpression { switch test { case .true: - return _SQLExpressionEqual(.equal, self, true.sqlExpression) + return SQLExpressionEqual(.equal, self, true.sqlExpression) case .false: - return _SQLExpressionEqual(.equal, self, false.sqlExpression) + return SQLExpressionEqual(.equal, self, false.sqlExpression) case .falsey: - return _SQLExpressionNot(self) + return SQLExpressionNot(self) } } -} - -extension SQLExpression { + /// :nodoc: - public func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { - _qualifiedExpression(with: alias) + public var _isConstantInRequest: Bool { false } + + /// :nodoc: + public var _isTrue: Bool { false } + + // MARK: SQLOrderingTerm + + /// :nodoc: + public func _orderingTermSQL(_ context: SQLGenerationContext) throws -> String { + try _expressionSQL(context, wrappedInParenthesis: false) } /// :nodoc: public func _qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { _qualifiedExpression(with: alias) } -} - -// SQLExpression: SQLExpressible - -extension SQLExpression { + /// :nodoc: - public var sqlExpression: SQLExpression { - self - } -} + public var _reversed: SQLOrderingTerm { desc } + + // MARK: SQLSelectable + + /// :nodoc: + public func _columnCount(_ db: Database) throws -> Int { 1 } -// SQLExpression: SQLSelectable - -extension SQLExpression { /// :nodoc: public func _count(distinct: Bool) -> _SQLCount? { if distinct { @@ -125,4 +226,19 @@ extension SQLExpression { return .all } } + + /// :nodoc: + public func _countedSQL(_ context: SQLGenerationContext) throws -> String { + try _expressionSQL(context, wrappedInParenthesis: false) + } + + /// :nodoc: + public func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { + _qualifiedExpression(with: alias) + } + + /// :nodoc: + public func _resultColumnSQL(_ context: SQLGenerationContext) throws -> String { + try _expressionSQL(context, wrappedInParenthesis: false) + } } diff --git a/GRDB/QueryInterface/SQL/SQLExpressionVisitor.swift b/GRDB/QueryInterface/SQL/SQLExpressionVisitor.swift deleted file mode 100644 index 24d99821a..000000000 --- a/GRDB/QueryInterface/SQL/SQLExpressionVisitor.swift +++ /dev/null @@ -1,25 +0,0 @@ -/// :nodoc: -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 - mutating func visit(_ expr: _SQLExpressionAssociativeBinary) throws - mutating func visit(_ expr: _SQLExpressionCollate) throws - mutating func visit(_ expr: _SQLExpressionContains) throws - mutating func visit(_ expr: _SQLExpressionCount) throws - mutating func visit(_ expr: _SQLExpressionCountDistinct) throws - mutating func visit(_ expr: _SQLExpressionEqual) throws - mutating func visit(_ expr: _SQLExpressionFastPrimaryKey) throws - mutating func visit(_ expr: _SQLExpressionFunction) throws - mutating func visit(_ expr: _SQLExpressionIsEmpty) throws - mutating func visit(_ expr: _SQLExpressionLiteral) throws - mutating func visit(_ expr: _SQLExpressionNot) throws - mutating func visit(_ expr: _SQLExpressionQualifiedFastPrimaryKey) throws - mutating func visit(_ expr: _SQLExpressionTableMatch) throws - mutating func visit(_ expr: _SQLExpressionUnary) throws -} diff --git a/GRDB/QueryInterface/SQL/SQLFunctions.swift b/GRDB/QueryInterface/SQL/SQLFunctions.swift index c6a9e2cbb..5f4e4a261 100644 --- a/GRDB/QueryInterface/SQL/SQLFunctions.swift +++ b/GRDB/QueryInterface/SQL/SQLFunctions.swift @@ -5,7 +5,7 @@ extension DatabaseFunction { /// /// See https://github.com/groue/GRDB.swift/#sql-functions public func callAsFunction(_ arguments: SQLExpressible...) -> SQLExpression { - _SQLExpressionFunction(name, arguments: arguments.map(\.sqlExpression)) + SQLExpressionFunction(name, arguments: arguments.map(\.sqlExpression)) } } @@ -17,7 +17,7 @@ extension DatabaseFunction { /// // ABS(amount) /// abs(Column("amount")) public func abs(_ value: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionFunction("ABS", arguments: value) + SQLExpressionFunction("ABS", arguments: value) } @@ -28,7 +28,7 @@ public func abs(_ value: SQLSpecificExpressible) -> SQLExpression { /// // AVG(length) /// average(Column("length")) public func average(_ value: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionFunction("AVG", arguments: value) + SQLExpressionFunction("AVG", arguments: value) } @@ -39,7 +39,7 @@ public func average(_ value: SQLSpecificExpressible) -> SQLExpression { /// // COUNT(email) /// count(Column("email")) public func count(_ counted: SQLSelectable) -> SQLExpression { - _SQLExpressionCount(counted) + SQLExpressionCount(counted) } @@ -50,7 +50,7 @@ public func count(_ counted: SQLSelectable) -> SQLExpression { /// // COUNT(DISTINCT email) /// count(distinct: Column("email")) public func count(distinct value: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionCountDistinct(value.sqlExpression) + SQLExpressionCountDistinct(value.sqlExpression) } @@ -61,7 +61,7 @@ public func count(distinct value: SQLSpecificExpressible) -> SQLExpression { /// // IFNULL(name, 'Anonymous') /// Column("name") ?? "Anonymous" public func ?? (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - _SQLExpressionFunction("IFNULL", arguments: lhs, rhs) + SQLExpressionFunction("IFNULL", arguments: lhs, rhs) } @@ -72,7 +72,7 @@ public func ?? (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// // LENGTH(name) /// length(Column("name")) public func length(_ value: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionFunction("LENGTH", arguments: value) + SQLExpressionFunction("LENGTH", arguments: value) } @@ -83,7 +83,7 @@ public func length(_ value: SQLSpecificExpressible) -> SQLExpression { /// // MAX(score) /// max(Column("score")) public func max(_ value: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionFunction("MAX", arguments: value) + SQLExpressionFunction("MAX", arguments: value) } @@ -94,7 +94,7 @@ public func max(_ value: SQLSpecificExpressible) -> SQLExpression { /// // MIN(score) /// min(Column("score")) public func min(_ value: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionFunction("MIN", arguments: value) + SQLExpressionFunction("MIN", arguments: value) } @@ -105,7 +105,7 @@ public func min(_ value: SQLSpecificExpressible) -> SQLExpression { /// // SUM(amount) /// sum(Column("amount")) public func sum(_ value: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionFunction("SUM", arguments: value) + SQLExpressionFunction("SUM", arguments: value) } @@ -186,7 +186,7 @@ extension SQLSpecificExpressible { /// `dateTime(_:_:)`. /// /// For more information, see https://www.sqlite.org/lang_datefunc.html -public enum SQLDateModifier: SQLExpression { +public enum SQLDateModifier: SQLSpecificExpressible { /// Adds the specified amount of seconds case second(Double) @@ -226,6 +226,10 @@ public enum SQLDateModifier: SQLExpression { /// See https://www.sqlite.org/lang_datefunc.html case utc + public var sqlExpression: SQLExpression { + rawValue.databaseValue + } + var rawValue: String { switch self { case let .day(value): @@ -256,16 +260,6 @@ public enum SQLDateModifier: SQLExpression { return "utc" } } - - /// :nodoc: - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - self - } - - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try rawValue.databaseValue._accept(&visitor) - } } // MARK: JULIANDAY(...) @@ -280,7 +274,7 @@ public enum SQLDateModifier: SQLExpression { /// /// For more information, see https://www.sqlite.org/lang_datefunc.html public func julianDay(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression { - _SQLExpressionFunction("JULIANDAY", arguments: [value.sqlExpression] + modifiers) + SQLExpressionFunction("JULIANDAY", arguments: [value.sqlExpression] + modifiers.map(\.sqlExpression)) } // MARK: DATETIME(...) @@ -295,5 +289,5 @@ public func julianDay(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModif /// /// For more information, see https://www.sqlite.org/lang_datefunc.html public func dateTime(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression { - _SQLExpressionFunction("DATETIME", arguments: [value.sqlExpression] + modifiers) + SQLExpressionFunction("DATETIME", arguments: [value.sqlExpression] + modifiers.map(\.sqlExpression)) } diff --git a/GRDB/QueryInterface/SQL/SQLOperators.swift b/GRDB/QueryInterface/SQL/SQLOperators.swift index 475deee30..84759d2b4 100644 --- a/GRDB/QueryInterface/SQL/SQLOperators.swift +++ b/GRDB/QueryInterface/SQL/SQLOperators.swift @@ -6,19 +6,19 @@ private func isEqual(_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpressio case let (lhs, rhs as DatabaseValue): switch rhs.storage { case .null: - return _SQLExpressionEqual(.is, lhs, rhs) + return SQLExpressionEqual(.is, lhs, rhs) default: - return _SQLExpressionEqual(.equal, lhs, rhs) + return SQLExpressionEqual(.equal, lhs, rhs) } case let (lhs as DatabaseValue, rhs): switch lhs.storage { case .null: - return _SQLExpressionEqual(.is, rhs, lhs) + return SQLExpressionEqual(.is, rhs, lhs) default: - return _SQLExpressionEqual(.equal, lhs, rhs) + return SQLExpressionEqual(.equal, lhs, rhs) } default: - return _SQLExpressionEqual(.equal, lhs, rhs) + return SQLExpressionEqual(.equal, lhs, rhs) } } @@ -45,7 +45,7 @@ public func == (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpress /// // name IS NULL /// Column("name").collating(.nocase) == nil public func == (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpression { - _SQLExpressionCollate(lhs.expression == rhs, collationName: lhs.collationName) + SQLExpressionCollate(lhs.expression == rhs, collationName: lhs.collationName) } /// An SQL expression that checks the boolean value of an expression. @@ -88,7 +88,7 @@ public func == (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpress /// // name IS NULL /// nil == Column("name").collating(.nocase) public func == (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression { - _SQLExpressionCollate(lhs == rhs.expression, collationName: rhs.collationName) + SQLExpressionCollate(lhs == rhs.expression, collationName: rhs.collationName) } /// An SQL expression that checks the boolean value of an expression. @@ -207,7 +207,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// // name IS 'Arthur' /// Column("name") === "Arthur" public func === (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { - _SQLExpressionEqual(.is, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null) + SQLExpressionEqual(.is, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null) } /// An SQL expression that compares two expressions with the `IS` SQL operator. @@ -215,7 +215,7 @@ public func === (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpres /// // name IS 'Arthur' COLLATE NOCASE /// Column("name").collating(.nocase) === "Arthur" public func === (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpression { - _SQLExpressionCollate(lhs.expression === rhs, collationName: lhs.collationName) + SQLExpressionCollate(lhs.expression === rhs, collationName: lhs.collationName) } /// An SQL expression that compares two expressions with the `IS` SQL operator. @@ -224,9 +224,9 @@ public func === (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpress /// "Arthur" === Column("name") public func === (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { if let lhs = lhs { - return _SQLExpressionEqual(.is, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionEqual(.is, lhs.sqlExpression, rhs.sqlExpression) } else { - return _SQLExpressionEqual(.is, rhs.sqlExpression, DatabaseValue.null) + return SQLExpressionEqual(.is, rhs.sqlExpression, DatabaseValue.null) } } @@ -235,7 +235,7 @@ public func === (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpres /// // name IS 'Arthur' COLLATE NOCASE /// "Arthur" === Column("name").collating(.nocase) public func === (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression { - _SQLExpressionCollate(lhs === rhs.expression, collationName: rhs.collationName) + SQLExpressionCollate(lhs === rhs.expression, collationName: rhs.collationName) } /// An SQL expression that compares two expressions with the `IS` SQL operator. @@ -243,7 +243,7 @@ public func === (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpress /// // email IS login /// Column("email") === Column("login") public func === (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionEqual(.is, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionEqual(.is, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `IS NOT` SQL operator. @@ -293,7 +293,7 @@ public func !== (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQ /// // score < 18 /// Column("score") < 18 public func < (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - _SQLExpressionBinary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `<` SQL operator. @@ -301,7 +301,7 @@ public func < (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// // name < 'Arthur' COLLATE NOCASE /// Column("name").collating(.nocase) < "Arthur" public func < (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression { - _SQLExpressionCollate(lhs.expression < rhs, collationName: lhs.collationName) + SQLExpressionCollate(lhs.expression < rhs, collationName: lhs.collationName) } /// An SQL expression that compares two expressions with the `<` SQL operator. @@ -309,7 +309,7 @@ public func < (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression /// // 18 < score /// 18 < Column("score") public func < (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionBinary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `<` SQL operator. @@ -317,7 +317,7 @@ public func < (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// // 'Arthur' < name COLLATE NOCASE /// "Arthur" < Column("name").collating(.nocase) public func < (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression { - _SQLExpressionCollate(lhs < rhs.expression, collationName: rhs.collationName) + SQLExpressionCollate(lhs < rhs.expression, collationName: rhs.collationName) } /// An SQL expression that compares two expressions with the `<` SQL operator. @@ -325,7 +325,7 @@ public func < (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression /// // width < height /// Column("width") < Column("height") public func < (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionBinary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `<=` SQL operator. @@ -333,7 +333,7 @@ public func < (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// // score <= 18 /// Column("score") <= 18 public func <= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - _SQLExpressionBinary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `<=` SQL operator. @@ -341,7 +341,7 @@ public func <= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// // name <= 'Arthur' COLLATE NOCASE /// Column("name").collating(.nocase) <= "Arthur" public func <= (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression { - _SQLExpressionCollate(lhs.expression <= rhs, collationName: lhs.collationName) + SQLExpressionCollate(lhs.expression <= rhs, collationName: lhs.collationName) } /// An SQL expression that compares two expressions with the `<=` SQL operator. @@ -349,7 +349,7 @@ public func <= (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpressio /// // 18 <= score /// 18 <= Column("score") public func <= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionBinary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `<=` SQL operator. @@ -357,7 +357,7 @@ public func <= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// // 'Arthur' <= name COLLATE NOCASE /// "Arthur" <= Column("name").collating(.nocase) public func <= (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression { - _SQLExpressionCollate(lhs <= rhs.expression, collationName: rhs.collationName) + SQLExpressionCollate(lhs <= rhs.expression, collationName: rhs.collationName) } /// An SQL expression that compares two expressions with the `<=` SQL operator. @@ -365,7 +365,7 @@ public func <= (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpressio /// // width <= height /// Column("width") <= Column("height") public func <= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionBinary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `>` SQL operator. @@ -373,7 +373,7 @@ public func <= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// // score > 18 /// Column("score") > 18 public func > (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - _SQLExpressionBinary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `>` SQL operator. @@ -381,7 +381,7 @@ public func > (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// // name > 'Arthur' COLLATE NOCASE /// Column("name").collating(.nocase) > "Arthur" public func > (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression { - _SQLExpressionCollate(lhs.expression > rhs, collationName: lhs.collationName) + SQLExpressionCollate(lhs.expression > rhs, collationName: lhs.collationName) } /// An SQL expression that compares two expressions with the `>` SQL operator. @@ -389,7 +389,7 @@ public func > (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression /// // 18 > score /// 18 > Column("score") public func > (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionBinary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `>` SQL operator. @@ -397,7 +397,7 @@ public func > (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// // 'Arthur' > name COLLATE NOCASE /// "Arthur" > Column("name").collating(.nocase) public func > (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression { - _SQLExpressionCollate(lhs > rhs.expression, collationName: rhs.collationName) + SQLExpressionCollate(lhs > rhs.expression, collationName: rhs.collationName) } /// An SQL expression that compares two expressions with the `>` SQL operator. @@ -405,7 +405,7 @@ public func > (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression /// // width > height /// Column("width") > Column("height") public func > (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionBinary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `>=` SQL operator. @@ -413,7 +413,7 @@ public func > (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// // score >= 18 /// Column("score") >= 18 public func >= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - _SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `>=` SQL operator. @@ -421,7 +421,7 @@ public func >= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// // name >= 'Arthur' COLLATE NOCASE /// Column("name").collating(.nocase) >= "Arthur" public func >= (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression { - _SQLExpressionCollate(lhs.expression >= rhs, collationName: lhs.collationName) + SQLExpressionCollate(lhs.expression >= rhs, collationName: lhs.collationName) } /// An SQL expression that compares two expressions with the `>=` SQL operator. @@ -429,7 +429,7 @@ public func >= (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpressio /// // 18 >= score /// 18 >= Column("score") public func >= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `>=` SQL operator. @@ -437,7 +437,7 @@ public func >= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// // 'Arthur' >= name COLLATE NOCASE /// "Arthur" >= Column("name").collating(.nocase) public func >= (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression { - _SQLExpressionCollate(lhs >= rhs.expression, collationName: rhs.collationName) + SQLExpressionCollate(lhs >= rhs.expression, collationName: rhs.collationName) } /// An SQL expression that compares two expressions with the `>=` SQL operator. @@ -445,7 +445,7 @@ public func >= (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpressio /// // width >= height /// Column("width") >= Column("height") public func >= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } // MARK: - Inclusion Operators (BETWEEN, IN) @@ -474,7 +474,7 @@ extension ClosedRange where Bound: SQLExpressible { /// // email BETWEEN 'A' AND 'B' /// ("A"..."B").contains(Column("email")) public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionBetween(element.sqlExpression, lowerBound.sqlExpression, upperBound.sqlExpression) + SQLExpressionBetween(element.sqlExpression, lowerBound.sqlExpression, upperBound.sqlExpression) } /// An SQL expression that checks the inclusion of an expression in a range. @@ -482,7 +482,7 @@ extension ClosedRange where Bound: SQLExpressible { /// // email BETWEEN 'A' AND 'B' COLLATE NOCASE /// ("A"..."B").contains(Column("email").collating(.nocase)) public func contains(_ element: SQLCollatedExpression) -> SQLExpression { - _SQLExpressionCollate(contains(element.expression), collationName: element.collationName) + SQLExpressionCollate(contains(element.expression), collationName: element.collationName) } } @@ -502,7 +502,7 @@ extension CountableClosedRange where Bound: SQLExpressible { /// // id BETWEEN 1 AND 10 /// (1...10).contains(Column("id")) public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionBetween(element.sqlExpression, lowerBound.sqlExpression, upperBound.sqlExpression) + SQLExpressionBetween(element.sqlExpression, lowerBound.sqlExpression, upperBound.sqlExpression) } } @@ -513,7 +513,7 @@ extension Sequence where Self.Iterator.Element: SQLExpressible { /// // id IN (1,2,3) /// [1, 2, 3].contains(Column("id")) public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionsArray(expressions: map(\.sqlExpression)).contains(element.sqlExpression) + SQLExpressionsArray(expressions: map(\.sqlExpression)).contains(element.sqlExpression) } /// An SQL expression that checks the inclusion of an expression in @@ -522,7 +522,7 @@ extension Sequence where Self.Iterator.Element: SQLExpressible { /// // name IN ('A', 'B') COLLATE NOCASE /// ["A", "B"].contains(Column("name").collating(.nocase)) public func contains(_ element: SQLCollatedExpression) -> SQLExpression { - _SQLExpressionCollate(contains(element.expression), collationName: element.collationName) + SQLExpressionCollate(contains(element.expression), collationName: element.collationName) } } @@ -533,7 +533,7 @@ extension Sequence where Self.Iterator.Element == SQLExpressible { /// // id IN (1,2,3) /// [1, 2, 3].contains(Column("id")) public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionsArray(expressions: map(\.sqlExpression)).contains(element.sqlExpression) + SQLExpressionsArray(expressions: map(\.sqlExpression)).contains(element.sqlExpression) } /// An SQL expression that checks the inclusion of an expression in @@ -542,7 +542,7 @@ extension Sequence where Self.Iterator.Element == SQLExpressible { /// // name IN ('A', 'B') COLLATE NOCASE /// ["A", "B"].contains(Column("name").collating(.nocase)) public func contains(_ element: SQLCollatedExpression) -> SQLExpression { - _SQLExpressionCollate(contains(element.expression), collationName: element.collationName) + SQLExpressionCollate(contains(element.expression), collationName: element.collationName) } } @@ -554,7 +554,7 @@ extension Sequence where Self.Iterator.Element == SQLExpressible { /// // width * 2 /// Column("width") * 2 public func * (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - _SQLExpressionAssociativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) + SQLExpressionAssociativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic multiplication. @@ -562,7 +562,7 @@ public func * (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// // 2 * width /// 2 * Column("width") public func * (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionAssociativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) + SQLExpressionAssociativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic multiplication. @@ -570,7 +570,7 @@ public func * (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// // width * height /// Column("width") * Column("height") public func * (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionAssociativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) + SQLExpressionAssociativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic division. @@ -578,7 +578,7 @@ public func * (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// // width / 2 /// Column("width") / 2 public func / (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - _SQLExpressionBinary(.divide, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.divide, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL arithmetic division. @@ -586,7 +586,7 @@ public func / (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// // 2 / width /// 2 / Column("width") public func / (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionBinary(.divide, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.divide, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL arithmetic division. @@ -594,7 +594,7 @@ public func / (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// // width / height /// Column("width") / Column("height") public func / (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionBinary(.divide, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.divide, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL arithmetic addition. @@ -602,7 +602,7 @@ public func / (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// // width + 2 /// Column("width") + 2 public func + (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - _SQLExpressionAssociativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) + SQLExpressionAssociativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic addition. @@ -610,7 +610,7 @@ public func + (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// // 2 + width /// 2 + Column("width") public func + (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionAssociativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) + SQLExpressionAssociativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic addition. @@ -618,7 +618,7 @@ public func + (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// // width + height /// Column("width") + Column("height") public func + (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionAssociativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) + SQLExpressionAssociativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) } /// A negated SQL arithmetic expression. @@ -626,7 +626,7 @@ public func + (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// // -width /// -Column("width") public prefix func - (value: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionUnary(.minus, value.sqlExpression) + SQLExpressionUnary(.minus, value.sqlExpression) } /// An SQL arithmetic substraction. @@ -634,7 +634,7 @@ public prefix func - (value: SQLSpecificExpressible) -> SQLExpression { /// // width - 2 /// Column("width") - 2 public func - (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - _SQLExpressionBinary(.subtract, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.subtract, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL arithmetic substraction. @@ -642,7 +642,7 @@ public func - (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// // 2 - width /// 2 - Column("width") public func - (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionBinary(.subtract, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.subtract, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL arithmetic substraction. @@ -650,7 +650,7 @@ public func - (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// // width - height /// Column("width") - Column("height") public func - (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionBinary(.subtract, lhs.sqlExpression, rhs.sqlExpression) + SQLExpressionBinary(.subtract, lhs.sqlExpression, rhs.sqlExpression) } @@ -661,7 +661,7 @@ public func - (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// // favorite AND 0 /// Column("favorite") && false public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - _SQLExpressionAssociativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) + SQLExpressionAssociativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `AND` SQL operator. @@ -669,7 +669,7 @@ public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// // 0 AND favorite /// false && Column("favorite") public func && (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionAssociativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) + SQLExpressionAssociativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `AND` SQL operator. @@ -677,7 +677,7 @@ public func && (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// // email IS NOT NULL AND favorite /// Column("email") != nil && Column("favorite") public func && (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionAssociativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) + SQLExpressionAssociativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -685,7 +685,7 @@ public func && (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// // favorite OR 1 /// Column("favorite") || true public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - _SQLExpressionAssociativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) + SQLExpressionAssociativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -693,7 +693,7 @@ public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// // 0 OR favorite /// true || Column("favorite") public func || (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionAssociativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) + SQLExpressionAssociativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -701,7 +701,7 @@ public func || (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// // email IS NULL OR hidden /// Column("email") == nil || Column("hidden") public func || (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - _SQLExpressionAssociativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) + SQLExpressionAssociativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) } /// A negated logical SQL expression with the `NOT` SQL operator. @@ -727,6 +727,6 @@ extension SQLSpecificExpressible { /// // email LIKE '%@example.com" /// Column("email").like("%@example.com") public func like(_ pattern: SQLExpressible) -> SQLExpression { - _SQLExpressionBinary(.like, self, pattern) + SQLExpressionBinary(.like, self, pattern) } } diff --git a/GRDB/QueryInterface/SQL/SQLOrdering.swift b/GRDB/QueryInterface/SQL/SQLOrdering.swift index 4e20e3f3b..1ae4dc6d8 100644 --- a/GRDB/QueryInterface/SQL/SQLOrdering.swift +++ b/GRDB/QueryInterface/SQL/SQLOrdering.swift @@ -1,5 +1,3 @@ -// MARK: - SQLOrderingTerm - /// Implementation details of `SQLOrderingTerm`. /// /// :nodoc: @@ -10,23 +8,24 @@ public protocol _SQLOrderingTerm { /// Returns a qualified ordering func _qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm - /// Accepts a visitor - func _accept(_ visitor: inout Visitor) throws + /// Returns the SQL that feeds the `ORDER BY` clause. + /// + /// - parameter context: An SQL generation context which accepts + /// statement arguments. + func _orderingTermSQL(_ context: SQLGenerationContext) throws -> String } /// The protocol for all types that can be used as an SQL ordering term, as /// described at https://www.sqlite.org/syntax/ordering-term.html public protocol SQLOrderingTerm: _SQLOrderingTerm { } -// MARK: - _SQLOrdering - /// :nodoc: -public enum _SQLOrdering: SQLOrderingTerm, Refinable { +enum SQLOrdering: SQLOrderingTerm, Refinable { case asc(SQLExpression) case desc(SQLExpression) - // Only available from 3.30.0. This enum is not public, so those cases don't - // harm as long as we don't expose them through public APIs. + // Only available from SQLite 3.30.0. This enum is not public, so those + // cases don't harm as long as we don't expose them through public APIs. case ascNullsLast(SQLExpression) case descNullsFirst(SQLExpression) @@ -57,27 +56,33 @@ public enum _SQLOrdering: SQLOrderingTerm, Refinable { } } - /// :nodoc: - public var _reversed: SQLOrderingTerm { + func _orderingTermSQL(_ context: SQLGenerationContext) throws -> String { switch self { case .asc(let expression): - return _SQLOrdering.desc(expression) + return try expression._expressionSQL(context, wrappedInParenthesis: false) + " ASC" case .desc(let expression): - return _SQLOrdering.asc(expression) + return try expression._expressionSQL(context, wrappedInParenthesis: false) + " DESC" case .ascNullsLast(let expression): - return _SQLOrdering.descNullsFirst(expression) + return try expression._expressionSQL(context, wrappedInParenthesis: false) + " ASC NULLS LAST" case .descNullsFirst(let expression): - return _SQLOrdering.ascNullsLast(expression) + return try expression._expressionSQL(context, wrappedInParenthesis: false) + " DESC NULLS FIRST" } } - /// :nodoc: - public func _qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { + func _qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { map(\.expression) { $0._qualifiedExpression(with: alias) } } - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) + var _reversed: SQLOrderingTerm { + switch self { + case .asc(let expression): + return SQLOrdering.desc(expression) + case .desc(let expression): + return SQLOrdering.asc(expression) + case .ascNullsLast(let expression): + return SQLOrdering.descNullsFirst(expression) + case .descNullsFirst(let expression): + return SQLOrdering.ascNullsLast(expression) + } } } diff --git a/GRDB/QueryInterface/SQL/SQLOrderingTermVisitor.swift b/GRDB/QueryInterface/SQL/SQLOrderingTermVisitor.swift deleted file mode 100644 index 70805fbcf..000000000 --- a/GRDB/QueryInterface/SQL/SQLOrderingTermVisitor.swift +++ /dev/null @@ -1,6 +0,0 @@ -/// :nodoc: -public protocol _SQLOrderingTermVisitor: _SQLExpressionVisitor { - mutating func visit(_ ordering: SQLCollatedExpression) throws - mutating func visit(_ ordering: _SQLOrdering) throws - mutating func visit(_ ordering: _SQLOrderingLiteral) throws -} diff --git a/GRDB/QueryInterface/SQL/SQLQuery.swift b/GRDB/QueryInterface/SQL/SQLQuery.swift index 1671eb1a2..558177cc6 100644 --- a/GRDB/QueryInterface/SQL/SQLQuery.swift +++ b/GRDB/QueryInterface/SQL/SQLQuery.swift @@ -119,9 +119,9 @@ extension SQLQuery { countQuery.isDistinct = false switch count { case .all: - countQuery = countQuery.select(_SQLExpressionCount(AllColumns())) + countQuery = countQuery.select(SQLExpressionCount(AllColumns())) case .distinct(let expression): - countQuery = countQuery.select(_SQLExpressionCountDistinct(expression)) + countQuery = countQuery.select(SQLExpressionCountDistinct(expression)) } return try QueryInterfaceRequest(query: countQuery).fetchOne(db)! } else { @@ -134,7 +134,7 @@ extension SQLQuery { // SELECT expr1, expr2, ... FROM tableName ... // -> // SELECT COUNT(*) FROM tableName ... - let countQuery = unordered().select(_SQLExpressionCount(AllColumns())) + let countQuery = unordered().select(SQLExpressionCount(AllColumns())) return try QueryInterfaceRequest(query: countQuery).fetchOne(db)! } } diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index a2697e549..154e63e35 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -632,7 +632,7 @@ extension JoinMapping { .map({ mapping -> SQLExpression in let leftValue = leftRow.databaseValue(at: mapping.leftIndex) // Force `=` operator, because SQLite doesn't match foreign keys on NULL - return _SQLExpressionEqual(.equal, mapping.rightColumn, leftValue) + return SQLExpressionEqual(.equal, mapping.rightColumn, leftValue) }) .joined(operator: .and) }) @@ -652,7 +652,7 @@ extension JoinMapping { /// the AND operator and qualified with the right table. func joinExpressions(leftAlias: TableAlias) -> [SQLExpression] { map { - Column($0.right) == _SQLQualifiedColumn($0.left, alias: leftAlias) + Column($0.right) == SQLQualifiedColumn($0.left, alias: leftAlias) } } } diff --git a/GRDB/QueryInterface/SQL/SQLRowValue.swift b/GRDB/QueryInterface/SQL/SQLRowValue.swift index 763cb70f6..97c250f2e 100644 --- a/GRDB/QueryInterface/SQL/SQLRowValue.swift +++ b/GRDB/QueryInterface/SQL/SQLRowValue.swift @@ -1,7 +1,7 @@ /// A [row value](https://www.sqlite.org/rowvalue.html). /// /// :nodoc: -public struct _SQLRowValue: SQLExpression { +struct SQLRowValue: SQLExpression { let expressions: [SQLExpression] /// SQLite row values were shipped in SQLite 3.15: @@ -14,15 +14,57 @@ public struct _SQLRowValue: SQLExpression { self.expressions = expressions } - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - _SQLRowValue(expressions.map { $0._qualifiedExpression(with: alias) }) + // MARK: - SQLExpression + + func _column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool) throws -> String? { + if let expression = expressions.first, expressions.count == 1 { + return try expression._column(db, for: alias, acceptsBijection: acceptsBijection) + } + + return nil } - public func _accept(_ visitor: inout Visitor) throws { + func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { if let expression = expressions.first, expressions.count == 1 { - try expression._accept(&visitor) - } else { - try visitor.visit(self) + return try expression._expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis) } + + let values = try expressions.map { + try $0._expressionSQL(context, wrappedInParenthesis: false) + } + + return "(" + + values.joined(separator: ", ") + + ")" + } + + func _identifyingColums(_ db: Database, for alias: TableAlias) throws -> Set { + if let expression = expressions.first, expressions.count == 1 { + return try expression._identifyingColums(db, for: alias) + } + + return try expressions.reduce(into: []) { try $0.formUnion($1._identifyingColums(db, for: alias)) } + } + + var _isConstantInRequest: Bool { + expressions.allSatisfy(\._isConstantInRequest) + } + + var _isTrue: Bool { + if let expression = expressions.first, expressions.count == 1 { + return expression._isTrue + } + + return false + } + + func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + SQLRowValue(expressions.map { $0._qualifiedExpression(with: alias) }) + } + + // MARK: - SQLSelectable + + var _isAggregate: Bool { + expressions.contains(where: \._isAggregate) } } diff --git a/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift index 84266ae68..8c585f9c2 100644 --- a/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift @@ -14,7 +14,7 @@ /// /// // SELECT *, rowid FROM player /// let request = Player.all() -public struct AllColumns { +public struct AllColumns: SQLSelectable { // As long as the CTE is embedded here, the following request will fail // at runtime, in `_columnCount(_:)`, because we can't access the number of // columns in the CTE: @@ -48,9 +48,16 @@ public struct AllColumns { init(cte: SQLCTE) { self.cte = cte } -} - -extension AllColumns: SQLSelectable { + + /// :nodoc: + public func _columnCount(_ db: Database) throws -> Int { + if let cte = cte { + return try cte.columnsCount(db) + } + + fatalError("Can't compute number of columns without an alias") + } + /// :nodoc: public func _count(distinct: Bool) -> _SQLCount? { // SELECT DISTINCT * FROM tableName ... @@ -65,32 +72,24 @@ extension AllColumns: SQLSelectable { return .all } + /// :nodoc: + public func _countedSQL(_ context: SQLGenerationContext) throws -> String { "*" } + /// :nodoc: public func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { - _SQLQualifiedAllColumns(alias: alias, cte: cte) + SQLQualifiedAllColumns(alias: alias, cte: cte) } /// :nodoc: - public func _columnCount(_ db: Database) throws -> Int { - if let cte = cte { - return try cte.columnsCount(db) - } - - fatalError("Can't compute number of columns without an alias") - } - - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) - } + public func _resultColumnSQL(_ context: SQLGenerationContext) throws -> String { "*" } } -// MARK: - _SQLQualifiedAllColumns +// MARK: - SQLQualifiedAllColumns /// _SQLQualifiedAllColumns is the `t.*` in `SELECT t.*`. /// /// :nodoc: -public struct _SQLQualifiedAllColumns { +struct SQLQualifiedAllColumns: SQLSelectable { /// When nil, select all columns from a regular database table. /// When not nil, select all columns from a common table expression. var cte: SQLCTE? @@ -100,20 +99,8 @@ public struct _SQLQualifiedAllColumns { self.alias = alias self.cte = cte } -} - -extension _SQLQualifiedAllColumns: SQLSelectable { - /// :nodoc: - public func _count(distinct: Bool) -> _SQLCount? { nil } - /// :nodoc: - public func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { - // Never requalify - return self - } - - /// :nodoc: - public func _columnCount(_ db: Database) throws -> Int { + func _columnCount(_ db: Database) throws -> Int { if let cte = cte { return try cte.columnsCount(db) } else { @@ -121,16 +108,34 @@ extension _SQLQualifiedAllColumns: SQLSelectable { } } - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) + func _count(distinct: Bool) -> _SQLCount? { nil } + + func _countedSQL(_ context: SQLGenerationContext) throws -> String { + if context.qualifier(for: alias) != nil { + // SELECT COUNT(t.*) is invalid SQL + fatalError("Not implemented, or invalid query") + } + + return "*" + } + + func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { + // Never requalify + return self + } + + func _resultColumnSQL(_ context: SQLGenerationContext) throws -> String { + if let qualifier = context.qualifier(for: alias) { + return qualifier.quotedDatabaseIdentifier + ".*" + } + return "*" } } -// MARK: - _SQLAliasedExpression +// MARK: - SQLAliasedExpression /// :nodoc: -public struct _SQLAliasedExpression: SQLSelectable { +struct SQLAliasedExpression: SQLSelectable { let expression: SQLExpression let name: String @@ -138,22 +143,26 @@ public struct _SQLAliasedExpression: SQLSelectable { self.expression = expression self.name = name } + + func _columnCount(_ db: Database) throws -> Int { 1 } - /// :nodoc: - public func _count(distinct: Bool) -> _SQLCount? { + func _count(distinct: Bool) -> _SQLCount? { expression._count(distinct: distinct) } - /// :nodoc: - public func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { - _SQLAliasedExpression(expression._qualifiedExpression(with: alias), name: name) + func _countedSQL(_ context: SQLGenerationContext) throws -> String { + try expression._countedSQL(context) } - /// :nodoc: - public func _columnCount(_ db: Database) throws -> Int { 1 } + var _isAggregate: Bool { expression._isAggregate } - /// :nodoc: - public func _accept(_ visitor: inout Visitor) throws { - try visitor.visit(self) + func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { + SQLAliasedExpression(expression._qualifiedExpression(with: alias), name: name) + } + + func _resultColumnSQL(_ context: SQLGenerationContext) throws -> String { + try expression._resultColumnSQL(context) + + " AS " + + name.quotedDatabaseIdentifier } } diff --git a/GRDB/QueryInterface/SQL/SQLSelectable.swift b/GRDB/QueryInterface/SQL/SQLSelectable.swift index 46b156f55..9c6941f96 100644 --- a/GRDB/QueryInterface/SQL/SQLSelectable.swift +++ b/GRDB/QueryInterface/SQL/SQLSelectable.swift @@ -1,20 +1,55 @@ -// MARK: - SQLSelectable - /// Implementation details of `SQLSelectable`. /// /// :nodoc: public protocol _SQLSelectable { + /// Returns the number of columns in the selectable. + func _columnCount(_ db: Database) throws -> Int + /// If the selectable can be counted, return how to count it. func _count(distinct: Bool) -> _SQLCount? - /// Returns the number of columns in the selectable. - func _columnCount(_ db: Database) throws -> Int + /// Returns the SQL that feeds the argument of the `COUNT` function. + /// + /// For example: + /// + /// COUNT(*) + /// COUNT(id) + /// ^---- countedSQL + /// + /// - parameter context: An SQL generation context which accepts + /// statement arguments. + func _countedSQL(_ context: SQLGenerationContext) throws -> String + /// Returns true if the selectable is an aggregate. + /// + /// When in doubt, returns false. + /// + /// SELECT * -- false + /// SELECT score -- false + /// SELECT COUNT(*) -- true + /// SELECT MAX(score) -- true + /// SELECT MAX(score) + 1 -- true + /// + /// Support for `SQLQueryGenerator.expectsSingleResult()` + var _isAggregate: Bool { get } + /// Returns a qualified selectable func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable - /// Accepts a visitor - func _accept(_ visitor: inout Visitor) throws + /// Returns the SQL that feeds the selection of a `SELECT` statement. + /// + /// For example: + /// + /// 1 + /// name + /// COUNT(*) + /// (score + bonus) AS total + /// + /// See https://sqlite.org/syntax/result-column.html + /// + /// - parameter context: An SQL generation context which accepts + /// statement arguments. + func _resultColumnSQL(_ context: SQLGenerationContext) throws -> String } /// SQLSelectable is the protocol for types that can be selected, as @@ -23,8 +58,6 @@ public protocol _SQLSelectable { /// :nodoc: public protocol SQLSelectable: _SQLSelectable { } -// MARK: - Counting - /// :nodoc: public enum _SQLCount { /// Represents `COUNT(*)` @@ -33,3 +66,8 @@ public enum _SQLCount { /// Represents `COUNT(DISTINCT expression)` case distinct(SQLExpression) } + +extension SQLSelectable { + /// :nodoc: + public var _isAggregate: Bool { false } +} diff --git a/GRDB/QueryInterface/SQL/SQLSelectableVisitor.swift b/GRDB/QueryInterface/SQL/SQLSelectableVisitor.swift deleted file mode 100644 index 760645781..000000000 --- a/GRDB/QueryInterface/SQL/SQLSelectableVisitor.swift +++ /dev/null @@ -1,7 +0,0 @@ -/// :nodoc: -public protocol _SQLSelectableVisitor: _SQLExpressionVisitor { - mutating func visit(_ selectable: AllColumns) throws - mutating func visit(_ selectable: _SQLAliasedExpression) throws - mutating func visit(_ selectable: _SQLQualifiedAllColumns) throws - mutating func visit(_ selectable: _SQLSelectionLiteral) throws -} diff --git a/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift index 3f65b53fb..d7ecbcf5c 100644 --- a/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift @@ -7,14 +7,14 @@ extension SQLSpecificExpressible { /// /// See https://github.com/groue/GRDB.swift/#the-query-interface public var asc: SQLOrderingTerm { - _SQLOrdering.asc(sqlExpression) + SQLOrdering.asc(sqlExpression) } /// Returns a value that can be used as an argument to QueryInterfaceRequest.order() /// /// See https://github.com/groue/GRDB.swift/#the-query-interface public var desc: SQLOrderingTerm { - _SQLOrdering.desc(sqlExpression) + SQLOrdering.desc(sqlExpression) } #if GRDBCUSTOMSQLITE @@ -22,14 +22,14 @@ extension SQLSpecificExpressible { /// /// See https://github.com/groue/GRDB.swift/#the-query-interface public var ascNullsLast: SQLOrderingTerm { - _SQLOrdering.ascNullsLast(sqlExpression) + SQLOrdering.ascNullsLast(sqlExpression) } /// Returns a value that can be used as an argument to QueryInterfaceRequest.order() /// /// See https://github.com/groue/GRDB.swift/#the-query-interface public var descNullsFirst: SQLOrderingTerm { - _SQLOrdering.descNullsFirst(sqlExpression) + SQLOrdering.descNullsFirst(sqlExpression) } #elseif !GRDBCIPHER /// Returns a value that can be used as an argument to QueryInterfaceRequest.order() @@ -37,7 +37,7 @@ extension SQLSpecificExpressible { /// See https://github.com/groue/GRDB.swift/#the-query-interface @available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) public var ascNullsLast: SQLOrderingTerm { - _SQLOrdering.ascNullsLast(sqlExpression) + SQLOrdering.ascNullsLast(sqlExpression) } /// Returns a value that can be used as an argument to QueryInterfaceRequest.order() @@ -45,7 +45,7 @@ extension SQLSpecificExpressible { /// See https://github.com/groue/GRDB.swift/#the-query-interface @available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) public var descNullsFirst: SQLOrderingTerm { - _SQLOrdering.descNullsFirst(sqlExpression) + SQLOrdering.descNullsFirst(sqlExpression) } #endif } @@ -66,7 +66,7 @@ extension SQLSpecificExpressible { /// let area: Int = row["area"] /// } public func forKey(_ key: String) -> SQLSelectable { - _SQLAliasedExpression(sqlExpression, name: key) + SQLAliasedExpression(sqlExpression, name: key) } /// Give the expression the same SQL name as the coding key. diff --git a/GRDB/QueryInterface/SQLGeneration/SQLCollectionGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLCollectionGenerator.swift deleted file mode 100644 index 10883d710..000000000 --- a/GRDB/QueryInterface/SQLGeneration/SQLCollectionGenerator.swift +++ /dev/null @@ -1,43 +0,0 @@ -extension SQLCollection { - /// Returns an SQL string that represents the collection. - /// - /// - parameter context: An SQL generation context which accepts - /// statement arguments. - func collectionSQL(_ context: SQLGenerationContext) throws -> String { - var generator = SQLCollectionGenerator(context: context) - try _accept(&generator) - return generator.resultSQL - } -} - -private struct SQLCollectionGenerator: _SQLCollectionVisitor { - let context: SQLGenerationContext - var resultSQL = "" - - mutating func visit(_ collection: _SQLExpressionsArray) throws { - resultSQL = try "(" + collection.expressions - .map { try $0.expressionSQL(context, wrappedInParenthesis: false) } - .joined(separator: ", ") + ")" - } - - mutating func visit(_ collection: _SQLTableCollection) throws { - switch collection { - case let .tableName(tableName): - resultSQL = tableName.quotedDatabaseIdentifier - } - } - - // MARK: _FetchRequestVisitor - - mutating func visit(_ request: AdaptedFetchRequest) throws { - resultSQL = try "(" + request.requestSQL(context, forSingleResult: false) + ")" - } - - mutating func visit(_ request: QueryInterfaceRequest) throws { - resultSQL = try "(" + request.requestSQL(context, forSingleResult: false) + ")" - } - - mutating func visit(_ request: SQLRequest) throws { - resultSQL = try "(" + request.requestSQL(context, forSingleResult: false) + ")" - } -} diff --git a/GRDB/QueryInterface/SQLGeneration/SQLExpressionGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLExpressionGenerator.swift deleted file mode 100644 index 38c1f5cb8..000000000 --- a/GRDB/QueryInterface/SQLGeneration/SQLExpressionGenerator.swift +++ /dev/null @@ -1,207 +0,0 @@ -extension SQLExpression { - /// Returns an SQL string that represents the expression. - /// - /// - parameter context: An SQL generation context which accepts - /// statement arguments. - /// - parameter wrappedInParenthesis: If true, the returned SQL should be - /// wrapped inside parenthesis. - func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - var generator = SQLExpressionGenerator(context: context, wrappedInParenthesis: wrappedInParenthesis) - try _accept(&generator) - return generator.resultSQL - } -} - -private struct SQLExpressionGenerator: _SQLExpressionVisitor { - let context: SQLGenerationContext - let wrappedInParenthesis: Bool - var resultSQL = "" - - mutating func visit(_ dbValue: DatabaseValue) throws { - if dbValue.isNull { - // fast path for NULL - resultSQL = "NULL" - } else if context.append(arguments: [dbValue]) { - // Use statement arguments - resultSQL = "?" - } else { - // Quoting needed: just use SQLite, which knows better. - resultSQL = try String.fetchOne(context.db, sql: "SELECT QUOTE(?)", arguments: [dbValue])! - } - } - - mutating func visit(_ column: Column) throws where Column: ColumnExpression { - resultSQL = column.name.quotedDatabaseIdentifier - } - - mutating func visit(_ column: _SQLQualifiedColumn) throws { - if let qualifier = context.qualifier(for: column.alias) { - resultSQL = qualifier.quotedDatabaseIdentifier + "." - } - 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)) \ - \(expr.isNegated ? "NOT BETWEEN" : "BETWEEN") \ - \(expr.lowerBound.expressionSQL(context, wrappedInParenthesis: true)) \ - AND \ - \(expr.upperBound.expressionSQL(context, wrappedInParenthesis: true)) - """ - if wrappedInParenthesis { - resultSQL = "(\(resultSQL))" - } - } - - mutating func visit(_ expr: _SQLExpressionBinary) throws { - resultSQL = try """ - \(expr.lhs.expressionSQL(context, wrappedInParenthesis: true)) \ - \(expr.op.sql) \ - \(expr.rhs.expressionSQL(context, wrappedInParenthesis: true)) - """ - if wrappedInParenthesis { - resultSQL = "(\(resultSQL))" - } - } - - mutating func visit(_ expr: _SQLExpressionAssociativeBinary) throws { - let expressionSQLs = try expr.expressions.map { - try $0.expressionSQL(context, wrappedInParenthesis: true) - } - let joiner = " \(expr.op.sql) " - resultSQL = expressionSQLs.joined(separator: joiner) - if wrappedInParenthesis { - resultSQL = "(\(resultSQL))" - } - } - - mutating func visit(_ expr: _SQLExpressionCollate) throws { - resultSQL = try """ - \(expr.expression.expressionSQL(context, wrappedInParenthesis: false)) \ - COLLATE \ - \(expr.collationName.rawValue) - """ - if wrappedInParenthesis { - resultSQL = "(\(resultSQL))" - } - } - - mutating func visit(_ expr: _SQLExpressionContains) throws { - resultSQL = try """ - \(expr.expression.expressionSQL(context, wrappedInParenthesis: true)) \ - \(expr.isNegated ? "NOT IN" : "IN") \ - \(expr.collection.collectionSQL(context)) - """ - if wrappedInParenthesis { - resultSQL = "(\(resultSQL))" - } - } - - mutating func visit(_ expr: _SQLExpressionCount) throws { - resultSQL = try "COUNT(" + expr.counted.countedSQL(context) + ")" - } - - mutating func visit(_ expr: _SQLExpressionCountDistinct) throws { - resultSQL = try "COUNT(DISTINCT " + expr.counted.expressionSQL(context, wrappedInParenthesis: false) + ")" - } - - mutating func visit(_ expr: _SQLExpressionEqual) throws { - resultSQL = try """ - \(expr.lhs.expressionSQL(context, wrappedInParenthesis: true)) \ - \(expr.op.rawValue) \ - \(expr.rhs.expressionSQL(context, wrappedInParenthesis: true)) - """ - if wrappedInParenthesis { - resultSQL = "(\(resultSQL))" - } - } - - mutating func visit(_ expr: _SQLExpressionFastPrimaryKey) throws { - // Likely a GRDB bug: how comes this expression is used before it - // has been qualified? - fatalError("_SQLExpressionFastPrimaryKey is not qualified.") - } - - mutating func visit(_ expr: _SQLExpressionFunction) throws { - resultSQL = expr.function - resultSQL += "(" - resultSQL += try expr.arguments - .map { try $0.expressionSQL(context, wrappedInParenthesis: false) } - .joined(separator: ", ") - resultSQL += ")" - } - - mutating func visit(_ expr: _SQLExpressionIsEmpty) throws { - resultSQL = try """ - \(expr.countExpression.expressionSQL(context, wrappedInParenthesis: true)) \ - \(expr.isEmpty ? "= 0" : "> 0") - """ - if wrappedInParenthesis { - resultSQL = "(\(resultSQL))" - } - } - - mutating func visit(_ expr: _SQLExpressionLiteral) throws { - resultSQL = try expr.sqlLiteral.sql(context) - if wrappedInParenthesis { - resultSQL = "(\(resultSQL))" - } - } - - mutating func visit(_ expr: _SQLExpressionNot) throws { - resultSQL = try "NOT \(expr.expression.expressionSQL(context, wrappedInParenthesis: true))" - if wrappedInParenthesis { - resultSQL = "(\(resultSQL))" - } - } - - mutating func visit(_ expr: _SQLExpressionQualifiedFastPrimaryKey) throws { - let column = try expr.columnName(context.db) - try _SQLQualifiedColumn(column, alias: expr.alias)._accept(&self) - } - - mutating func visit(_ expr: _SQLExpressionTableMatch) throws { - resultSQL = try """ - \(context.resolvedName(for: expr.alias).quotedDatabaseIdentifier) \ - MATCH \ - \(expr.pattern.expressionSQL(context, wrappedInParenthesis: true)) - """ - if wrappedInParenthesis { - resultSQL = "(\(resultSQL))" - } - } - - mutating func visit(_ expr: _SQLExpressionUnary) throws { - resultSQL = try expr.op.sql - + (expr.op.needsRightSpace ? " " : "") - + expr.expression.expressionSQL(context, wrappedInParenthesis: true) - if wrappedInParenthesis { - resultSQL = "(\(resultSQL))" - } - } - - // MARK: _FetchRequestVisitor - - mutating func visit(_ request: AdaptedFetchRequest) throws { - let sql = try request.requestSQL(context, forSingleResult: false) - resultSQL = "(\(sql))" - } - - mutating func visit(_ request: QueryInterfaceRequest) throws { - let sql = try request.requestSQL(context, forSingleResult: false) - resultSQL = "(\(sql))" - } - - mutating func visit(_ request: SQLRequest) throws { - let sql = try request.requestSQL(context, forSingleResult: false) - resultSQL = "(\(sql))" - } -} diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index 2c2a0f754..13121066e 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -413,7 +413,7 @@ public class TableAlias: Hashable { /// } public var exists: SQLExpression { // TODO: this fails with SQL views. Can we do something? - _SQLExpressionQualifiedFastPrimaryKey(alias: self) != nil + SQLExpressionQualifiedFastPrimaryKey(alias: self) != nil } /// :nodoc: diff --git a/GRDB/QueryInterface/SQLGeneration/SQLOrderingGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLOrderingGenerator.swift deleted file mode 100644 index 75efa42d1..000000000 --- a/GRDB/QueryInterface/SQLGeneration/SQLOrderingGenerator.swift +++ /dev/null @@ -1,135 +0,0 @@ -extension SQLOrderingTerm { - /// Returns the SQL that feeds the `ORDER BY` clause. - /// - /// - parameter context: An SQL generation context which accepts - /// statement arguments. - func orderingTermSQL(_ context: SQLGenerationContext) throws -> String { - var generator = SQLOrderingGenerator(context: context) - try _accept(&generator) - return generator.resultSQL - } -} - -private struct SQLOrderingGenerator: _SQLOrderingTermVisitor { - let context: SQLGenerationContext - var resultSQL = "" - - // MARK: - _SQLOrderingTermVisitor - - mutating func visit(_ ordering: SQLCollatedExpression) throws { - resultSQL = try ordering.sqlExpression.orderingTermSQL(context) - } - - mutating func visit(_ ordering: _SQLOrdering) throws { - switch ordering { - case .asc(let expression): - resultSQL = try expression.expressionSQL(context, wrappedInParenthesis: false) + " ASC" - case .desc(let expression): - resultSQL = try expression.expressionSQL(context, wrappedInParenthesis: false) + " DESC" - case .ascNullsLast(let expression): - resultSQL = try expression.expressionSQL(context, wrappedInParenthesis: false) + " ASC NULLS LAST" - case .descNullsFirst(let expression): - resultSQL = try expression.expressionSQL(context, wrappedInParenthesis: false) + " DESC NULLS FIRST" - } - } - - mutating func visit(_ ordering: _SQLOrderingLiteral) throws { - resultSQL = try ordering.sqlLiteral.sql(context) - } - - // MARK: - _SQLExpressionVisitor - - mutating func visit(_ expr: DatabaseValue) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: Column) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLQualifiedColumn) throws { - 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) - } - - mutating func visit(_ expr: _SQLExpressionBinary) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionAssociativeBinary) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionCollate) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionContains) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionCount) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionCountDistinct) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionEqual) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionFastPrimaryKey) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionFunction) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionIsEmpty) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionLiteral) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionNot) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionQualifiedFastPrimaryKey) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionTableMatch) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionUnary) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - // MARK: - _FetchRequestVisitor - - mutating func visit(_ request: AdaptedFetchRequest) throws { - resultSQL = try request.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ request: QueryInterfaceRequest) throws { - resultSQL = try request.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ request: SQLRequest) throws { - resultSQL = try request.expressionSQL(context, wrappedInParenthesis: false) - } -} diff --git a/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift deleted file mode 100644 index 86acd491d..000000000 --- a/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift +++ /dev/null @@ -1,378 +0,0 @@ -// MARK: - PreparedRequest - -/// A PreparedRequest is a request that is ready to be executed. -public struct PreparedRequest { - /// A prepared statement - public var statement: SelectStatement - - /// An eventual adapter for rows fetched by the select statement - public var adapter: RowAdapter? - - /// Support for eager loading of hasMany associations. - var supplementaryFetch: ((Database, [Row]) throws -> Void)? - - init( - statement: SelectStatement, - adapter: RowAdapter?, - supplementaryFetch: ((Database, [Row]) throws -> Void)? = nil) - { - self.statement = statement - self.adapter = adapter - self.supplementaryFetch = supplementaryFetch - } -} - -extension PreparedRequest: Refinable { } - -extension FetchRequest { - /// Returns a PreparedRequest that is ready to be executed. - /// - /// - parameter db: A database connection. - /// - parameter singleResult: A hint that a single result row will be - /// consumed. Implementations can optionally use it to optimize the - /// prepared statement, for example by adding a `LIMIT 1` SQL clause. - /// - /// // Calls makePreparedRequest(db, forSingleResult: true) - /// try request.fetchOne(db) - /// - /// // Calls makePreparedRequest(db, forSingleResult: false) - /// try request.fetchAll(db) - /// - returns: A prepared request. - public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { - var visitor = SQLPreparedRequestGenerator(db, forSingleResult: singleResult) - try _accept(&visitor) - return visitor.preparedRequest! - } - - /// Returns the database region that the request feeds from. - /// - /// - parameter db: A database connection. - public func databaseRegion(_ db: Database) throws -> DatabaseRegion { - try makePreparedRequest(db, forSingleResult: false).statement.databaseRegion - } - - /// Returns the number of rows fetched by the request. - /// - /// - parameter db: A database connection. - public func fetchCount(_ db: Database) throws -> Int { - var visitor = SQLRequestCounter(db) - try _accept(&visitor) - return visitor.count - } -} - -private struct SQLPreparedRequestGenerator: _FetchRequestVisitor { - let db: Database - let singleResult: Bool - var preparedRequest: PreparedRequest? - - init(_ db: Database, forSingleResult singleResult: Bool) { - self.db = db - self.singleResult = singleResult - } - - mutating func visit(_ request: AdaptedFetchRequest) throws { - try request.base._accept(&self) - if let baseAdapter = preparedRequest!.adapter { - preparedRequest!.adapter = try ChainedAdapter(first: baseAdapter, second: request.adapter(db)) - } else { - preparedRequest!.adapter = try request.adapter(db) - } - } - - mutating func visit(_ request: QueryInterfaceRequest) throws { - let generator = SQLQueryGenerator(query: request.query, forSingleResult: singleResult) - var preparedRequest = try generator.makePreparedRequest(db) - let associations = request.query.relation.prefetchedAssociations - if associations.isEmpty == false { - // Eager loading of prefetched associations - preparedRequest = preparedRequest.with(\.supplementaryFetch) { db, rows in - try prefetch(db, associations: associations, into: rows, from: request) - } - } - self.preparedRequest = preparedRequest - } - - mutating func visit(_ request: SQLRequest) throws { - let context = SQLGenerationContext(db) - let sql = try request.sqlLiteral.sql(context) - let statement: SelectStatement - switch request.cache { - case .none: - statement = try db.makeSelectStatement(sql: sql) - case .public?: - statement = try db.cachedSelectStatement(sql: sql) - case .internal?: - statement = try db.internalCachedSelectStatement(sql: sql) - } - try statement.setArguments(context.arguments) - preparedRequest = PreparedRequest(statement: statement, adapter: request.adapter) - } -} - -private struct SQLRequestCounter: _FetchRequestVisitor { - let db: Database - var count = 0 - - init(_ db: Database) { - self.db = db - } - - mutating func visit(_ request: AdaptedFetchRequest) throws { - try request.base._accept(&self) - } - - mutating func visit(_ request: QueryInterfaceRequest) throws { - count = try request.query.fetchCount(db) - } - - mutating func visit(_ request: SQLRequest) throws { - let countRequest: SQLRequest = "SELECT COUNT(*) FROM (\(request))" - count = try countRequest.fetchOne(db)! - } -} - -// MARK: - Eager loading of hasMany associations - -// CAUTION: Keep this code in sync with prefetchedRegion(_:_:) -/// 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 baseRequest: The request that was used to fetch `baseRows`. -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: - // Likely a GRDB bug: such condition only exist for CTEs, which - // are not prefetched with including(all:) - fatalError("Not implemented: prefetch association without any foreign key") - - case let .foreignKey(request: foreignKeyRequest, originIsLeft: originIsLeft): - let pivotMapping = try foreignKeyRequest - .fetchForeignKeyMapping(db) - .joinMapping(originIsLeft: originIsLeft) - let pivotColumns = pivotMapping.map(\.right) - let leftColumns = pivotMapping.map(\.left) - - // We want to avoid the "Expression tree is too large" SQLite error - // 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 - // - // -- May be too complex for the SQLite engine - // SELECT * FROM child - // WHERE (a = ? AND b = ?) - // OR (a = ? AND b = ?) - // OR ... - // - // 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 is one precondition: row - // values must be available (https://www.sqlite.org/rowvalue.html). - // This is the case of almost all our target platforms. - // - // 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 { - // 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 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 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.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) - } - } - } -} - -/// 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 -{ - // We annotate prefetched rows with pivot columns, so that we can - // group them. - // - // Those pivot columns are necessary when we prefetch - // indirect associations: - // - // // SELECT country.*, passport.citizenId AS grdb_citizenId - // // -- ^ the necessary pivot column - // // FROM country - // // JOIN passport ON passport.countryCode = country.code - // // AND passport.citizenId IN (1, 2, 3) - // Citizen.including(all: Citizen.countries) - // - // Those pivot columns are redundant when we prefetch direct - // associations (maybe we'll remove this redundancy later): - // - // // SELECT *, authorId AS grdb_authorId - // // -- ^ the redundant pivot column - // // FROM book - // // WHERE authorId IN (1, 2, 3) - // Author.including(all: Author.books) - let pivotAlias = TableAlias() - - let prefetchRelation = association - .map(\.pivot.relation, { $0.qualified(with: pivotAlias).filter(pivotFilter) }) - .destinationRelation() - .annotated(with: pivotColumns.map { pivotAlias[$0].forKey("grdb_\($0)") }) - - return QueryInterfaceRequest(relation: prefetchRelation) -} - -// CAUTION: Keep this code in sync with prefetch(_:associations:in:) -/// Returns the region of prefetched associations -func prefetchedRegion(_ db: Database, associations: [_SQLAssociation]) throws -> DatabaseRegion { - try associations.reduce(into: DatabaseRegion()) { (region, association) in - switch association.pivot.condition { - case .expression: - // Likely a GRDB bug: such condition only exist for CTEs, which - // are not prefetched with including(all:) - fatalError("Not implemented: prefetch association without any foreign key") - - case let .foreignKey(request: foreignKeyRequest, originIsLeft: originIsLeft): - let pivotMapping = try foreignKeyRequest - .fetchForeignKeyMapping(db) - .joinMapping(originIsLeft: originIsLeft) - let prefetchRegion = try prefetchedRegion(db, association: association, pivotMapping: pivotMapping) - region.formUnion(prefetchRegion) - } - } -} - -// CAUTION: Keep this code in sync with prefetch(_:associations:in:) -func prefetchedRegion( - _ db: Database, - association: _SQLAssociation, - pivotMapping: JoinMapping) -throws -> DatabaseRegion -{ - // 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 = ? - // ^ content of the DummyRow - let pivotFilter = pivotMapping.joinExpression(leftRows: [DummyRow()]) - - let prefetchRelation = association - .map(\.pivot.relation) { $0.filter(pivotFilter) } - .destinationRelation() - - let prefetchQuery = SQLQuery(relation: prefetchRelation) - - return try SQLQueryGenerator(query: prefetchQuery) - .makeSelectStatement(db) - .databaseRegion // contains region of nested associations -} - -extension Array where Element == Row { - /// - precondition: Columns all exist in all rows. All rows have the same - /// columnns, in the same order. - fileprivate func grouped(byDatabaseValuesOnColumns columns: [String]) -> [[DatabaseValue]: [Row]] { - guard let firstRow = first else { - return [:] - } - let indexes = firstRow.indexes(forColumns: columns) - return Dictionary(grouping: self, by: { row in - indexes.map { row.impl.databaseValue(atUncheckedIndex: $0) } - }) - } -} - -extension Row { - /// - precondition: Columns all exist in the row. - fileprivate func indexes(forColumns columns: [String]) -> [Int] { - columns.map { column -> Int in - guard let index = index(forColumn: column) else { - fatalError("Column \(column) is not selected") - } - return index - } - } -} diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 134763c21..2f316ba71 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -75,7 +75,7 @@ struct SQLQueryGenerator: Refinable { let selection = try relation.selectionPromise.resolve(context.db) GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with an empty selection") - sql += try " " + selection.map { try $0.resultColumnSQL(context) }.joined(separator: ", ") + sql += try " " + selection.map { try $0._resultColumnSQL(context) }.joined(separator: ", ") sql += " FROM " sql += try relation.source.sql(context) @@ -91,28 +91,28 @@ struct SQLQueryGenerator: Refinable { let filters = try relation.filtersPromise.resolve(context.db) if filters.isEmpty == false { sql += " WHERE " - sql += try filters.joined(operator: .and).expressionSQL(context, wrappedInParenthesis: false) + sql += try filters.joined(operator: .and)._expressionSQL(context, wrappedInParenthesis: false) } let groupExpressions = try groupPromise?.resolve(context.db) ?? [] if !groupExpressions.isEmpty { sql += " GROUP BY " sql += try groupExpressions - .map { try $0.expressionSQL(context, wrappedInParenthesis: false) } + .map { try $0._expressionSQL(context, wrappedInParenthesis: false) } .joined(separator: ", ") } let havingExpressions = try havingExpressionsPromise.resolve(context.db) if havingExpressions.isEmpty == false { sql += " HAVING " - sql += try havingExpressions.joined(operator: .and).expressionSQL(context, wrappedInParenthesis: false) + sql += try havingExpressions.joined(operator: .and)._expressionSQL(context, wrappedInParenthesis: false) } let orderings = try relation.ordering.resolve(context.db) if !orderings.isEmpty { sql += " ORDER BY " sql += try orderings - .map { try $0.orderingTermSQL(context) } + .map { try $0._orderingTermSQL(context) } .joined(separator: ", ") } @@ -140,6 +140,16 @@ struct SQLQueryGenerator: Refinable { adapter: rowAdapter(db)) } + /// The number of fetched columns. + func columnsCount(_ db: Database) throws -> Int { + try relation + .selectionPromise + .resolve(db) + .reduce(0) { + try $0 + $1._columnCount(db) + } + } + /// Returns a select statement func makeSelectStatement(_ db: Database) throws -> SelectStatement { // Build @@ -187,7 +197,7 @@ struct SQLQueryGenerator: Refinable { // The filter knows better let filter = try relation.filtersPromise.resolve(db).joined(operator: .and) - guard let rowIDs = try filter.identifyingRowIDs(db, for: relation.source.alias) else { + guard let rowIDs = try filter._identifyingRowIDs(db, for: relation.source.alias) else { return selectedRegion } @@ -215,7 +225,7 @@ struct SQLQueryGenerator: Refinable { if try db.tableExists(tableName) { // skip views let identifyingColums = try filters .joined(operator: .and) - .identifyingColums(db, for: relation.source.alias) + ._identifyingColums(db, for: relation.source.alias) if try db.table(tableName, hasUniqueKey: identifyingColums) { // Filter by unique key: guaranteed single row! return true @@ -223,8 +233,8 @@ struct SQLQueryGenerator: Refinable { } // Do we aggregate without grouping? - if groupExpressions.isEmpty && selection.contains(where: { $0.isAggregate() }) { - // Selection contains an aggregate function: guaranteed single row! + if groupExpressions.isEmpty && selection.contains(where: \._isAggregate) { + // Selection contains an aggregate function: guaranteed single row!Ë return true } @@ -248,13 +258,13 @@ struct SQLQueryGenerator: Refinable { sql += " WHERE " sql += try filters .joined(operator: .and) - .expressionSQL(context, wrappedInParenthesis: false) + ._expressionSQL(context, wrappedInParenthesis: false) } if let limit = limit { let orderings = try relation.ordering.resolve(db) if !orderings.isEmpty { - sql += try " ORDER BY " + orderings.map { try $0.orderingTermSQL(context) }.joined(separator: ", ") + sql += try " ORDER BY " + orderings.map { try $0._orderingTermSQL(context) }.joined(separator: ", ") } sql += " LIMIT " + limit.sql } @@ -278,10 +288,10 @@ struct SQLQueryGenerator: Refinable { let alias = TableAlias(tableName: tableName) let context = SQLGenerationContext(db, aliases: [alias]) let subqueryContext = SQLGenerationContext(parent: context, aliases: relation.allAliases) - let primaryKey = _SQLExpressionFastPrimaryKey() + let primaryKey = SQLExpressionFastPrimaryKey() var sql = "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE " - sql += try alias[primaryKey].expressionSQL(context, wrappedInParenthesis: false) + sql += try alias[primaryKey]._expressionSQL(context, wrappedInParenthesis: false) sql += " IN (" sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).requestSQL(subqueryContext) sql += ")" @@ -334,13 +344,13 @@ struct SQLQueryGenerator: Refinable { sql += " WHERE " sql += try filters .joined(operator: .and) - .expressionSQL(context, wrappedInParenthesis: false) + ._expressionSQL(context, wrappedInParenthesis: false) } if let limit = limit { let orderings = try relation.ordering.resolve(db) if !orderings.isEmpty { - sql += try " ORDER BY " + orderings.map { try $0.orderingTermSQL(context) }.joined(separator: ", ") + sql += try " ORDER BY " + orderings.map { try $0._orderingTermSQL(context) }.joined(separator: ", ") } sql += " LIMIT " + limit.sql } @@ -376,7 +386,7 @@ struct SQLQueryGenerator: Refinable { let alias = TableAlias(tableName: tableName) let context = SQLGenerationContext(db, aliases: [alias]) let subqueryContext = SQLGenerationContext(parent: context, aliases: relation.allAliases) - let primaryKey = _SQLExpressionFastPrimaryKey() + let primaryKey = SQLExpressionFastPrimaryKey() // UPDATE table... var sql = "UPDATE " @@ -393,7 +403,7 @@ struct SQLQueryGenerator: Refinable { // WHERE id IN (SELECT id FROM ...) sql += " WHERE " - sql += try alias[primaryKey].expressionSQL(context, wrappedInParenthesis: false) + sql += try alias[primaryKey]._expressionSQL(context, wrappedInParenthesis: false) sql += " IN (" sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).requestSQL(subqueryContext) sql += ")" @@ -423,7 +433,7 @@ struct SQLQueryGenerator: Refinable { let cteContext = SQLGenerationContext(parent: context) let requestSQL = try cte.requestPromise .resolve(context.db) - .requestSQL(cteContext, forSingleResult: false) + ._requestSQL(cteContext, forSingleResult: false) return "\(tableName.quotedDatabaseIdentifier)\(columnsSQL) AS (\(requestSQL))" } .joined(separator: ", ") @@ -459,7 +469,7 @@ struct SQLQueryGenerator: Refinable { var groupingColumns: Set = [] for expression in groupExpressions { - guard let column = try expression.column(db, for: relation.source.alias, acceptsBijection: true) else { + guard let column = try expression._column(db, for: relation.source.alias, acceptsBijection: true) else { // Grouping by something which is not a column: assume non // unique grouping. return .nonUnique @@ -508,38 +518,6 @@ struct SQLQueryGenerator: Refinable { } } -/// A FetchRequest visitor that counts the selected columns -struct SelectedColumnsCounter: _FetchRequestVisitor { - let db: Database - var columnCount = 0 - - mutating func visit(_ request: AdaptedFetchRequest) throws { - try request.base._accept(&self) - } - - mutating func visit(_ request: QueryInterfaceRequest) throws { - // We need a qualified relation so that the selected columns are - // qualified with a table name: naked `SELECT *` are replaced - // with `SELECT player.*`, which we can count. - let qualifiedRelation = SQLQualifiedRelation(request.query.relation) - columnCount = try qualifiedRelation - .selectionPromise - .resolve(db) - .reduce(0) { - try $0 + $1._columnCount(db) - } - } - - mutating func visit(_ request: SQLRequest) throws { - // Compile request. We can freely use the statement cache because we - // do not execute the statement or modify its arguments. - let context = SQLGenerationContext(db) - let sql = try request.requestSQL(context, forSingleResult: false) - let statement = try db.cachedSelectStatement(sql: sql) - columnCount = statement.columnCount - } -} - /// A "qualified" relation, where all tables are identified with a table alias. /// /// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ... @@ -808,13 +786,13 @@ private struct SQLQualifiedJoin: Refinable { joinExpressions += try relation.filtersPromise.resolve(context.db) // Avoid generating on ON clause for trivially true conditions - joinExpressions = joinExpressions.filter { !$0.isTrue } + joinExpressions = joinExpressions.filter { !$0._isTrue } if joinExpressions.isEmpty == false { let joiningSQL = try joinExpressions .joined(operator: .and) ._qualifiedExpression(with: rightAlias) - .expressionSQL(context, wrappedInParenthesis: false) + ._expressionSQL(context, wrappedInParenthesis: false) sql += " ON \(joiningSQL)" } @@ -826,830 +804,3 @@ private struct SQLQualifiedJoin: Refinable { return sql } } - -// MARK: - SQLExpressionIsTrue - -extension SQLExpression { - /// Returns true if the expression is trivially true. - /// - /// When in doubt, returns false. - /// - /// Support for removing the ON clause when possible. - var isTrue: Bool { - var visitor = SQLExpressionIsTrue() - do { - try _accept(&visitor) - } catch is SQLExpressionIsTrue.BreakError { - } catch { - try! { throw error }() - } - return visitor.isTrue - } -} - -/// Support for `SQLExpression.isTrue` -private struct SQLExpressionIsTrue: _SQLExpressionVisitor { - struct BreakError: Error { } - var isTrue = true - - private mutating func setFalse() throws -> Never { - isTrue = false - // Poor man's short-circuiting - throw BreakError() - } - - mutating func visit(_ dbValue: DatabaseValue) throws { - if dbValue != true.databaseValue { - try setFalse() - } - } - - mutating func visit(_ column: Column) throws where Column: ColumnExpression { - try setFalse() - } - - mutating func visit(_ column: _SQLQualifiedColumn) throws { - try setFalse() - } - - mutating func visit(_ expr: _SQLRowValue) throws { - try setFalse() - } - - mutating func visit(_ expr: _SQLExpressionBetween) throws { - try setFalse() - } - - mutating func visit(_ expr: _SQLExpressionBinary) throws { - try setFalse() - } - - mutating func visit(_ expr: _SQLExpressionAssociativeBinary) throws { - try setFalse() - } - - mutating func visit(_ expr: _SQLExpressionCollate) throws { - try setFalse() - } - - mutating func visit(_ expr: _SQLExpressionContains) throws { - try setFalse() - } - - mutating func visit(_ expr: _SQLExpressionCount) throws { - try setFalse() - } - - mutating func visit(_ expr: _SQLExpressionCountDistinct) throws { - try setFalse() - } - - mutating func visit(_ expr: _SQLExpressionEqual) throws { - try setFalse() - } - - mutating func visit(_ expr: _SQLExpressionFastPrimaryKey) throws { - try setFalse() - } - - mutating func visit(_ expr: _SQLExpressionFunction) throws { - try setFalse() - } - - mutating func visit(_ expr: _SQLExpressionIsEmpty) throws { - try setFalse() - } - - mutating func visit(_ expr: _SQLExpressionLiteral) throws { - try setFalse() // Don't know - assume not true - } - - mutating func visit(_ expr: _SQLExpressionNot) throws { - try setFalse() // Could do better - } - - mutating func visit(_ expr: _SQLExpressionQualifiedFastPrimaryKey) throws { - try setFalse() - } - - mutating func visit(_ expr: _SQLExpressionTableMatch) throws { - try setFalse() - } - - mutating func visit(_ expr: _SQLExpressionUnary) throws { - try setFalse() - } - - // MARK: - _FetchRequestVisitor - - mutating func visit(_ request: AdaptedFetchRequest) throws { - try setFalse() // Don't know - assume not true - } - - mutating func visit(_ request: QueryInterfaceRequest) throws { - try setFalse() // Don't know - assume not true - } - - mutating func visit(_ request: SQLRequest) throws { - try setFalse() // Don't know - assume not true - } -} - -// MARK: - SQLExpressionIsConstantInRequest - -extension SQLExpression { - /// Returns true if the expression has a unique value when SQLite runs - /// a request. - /// - /// When in doubt, returns false. - /// - /// 1 -- true - /// 1 + 2 -- true - /// score -- false - /// - /// Support for `SQLExpression.identifyingColums(_:for:)` - var isConstantInRequest: Bool { - var visitor = SQLExpressionIsConstantInRequest() - do { - try _accept(&visitor) - } catch is SQLExpressionIsConstantInRequest.BreakError { - } catch { - try! { throw error }() - } - return visitor.isConstant - } -} - -/// Support for `SQLExpression.isConstantInRequest` -private struct SQLExpressionIsConstantInRequest: _SQLExpressionVisitor { - struct BreakError: Error { } - var isConstant = true - - private mutating func setNotConstant() throws -> Never { - isConstant = false - // Poor man's short-circuiting - throw BreakError() - } - - mutating func visit(_ dbValue: DatabaseValue) throws { } - - mutating func visit(_ column: Column) throws where Column: ColumnExpression { - try setNotConstant() - } - - mutating func visit(_ column: _SQLQualifiedColumn) throws { - 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) - try expr.upperBound._accept(&self) - } - - mutating func visit(_ expr: _SQLExpressionBinary) throws { - try expr.lhs._accept(&self) - try expr.rhs._accept(&self) - } - - mutating func visit(_ expr: _SQLExpressionAssociativeBinary) throws { - for expression in expr.expressions { - try expression._accept(&self) - } - } - - mutating func visit(_ expr: _SQLExpressionCollate) throws { - try expr.expression._accept(&self) - } - - mutating func visit(_ expr: _SQLExpressionContains) throws { - guard let expressions = expr.collection.expressions() else { - try setNotConstant() // Don't know - assume not constant - } - try expr.expression._accept(&self) - for expression in expressions { - try expression._accept(&self) - } - } - - mutating func visit(_ expr: _SQLExpressionCount) throws { - try setNotConstant() // Don't know - assume not constant - } - - mutating func visit(_ expr: _SQLExpressionCountDistinct) throws { - try setNotConstant() // Don't know - assume not constant - } - - mutating func visit(_ expr: _SQLExpressionEqual) throws { - try expr.lhs._accept(&self) - try expr.rhs._accept(&self) - } - - mutating func visit(_ expr: _SQLExpressionFastPrimaryKey) throws { - try setNotConstant() - } - - static let knownPureFunctions = [ - "ABS", "CHAR", "COALESCE", "GLOB", "HEX", "IFNULL", - "IIF", "INSTR", "LENGTH", "LIKE", "LIKELIHOOD", - "LIKELY", "LOAD_EXTENSION", "LOWER", "LTRIM", - "NULLIF", "PRINTF", "QUOTE", "REPLACE", "ROUND", - "RTRIM", "SOUNDEX", "SQLITE_COMPILEOPTION_GET", - "SQLITE_COMPILEOPTION_USED", "SQLITE_SOURCE_ID", - "SQLITE_VERSION", "SUBSTR", "TRIM", "TRIM", - "TYPEOF", "UNICODE", "UNLIKELY", "UPPER", "ZEROBLOB", - ] - mutating func visit(_ expr: _SQLExpressionFunction) throws { - let function = expr.function.uppercased() - guard - ((function == "MAX" || function == "MIN") && expr.arguments.count > 1) - || Self.knownPureFunctions.contains(function) - else { - try setNotConstant() // Don't know - assume not constant - } - for expression in expr.arguments { - try expression._accept(&self) - } - } - - mutating func visit(_ expr: _SQLExpressionIsEmpty) throws { - try expr.countExpression._accept(&self) - } - - mutating func visit(_ expr: _SQLExpressionLiteral) throws { - try setNotConstant() // Don't know - assume not constant - } - - mutating func visit(_ expr: _SQLExpressionNot) throws { - try expr.expression._accept(&self) - } - - mutating func visit(_ expr: _SQLExpressionQualifiedFastPrimaryKey) throws { - try setNotConstant() - } - - mutating func visit(_ expr: _SQLExpressionTableMatch) throws { - try setNotConstant() - } - - mutating func visit(_ expr: _SQLExpressionUnary) throws { - try expr.expression._accept(&self) - } - - // MARK: - _FetchRequestVisitor - - mutating func visit(_ request: AdaptedFetchRequest) throws { - try setNotConstant() // Don't know - assume not constant - } - - mutating func visit(_ request: QueryInterfaceRequest) throws { - try setNotConstant() // Don't know - assume not constant - } - - mutating func visit(_ request: SQLRequest) throws { - try setNotConstant() // Don't know - assume not constant - } -} - -// MARK: - SQLTableColumnVisitor - -extension SQLExpression { - /// If this expression is a table colum, returns the name of this column. - /// - /// When in doubt, returns nil. - /// - /// - parameter acceptsBijection: If true, expressions that define a - /// bijection on a column return this column. For example: `-score` - /// returns `score`. - func column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool = false) throws -> String? { - var visitor = SQLTableColumnVisitor(db: db, alias: alias, acceptsBijection: acceptsBijection) - try _accept(&visitor) - return visitor.column - } -} - -/// Support for `SQLExpression.column(_:for:)` -private struct SQLTableColumnVisitor: _SQLExpressionVisitor { - let db: Database - let alias: TableAlias - let acceptsBijection: Bool - var column: String? - - mutating func visit(_ dbValue: DatabaseValue) throws { } - - mutating func visit(_ column: Column) throws where Column: ColumnExpression { } - - mutating func visit(_ column: _SQLQualifiedColumn) throws { - if column.alias == alias { - self.column = column.name - } - } - - mutating func visit(_ expr: _SQLRowValue) throws { } - - mutating func visit(_ expr: _SQLExpressionBetween) throws { } - - mutating func visit(_ expr: _SQLExpressionBinary) throws { - if acceptsBijection && expr.op == .subtract { - if expr.lhs.isConstantInRequest { - try expr.rhs._accept(&self) - } else if expr.rhs.isConstantInRequest { - try expr.lhs._accept(&self) - } - } - } - - mutating func visit(_ expr: _SQLExpressionAssociativeBinary) throws { - if acceptsBijection && (expr.op == .add || expr.op == .concat) { - let nonConstants = expr.expressions.filter { $0.isConstantInRequest == false } - if nonConstants.count == 1 { - try nonConstants[0]._accept(&self) - } - } - } - - mutating func visit(_ expr: _SQLExpressionCollate) throws { - try expr.expression._accept(&self) - } - - mutating func visit(_ expr: _SQLExpressionContains) throws { } - - mutating func visit(_ expr: _SQLExpressionCount) throws { } - - mutating func visit(_ expr: _SQLExpressionCountDistinct) throws { } - - mutating func visit(_ expr: _SQLExpressionEqual) throws { } - - mutating func visit(_ expr: _SQLExpressionFastPrimaryKey) throws { } - - mutating func visit(_ expr: _SQLExpressionFunction) throws { - if acceptsBijection { - let function = expr.function.uppercased() - if ["HEX", "QUOTE"].contains(function) && expr.arguments.count == 1 { - try expr.arguments[0]._accept(&self) - } else if function == "IFNULL" && expr.arguments.count == 2 && expr.arguments[1].isConstantInRequest { - try expr.arguments[0]._accept(&self) - } - } - } - - mutating func visit(_ expr: _SQLExpressionIsEmpty) throws { } - - mutating func visit(_ expr: _SQLExpressionLiteral) throws { } - - mutating func visit(_ expr: _SQLExpressionNot) throws { } - - mutating func visit(_ expr: _SQLExpressionQualifiedFastPrimaryKey) throws { - if expr.alias == alias { - self.column = try expr.columnName(db) - } - } - - mutating func visit(_ expr: _SQLExpressionTableMatch) throws { } - - mutating func visit(_ expr: _SQLExpressionUnary) throws { - if acceptsBijection && expr.op == .minus { - try expr.expression._accept(&self) - } - } - - // MARK: - _FetchRequestVisitor - - mutating func visit(_ request: AdaptedFetchRequest) throws { } - - mutating func visit(_ request: QueryInterfaceRequest) throws { } - - mutating func visit(_ request: SQLRequest) throws { } -} - -// MARK: - SQLIdentifyingColumns - -extension SQLExpression { - /// Returns the columns that identify a unique row in the request - /// - /// When in doubt, returns an empty set. - /// - /// WHERE 0 -- [] - /// WHERE a -- [] - /// WHERE a = b -- [] - /// WHERE a = 1 -- ["a"] - /// WHERE a = 1 AND b = 2 -- ["a", "b"] - /// WHERE a = 1 AND b = 2 AND c > 0 -- ["a", "b"] - /// 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) - do { - try _accept(&visitor) - } catch is SQLIdentifyingColumns.BreakError { - } catch { - try! { throw error }() - } - return visitor.columns - } -} - -/// Support for `SQLExpression.identifyingColums(_:for:)` -private struct SQLIdentifyingColumns: _SQLExpressionVisitor { - struct BreakError: Error { } - let db: Database - let alias: TableAlias - var columns: Set = [] - - mutating func visit(_ dbValue: DatabaseValue) throws { } - - mutating func visit(_ column: Column) throws where Column: ColumnExpression { } - - mutating func visit(_ column: _SQLQualifiedColumn) throws { } - - mutating func visit(_ expr: _SQLRowValue) throws { } - - mutating func visit(_ expr: _SQLExpressionBetween) throws { } - - mutating func visit(_ expr: _SQLExpressionBinary) throws { } - - mutating func visit(_ expr: _SQLExpressionAssociativeBinary) throws { - if expr.op == .and { - for expression in expr.expressions { - try expression._accept(&self) - } - } else if expr.op == .or { - columns = [] - throw BreakError() - } - } - - mutating func visit(_ expr: _SQLExpressionCollate) throws { - try expr.expression._accept(&self) - } - - mutating func visit(_ expr: _SQLExpressionContains) throws { } - - mutating func visit(_ expr: _SQLExpressionCount) throws { } - - mutating func visit(_ expr: _SQLExpressionCountDistinct) throws { } - - mutating func visit(_ expr: _SQLExpressionEqual) throws { - switch expr.op { - case .equal, .is: - if - let column = try expr.lhs.column(db, for: alias), - expr.rhs.isConstantInRequest - { - columns.insert(column) - } else if - let column = try expr.rhs.column(db, for: alias), - expr.lhs.isConstantInRequest - { - columns.insert(column) - } - - case .notEqual, .isNot: - break - } - } - - mutating func visit(_ expr: _SQLExpressionFastPrimaryKey) throws { } - - mutating func visit(_ expr: _SQLExpressionFunction) throws { } - - mutating func visit(_ expr: _SQLExpressionIsEmpty) throws { } - - mutating func visit(_ expr: _SQLExpressionLiteral) throws { } - - mutating func visit(_ expr: _SQLExpressionNot) throws { } - - mutating func visit(_ expr: _SQLExpressionQualifiedFastPrimaryKey) throws { } - - mutating func visit(_ expr: _SQLExpressionTableMatch) throws { } - - mutating func visit(_ expr: _SQLExpressionUnary) throws { } - - // MARK: - _FetchRequestVisitor - - mutating func visit(_ request: AdaptedFetchRequest) throws { } - - mutating func visit(_ request: QueryInterfaceRequest) throws { } - - mutating func visit(_ request: SQLRequest) throws { } -} - -// MARK: - SQLIdentifyingRowIDs - -extension SQLExpression { - /// Returns the rowIds that identify rows in the request. A nil result means - /// an unbounded list. - /// - /// When in doubt, returns nil. - /// - /// WHERE 1 -- nil - /// WHERE 0 -- [] - /// WHERE NULL -- [] - /// WHERE id IS NULL -- [] - /// WHERE id = 1 -- [1] - /// WHERE id = 1 AND b = 2 -- [1] - /// WHERE id = 1 OR id = 2 -- [1, 2] - /// WHERE id IN (1, 2, 3) -- [1, 2, 3] - /// 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) - try _accept(&visitor) - return visitor.rowIDs - } -} - -/// Support for `SQLExpression.identifyingRowIDs(_:for:)` -private struct SQLIdentifyingRowIDs: _SQLExpressionVisitor { - let db: Database - let alias: TableAlias - var rowIDs: Set? = nil - - mutating func visit(_ dbValue: DatabaseValue) throws { - if dbValue.isNull || dbValue == false.databaseValue { - rowIDs = [] - } - } - - mutating func visit(_ column: Column) throws where Column: ColumnExpression { } - - mutating func visit(_ column: _SQLQualifiedColumn) throws { } - - mutating func visit(_ expr: _SQLRowValue) throws { } - - mutating func visit(_ expr: _SQLExpressionBetween) throws { } - - mutating func visit(_ expr: _SQLExpressionBinary) throws { } - - mutating func visit(_ expr: _SQLExpressionAssociativeBinary) throws { - if expr.op == .and { - for expression in expr.expressions { - if let expressionRowIDs = try expression.identifyingRowIDs(db, for: alias) { - if var rowIDs = self.rowIDs { - rowIDs.formIntersection(expressionRowIDs) - self.rowIDs = rowIDs - if rowIDs.isEmpty { - break - } - } else { - self.rowIDs = expressionRowIDs - } - } - } - } else if expr.op == .or { - var rowIDs: Set = [] - for expression in expr.expressions { - if let expressionRowIDs = try expression.identifyingRowIDs(db, for: alias) { - rowIDs.formUnion(expressionRowIDs) - } else { - self.rowIDs = nil - return - } - } - self.rowIDs = rowIDs - } - } - - mutating func visit(_ expr: _SQLExpressionCollate) throws { - try expr.expression._accept(&self) - } - - mutating func visit(_ expr: _SQLExpressionContains) throws { - if - let expressions = expr.collection.expressions(), - let column = try expr.expression.column(db, for: alias), - try db.columnIsRowID(column, of: alias.tableName) - { - rowIDs = Set(expressions.compactMap { - ($0 as? DatabaseValue).flatMap { Int64.fromDatabaseValue($0) } - }) - } - } - - mutating func visit(_ expr: _SQLExpressionCount) throws { } - - mutating func visit(_ expr: _SQLExpressionCountDistinct) throws { } - - mutating func visit(_ expr: _SQLExpressionEqual) throws { - switch expr.op { - case .equal, .is: - if - let column = try expr.lhs.column(db, for: alias), - try db.columnIsRowID(column, of: alias.tableName), - let dbValue = expr.rhs as? DatabaseValue - { - if let rowID = Int64.fromDatabaseValue(dbValue) { - rowIDs = [rowID] - } else { - // We miss `rowid = '1'` here, because SQLite would interpret the '1' string as a number - rowIDs = [] - } - } else if - let column = try expr.rhs.column(db, for: alias), - try db.columnIsRowID(column, of: alias.tableName), - let dbValue = expr.lhs as? DatabaseValue - { - if let rowID = Int64.fromDatabaseValue(dbValue) { - rowIDs = [rowID] - } else { - // We miss `rowid = '1'` here, because SQLite would interpret the '1' string as a number - rowIDs = [] - } - } - - case .notEqual, .isNot: - break - } - } - - mutating func visit(_ expr: _SQLExpressionFastPrimaryKey) throws { } - - mutating func visit(_ expr: _SQLExpressionFunction) throws { } - - mutating func visit(_ expr: _SQLExpressionIsEmpty) throws { } - - mutating func visit(_ expr: _SQLExpressionLiteral) throws { } - - mutating func visit(_ expr: _SQLExpressionNot) throws { } - - mutating func visit(_ expr: _SQLExpressionQualifiedFastPrimaryKey) throws { } - - mutating func visit(_ expr: _SQLExpressionTableMatch) throws { } - - mutating func visit(_ expr: _SQLExpressionUnary) throws { } - - // MARK: - _FetchRequestVisitor - - mutating func visit(_ request: AdaptedFetchRequest) throws { } - - mutating func visit(_ request: QueryInterfaceRequest) throws { } - - mutating func visit(_ request: SQLRequest) throws { } -} - -// MARK: - SQLSelectableIsAggregate - -extension SQLSelectable { - /// Returns true if the selectable is an aggregate. - /// - /// When in doubt, returns false. - /// - /// SELECT * -- false - /// SELECT score -- false - /// SELECT COUNT(*) -- true - /// SELECT MAX(score) -- true - /// SELECT MAX(score) + 1 -- true - /// - /// Support for `SQLQueryGenerator.expectsSingleResult()` - func isAggregate() -> Bool { - var visitor = SQLSelectableIsAggregate() - do { - try _accept(&visitor) - } catch is SQLSelectableIsAggregate.BreakError { - } catch { - try! { throw error }() - } - return visitor.isAggregate - } -} - -private struct SQLSelectableIsAggregate: _SQLSelectableVisitor { - struct BreakError: Error { } - var isAggregate = false - - private mutating func setAggregate() throws -> Never { - isAggregate = true - // Poor man's short-circuiting - throw BreakError() - } - - // MARK: _SQLSelectableVisitor - - mutating func visit(_ selectable: AllColumns) throws { } - - mutating func visit(_ selectable: _SQLAliasedExpression) throws { - try selectable.expression._accept(&self) - } - - 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 - } - - // MARK: _SQLExpressionVisitor - - mutating func visit(_ dbValue: DatabaseValue) throws { } - - mutating func visit(_ column: Column) throws { } - - mutating func visit(_ column: _SQLQualifiedColumn) throws { } - - mutating func visit(_ expr: _SQLExpressionBetween) throws { - try expr.expression._accept(&self) - } - - mutating func visit(_ expr: _SQLExpressionBinary) throws { - try expr.lhs._accept(&self) - try expr.rhs._accept(&self) - } - - mutating func visit(_ expr: _SQLExpressionAssociativeBinary) throws { - for expression in expr.expressions { - try expression._accept(&self) - } - } - - mutating func visit(_ expr: _SQLExpressionCollate) throws { - try expr.expression._accept(&self) - } - - mutating func visit(_ expr: _SQLExpressionContains) throws { - // SELECT aggregate IN (...) - try expr.expression._accept(&self) - - // SELECT expr IN (aggregate, ...) - if - let expressions = expr.collection.expressions(), - expressions.contains(where: { $0.isAggregate() }) - { - try setAggregate() - } - } - - mutating func visit(_ expr: _SQLExpressionCount) throws { - try setAggregate() - } - - mutating func visit(_ expr: _SQLExpressionCountDistinct) throws { - try setAggregate() - } - - mutating func visit(_ expr: _SQLExpressionEqual) throws { - try expr.lhs._accept(&self) - try expr.rhs._accept(&self) - } - - mutating func visit(_ expr: _SQLExpressionFastPrimaryKey) throws { } - - mutating func visit(_ expr: _SQLExpressionFunction) throws { - let function = expr.function.uppercased() - if ["MIN", "MAX"].contains(function) && expr.arguments.count == 1 { - try setAggregate() - } else if ["AVG", "COUNT", "SUM", "TOTAL"].contains(function) && expr.arguments.count == 1 { - try setAggregate() - } else if function == "GROUP_CONCAT" && (expr.arguments.count == 1 || expr.arguments.count == 2) { - try setAggregate() - } - } - - mutating func visit(_ expr: _SQLExpressionIsEmpty) throws { - try expr.countExpression._accept(&self) - } - - mutating func visit(_ expr: _SQLExpressionLiteral) throws { - // Don't know - assume not an aggregate - } - - mutating func visit(_ expr: _SQLExpressionNot) throws { - try expr.expression._accept(&self) - } - - mutating func visit(_ expr: _SQLExpressionQualifiedFastPrimaryKey) throws { } - - mutating func visit(_ expr: _SQLExpressionTableMatch) throws { } - - mutating func visit(_ expr: _SQLExpressionUnary) throws { - try expr.expression._accept(&self) - } - - // MARK: _FetchRequestVisitor - - mutating func visit(_ request: AdaptedFetchRequest) throws { } - - mutating func visit(_ request: QueryInterfaceRequest) throws { } - - mutating func visit(_ request: SQLRequest) throws { } -} diff --git a/GRDB/QueryInterface/SQLGeneration/SQLRequestGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLRequestGenerator.swift deleted file mode 100644 index 9cdeeadc2..000000000 --- a/GRDB/QueryInterface/SQLGeneration/SQLRequestGenerator.swift +++ /dev/null @@ -1,38 +0,0 @@ -extension _FetchRequest { - /// Returns the request SQL. - /// - /// - parameter context: An SQL generation context. - /// - parameter singleResult: A hint that a single result row will be - /// consumed. Implementations can optionally use it to optimize the - /// generated SQL, for example by adding a `LIMIT 1` SQL clause. - /// - returns: An SQL string. - func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { - var visitor = SQLRequestGenerator(context: context, forSingleResult: singleResult) - try _accept(&visitor) - return visitor.sql - } -} - -private struct SQLRequestGenerator: _FetchRequestVisitor { - let context: SQLGenerationContext - let singleResult: Bool - var sql = "" - - init(context: SQLGenerationContext, forSingleResult singleResult: Bool) { - self.context = context - self.singleResult = singleResult - } - - mutating func visit(_ request: AdaptedFetchRequest) throws { - try request.base._accept(&self) - } - - mutating func visit(_ request: QueryInterfaceRequest) throws { - let generator = SQLQueryGenerator(query: request.query, forSingleResult: singleResult) - sql = try generator.requestSQL(context) - } - - mutating func visit(_ request: SQLRequest) throws { - sql = try request.sqlLiteral.sql(context) - } -} diff --git a/GRDB/QueryInterface/SQLGeneration/SQLSelectableCountGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLSelectableCountGenerator.swift deleted file mode 100644 index 18c82f09d..000000000 --- a/GRDB/QueryInterface/SQLGeneration/SQLSelectableCountGenerator.swift +++ /dev/null @@ -1,144 +0,0 @@ -extension SQLSelectable { - /// Returns the SQL that feeds the argument of the `COUNT` function. - /// - /// For example: - /// - /// COUNT(*) - /// COUNT(id) - /// ^---- countedSQL - /// - /// - parameter context: An SQL generation context which accepts - /// statement arguments. - func countedSQL(_ context: SQLGenerationContext) throws -> String { - var generator = SQLSelectableCountGenerator(context: context) - try _accept(&generator) - return generator.resultSQL - } -} - -private struct SQLSelectableCountGenerator: _SQLSelectableVisitor { - let context: SQLGenerationContext - var resultSQL = "" - - // MARK: - _SQLSelectableVisitor - - mutating func visit(_ selectable: AllColumns) throws { - resultSQL = "*" - } - - mutating func visit(_ selectable: _SQLAliasedExpression) throws { - try selectable.expression._accept(&self) - } - - mutating func visit(_ selectable: _SQLQualifiedAllColumns) throws { - if context.qualifier(for: selectable.alias) != nil { - // SELECT COUNT(t.*) is invalid SQL - fatalError("Not implemented, or invalid query") - } - resultSQL = "*" - } - - mutating func visit(_ selectable: _SQLSelectionLiteral) throws { - fatalError(""" - Selection literals can't be counted. \ - To resolve this error, select one or several literal expressions instead. \ - See SQLLiteral.sqlExpression. - """) - } - - // MARK: - _SQLExpressionVisitor - - mutating func visit(_ expr: DatabaseValue) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: Column) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLQualifiedColumn) throws { - 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) - } - - mutating func visit(_ expr: _SQLExpressionBinary) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionAssociativeBinary) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionCollate) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionContains) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionCount) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionCountDistinct) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionEqual) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionFastPrimaryKey) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionFunction) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionIsEmpty) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionLiteral) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionNot) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionQualifiedFastPrimaryKey) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionTableMatch) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionUnary) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - // MARK: - _FetchRequestVisitor - - mutating func visit(_ request: AdaptedFetchRequest) throws { - resultSQL = try request.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ request: QueryInterfaceRequest) throws { - resultSQL = try request.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ request: SQLRequest) throws { - resultSQL = try request.expressionSQL(context, wrappedInParenthesis: false) - } -} diff --git a/GRDB/QueryInterface/SQLGeneration/SQLSelectableResultColumnGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLSelectableResultColumnGenerator.swift deleted file mode 100644 index 1b9d0d2a1..000000000 --- a/GRDB/QueryInterface/SQLGeneration/SQLSelectableResultColumnGenerator.swift +++ /dev/null @@ -1,143 +0,0 @@ -extension SQLSelectable { - /// Returns the SQL that feeds the selection of a `SELECT` statement. - /// - /// For example: - /// - /// 1 - /// name - /// COUNT(*) - /// (score + bonus) AS total - /// - /// See https://sqlite.org/syntax/result-column.html - /// - /// - parameter context: An SQL generation context which accepts - /// statement arguments. - func resultColumnSQL(_ context: SQLGenerationContext) throws -> String { - var generator = SQLSelectableResultColumnGenerator(context: context) - try _accept(&generator) - return generator.resultSQL - } -} - -private struct SQLSelectableResultColumnGenerator: _SQLSelectableVisitor { - let context: SQLGenerationContext - var resultSQL = "" - - // MARK: - _SQLSelectableVisitor - - mutating func visit(_ selectable: AllColumns) throws { - resultSQL = "*" - } - - mutating func visit(_ selectable: _SQLAliasedExpression) throws { - try selectable.expression._accept(&self) - resultSQL += " AS " + selectable.name.quotedDatabaseIdentifier - } - - mutating func visit(_ selectable: _SQLQualifiedAllColumns) throws { - if let qualifier = context.qualifier(for: selectable.alias) { - resultSQL = qualifier.quotedDatabaseIdentifier + "." - } - resultSQL += "*" - } - - mutating func visit(_ selectable: _SQLSelectionLiteral) throws { - resultSQL = try selectable.sqlLiteral.sql(context) - } - - // MARK: - _SQLExpressionVisitor - - mutating func visit(_ expr: DatabaseValue) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: Column) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLQualifiedColumn) throws { - 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) - } - - mutating func visit(_ expr: _SQLExpressionBinary) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionAssociativeBinary) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionCollate) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionContains) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionCount) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionCountDistinct) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionEqual) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionFastPrimaryKey) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionFunction) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionIsEmpty) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionLiteral) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionNot) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionQualifiedFastPrimaryKey) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionTableMatch) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ expr: _SQLExpressionUnary) throws { - resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) - } - - // MARK: - _FetchRequestVisitor - - mutating func visit(_ request: AdaptedFetchRequest) throws { - resultSQL = try request.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ request: QueryInterfaceRequest) throws { - resultSQL = try request.expressionSQL(context, wrappedInParenthesis: false) - } - - mutating func visit(_ request: SQLRequest) throws { - resultSQL = try request.expressionSQL(context, wrappedInParenthesis: false) - } -} diff --git a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift index 9a9f5a4d3..e53685a5f 100644 --- a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift @@ -206,7 +206,7 @@ extension SQLInterpolation { /// SELECT * FROM player WHERE score = (\(subquery)) /// """ public mutating func appendInterpolation(_ request: T) - where T: _FetchRequest & SQLExpression + where T: FetchRequest & SQLExpression { elements.append(.subquery(DatabasePromise(value: request))) } diff --git a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift index d9eb54f40..868b9960d 100644 --- a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift +++ b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift @@ -66,8 +66,11 @@ public enum ValueReducers { // ValueObservation.tracking(_:). /// :nodoc: public enum Auto: ValueReducer { + /// :nodoc: public var _isSelectedRegionDeterministic: Bool { preconditionFailure() } + /// :nodoc: public func _fetch(_ db: Database) throws -> Never { preconditionFailure() } + /// :nodoc: public mutating func _value(_ fetched: Never) -> Never? { } } } diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 44755329d..e1ef35b63 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -509,38 +509,14 @@ 56EA63CA209C7F1E009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C7209C7F1E009715B8 /* DerivableRequestTests.swift */; }; 56ED8A7F1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */; }; 56ED8A801DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */; }; - 56F34F9524AE78BE007513FC /* SQLExpressionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34F9424AE78BE007513FC /* SQLExpressionVisitor.swift */; }; - 56F34F9624AE78BE007513FC /* SQLExpressionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34F9424AE78BE007513FC /* SQLExpressionVisitor.swift */; }; - 56F34FA024B06A29007513FC /* SQLExpressionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34F9F24B06A29007513FC /* SQLExpressionGenerator.swift */; }; - 56F34FA124B06A29007513FC /* SQLExpressionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34F9F24B06A29007513FC /* SQLExpressionGenerator.swift */; }; 56F34FBF24B094D2007513FC /* SQLExpressionIsConstantTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FBD24B094D1007513FC /* SQLExpressionIsConstantTests.swift */; }; 56F34FC024B094D2007513FC /* SQLExpressionIsConstantTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FBD24B094D1007513FC /* SQLExpressionIsConstantTests.swift */; }; 56F34FC624B0A0C9007513FC /* SQLIdentifyingColumnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC524B0A0C8007513FC /* SQLIdentifyingColumnsTests.swift */; }; 56F34FC724B0A0C9007513FC /* SQLIdentifyingColumnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC524B0A0C8007513FC /* SQLIdentifyingColumnsTests.swift */; }; - 56F34FCE24B0DE0B007513FC /* SQLSelectableVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FCD24B0DE0B007513FC /* SQLSelectableVisitor.swift */; }; - 56F34FCF24B0DE0C007513FC /* SQLSelectableVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FCD24B0DE0B007513FC /* SQLSelectableVisitor.swift */; }; - 56F34FDC24B0E53F007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FDA24B0E53E007513FC /* SQLSelectableResultColumnGenerator.swift */; }; - 56F34FDD24B0E53F007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FDA24B0E53E007513FC /* SQLSelectableResultColumnGenerator.swift */; }; - 56F34FDE24B0E53F007513FC /* SQLSelectableCountGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FDB24B0E53F007513FC /* SQLSelectableCountGenerator.swift */; }; - 56F34FDF24B0E53F007513FC /* SQLSelectableCountGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FDB24B0E53F007513FC /* SQLSelectableCountGenerator.swift */; }; - 56F34FE624B0E94C007513FC /* SQLOrderingTermVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE524B0E94C007513FC /* SQLOrderingTermVisitor.swift */; }; - 56F34FE724B0E94C007513FC /* SQLOrderingTermVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE524B0E94C007513FC /* SQLOrderingTermVisitor.swift */; }; - 56F34FEE24B0EEA6007513FC /* SQLOrderingGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FED24B0EEA6007513FC /* SQLOrderingGenerator.swift */; }; - 56F34FEF24B0EEA6007513FC /* SQLOrderingGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FED24B0EEA6007513FC /* SQLOrderingGenerator.swift */; }; 56F34FF124B0F0D8007513FC /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FF024B0F0D8007513FC /* SQLCollatedExpression.swift */; }; 56F34FF224B0F0D8007513FC /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FF024B0F0D8007513FC /* SQLCollatedExpression.swift */; }; - 56F34FF924B0F85C007513FC /* SQLCollectionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FF824B0F85C007513FC /* SQLCollectionVisitor.swift */; }; - 56F34FFA24B0F85C007513FC /* SQLCollectionVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FF824B0F85C007513FC /* SQLCollectionVisitor.swift */; }; - 56F34FFC24B0FB43007513FC /* SQLCollectionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FFB24B0FB43007513FC /* SQLCollectionGenerator.swift */; }; - 56F34FFD24B0FB43007513FC /* SQLCollectionGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FFB24B0FB43007513FC /* SQLCollectionGenerator.swift */; }; 56F3E74C1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; }; 56F3E7501E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; }; - 56F896B324B9E679005FB062 /* SQLRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896B224B9E679005FB062 /* SQLRequestGenerator.swift */; }; - 56F896B424B9E679005FB062 /* SQLRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896B224B9E679005FB062 /* SQLRequestGenerator.swift */; }; - 56F896C024B9E73F005FB062 /* SQLPreparedRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896BF24B9E73F005FB062 /* SQLPreparedRequestGenerator.swift */; }; - 56F896C124B9E73F005FB062 /* SQLPreparedRequestGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896BF24B9E73F005FB062 /* SQLPreparedRequestGenerator.swift */; }; - 56F896C324BA042E005FB062 /* FetchRequestVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896C224BA042E005FB062 /* FetchRequestVisitor.swift */; }; - 56F896C424BA042E005FB062 /* FetchRequestVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F896C224BA042E005FB062 /* FetchRequestVisitor.swift */; }; 56FBFED62210731100945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED52210731000945324 /* SQLRequest.swift */; }; 56FBFED72210731100945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED52210731000945324 /* SQLRequest.swift */; }; 56FEB8FE248403270081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */; }; @@ -1125,22 +1101,10 @@ 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataMemoryTests.swift; sourceTree = ""; }; 56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizerTests.swift; sourceTree = ""; }; 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDateTests.swift; sourceTree = ""; }; - 56F34F9424AE78BE007513FC /* SQLExpressionVisitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLExpressionVisitor.swift; sourceTree = ""; }; - 56F34F9F24B06A29007513FC /* SQLExpressionGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLExpressionGenerator.swift; sourceTree = ""; }; 56F34FBD24B094D1007513FC /* SQLExpressionIsConstantTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLExpressionIsConstantTests.swift; sourceTree = ""; }; 56F34FC524B0A0C8007513FC /* SQLIdentifyingColumnsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLIdentifyingColumnsTests.swift; sourceTree = ""; }; - 56F34FCD24B0DE0B007513FC /* SQLSelectableVisitor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectableVisitor.swift; sourceTree = ""; }; - 56F34FDA24B0E53E007513FC /* SQLSelectableResultColumnGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectableResultColumnGenerator.swift; sourceTree = ""; }; - 56F34FDB24B0E53F007513FC /* SQLSelectableCountGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectableCountGenerator.swift; sourceTree = ""; }; - 56F34FE524B0E94C007513FC /* SQLOrderingTermVisitor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOrderingTermVisitor.swift; sourceTree = ""; }; - 56F34FED24B0EEA6007513FC /* SQLOrderingGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOrderingGenerator.swift; sourceTree = ""; }; 56F34FF024B0F0D8007513FC /* SQLCollatedExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollatedExpression.swift; sourceTree = ""; }; - 56F34FF824B0F85C007513FC /* SQLCollectionVisitor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollectionVisitor.swift; sourceTree = ""; }; - 56F34FFB24B0FB43007513FC /* SQLCollectionGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLCollectionGenerator.swift; sourceTree = ""; }; 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = ""; }; - 56F896B224B9E679005FB062 /* SQLRequestGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequestGenerator.swift; sourceTree = ""; }; - 56F896BF24B9E73F005FB062 /* SQLPreparedRequestGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLPreparedRequestGenerator.swift; sourceTree = ""; }; - 56F896C224BA042E005FB062 /* FetchRequestVisitor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequestVisitor.swift; sourceTree = ""; }; 56FBFED52210731000945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = ""; }; 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = ""; }; 56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTraceTests.swift; sourceTree = ""; }; @@ -1538,15 +1502,8 @@ 5656A8292295BD56001FF3FF /* SQLGeneration */ = { isa = PBXGroup; children = ( - 56F34FFB24B0FB43007513FC /* SQLCollectionGenerator.swift */, - 56F34F9F24B06A29007513FC /* SQLExpressionGenerator.swift */, 5656A82B2295BD56001FF3FF /* SQLGenerationContext.swift */, - 56F34FED24B0EEA6007513FC /* SQLOrderingGenerator.swift */, - 56F896BF24B9E73F005FB062 /* SQLPreparedRequestGenerator.swift */, 5656A82A2295BD56001FF3FF /* SQLQueryGenerator.swift */, - 56F896B224B9E679005FB062 /* SQLRequestGenerator.swift */, - 56F34FDB24B0E53F007513FC /* SQLSelectableCountGenerator.swift */, - 56F34FDA24B0E53E007513FC /* SQLSelectableResultColumnGenerator.swift */, ); path = SQLGeneration; sourceTree = ""; @@ -1595,22 +1552,18 @@ 5656A8412295BD56001FF3FF /* SQLAssociation.swift */, 56F34FF024B0F0D8007513FC /* SQLCollatedExpression.swift */, 5656A8432295BD56001FF3FF /* SQLCollection.swift */, - 56F34FF824B0F85C007513FC /* SQLCollectionVisitor.swift */, 5656A8472295BD56001FF3FF /* SQLExpressible.swift */, 5656A8442295BD56001FF3FF /* SQLExpression.swift */, 5656A8482295BD56001FF3FF /* SQLExpression+QueryInterface.swift */, - 56F34F9424AE78BE007513FC /* SQLExpressionVisitor.swift */, 5656A8422295BD56001FF3FF /* SQLForeignKeyRequest.swift */, 5656A84C2295BD56001FF3FF /* SQLFunctions.swift */, 5656A8462295BD56001FF3FF /* SQLOperators.swift */, 5656A8452295BD56001FF3FF /* SQLOrdering.swift */, - 56F34FE524B0E94C007513FC /* SQLOrderingTermVisitor.swift */, 5656A8502295BD56001FF3FF /* SQLQuery.swift */, 5656A84E2295BD56001FF3FF /* SQLRelation.swift */, 56D8B40B257D0FBE008AA1F7 /* SQLRowValue.swift */, 5656A8492295BD56001FF3FF /* SQLSelectable.swift */, 5656A84F2295BD56001FF3FF /* SQLSelectable+QueryInterface.swift */, - 56F34FCD24B0DE0B007513FC /* SQLSelectableVisitor.swift */, 5656A84B2295BD56001FF3FF /* SQLSpecificExpressible+QueryInterface.swift */, ); path = SQL; @@ -1825,7 +1778,6 @@ 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */, 563363C31C942C37000BE133 /* DatabaseWriter.swift */, 5636E9BB1D22574100B9B05F /* FetchRequest.swift */, - 56F896C224BA042E005FB062 /* FetchRequestVisitor.swift */, 56A238761B9C75030082EB20 /* Row.swift */, 567404871CEF84C8003ED5CC /* RowAdapter.swift */, 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */, @@ -2313,8 +2265,6 @@ 5656A8722295BD56001FF3FF /* HasOneThroughAssociation.swift in Sources */, 5636E9C11D22574100B9B05F /* FetchRequest.swift in Sources */, F3BA801B1CFB2886003DC1BA /* CGFloat.swift in Sources */, - 56F34FEF24B0EEA6007513FC /* SQLOrderingGenerator.swift in Sources */, - 56F34FDF24B0E53F007513FC /* SQLSelectableCountGenerator.swift in Sources */, 563B8FBE24A1D388007A48C9 /* OnDemandFuture.swift in Sources */, 5656A85E2295BD56001FF3FF /* VirtualTableModule.swift in Sources */, 5656A8882295BD56001FF3FF /* SQLOperators.swift in Sources */, @@ -2345,7 +2295,6 @@ F3BA800B1CFB286D003DC1BA /* Database.swift in Sources */, F3BA80341CFB28A4003DC1BA /* Record.swift in Sources */, 56C0539422ACEECD0029D27D /* Fetch.swift in Sources */, - 56F34FE724B0E94C007513FC /* SQLOrderingTermVisitor.swift in Sources */, 56E9FAC52210468500C703A8 /* SQLInterpolation.swift in Sources */, 563EF421215F8A76007DAACD /* OrderedDictionary.swift in Sources */, F3BA80161CFB2876003DC1BA /* Row.swift in Sources */, @@ -2353,7 +2302,6 @@ F3BA80101CFB2876003DC1BA /* DatabaseReader.swift in Sources */, 563B8FBA24A1D036007A48C9 /* ReceiveValuesOn.swift in Sources */, 564F9C331F07611800877A00 /* DatabaseFunction.swift in Sources */, - 56F34FDD24B0E53F007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */, 5656A8942295BD56001FF3FF /* SQLFunctions.swift in Sources */, 5659F49D1EA8D989004A4992 /* Pool.swift in Sources */, 563A4B72242E7CE60075D8CF /* ValueObservationScheduler.swift in Sources */, @@ -2362,7 +2310,6 @@ 5698AC3C1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 5698AD171DAAD16F0056AF8C /* FTS5Tokenizer.swift in Sources */, 569BBA4C229170B300478429 /* Inflections+English.swift in Sources */, - 56F34FFD24B0FB43007513FC /* SQLCollectionGenerator.swift in Sources */, 5656A8762295BD56001FF3FF /* RequestProtocols.swift in Sources */, 561729552235340E0006E219 /* EncodableRecord.swift in Sources */, 5656A87E2295BD56001FF3FF /* SQLAssociation.swift in Sources */, @@ -2377,7 +2324,6 @@ F3BA80201CFB288C003DC1BA /* Date.swift in Sources */, 56A8C2351D1914540096E9D4 /* UUID.swift in Sources */, 5656A8822295BD56001FF3FF /* SQLCollection.swift in Sources */, - 56F34FA124B06A29007513FC /* SQLExpressionGenerator.swift in Sources */, 56D51D051EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 56DF37A823D77AA0009AAA05 /* Refinable.swift in Sources */, F3BA80151CFB2876003DC1BA /* DatabaseWriter.swift in Sources */, @@ -2386,14 +2332,10 @@ 5656A88E2295BD56001FF3FF /* SQLSelectable.swift in Sources */, 5671FC251DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 5656A8862295BD56001FF3FF /* SQLOrdering.swift in Sources */, - 56F896C124B9E73F005FB062 /* SQLPreparedRequestGenerator.swift in Sources */, F3BA80311CFB289F003DC1BA /* Migration.swift in Sources */, - 56F896B424B9E679005FB062 /* SQLRequestGenerator.swift in Sources */, F3BA801D1CFB288C003DC1BA /* DatabaseDateComponents.swift in Sources */, 5674A6ED1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 5657AB141D10899D006283EF /* URL.swift in Sources */, - 56F34FFA24B0F85C007513FC /* SQLCollectionVisitor.swift in Sources */, - 56F34F9624AE78BE007513FC /* SQLExpressionVisitor.swift in Sources */, 56F34FF224B0F0D8007513FC /* SQLCollatedExpression.swift in Sources */, 5644DE7920F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */, 56DAA2E01DE9C827006E10C8 /* Cursor.swift in Sources */, @@ -2404,7 +2346,6 @@ 56C0539C22ACEECD0029D27D /* Map.swift in Sources */, F3BA80221CFB288C003DC1BA /* NSNumber.swift in Sources */, 5656A8582295BD56001FF3FF /* SQLQueryGenerator.swift in Sources */, - 56F896C424BA042E005FB062 /* FetchRequestVisitor.swift in Sources */, 5656A8842295BD56001FF3FF /* SQLExpression.swift in Sources */, 5659F48D1EA8D94E004A4992 /* Utils.swift in Sources */, F3BA80231CFB288C003DC1BA /* NSString.swift in Sources */, @@ -2448,7 +2389,6 @@ 5656A8662295BD56001FF3FF /* BelongsToAssociation.swift in Sources */, F3BA800E1CFB2876003DC1BA /* DatabaseQueue.swift in Sources */, F3BA80191CFB2876003DC1BA /* Statement.swift in Sources */, - 56F34FCF24B0DE0C007513FC /* SQLSelectableVisitor.swift in Sources */, 56B964A21DA51B4C0002DA19 /* FTS5.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -2686,8 +2626,6 @@ 5656A8712295BD56001FF3FF /* HasOneThroughAssociation.swift in Sources */, 5636E9BE1D22574100B9B05F /* FetchRequest.swift in Sources */, F3BA80771CFB2E5C003DC1BA /* CGFloat.swift in Sources */, - 56F34FEE24B0EEA6007513FC /* SQLOrderingGenerator.swift in Sources */, - 56F34FDE24B0E53F007513FC /* SQLSelectableCountGenerator.swift in Sources */, 563B8FBD24A1D388007A48C9 /* OnDemandFuture.swift in Sources */, 5656A85D2295BD56001FF3FF /* VirtualTableModule.swift in Sources */, 5656A8872295BD56001FF3FF /* SQLOperators.swift in Sources */, @@ -2718,7 +2656,6 @@ F3BA80671CFB2E55003DC1BA /* Database.swift in Sources */, F3BA80901CFB2E7A003DC1BA /* Record.swift in Sources */, 56C0539322ACEECD0029D27D /* Fetch.swift in Sources */, - 56F34FE624B0E94C007513FC /* SQLOrderingTermVisitor.swift in Sources */, 56E9FAC42210468500C703A8 /* SQLInterpolation.swift in Sources */, 563EF420215F8A76007DAACD /* OrderedDictionary.swift in Sources */, F3BA80721CFB2E55003DC1BA /* Row.swift in Sources */, @@ -2726,7 +2663,6 @@ F3BA806C1CFB2E55003DC1BA /* DatabaseReader.swift in Sources */, 563B8FBB24A1D036007A48C9 /* ReceiveValuesOn.swift in Sources */, 564F9C301F07611500877A00 /* DatabaseFunction.swift in Sources */, - 56F34FDC24B0E53F007513FC /* SQLSelectableResultColumnGenerator.swift in Sources */, 5656A8932295BD56001FF3FF /* SQLFunctions.swift in Sources */, 5659F49A1EA8D989004A4992 /* Pool.swift in Sources */, 563A4B71242E7CE60075D8CF /* ValueObservationScheduler.swift in Sources */, @@ -2735,7 +2671,6 @@ 5698AC391D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 5698AD161DAAD16F0056AF8C /* FTS5Tokenizer.swift in Sources */, 569BBA4D229170B300478429 /* Inflections+English.swift in Sources */, - 56F34FFC24B0FB43007513FC /* SQLCollectionGenerator.swift in Sources */, 5656A8752295BD56001FF3FF /* RequestProtocols.swift in Sources */, 561729562235340E0006E219 /* EncodableRecord.swift in Sources */, 5656A87D2295BD56001FF3FF /* SQLAssociation.swift in Sources */, @@ -2750,7 +2685,6 @@ F3BA807C1CFB2E61003DC1BA /* Date.swift in Sources */, 56A8C2321D1914540096E9D4 /* UUID.swift in Sources */, 5656A8812295BD56001FF3FF /* SQLCollection.swift in Sources */, - 56F34FA024B06A29007513FC /* SQLExpressionGenerator.swift in Sources */, 56D51D021EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 56DF37A723D77AA0009AAA05 /* Refinable.swift in Sources */, F3BA80711CFB2E55003DC1BA /* DatabaseWriter.swift in Sources */, @@ -2759,14 +2693,10 @@ 5656A88D2295BD56001FF3FF /* SQLSelectable.swift in Sources */, 5671FC221DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 5656A8852295BD56001FF3FF /* SQLOrdering.swift in Sources */, - 56F896C024B9E73F005FB062 /* SQLPreparedRequestGenerator.swift in Sources */, F3BA808D1CFB2E75003DC1BA /* Migration.swift in Sources */, - 56F896B324B9E679005FB062 /* SQLRequestGenerator.swift in Sources */, F3BA80791CFB2E61003DC1BA /* DatabaseDateComponents.swift in Sources */, 5674A6EC1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 5657AB111D10899D006283EF /* URL.swift in Sources */, - 56F34FF924B0F85C007513FC /* SQLCollectionVisitor.swift in Sources */, - 56F34F9524AE78BE007513FC /* SQLExpressionVisitor.swift in Sources */, 56F34FF124B0F0D8007513FC /* SQLCollatedExpression.swift in Sources */, 5644DE7820F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */, 56DAA2DD1DE9C827006E10C8 /* Cursor.swift in Sources */, @@ -2777,7 +2707,6 @@ 56C0539B22ACEECD0029D27D /* Map.swift in Sources */, F3BA807E1CFB2E61003DC1BA /* NSNumber.swift in Sources */, 5656A8572295BD56001FF3FF /* SQLQueryGenerator.swift in Sources */, - 56F896C324BA042E005FB062 /* FetchRequestVisitor.swift in Sources */, 5656A8832295BD56001FF3FF /* SQLExpression.swift in Sources */, 5659F48A1EA8D94E004A4992 /* Utils.swift in Sources */, F3BA807F1CFB2E61003DC1BA /* NSString.swift in Sources */, @@ -2821,7 +2750,6 @@ 5656A8652295BD56001FF3FF /* BelongsToAssociation.swift in Sources */, F3BA806A1CFB2E55003DC1BA /* DatabaseQueue.swift in Sources */, F3BA80751CFB2E55003DC1BA /* Statement.swift in Sources */, - 56F34FCE24B0DE0B007513FC /* SQLSelectableVisitor.swift in Sources */, 56B9649F1DA51B4C0002DA19 /* FTS5.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift b/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift index 28739c642..b00ec958c 100644 --- a/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift +++ b/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift @@ -49,6 +49,81 @@ class DatabaseReaderReadPublisherTests : XCTestCase { // MARK: - + #warning("TODO: fix crasher") + // * thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x20) + // frame #0: 0x00007fff7115c6e8 libobjc.A.dylib`objc_retain + 24 + // frame #1: 0x00007fff71c313a1 libswiftCore.dylib`swift::metadataimpl::ValueWitnesses::initializeWithCopy(swift::OpaqueValue*, swift::OpaqueValue*, swift::TargetMetadata const*) + 17 + // frame #2: 0x000000010d926309 GRDB`outlined init with copy of Subscribers.Completion at :0 + // frame #3: 0x000000010d92474b GRDB`ReceiveValuesOnSubscription._receive(completion=failure, self=0x00000001064c13c0) at ReceiveValuesOn.swift:184:9 + // frame #4: 0x000000010d92392c GRDB`closure #1 in closure #1 in closure #1 in ReceiveValuesOnSubscription.receive(self=0x00000001064c13c0, completion=failure) at ReceiveValuesOn.swift:158:26 + // frame #5: 0x00007fff71d88f49 libswiftDispatch.dylib`reabstraction thunk helper from @escaping @callee_guaranteed () -> () to @escaping @callee_unowned @convention(block) () -> () + 25 + // frame #6: 0x00007fff722b76c4 libdispatch.dylib`_dispatch_call_block_and_release + 12 + // frame #7: 0x00007fff722b8658 libdispatch.dylib`_dispatch_client_callout + 8 + // frame #8: 0x00007fff722c3cab libdispatch.dylib`_dispatch_main_queue_callback_4CF + 936 + // frame #9: 0x00007fff38299e81 CoreFoundation`__CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9 + // frame #10: 0x00007fff38259c87 CoreFoundation`__CFRunLoopRun + 2028 + // frame #11: 0x00007fff38258e3e CoreFoundation`CFRunLoopRunSpecific + 462 + // frame #12: 0x00000001003aa82b XCTest`-[XCTWaiter waitForExpectations:timeout:enforceOrder:] + 823 + // frame #13: 0x0000000100324a04 XCTest`-[XCTestCase(AsynchronousTesting) waitForExpectations:timeout:enforceOrder:] + 102 + // frame #14: 0x000000010961363d GRDBOSXTests`XCTestCase.wait(publisherExpectation=GRDBOSXTests.PublisherExpectations.Recording, Swift.Error> @ 0x00007ffeefbfd2f0, timeout=1, description="", self=0x0000000101d8a9c0) at PublisherExpectation.swift:97:9 + // frame #15: 0x000000010915dbcf GRDBOSXTests`test #1 (reader=0x000000010672f210, self=0x0000000101d8a9c0) in DatabaseReaderReadPublisherTests.testReadPublisherError() at DatabaseReaderReadPublisherTests.swift:62:33 + // frame #16: 0x000000010915dfc0 GRDBOSXTests`partial apply for test #1 (reader:) in DatabaseReaderReadPublisherTests.testReadPublisherError() at :0 + // frame #17: 0x000000010915c334 GRDBOSXTests`thunk for @escaping @callee_guaranteed (@guaranteed DatabaseReader) -> (@error @owned Error) at :0 + // frame #18: 0x000000010915e014 GRDBOSXTests`thunk for @escaping @callee_guaranteed (@guaranteed DatabaseReader) -> (@error @owned Error)partial apply at :0 + // frame #19: 0x00000001095a85f8 GRDBOSXTests`closure #1 in Test.init(context=0x000000010672f210, _0=, test=0x000000010915e000 GRDBOSXTests`reabstraction thunk helper from @escaping @callee_guaranteed (@guaranteed GRDB.DatabaseReader) -> (@error @owned Swift.Error) to @escaping @callee_guaranteed (@in_guaranteed GRDB.DatabaseReader) -> (@error @owned Swift.Error)partial apply forwarder with unmangled suffix ".16" at ) at Support.swift:13:41 + // frame #20: 0x00000001095a86af GRDBOSXTests`partial apply for closure #1 in Test.init(repeatCount:_:) at :0 + // frame #21: 0x00000001095a8a8f GRDBOSXTests`Test.run(context=0x000000010915e880 GRDBOSXTests`reabstraction thunk helper from @callee_guaranteed () -> (@owned GRDB.DatabaseReader, @error @owned Swift.Error) to @escaping @callee_guaranteed () -> (@out GRDB.DatabaseReader, @error @owned Swift.Error)partial apply forwarder with unmangled suffix ".17" at , self=(repeatCount = 1, test = 0x00000001095a8690 GRDBOSXTests`partial apply forwarder for closure #1 (A, Swift.Int) throws -> () in GRDBOSXTests.Test.init(repeatCount: Swift.Int, _: (A) throws -> ()) -> GRDBOSXTests.Test at )) at Support.swift:24:17 + // * frame #22: 0x000000010915d4ec GRDBOSXTests`DatabaseReaderReadPublisherTests.testReadPublisherError(self=0x0000000101d8a9c0) at DatabaseReaderReadPublisherTests.swift:71:14 + // frame #23: 0x000000010915f26a GRDBOSXTests`@objc DatabaseReaderReadPublisherTests.testReadPublisherError() at :0 + // frame #24: 0x00007fff3823c8ac CoreFoundation`__invoking___ + 140 + // frame #25: 0x00007fff3823c751 CoreFoundation`-[NSInvocation invoke] + 303 + // frame #26: 0x0000000100339d3a XCTest`__24-[XCTestCase invokeTest]_block_invoke_3 + 52 + // frame #27: 0x0000000100402215 XCTest`+[XCTSwiftErrorObservation observeErrorsInBlock:] + 69 + // frame #28: 0x0000000100339c3c XCTest`__24-[XCTestCase invokeTest]_block_invoke_2 + 119 + // frame #29: 0x00000001003c959a XCTest`-[XCTMemoryChecker _assertInvalidObjectsDeallocatedAfterScope:] + 65 + // frame #30: 0x00000001003448ea XCTest`-[XCTestCase assertInvalidObjectsDeallocatedAfterScope:] + 61 + // frame #31: 0x0000000100339b82 XCTest`__24-[XCTestCase invokeTest]_block_invoke.231 + 199 + // frame #32: 0x00000001003ae6d8 XCTest`-[XCTestCase(XCTIssueHandling) _caughtUnhandledDeveloperExceptionPermittingControlFlowInterruptions:caughtInterruptionException:whileExecutingBlock:] + 179 + // frame #33: 0x0000000100339645 XCTest`-[XCTestCase invokeTest] + 1037 + // frame #34: 0x000000010033b023 XCTest`__26-[XCTestCase performTest:]_block_invoke_2 + 43 + // frame #35: 0x00000001003ae6d8 XCTest`-[XCTestCase(XCTIssueHandling) _caughtUnhandledDeveloperExceptionPermittingControlFlowInterruptions:caughtInterruptionException:whileExecutingBlock:] + 179 + // frame #36: 0x000000010033af5a XCTest`__26-[XCTestCase performTest:]_block_invoke.362 + 86 + // frame #37: 0x00000001003bfb9f XCTest`+[XCTContext runInContextForTestCase:markAsReportingBase:block:] + 220 + // frame #38: 0x000000010033a7c7 XCTest`-[XCTestCase performTest:] + 695 + // frame #39: 0x000000010038c6da XCTest`-[XCTest runTest] + 57 + // frame #40: 0x0000000100334035 XCTest`__27-[XCTestSuite performTest:]_block_invoke + 329 + // frame #41: 0x0000000100333856 XCTest`__59-[XCTestSuite _performProtectedSectionForTest:testSection:]_block_invoke + 24 + // frame #42: 0x00000001003bfb9f XCTest`+[XCTContext runInContextForTestCase:markAsReportingBase:block:] + 220 + // frame #43: 0x00000001003bfab0 XCTest`+[XCTContext runInContextForTestCase:block:] + 52 + // frame #44: 0x000000010033380d XCTest`-[XCTestSuite _performProtectedSectionForTest:testSection:] + 148 + // frame #45: 0x0000000100333b11 XCTest`-[XCTestSuite performTest:] + 290 + // frame #46: 0x000000010038c6da XCTest`-[XCTest runTest] + 57 + // frame #47: 0x0000000100334035 XCTest`__27-[XCTestSuite performTest:]_block_invoke + 329 + // frame #48: 0x0000000100333856 XCTest`__59-[XCTestSuite _performProtectedSectionForTest:testSection:]_block_invoke + 24 + // frame #49: 0x00000001003bfb9f XCTest`+[XCTContext runInContextForTestCase:markAsReportingBase:block:] + 220 + // frame #50: 0x00000001003bfab0 XCTest`+[XCTContext runInContextForTestCase:block:] + 52 + // frame #51: 0x000000010033380d XCTest`-[XCTestSuite _performProtectedSectionForTest:testSection:] + 148 + // frame #52: 0x0000000100333b11 XCTest`-[XCTestSuite performTest:] + 290 + // frame #53: 0x000000010038c6da XCTest`-[XCTest runTest] + 57 + // frame #54: 0x0000000100334035 XCTest`__27-[XCTestSuite performTest:]_block_invoke + 329 + // frame #55: 0x0000000100333856 XCTest`__59-[XCTestSuite _performProtectedSectionForTest:testSection:]_block_invoke + 24 + // frame #56: 0x00000001003bfb9f XCTest`+[XCTContext runInContextForTestCase:markAsReportingBase:block:] + 220 + // frame #57: 0x00000001003bfab0 XCTest`+[XCTContext runInContextForTestCase:block:] + 52 + // frame #58: 0x000000010033380d XCTest`-[XCTestSuite _performProtectedSectionForTest:testSection:] + 148 + // frame #59: 0x0000000100333b11 XCTest`-[XCTestSuite performTest:] + 290 + // frame #60: 0x000000010038c6da XCTest`-[XCTest runTest] + 57 + // frame #61: 0x00000001003dc8b5 XCTest`__44-[XCTTestRunSession runTestsAndReturnError:]_block_invoke_2 + 148 + // frame #62: 0x00000001003bfb9f XCTest`+[XCTContext runInContextForTestCase:markAsReportingBase:block:] + 220 + // frame #63: 0x00000001003bfab0 XCTest`+[XCTContext runInContextForTestCase:block:] + 52 + // frame #64: 0x00000001003dc81a XCTest`__44-[XCTTestRunSession runTestsAndReturnError:]_block_invoke + 111 + // frame #65: 0x00000001003dc99b XCTest`__44-[XCTTestRunSession runTestsAndReturnError:]_block_invoke.95 + 96 + // frame #66: 0x000000010035acb8 XCTest`-[XCTestObservationCenter _observeTestExecutionForBlock:] + 325 + // frame #67: 0x00000001003dc5e0 XCTest`-[XCTTestRunSession runTestsAndReturnError:] + 615 + // frame #68: 0x0000000100317a7e XCTest`-[XCTestDriver _runTests] + 466 + // frame #69: 0x00000001003bbb82 XCTest`_XCTestMain + 108 + // frame #70: 0x0000000100002f07 xctest`main + 210 + // frame #71: 0x00007fff72311cc9 libdyld.dylib`start + 1 + // frame #72: 0x00007fff72311cc9 libdyld.dylib`start + 1 func testReadPublisherError() throws { guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else { throw XCTSkip("Combine is not available") diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index a3d4d47f4..380b05e78 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -1342,7 +1342,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { "SELECT avgOf(\"age\", 1, 2) FROM \"readers\"") } - // MARK: - _SQLExpressionFastPrimaryKey + // MARK: - SQLExpressionFastPrimaryKey func testFastPrimaryKeyExpression() throws { struct IntegerPrimaryKeyRecord: TableRecord { } @@ -1361,19 +1361,19 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { CREATE TABLE compoundPrimaryKeyRecord (a INTEGER, b INTEGER, PRIMARY KEY (a, b)); """) - try assertEqualSQL(db, IntegerPrimaryKeyRecord.select(_SQLExpressionFastPrimaryKey()), """ + try assertEqualSQL(db, IntegerPrimaryKeyRecord.select(SQLExpressionFastPrimaryKey()), """ SELECT "id" FROM "integerPrimaryKeyRecord" """) - try assertEqualSQL(db, UUIDRecord.select(_SQLExpressionFastPrimaryKey()), """ + try assertEqualSQL(db, UUIDRecord.select(SQLExpressionFastPrimaryKey()), """ SELECT "rowid" FROM "uuidRecord" """) - try assertEqualSQL(db, UUIDRecordWithoutRowID.select(_SQLExpressionFastPrimaryKey()), """ + try assertEqualSQL(db, UUIDRecordWithoutRowID.select(SQLExpressionFastPrimaryKey()), """ SELECT "uuid" FROM "uuidRecordWithoutRowID" """) - try assertEqualSQL(db, RowIDRecord.select(_SQLExpressionFastPrimaryKey()), """ + try assertEqualSQL(db, RowIDRecord.select(SQLExpressionFastPrimaryKey()), """ SELECT "rowid" FROM "rowIDRecord" """) - try assertEqualSQL(db, CompoundPrimaryKeyRecord.select(_SQLExpressionFastPrimaryKey()), """ + try assertEqualSQL(db, CompoundPrimaryKeyRecord.select(SQLExpressionFastPrimaryKey()), """ SELECT "rowid" FROM "compoundPrimaryKeyRecord" """) } diff --git a/Tests/GRDBTests/SQLExpressionIsConstantTests.swift b/Tests/GRDBTests/SQLExpressionIsConstantTests.swift index fa3faf4f4..e807cde4b 100644 --- a/Tests/GRDBTests/SQLExpressionIsConstantTests.swift +++ b/Tests/GRDBTests/SQLExpressionIsConstantTests.swift @@ -1,47 +1,353 @@ import XCTest @testable import GRDB -class SQLExpressionIsConstantTests: XCTestCase { - func testIsConstant() { - XCTAssertTrue(1.databaseValue.isConstantInRequest) +// Column +// DatabaseValue +// SQLExpressionAssociativeBinary +// SQLExpressionBetween +// SQLExpressionBinary +// SQLExpressionCollate +// SQLExpressionContains +// SQLExpressionCount +// SQLExpressionCountDistinct +// SQLExpressionEqual +// SQLExpressionFastPrimaryKey +// SQLExpressionFunction +// SQLExpressionIsEmpty +// SQLExpressionLiteral +// SQLExpressionNot +// SQLExpressionQualifiedFastPrimaryKey +// SQLExpressionTableMatch +// SQLExpressionUnary +// SQLQualifiedColumn +// SQLRowValue +class SQLExpressionIsConstantTests: GRDBTestCase { + func testColumn() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "t") { $0.autoIncrementedPrimaryKey("id") } + let alias = TableAlias(tableName: "t") + + // Column + try XCTAssertEqual(Column("a")._column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual(Column("a")._column(db, for: alias, acceptsBijection: false), nil) + + // DatabaseValue + try XCTAssertEqual("foo".databaseValue._column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual("foo".databaseValue._column(db, for: alias, acceptsBijection: false), nil) + + // SQLExpressionAssociativeBinary + try XCTAssertEqual([].joined(operator: .multiply)._column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual([].joined(operator: .multiply)._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual([Column("a")].joined(operator: .multiply)._column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual([Column("a")].joined(operator: .multiply)._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual([alias[Column("a")]].joined(operator: .multiply)._column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual([alias[Column("a")]].joined(operator: .multiply)._column(db, for: alias, acceptsBijection: false), "a") + try XCTAssertEqual([-alias[Column("a")]].joined(operator: .multiply)._column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual([-alias[Column("a")]].joined(operator: .multiply)._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((alias[Column("a")] * "foo".databaseValue)._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((alias[Column("a")] * "foo".databaseValue)._column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual((alias[Column("a")] + "foo".databaseValue)._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((alias[Column("a")] + "foo".databaseValue)._column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual((alias[Column("a")] + alias[Column("b")])._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((alias[Column("a")] + alias[Column("b")])._column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual([alias[Column("a")], "foo".databaseValue].joined(operator: .concat)._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual([alias[Column("a")], "foo".databaseValue].joined(operator: .concat)._column(db, for: alias, acceptsBijection: true), "a") + + // SQLExpressionBetween + try XCTAssertEqual((1...3).contains(alias[Column("a")])._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((1...3).contains(alias[Column("a")])._column(db, for: alias, acceptsBijection: false), nil) + + // SQLExpressionBinary + try XCTAssertEqual((alias[Column("a")] - "foo".databaseValue)._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((alias[Column("a")] - "foo".databaseValue)._column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual((alias[Column("a")] - alias[Column("b")])._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((alias[Column("a")] - alias[Column("b")])._column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual((alias[Column("a")] < "foo".databaseValue)._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((alias[Column("a")] < "foo".databaseValue)._column(db, for: alias, acceptsBijection: true), nil) + + // SQLExpressionCollate + try XCTAssertEqual(Column("a").collating(.binary).sqlExpression._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(Column("a").collating(.binary).sqlExpression._column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual(alias[Column("a")].collating(.binary).sqlExpression._column(db, for: alias, acceptsBijection: false), "a") + try XCTAssertEqual(alias[Column("a")].collating(.binary).sqlExpression._column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual((alias[Column("a")] + "foo".databaseValue).collating(.binary).sqlExpression._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((alias[Column("a")] + "foo".databaseValue).collating(.binary).sqlExpression._column(db, for: alias, acceptsBijection: true), "a") + + // SQLExpressionContains + try XCTAssertEqual([1, 2, 3].contains(alias[Column("a")])._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual([1, 2, 3].contains(alias[Column("a")])._column(db, for: alias, acceptsBijection: true), nil) + + // SQLExpressionCount + try XCTAssertEqual(count(alias[Column("a")])._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(count(alias[Column("a")])._column(db, for: alias, acceptsBijection: true), nil) + + // SQLExpressionCountDistinct + try XCTAssertEqual(count(distinct: alias[Column("a")])._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(count(distinct: alias[Column("a")])._column(db, for: alias, acceptsBijection: true), nil) + + // SQLExpressionEqual + try XCTAssertEqual((alias[Column("a")] == "foo")._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((alias[Column("a")] == "foo")._column(db, for: alias, acceptsBijection: true), nil) + + // SQLExpressionFastPrimaryKey + try XCTAssertEqual(SQLExpressionFastPrimaryKey()._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(SQLExpressionFastPrimaryKey()._column(db, for: alias, acceptsBijection: true), nil) + + // SQLExpressionFunction + try XCTAssertEqual(length(alias[Column("a")])._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(length(alias[Column("a")])._column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual((alias[Column("a")] ?? "foo")._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((alias[Column("a")] ?? "foo")._column(db, for: alias, acceptsBijection: true), "a") + + // SQLExpressionIsEmpty + try XCTAssertEqual(SQLExpressionIsEmpty(alias[Column("a")])._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(SQLExpressionIsEmpty(alias[Column("a")])._column(db, for: alias, acceptsBijection: true), nil) + + // SQLExpressionLiteral + try XCTAssertEqual(SQLLiteral("\(alias[Column("a")]) * 2").sqlExpression._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(SQLLiteral("\(alias[Column("a")]) * 2").sqlExpression._column(db, for: alias, acceptsBijection: true), nil) + + // SQLExpressionNot + try XCTAssertEqual((!alias[Column("a")])._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((!alias[Column("a")])._column(db, for: alias, acceptsBijection: true), nil) + + // SQLExpressionQualifiedFastPrimaryKey + try XCTAssertEqual(alias[SQLExpressionFastPrimaryKey()]._column(db, for: alias, acceptsBijection: false), "id") + try XCTAssertEqual(alias[SQLExpressionFastPrimaryKey()]._column(db, for: alias, acceptsBijection: true), "id") + + // SQLExpressionTableMatch + try XCTAssertEqual(SQLExpressionTableMatch(alias: alias, pattern: alias[Column("a")])._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(SQLExpressionTableMatch(alias: alias, pattern: alias[Column("a")])._column(db, for: alias, acceptsBijection: true), nil) + + // SQLExpressionUnary + try XCTAssertEqual((-Column("a"))._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((-Column("a"))._column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual((-alias[Column("a")])._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((-alias[Column("a")])._column(db, for: alias, acceptsBijection: true), "a") + + // SQLQualifiedColumn + try XCTAssertEqual(alias[Column("a")]._column(db, for: alias, acceptsBijection: false), "a") + try XCTAssertEqual(alias[Column("a")]._column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual(TableAlias()[Column("a")]._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(TableAlias()[Column("a")]._column(db, for: alias, acceptsBijection: true), nil) + + // SQLRowValue + try XCTAssertEqual(SQLRowValue([1.databaseValue])._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(SQLRowValue([1.databaseValue])._column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual(SQLRowValue([alias[Column("a")]])._column(db, for: alias, acceptsBijection: false), "a") + try XCTAssertEqual(SQLRowValue([alias[Column("a")]])._column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual(SQLRowValue([-alias[Column("a")]])._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(SQLRowValue([-alias[Column("a")]])._column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual(SQLRowValue([1.databaseValue, 2.databaseValue])._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(SQLRowValue([1.databaseValue, 2.databaseValue])._column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual(SQLRowValue([alias[Column("a")], 2.databaseValue])._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(SQLRowValue([alias[Column("a")], 2.databaseValue])._column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual(SQLRowValue([1.databaseValue, alias[Column("a")]])._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(SQLRowValue([1.databaseValue, alias[Column("a")]])._column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual(SQLRowValue([alias[Column("a")], alias[Column("a")]])._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(SQLRowValue([alias[Column("a")], alias[Column("a")]])._column(db, for: alias, acceptsBijection: true), nil) + } + } + + func testIdentifyingColumns() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "t") { $0.autoIncrementedPrimaryKey("id") } + let alias = TableAlias(tableName: "t") + + // Column + try XCTAssertEqual(Column("a")._identifyingColums(db, for: alias), []) + + // DatabaseValue + try XCTAssertEqual("foo".databaseValue._identifyingColums(db, for: alias), []) + + // SQLExpressionAssociativeBinary + try XCTAssertEqual((alias[Column("a")] == 1 || alias[Column("b")] == 2)._identifyingColums(db, for: alias), []) + try XCTAssertEqual((alias[Column("a")] == 1 && alias[Column("b")] == 2)._identifyingColums(db, for: alias), ["a", "b"]) + try XCTAssertEqual((alias[Column("a")] == 1 && TableAlias()[Column("b")] == 2)._identifyingColums(db, for: alias), ["a"]) + + // SQLExpressionBetween + try XCTAssertEqual((1...3).contains(alias[Column("a")])._identifyingColums(db, for: alias), []) + + // SQLExpressionBinary + try XCTAssertEqual((alias[Column("a")] - 1)._identifyingColums(db, for: alias), []) + + // SQLExpressionCollate + try XCTAssertEqual((alias[Column("a")] == 1).collating(.binary).sqlExpression._identifyingColums(db, for: alias), ["a"]) + + // SQLExpressionContains + try XCTAssertEqual([1, 2, 3].contains(alias[Column("a")])._identifyingColums(db, for: alias), []) + + // SQLExpressionCount + try XCTAssertEqual(count(alias[Column("a")])._identifyingColums(db, for: alias), []) + + // SQLExpressionCountDistinct + try XCTAssertEqual(count(distinct: alias[Column("a")])._identifyingColums(db, for: alias), []) + + // SQLExpressionEqual + try XCTAssertEqual((alias[Column("a")] == nil)._identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual((alias[Column("a")] == 1)._identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual((1 == alias[Column("a")])._identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual((-alias[Column("a")] == 1)._identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual(((alias[Column("a")] * 2) == 1)._identifyingColums(db, for: alias), []) + try XCTAssertEqual(((alias[Column("a")] + 2) == 1)._identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual(((alias[Column("a")] - 2) == 1)._identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual((alias[SQLExpressionFastPrimaryKey()] == 1)._identifyingColums(db, for: alias), ["id"]) + try XCTAssertEqual((alias[Column("a")] == alias[Column("b")])._identifyingColums(db, for: alias), []) + try XCTAssertEqual((TableAlias()[Column("a")] == nil)._identifyingColums(db, for: alias), []) + try XCTAssertEqual((TableAlias()[Column("a")] == 1)._identifyingColums(db, for: alias), []) + try XCTAssertEqual((SQLRowValue([alias[SQLExpressionFastPrimaryKey()]]) == 1)._identifyingColums(db, for: alias), ["id"]) + + // SQLExpressionFastPrimaryKey + try XCTAssertEqual(SQLExpressionFastPrimaryKey()._identifyingColums(db, for: alias), []) + + // SQLExpressionFunction + try XCTAssertEqual(length(alias[Column("a")])._identifyingColums(db, for: alias), []) + + // SQLExpressionIsEmpty + try XCTAssertEqual(SQLExpressionIsEmpty(alias[Column("a")])._identifyingColums(db, for: alias), []) + + // SQLExpressionLiteral + // SQLExpressionNot + try XCTAssertEqual((!alias[Column("a")])._identifyingColums(db, for: alias), []) + + // SQLExpressionQualifiedFastPrimaryKey + try XCTAssertEqual(alias[SQLExpressionFastPrimaryKey()]._identifyingColums(db, for: alias), []) + + // SQLExpressionTableMatch + // SQLExpressionUnary + try XCTAssertEqual((-alias[Column("a")])._identifyingColums(db, for: alias), []) + + // SQLQualifiedColumn + try XCTAssertEqual(alias[Column("a")]._identifyingColums(db, for: alias), []) + + // SQLRowValue + try XCTAssertEqual(SQLRowValue([alias[SQLExpressionFastPrimaryKey()]])._identifyingColums(db, for: alias), []) + try XCTAssertEqual(SQLRowValue([alias[SQLExpressionFastPrimaryKey()] == 1])._identifyingColums(db, for: alias), ["id"]) + } + } + + func testIdentifyingRowIDs() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "t") { $0.autoIncrementedPrimaryKey("id") } + let alias = TableAlias(tableName: "t") + + // Column + // DatabaseValue + // SQLExpressionAssociativeBinary + try XCTAssertEqual((alias[Column("id")] == 1 || alias[Column("id")] == 3)._identifyingRowIDs(db, for: alias), [1, 3]) + try XCTAssertEqual((alias[Column("id")] == 1 && alias[Column("id")] == 3)._identifyingRowIDs(db, for: alias), []) + try XCTAssertEqual((alias[Column("id")] == 1 && alias[Column("id")] == 1)._identifyingRowIDs(db, for: alias), [1]) + + // SQLExpressionBetween + try XCTAssertEqual((0...Int.max).contains(TableAlias()[Column("id")])._identifyingRowIDs(db, for: alias), nil) + + // SQLExpressionBinary + // SQLExpressionCollate + // SQLExpressionContains + try XCTAssertEqual([1, 2, 3].contains(TableAlias()[Column("id")])._identifyingRowIDs(db, for: alias), nil) + try XCTAssertEqual([1, 2, 3].contains(alias[Column("id")])._identifyingRowIDs(db, for: alias), [1, 2, 3]) + try XCTAssertEqual([].contains(alias[Column("id")])._identifyingRowIDs(db, for: alias), []) + try XCTAssertEqual([1, 2, 3].contains(alias[Column("id")] + 1)._identifyingRowIDs(db, for: alias), nil) + + // SQLExpressionCount + // SQLExpressionCountDistinct + // SQLExpressionEqual + try XCTAssertEqual((TableAlias()[Column("id")] == 1)._identifyingRowIDs(db, for: alias), nil) + try XCTAssertEqual((alias[Column("id")] == 1)._identifyingRowIDs(db, for: alias), [1]) + try XCTAssertEqual((alias[Column("id")] == nil)._identifyingRowIDs(db, for: alias), []) + try XCTAssertEqual(((alias[Column("id")] + 1) == 2)._identifyingRowIDs(db, for: alias), nil) + + // SQLExpressionFastPrimaryKey + // SQLExpressionFunction + // SQLExpressionIsEmpty + // SQLExpressionLiteral + // SQLExpressionNot + // SQLExpressionQualifiedFastPrimaryKey + // SQLExpressionTableMatch + // SQLExpressionUnary + // SQLQualifiedColumn + // SQLRowValue + } + } + + func testIsConstantInRequest() { + // Column + XCTAssertFalse(Column("a")._isConstantInRequest) - XCTAssertFalse(Column("a").isConstantInRequest) + // DatabaseValue + XCTAssertTrue(1.databaseValue._isConstantInRequest) - XCTAssertFalse(Column("a")._qualifiedExpression(with: TableAlias()).isConstantInRequest) + // SQLExpressionAssociativeBinary + XCTAssertTrue([].joined(operator: .multiply)._isConstantInRequest) + XCTAssertTrue([1.databaseValue].joined(operator: .multiply)._isConstantInRequest) + XCTAssertFalse([Column("a")].joined(operator: .multiply)._isConstantInRequest) + XCTAssertTrue([1.databaseValue, 2.databaseValue].joined(operator: .multiply)._isConstantInRequest) + XCTAssertFalse([Column("a"), 2.databaseValue].joined(operator: .multiply)._isConstantInRequest) + XCTAssertFalse([1.databaseValue, Column("a")].joined(operator: .multiply)._isConstantInRequest) - XCTAssertTrue(SQLDateModifier.day(1).isConstantInRequest) + // SQLExpressionBetween + XCTAssertTrue((1...3).contains(1.databaseValue)._isConstantInRequest) + XCTAssertFalse((1...3).contains(Column("a"))._isConstantInRequest) - XCTAssertTrue((1...3).contains(1.databaseValue).isConstantInRequest) - XCTAssertFalse((1...3).contains(Column("a")).isConstantInRequest) + // SQLExpressionBinary + XCTAssertTrue((1.databaseValue - 2.databaseValue)._isConstantInRequest) + XCTAssertFalse((Column("a") - 2.databaseValue)._isConstantInRequest) + XCTAssertFalse((1.databaseValue - Column("a"))._isConstantInRequest) - XCTAssertTrue("foo".databaseValue.collating(.binary).sqlExpression.isConstantInRequest) - XCTAssertFalse(Column("a").collating(.binary).sqlExpression.isConstantInRequest) + // SQLExpressionCollate + XCTAssertTrue("foo".databaseValue.collating(.binary).sqlExpression._isConstantInRequest) + XCTAssertFalse(Column("a").collating(.binary).sqlExpression._isConstantInRequest) - XCTAssertFalse([1, 2, 3].contains(Column("a")).isConstantInRequest) + // SQLExpressionContains + XCTAssertFalse([1, 2, 3].contains(Column("a"))._isConstantInRequest) - XCTAssertTrue((1.databaseValue - 2.databaseValue).isConstantInRequest) - XCTAssertFalse((Column("a") - 2.databaseValue).isConstantInRequest) - XCTAssertFalse((1.databaseValue - Column("a")).isConstantInRequest) + // SQLExpressionCount + XCTAssertFalse(count(Column("a"))._isConstantInRequest) - XCTAssertTrue([1.databaseValue, 2.databaseValue].joined(operator: .multiply).isConstantInRequest) - XCTAssertFalse([Column("a"), 2.databaseValue].joined(operator: .multiply).isConstantInRequest) - XCTAssertFalse([1.databaseValue, Column("a")].joined(operator: .multiply).isConstantInRequest) + // SQLExpressionCountDistinct + XCTAssertFalse(count(distinct: Column("a"))._isConstantInRequest) - XCTAssertTrue((1.databaseValue == 2.databaseValue).isConstantInRequest) - XCTAssertFalse((Column("a") == 2.databaseValue).isConstantInRequest) - XCTAssertFalse((1.databaseValue == Column("a")).isConstantInRequest) + // SQLExpressionEqual + XCTAssertTrue((1.databaseValue == 2.databaseValue)._isConstantInRequest) + XCTAssertFalse((Column("a") == 2.databaseValue)._isConstantInRequest) + XCTAssertFalse((1.databaseValue == Column("a"))._isConstantInRequest) - XCTAssertFalse(_SQLExpressionFastPrimaryKey().isConstantInRequest) + // SQLExpressionFastPrimaryKey + XCTAssertFalse(SQLExpressionFastPrimaryKey()._isConstantInRequest) - XCTAssertFalse(_SQLExpressionFastPrimaryKey()._qualifiedExpression(with: TableAlias()).isConstantInRequest) + // SQLExpressionFunction + XCTAssertTrue(length("foo".databaseValue)._isConstantInRequest) + XCTAssertFalse(length(Column("a"))._isConstantInRequest) - XCTAssertTrue(length("foo".databaseValue).isConstantInRequest) - XCTAssertFalse(length(Column("a")).isConstantInRequest) + // SQLExpressionIsEmpty + XCTAssertTrue(SQLExpressionIsEmpty("foo".databaseValue)._isConstantInRequest) + XCTAssertFalse(SQLExpressionIsEmpty(Column("a"))._isConstantInRequest) + + // SQLExpressionLiteral + XCTAssertFalse(SQLLiteral("1").sqlExpression._isConstantInRequest) - XCTAssertTrue((!(true.databaseValue)).isConstantInRequest) - XCTAssertFalse((!Column("a")).isConstantInRequest) + // SQLExpressionNot + XCTAssertTrue((!(true.databaseValue))._isConstantInRequest) + XCTAssertFalse((!Column("a"))._isConstantInRequest) - XCTAssertTrue((-(1.databaseValue)).isConstantInRequest) - XCTAssertFalse((Column("a")).isConstantInRequest) + // SQLExpressionQualifiedFastPrimaryKey + XCTAssertFalse(SQLExpressionFastPrimaryKey()._qualifiedExpression(with: TableAlias())._isConstantInRequest) + + // SQLExpressionTableMatch + XCTAssertFalse(SQLExpressionTableMatch(alias: TableAlias(), pattern: "foo".databaseValue)._isConstantInRequest) + + // SQLExpressionUnary + XCTAssertTrue((-(1.databaseValue))._isConstantInRequest) + XCTAssertFalse((-Column("a"))._isConstantInRequest) + + // SQLQualifiedColumn + XCTAssertFalse(Column("a")._qualifiedExpression(with: TableAlias())._isConstantInRequest) + + // SQLRowValue + XCTAssertTrue(SQLRowValue([1.databaseValue])._isConstantInRequest) + XCTAssertFalse(SQLRowValue([Column("a")])._isConstantInRequest) + XCTAssertTrue(SQLRowValue([1.databaseValue, 2.databaseValue])._isConstantInRequest) + XCTAssertFalse(SQLRowValue([Column("a"), 2.databaseValue])._isConstantInRequest) + XCTAssertFalse(SQLRowValue([1.databaseValue, Column("a")])._isConstantInRequest) } } diff --git a/Tests/GRDBTests/SQLExpressionLiteralTests.swift b/Tests/GRDBTests/SQLExpressionLiteralTests.swift index db2b59e41..84e5035e8 100644 --- a/Tests/GRDBTests/SQLExpressionLiteralTests.swift +++ b/Tests/GRDBTests/SQLExpressionLiteralTests.swift @@ -8,7 +8,7 @@ class SQLExpressionLiteralTests: GRDBTestCase { try DatabaseQueue().inDatabase { db in let expression = Column("foo").collating(.nocase) == "'fooéı👨👨🏿🇫🇷🇨🇮'" && Column("baz") >= 1 let context = SQLGenerationContext(db) - let sql = try expression.expressionSQL(context, wrappedInParenthesis: true) + let sql = try expression._expressionSQL(context, wrappedInParenthesis: true) XCTAssertEqual(sql, "((\"foo\" = ? COLLATE NOCASE) AND (\"baz\" >= ?))") let values = context.arguments.values XCTAssertEqual(values.count, 2) @@ -21,7 +21,7 @@ class SQLExpressionLiteralTests: GRDBTestCase { try DatabaseQueue().inDatabase { db in let expression = Column("foo").collating(.nocase) == "'fooéı👨👨🏿🇫🇷🇨🇮'" && Column("baz") >= 1 let context = SQLGenerationContext(db, argumentsSink: .forRawSQL) - let sql = try expression.expressionSQL(context, wrappedInParenthesis: true) + let sql = try expression._expressionSQL(context, wrappedInParenthesis: true) XCTAssert(context.arguments.isEmpty) XCTAssertEqual(sql, "((\"foo\" = '''fooéı👨👨🏿🇫🇷🇨🇮''' COLLATE NOCASE) AND (\"baz\" >= 1))") } diff --git a/Tests/GRDBTests/SQLIdentifyingColumnsTests.swift b/Tests/GRDBTests/SQLIdentifyingColumnsTests.swift index d80a333d4..8d9a31651 100644 --- a/Tests/GRDBTests/SQLIdentifyingColumnsTests.swift +++ b/Tests/GRDBTests/SQLIdentifyingColumnsTests.swift @@ -10,21 +10,21 @@ class SQLIdentifyingColumnsTests: GRDBTestCase { let alias = TableAlias(tableName: "t") let otherAlias = TableAlias() - try XCTAssertEqual((alias[Column("a")] == 1).identifyingColums(db, for: alias), ["a"]) - try XCTAssertEqual((alias[Column("a")] === 1).identifyingColums(db, for: alias), ["a"]) - try XCTAssertEqual((alias[Column("a")] == nil).identifyingColums(db, for: alias), ["a"]) - try XCTAssertEqual((1 == alias[Column("a")]).identifyingColums(db, for: alias), ["a"]) - try XCTAssertEqual((alias[_SQLExpressionFastPrimaryKey()] == 1).identifyingColums(db, for: alias), ["id"]) - try XCTAssertEqual((alias[Column("a")] == 1 && alias[Column("a")] == 2).identifyingColums(db, for: alias), ["a"]) - try XCTAssertEqual((alias[Column("a")] == 1 && alias[Column("b")] == 1).identifyingColums(db, for: alias), ["a", "b"]) - try XCTAssertEqual((alias[Column("a")] == 1 && alias[Column("b")] > 1).identifyingColums(db, for: alias), ["a"]) - try XCTAssertEqual((otherAlias[Column("a")] == 1 && alias[Column("b")] == 1).identifyingColums(db, for: alias), ["b"]) + try XCTAssertEqual((alias[Column("a")] == 1)._identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual((alias[Column("a")] === 1)._identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual((alias[Column("a")] == nil)._identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual((1 == alias[Column("a")])._identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual((alias[SQLExpressionFastPrimaryKey()] == 1)._identifyingColums(db, for: alias), ["id"]) + try XCTAssertEqual((alias[Column("a")] == 1 && alias[Column("a")] == 2)._identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual((alias[Column("a")] == 1 && alias[Column("b")] == 1)._identifyingColums(db, for: alias), ["a", "b"]) + try XCTAssertEqual((alias[Column("a")] == 1 && alias[Column("b")] > 1)._identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual((otherAlias[Column("a")] == 1 && alias[Column("b")] == 1)._identifyingColums(db, for: alias), ["b"]) - try XCTAssertEqual((otherAlias[Column("a")]).identifyingColums(db, for: alias), []) - try XCTAssertEqual((alias[Column("a")] == 1 || alias[Column("a")] == 2).identifyingColums(db, for: alias), []) - try XCTAssertEqual((alias[Column("a")] == alias[Column("b")]).identifyingColums(db, for: alias), []) - try XCTAssertEqual((alias[Column("a")] > 1).identifyingColums(db, for: alias), []) - try XCTAssertEqual((alias[Column("a")] != 1).identifyingColums(db, for: alias), []) + try XCTAssertEqual((otherAlias[Column("a")])._identifyingColums(db, for: alias), []) + try XCTAssertEqual((alias[Column("a")] == 1 || alias[Column("a")] == 2)._identifyingColums(db, for: alias), []) + try XCTAssertEqual((alias[Column("a")] == alias[Column("b")])._identifyingColums(db, for: alias), []) + try XCTAssertEqual((alias[Column("a")] > 1)._identifyingColums(db, for: alias), []) + try XCTAssertEqual((alias[Column("a")] != 1)._identifyingColums(db, for: alias), []) } } }