From 90f2642ec6b452c128340ec27aa093025ee5fd4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 5 Jul 2020 15:07:52 +0200 Subject: [PATCH] Make good use of the visitor pattern --- GRDB.xcodeproj/project.pbxproj | 108 ++- GRDB/Core/Database+Schema.swift | 8 +- GRDB/Core/DatabaseValue.swift | 31 +- GRDB/Core/DatabaseValueConvertible.swift | 1 - GRDB/Core/FetchRequest.swift | 3 - GRDB/Core/SQLLiteral.swift | 84 +- GRDB/Core/SQLRequestProtocol.swift | 35 +- ...aseValueConvertible+RawRepresentable.swift | 1 + GRDB/Core/TransactionObserver.swift | 14 +- GRDB/Fixit/GRDB-5.0.swift | 4 +- GRDB/QueryInterface/FTS3+QueryInterface.swift | 4 +- GRDB/QueryInterface/FTS5+QueryInterface.swift | 2 +- .../Request/Association/Association.swift | 31 +- .../Association/AssociationAggregate.swift | 12 +- .../Association/BelongsToAssociation.swift | 6 +- .../Association/HasManyAssociation.swift | 6 +- .../HasManyThroughAssociation.swift | 4 +- .../Association/HasOneAssociation.swift | 6 +- .../HasOneThroughAssociation.swift | 4 +- .../Request/RequestProtocols.swift | 49 +- GRDB/QueryInterface/SQL/Column.swift | 31 +- .../SQL/SQLCollatedExpression.swift | 30 +- GRDB/QueryInterface/SQL/SQLCollection.swift | 59 +- .../SQL/SQLCollectionVisitor.swift | 5 + GRDB/QueryInterface/SQL/SQLExpressible.swift | 49 +- .../SQL/SQLExpression+QueryInterface.swift | 794 +++++++----------- GRDB/QueryInterface/SQL/SQLExpression.swift | 124 +-- .../SQL/SQLExpressionVisitor.swift | 33 + GRDB/QueryInterface/SQL/SQLFunctions.swift | 79 +- GRDB/QueryInterface/SQL/SQLOperators.swift | 254 ++---- GRDB/QueryInterface/SQL/SQLOrdering.swift | 75 +- .../SQL/SQLOrderingVisitor.swift | 6 + GRDB/QueryInterface/SQL/SQLQuery.swift | 10 +- GRDB/QueryInterface/SQL/SQLRelation.swift | 8 +- .../SQL/SQLSelectable+QueryInterface.swift | 97 +-- GRDB/QueryInterface/SQL/SQLSelectable.swift | 46 +- .../SQL/SQLSelectableVisitor.swift | 7 + ...QLSpecificExpressible+QueryInterface.swift | 10 +- .../SQLCollectionGenerator.swift | 26 + .../SQLExpressionGenerator.swift | 188 +++++ .../SQLGeneration/SQLGenerationContext.swift | 20 +- .../SQLGeneration/SQLOrderingGenerator.swift | 123 +++ .../SQLGeneration/SQLQueryGenerator.swift | 745 +++++++++++++--- .../SQLSelectableCountGenerator.swift | 130 +++ .../SQLSelectableResultColumnGenerator.swift | 129 +++ .../SQLInterpolation+QueryInterface.swift | 2 +- .../TableRecord+Association.swift | 8 +- GRDB/Record/TableRecord.swift | 2 +- GRDB/Utils/Utils.swift | 6 - .../ValueObservation/ValueReducer/Fetch.swift | 5 +- GRDB/ValueObservation/ValueReducer/Map.swift | 8 +- .../ValueReducer/RemoveDuplicates.swift | 4 +- .../ValueObservation/ValueReducer/Trace.swift | 2 - .../ValueReducer/ValueReducer.swift | 2 - GRDBCustom.xcodeproj/project.pbxproj | 80 +- TODO.md | 1 - Tests/GRDBTests/DatabaseRegionTests.swift | 13 +- .../MutablePersistableRecordDeleteTests.swift | 18 + .../QueryInterfaceExpressionsTests.swift | 16 +- .../QueryInterfaceExtensibilityTests.swift | 72 -- .../QueryInterfaceRequestTests.swift | 65 ++ .../SQLExpressionIsConstantTests.swift | 47 ++ .../SQLIdentifyingColumnsTests.swift | 30 + 63 files changed, 2391 insertions(+), 1481 deletions(-) create mode 100644 GRDB/QueryInterface/SQL/SQLCollectionVisitor.swift create mode 100644 GRDB/QueryInterface/SQL/SQLExpressionVisitor.swift create mode 100644 GRDB/QueryInterface/SQL/SQLOrderingVisitor.swift create mode 100644 GRDB/QueryInterface/SQL/SQLSelectableVisitor.swift create mode 100644 GRDB/QueryInterface/SQLGeneration/SQLCollectionGenerator.swift create mode 100644 GRDB/QueryInterface/SQLGeneration/SQLExpressionGenerator.swift create mode 100644 GRDB/QueryInterface/SQLGeneration/SQLOrderingGenerator.swift create mode 100644 GRDB/QueryInterface/SQLGeneration/SQLSelectableCountGenerator.swift create mode 100644 GRDB/QueryInterface/SQLGeneration/SQLSelectableResultColumnGenerator.swift create mode 100644 Tests/GRDBTests/SQLExpressionIsConstantTests.swift create mode 100644 Tests/GRDBTests/SQLIdentifyingColumnsTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index d7484d380..ac53d578e 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -856,6 +856,48 @@ 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 /* SQLOrderingVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE024B0E915007513FC /* SQLOrderingVisitor.swift */; }; + 56F34FE224B0E915007513FC /* SQLOrderingVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE024B0E915007513FC /* SQLOrderingVisitor.swift */; }; + 56F34FE324B0E915007513FC /* SQLOrderingVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE024B0E915007513FC /* SQLOrderingVisitor.swift */; }; + 56F34FE424B0E915007513FC /* SQLOrderingVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE024B0E915007513FC /* SQLOrderingVisitor.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 */; }; 56F409212465C8D400A7A152 /* SQLRequestProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F409202465C8D400A7A152 /* SQLRequestProtocol.swift */; }; @@ -1579,6 +1621,17 @@ 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 /* SQLOrderingVisitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLOrderingVisitor.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 = ""; }; 56F409202465C8D400A7A152 /* SQLRequestProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequestProtocol.swift; sourceTree = ""; }; 56FBFED82210731A00945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = ""; }; @@ -1838,7 +1891,6 @@ 56300B5C1C53C38F005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( - 5653EABF20944B1300F46237 /* Association */, 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */, 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */, 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, @@ -1847,9 +1899,12 @@ 563EF45221631E21007DAACD /* QueryInterfacePromiseTests.swift */, 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */, 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */, + 56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */, + 56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */, 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */, 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */, 5698AC7F1DA380A20056AF8C /* VirtualTableModuleTests.swift */, + 5653EABF20944B1300F46237 /* Association */, ); name = QueryInterface; sourceTree = ""; @@ -2011,8 +2066,13 @@ 5656A8162295AFD6001FF3FF /* SQLGeneration */ = { isa = PBXGroup; children = ( + 56F34FFE24B0FB69007513FC /* SQLCollectionGenerator.swift */, + 56F34FA324B06A3B007513FC /* SQLExpressionGenerator.swift */, 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */, + 56F34FE824B0EE9C007513FC /* SQLOrderingGenerator.swift */, 568D13182207213E00674B58 /* SQLQueryGenerator.swift */, + 56F34FD524B0E532007513FC /* SQLSelectableCountGenerator.swift */, + 56F34FD024B0DE44007513FC /* SQLSelectableResultColumnGenerator.swift */, ); path = SQLGeneration; sourceTree = ""; @@ -2025,17 +2085,21 @@ 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 /* SQLOrderingVisitor.swift */, 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */, 56D91AA12205E03700770D8D /* SQLRelation.swift */, 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */, 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */, + 56F34FC824B0DD6A007513FC /* SQLSelectableVisitor.swift */, 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */, ); path = SQL; @@ -2843,10 +2907,12 @@ 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 */, @@ -2869,6 +2935,7 @@ 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 */, @@ -2919,6 +2986,7 @@ 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 */, @@ -2938,6 +3006,7 @@ 56FBFEDB2210731A00945324 /* SQLRequest.swift in Sources */, 56F5ABD91D814330001F60CB /* Data.swift in Sources */, 565490D41D5AE252005622CB /* (null) in Sources */, + 56F34FA624B06A3B007513FC /* SQLExpressionGenerator.swift in Sources */, 566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, 56F409232465C8D500A7A152 /* SQLRequestProtocol.swift in Sources */, 565490B61D5AE236005622CB /* Configuration.swift in Sources */, @@ -2967,8 +3036,12 @@ 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 /* SQLOrderingVisitor.swift in Sources */, + 56F34FF624B0F83E007513FC /* SQLCollectionVisitor.swift in Sources */, 5653EB0820944C7C00F46237 /* SQLForeignKeyRequest.swift in Sources */, 565490BE1D5AE236005622CB /* DatabaseValue.swift in Sources */, ); @@ -2998,6 +3071,8 @@ 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 */, @@ -3027,6 +3102,7 @@ 5664759D1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 568D13202207213E00674B58 /* SQLQueryGenerator.swift in Sources */, 5674048A1CEF84C8003ED5CC /* RowAdapter.swift in Sources */, + 56F34FE224B0E915007513FC /* SQLOrderingVisitor.swift in Sources */, 563EF416215F87EB007DAACD /* OrderedDictionary.swift in Sources */, 563363C51C942C37000BE133 /* DatabaseWriter.swift in Sources */, 5698AD1B1DAAD17D0056AF8C /* FTS5Tokenizer.swift in Sources */, @@ -3034,6 +3110,7 @@ 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 */, @@ -3042,6 +3119,7 @@ 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 */, @@ -3057,6 +3135,7 @@ 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 */, @@ -3069,6 +3148,8 @@ 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 */, @@ -3119,6 +3200,7 @@ 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 */, ); @@ -3312,7 +3394,9 @@ 5676FBA722F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 5623931C1DECC02000A6B01F /* RowFetchTests.swift in Sources */, 5653EAD720944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */, + 56F34FBB24B094B6007513FC /* SQLExpressionIsConstantTests.swift in Sources */, 569BBA28228DE51800478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, + 56F34FC324B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */, 562393641DEE06D300A6B01F /* CursorTests.swift in Sources */, 5657AB5A1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, 560432A1228F00C2009D3FE2 /* OrderedDictionaryTests.swift in Sources */, @@ -3535,7 +3619,9 @@ 56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, 5676FBA622F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */, + 56F34FBA24B094B6007513FC /* SQLExpressionIsConstantTests.swift in Sources */, 56D496951D81317B008276D7 /* MutablePersistableRecordTests.swift in Sources */, + 56F34FC224B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */, 569BBA27228DE51800478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, 5653EAD620944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */, 5698AC801DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, @@ -3577,6 +3663,8 @@ 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 */, @@ -3606,6 +3694,7 @@ AAA4DC93230F1E0600C74B15 /* SQLCollection.swift in Sources */, AAA4DC94230F1E0600C74B15 /* SQLQueryGenerator.swift in Sources */, AAA4DC95230F1E0600C74B15 /* RowAdapter.swift in Sources */, + 56F34FE424B0E915007513FC /* SQLOrderingVisitor.swift in Sources */, AAA4DC96230F1E0600C74B15 /* OrderedDictionary.swift in Sources */, AAA4DC97230F1E0600C74B15 /* DatabaseWriter.swift in Sources */, AAA4DC98230F1E0600C74B15 /* FTS5Tokenizer.swift in Sources */, @@ -3613,6 +3702,7 @@ 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 */, @@ -3621,6 +3711,7 @@ 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 */, @@ -3636,6 +3727,7 @@ 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 */, @@ -3648,6 +3740,8 @@ 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 */, @@ -3698,6 +3792,7 @@ 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 */, ); @@ -3891,7 +3986,9 @@ AAA4DDAB230F262000C74B15 /* ValueObservationRegionRecordingTests.swift in Sources */, AAA4DDAC230F262000C74B15 /* RowFetchTests.swift in Sources */, AAA4DDAD230F262000C74B15 /* AssociationChainRowScopesTests.swift in Sources */, + 56F34FBC24B094B6007513FC /* SQLExpressionIsConstantTests.swift in Sources */, AAA4DDAE230F262000C74B15 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, + 56F34FC424B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */, AAA4DDAF230F262000C74B15 /* CursorTests.swift in Sources */, AAA4DDB1230F262000C74B15 /* FoundationNSStringTests.swift in Sources */, AAA4DDB2230F262000C74B15 /* OrderedDictionaryTests.swift in Sources */, @@ -3933,6 +4030,8 @@ 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 */, @@ -3962,6 +4061,7 @@ 5605F1591C672E4000235C62 /* CGFloat.swift in Sources */, 5674A7031F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, 5605F1631C672E4000235C62 /* Date.swift in Sources */, + 56F34FE124B0E915007513FC /* SQLOrderingVisitor.swift in Sources */, 5605F1711C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */, 566475CC1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, @@ -3969,6 +4069,7 @@ 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 */, @@ -3977,6 +4078,7 @@ 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 */, @@ -3992,6 +4094,7 @@ 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 */, @@ -4004,6 +4107,8 @@ 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 */, @@ -4054,6 +4159,7 @@ 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/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 79b283e5b..175610bec 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -151,12 +151,18 @@ extension Database { return primaryKey } + /// Returns whether the column identifies the rowid column + func columnIsRowID(_ column: String, of tableName: String) throws -> Bool { + let pk = try primaryKey(tableName) + return pk.rowIDColumn == column || (pk.tableHasRowID && column.uppercased() == "ROWID") + } + /// Returns whether the table has a rowid column. private func tableHasRowID(_ tableName: String) throws -> Bool { // Not need to cache the result, because this information feeds // `PrimaryKeyInfo`, which is cached. do { - _ = try makeSelectStatement(sql: "SELECT rowID FROM \(tableName.quotedDatabaseIdentifier)") + _ = try makeSelectStatement(sql: "SELECT rowid FROM \(tableName.quotedDatabaseIdentifier)") return true } catch DatabaseError.SQLITE_ERROR { return false diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index f83e50453..d23325b5d 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -213,7 +213,6 @@ extension DatabaseValue { // SQLExpressible extension DatabaseValue { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public var sqlExpression: SQLExpression { self @@ -222,24 +221,8 @@ extension DatabaseValue { // SQLExpression extension DatabaseValue { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :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])! - } - } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// :nodoc: - public var negated: SQLExpression { + public var _negated: SQLExpression { switch storage { case .null: // SELECT NOT NULL -- NULL @@ -253,7 +236,7 @@ extension DatabaseValue { // // SELECT NOT '1' -- 0 (because '1' is turned into the integer 1, which is negated into 0) // SELECT NOT '0' -- 1 (because '0' is turned into the integer 0, which is negated into 1) - return SQLExpressionNot(self) + return _SQLExpressionNot(self) case .blob: // We can't assume all blobs are true, and return false: // @@ -261,15 +244,19 @@ extension DatabaseValue { // then into integer 1, which is negated into 0) // SELECT NOT X'30' -- 1 (because X'30' is turned into the string '0', // then into integer 0, which is negated into 1) - return SQLExpressionNot(self) + return _SQLExpressionNot(self) } } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { self } + + /// :nodoc: + public func _accept(_ visitor: inout Visitor) throws { + try visitor.visit(self) + } } // CustomStringConvertible diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 32e94ab27..a16caba3c 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -23,7 +23,6 @@ public protocol DatabaseValueConvertible: SQLExpressible { } extension DatabaseValueConvertible { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public var sqlExpression: SQLExpression { databaseValue diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index c1cc14648..4245d5f59 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -180,7 +180,6 @@ public struct AdaptedFetchRequest: FetchRequest { try base.requestSQL(context, forSingleResult: singleResult) } - /// :nodoc: public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { var request = try base.makePreparedRequest(db, forSingleResult: singleResult) if let baseAdapter = request.adapter { @@ -191,12 +190,10 @@ public struct AdaptedFetchRequest: FetchRequest { return request } - /// :nodoc: public func fetchCount(_ db: Database) throws -> Int { try base.fetchCount(db) } - /// :nodoc: public func databaseRegion(_ db: Database) throws -> DatabaseRegion { try base.databaseRegion(db) } diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index 97f923c9f..e0668b6ed 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -49,11 +49,11 @@ public struct SQLLiteral { // Subqueries don't need table alias return self case let .expression(expression): - return .expression(expression.qualifiedExpression(with: alias)) + return .expression(expression._qualifiedExpression(with: alias)) case let .selectable(selectable): - return .selectable(selectable.qualifiedSelectable(with: alias)) + return .selectable(selectable._qualifiedSelectable(with: alias)) case let .orderingTerm(orderingTerm): - return .orderingTerm(orderingTerm.qualifiedOrdering(with: alias)) + return .orderingTerm(orderingTerm._qualifiedOrdering(with: alias)) } } } @@ -243,57 +243,43 @@ extension SQLLiteral: ExpressibleByStringInterpolation { /// /// SQLExpressionLiteral(sql: "? + ?", arguments: [1, 2]) /// SQLExpressionLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]) -private struct _SQLExpressionLiteral: SQLExpression { - private let sqlLiteral: SQLLiteral +/// +/// :nodoc: +public struct _SQLExpressionLiteral: SQLExpression { + let sqlLiteral: SQLLiteral // Prefer SQLLiteral.sqlExpression - init(sqlLiteral: SQLLiteral) { + fileprivate init(sqlLiteral: SQLLiteral) { self.sqlLiteral = sqlLiteral } - func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - if wrappedInParenthesis { - return try "(\(expressionSQL(context, wrappedInParenthesis: false)))" - } - return try sqlLiteral.sql(context) + /// :nodoc: + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + sqlLiteral.qualified(with: alias).sqlExpression } - func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - sqlLiteral.qualified(with: alias).sqlExpression + /// :nodoc: + public func _accept(_ visitor: inout Visitor) throws { + try visitor.visit(self) } } // MARK: - _SQLSelectionLiteral -private struct _SQLSelectionLiteral: SQLSelectable { - private let sqlLiteral: SQLLiteral +/// :nodoc: +public struct _SQLSelectionLiteral: SQLSelectable { + let sqlLiteral: SQLLiteral // Prefer SQLLiteral.sqlSelectable fileprivate init(sqlLiteral: SQLLiteral) { self.sqlLiteral = sqlLiteral } - func resultColumnSQL(_ context: SQLGenerationContext) throws -> String { - try sqlLiteral.sql(context) - } + /// :nodoc: + public 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 count(distinct: Bool) -> SQLCount? { - fatalError(""" - Selection literals can't be counted. \ - To resolve this error, select one or several literal expressions instead. \ - See SQLLiteral.sqlExpression. - """) - } - - func columnCount(_ db: Database) throws -> Int { + /// :nodoc: + public 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. \ @@ -301,33 +287,43 @@ private struct _SQLSelectionLiteral: SQLSelectable { """) } - func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { + /// :nodoc: + public func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { sqlLiteral.qualified(with: alias).sqlSelectable } + + /// :nodoc: + public func _accept(_ visitor: inout Visitor) throws { + try visitor.visit(self) + } } // MARK: - _SQLOrderingLiteral -private struct _SQLOrderingLiteral: SQLOrderingTerm { - private let sqlLiteral: SQLLiteral +/// :nodoc: +public struct _SQLOrderingLiteral: SQLOrderingTerm { + let sqlLiteral: SQLLiteral // Prefer SQLLiteral.sqlOrderingTerm fileprivate init(sqlLiteral: SQLLiteral) { self.sqlLiteral = sqlLiteral } - var reversed: SQLOrderingTerm { + /// :nodoc: + public var _reversed: SQLOrderingTerm { fatalError(""" Ordering literals can't be reversed. \ To resolve this error, order by expression literals instead. """) } - func orderingTermSQL(_ context: SQLGenerationContext) throws -> String { - try sqlLiteral.sql(context) - } - - func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { + /// :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/SQLRequestProtocol.swift b/GRDB/Core/SQLRequestProtocol.swift index edaa9d290..e8876e417 100644 --- a/GRDB/Core/SQLRequestProtocol.swift +++ b/GRDB/Core/SQLRequestProtocol.swift @@ -1,5 +1,8 @@ -/// The protocol that can generate SQL requests and subqueries. -public protocol SQLRequestProtocol: SQLExpression, SQLCollection { +/// Implementation details of SQLRequestProtocol. +/// +/// :nodoc: +public protocol _SQLRequestProtocol { + // TODO: rename to _requestSQL when FetchRequest is a closed protocol. /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Returns the request SQL. @@ -12,35 +15,33 @@ public protocol SQLRequestProtocol: SQLExpression, SQLCollection { func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String } +/// The protocol that can generate SQL requests and subqueries. +public protocol SQLRequestProtocol: _SQLRequestProtocol, SQLExpression, SQLCollection { } + // MARK: - SQLExpression extension SQLRequestProtocol { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - let sql = try requestSQL(context, forSingleResult: false) - return "(\(sql))" + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + self } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - self + public func _accept(_ visitor: inout Visitor) throws { + try visitor.visit(self) } } // MARK: - SQLCollection extension SQLRequestProtocol { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func collectionSQL(_ context: SQLGenerationContext) throws -> String { - try requestSQL(context, forSingleResult: false) - } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// :nodoc: - public func qualifiedCollection(with alias: TableAlias) -> SQLCollection { + public func _qualifiedCollection(with alias: TableAlias) -> SQLCollection { self } + + /// :nodoc: + public func _accept(_ visitor: inout Visitor) throws { + try visitor.visit(self) + } } diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+RawRepresentable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+RawRepresentable.swift index 77170fa3c..2d61c9fd4 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+RawRepresentable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+RawRepresentable.swift @@ -11,6 +11,7 @@ /// // ... then the RawRepresentable type can freely adopt SQLExpressible: /// extension Color : SQLExpressible { /* empty */ } extension SQLExpressible where Self: RawRepresentable, Self.RawValue: SQLExpressible { + /// Returns the raw value as an SQL expression. public var sqlExpression: SQLExpression { rawValue.sqlExpression } diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index a60bda7a1..96a9d47dd 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -1049,7 +1049,7 @@ public struct DatabasePreUpdateEvent { public var tableName: String { impl.tableName } /// The number of columns in the row that is being inserted, updated, or deleted. - public var count: Int { Int(impl.columnsCount) } + public var count: Int { Int(impl.columnCount) } /// The triggering depth of the row update /// Returns: @@ -1174,7 +1174,7 @@ private protocol DatabasePreUpdateEventImpl { var databaseName: String { get } var tableName: String { get } - var columnsCount: CInt { get } + var columnCount: CInt { get } var depth: CInt { get } var initialDatabaseValues: [DatabaseValue]? { get } var finalDatabaseValues: [DatabaseValue]? { get } @@ -1199,7 +1199,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { var databaseName: String { String(cString: databaseNameCString!) } var tableName: String { String(cString: tableNameCString!) } - var columnsCount: CInt { sqlite3_preupdate_count(connection) } + var columnCount: CInt { sqlite3_preupdate_count(connection) } var depth: CInt { sqlite3_preupdate_depth(connection) } var initialDatabaseValues: [DatabaseValue]? { guard kind == .update || kind == .delete else { return nil } @@ -1212,7 +1212,6 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { } func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { - let columnCount = columnsCount precondition(index >= 0 && index < Int(columnCount), "row index out of range") return getValue( connection, @@ -1223,7 +1222,6 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { } func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { - let columnCount = columnsCount precondition(index >= 0 && index < Int(columnCount), "row index out of range") return getValue( connection, @@ -1241,7 +1239,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { impl: CopiedDatabasePreUpdateEventImpl( databaseName: databaseName, tableName: tableName, - columnsCount: columnsCount, + columnCount: columnCount, depth: depth, initialDatabaseValues: initialDatabaseValues, finalDatabaseValues: finalDatabaseValues)) @@ -1252,7 +1250,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt) -> [DatabaseValue]? { - let columnCount = sqlite3_preupdate_count(connection) + let columnCount = self.columnCount guard columnCount > 0 else { return nil } var columnValues = [DatabaseValue]() @@ -1300,7 +1298,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { private struct CopiedDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl { let databaseName: String let tableName: String - let columnsCount: CInt + let columnCount: CInt let depth: CInt let initialDatabaseValues: [DatabaseValue]? let finalDatabaseValues: [DatabaseValue]? diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift index caffee00c..9c69272fe 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -180,10 +180,10 @@ public struct SQLExpressionLiteral: SQLExpression { public init(literal sqlLiteral: SQLLiteral) { preconditionFailure() } - public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { preconditionFailure() } - public func qualifiedExpression(with alias: TableAlias) -> SQLExpression + public func _accept(_ visitor: inout Visitor) { preconditionFailure() } } diff --git a/GRDB/QueryInterface/FTS3+QueryInterface.swift b/GRDB/QueryInterface/FTS3+QueryInterface.swift index 7e87699a6..8974ce7c0 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 = TableMatchExpression(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 000b536dd..6e66e3806 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 = TableMatchExpression(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/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index 68cc56433..8f1e682c0 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -1,11 +1,18 @@ import Foundation -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// Implementation details of Association. /// +/// :nodoc: +public protocol _Association { + init(sqlAssociation: SQLAssociation) + var _sqlAssociation: SQLAssociation { get } +} + /// The base protocol for all associations that define a connection between two /// record types. -public protocol Association: DerivableRequest { - // OriginRowDecoder and RowDecoder provide type safety: +public protocol Association: _Association, DerivableRequest { + // OriginRowDecoder and RowDecoder inherited from DerivableRequest provide + // type safety: // // Book.including(required: Book.author) // compiles // Fruit.including(required: Book.author) // does not compile @@ -20,9 +27,6 @@ public protocol Association: DerivableRequest { /// } associatedtype OriginRowDecoder: TableRecord - /// :nodoc: - var sqlAssociation: SQLAssociation { get } - /// Creates an association with the given key. /// /// This new key impacts how rows fetched from the resulting association @@ -38,9 +42,6 @@ public protocol Association: DerivableRequest { /// let team: Team = row["custom"] /// } func forKey(_ key: String) -> Self - - /// :nodoc: - init(sqlAssociation: SQLAssociation) } extension Association { @@ -72,7 +73,7 @@ extension Association { extension Association { private func mapDestinationRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self { - .init(sqlAssociation: sqlAssociation.map(\.destination.relation, transform)) + .init(sqlAssociation: _sqlAssociation.map(\.destination.relation, transform)) } } @@ -102,7 +103,7 @@ extension Association { /// for row in Row.fetchAll(db, request) { /// let team: Team = row["custom"] /// } - var key: SQLAssociationKey { sqlAssociation.destination.key } + var key: SQLAssociationKey { _sqlAssociation.destination.key } /// Creates an association which selects *selection*. /// @@ -296,28 +297,24 @@ extension Association { // MARK: - AssociationToOne -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// /// The base protocol for all associations that define a one-to-one connection. public protocol AssociationToOne: Association { } extension AssociationToOne { public func forKey(_ key: String) -> Self { let associationKey = SQLAssociationKey.fixedSingular(key) - return .init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey)) + return .init(sqlAssociation: _sqlAssociation.forDestinationKey(associationKey)) } } // MARK: - AssociationToMany -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// /// The base protocol for all associations that define a one-to-many connection. public protocol AssociationToMany: Association { } extension AssociationToMany { public func forKey(_ key: String) -> Self { let associationKey = SQLAssociationKey.fixedPlural(key) - return .init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey)) + return .init(sqlAssociation: _sqlAssociation.forDestinationKey(associationKey)) } } diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index 6df9793b6..41194075e 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(FastPrimaryKeyExpression()) + 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(FastPrimaryKeyExpression())) + 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/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift index 3cf1df3ea..4c013cff8 100644 --- a/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift @@ -66,11 +66,11 @@ public struct BelongsToAssociation: public typealias RowDecoder = Destination /// :nodoc: - public var sqlAssociation: SQLAssociation + public var _sqlAssociation: SQLAssociation /// :nodoc: public init(sqlAssociation: SQLAssociation) { - self.sqlAssociation = sqlAssociation + self._sqlAssociation = sqlAssociation } init( @@ -93,7 +93,7 @@ public struct HasManyAssociation: associationKey = .inflected(Destination.databaseTableName) } - sqlAssociation = SQLAssociation( + _sqlAssociation = SQLAssociation( key: associationKey, condition: condition, relation: Destination.relationForAll, diff --git a/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift b/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift index 8b1aec3f5..6881e6255 100644 --- a/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift @@ -49,10 +49,10 @@ public struct HasManyThroughAssociation: public typealias RowDecoder = Destination /// :nodoc: - public var sqlAssociation: SQLAssociation + public var _sqlAssociation: SQLAssociation /// :nodoc: public init(sqlAssociation: SQLAssociation) { - self.sqlAssociation = sqlAssociation + self._sqlAssociation = sqlAssociation } init( @@ -95,7 +95,7 @@ public struct HasOneAssociation: associationKey = .inflected(Destination.databaseTableName) } - sqlAssociation = SQLAssociation( + _sqlAssociation = SQLAssociation( key: associationKey, condition: condition, relation: Destination.relationForAll, diff --git a/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift b/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift index 47a1b3dfe..940cc413b 100644 --- a/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift @@ -29,10 +29,10 @@ public struct HasOneThroughAssociation [SQLSelectable]) -> Self } -/// :nodoc: extension SelectionRequest { /// Creates a request which selects *selection*. /// @@ -135,11 +130,7 @@ extension SelectionRequest { // MARK: - FilteredRequest -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// /// The protocol for all requests that can be filtered. -/// -/// :nodoc: public protocol FilteredRequest { /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. @@ -150,7 +141,6 @@ public protocol FilteredRequest { func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self } -/// :nodoc: extension FilteredRequest { /// Creates a request with the provided *predicate* added to the /// eventual set of already applied predicates. @@ -203,11 +193,7 @@ extension FilteredRequest { // MARK: - TableRequest { -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// /// The protocol for all requests that feed from a database table -/// -/// :nodoc: public protocol TableRequest { /// The name of the database table var databaseTableName: String { get } @@ -232,7 +218,6 @@ public protocol TableRequest { func aliased(_ alias: TableAlias) -> Self } -/// :nodoc: extension TableRequest where Self: FilteredRequest { /// Creates a request with the provided primary key *predicate*. @@ -313,7 +298,6 @@ extension TableRequest where Self: FilteredRequest { } } -/// :nodoc: extension TableRequest where Self: OrderedRequest { /// Creates a request ordered by primary key. public func orderByPrimaryKey() -> Self { @@ -324,7 +308,6 @@ extension TableRequest where Self: OrderedRequest { } } -/// :nodoc: extension TableRequest where Self: AggregatingRequest { /// Creates a request grouped by primary key. public func groupByPrimaryKey() -> Self { @@ -347,11 +330,7 @@ extension TableRequest where Self: AggregatingRequest { // MARK: - AggregatingRequest -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// /// The protocol for all requests that can aggregate. -/// -/// :nodoc: public protocol AggregatingRequest { /// Creates a request grouped according to *expressions promise*. func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> Self @@ -361,7 +340,6 @@ public protocol AggregatingRequest { func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self } -/// :nodoc: extension AggregatingRequest { /// Creates a request grouped according to *expressions*. public func group(_ expressions: [SQLExpressible]) -> Self { @@ -406,11 +384,7 @@ extension AggregatingRequest { // MARK: - OrderedRequest -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// /// The protocol for all requests that can be ordered. -/// -/// :nodoc: public protocol OrderedRequest { /// Creates a request with the provided *orderings promise*. /// @@ -448,7 +422,6 @@ public protocol OrderedRequest { func unordered() -> Self } -/// :nodoc: extension OrderedRequest { /// Creates a request with the provided *orderings*. /// @@ -520,9 +493,7 @@ extension OrderedRequest { // MARK: - JoinableRequest -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// -/// Type-unsafe support for the JoinableRequest protocol. +/// Implementation details of the JoinableRequest protocol. /// /// :nodoc: public protocol _JoinableRequest { @@ -550,11 +521,7 @@ public protocol _JoinableRequest { func _joining(required association: SQLAssociation) -> Self } -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// /// The protocol for all requests that can be associated. -/// -/// :nodoc: public protocol JoinableRequest: _JoinableRequest { /// The record type that can be associated to. /// @@ -574,43 +541,39 @@ public protocol JoinableRequest: _JoinableRequest { extension JoinableRequest { /// Creates a request that prefetches an association. public func including(all association: A) -> Self where A.OriginRowDecoder == RowDecoder { - _including(all: association.sqlAssociation) + _including(all: association._sqlAssociation) } /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned request does not /// require that the associated database table contains a matching row. public func including(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder { - _including(optional: association.sqlAssociation) + _including(optional: association._sqlAssociation) } /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned request requires /// that the associated database table contains a matching row. public func including(required association: A) -> Self where A.OriginRowDecoder == RowDecoder { - _including(required: association.sqlAssociation) + _including(required: association._sqlAssociation) } /// Creates a request that joins an association. The columns of the /// associated record are not selected. The returned request does not /// require that the associated database table contains a matching row. public func joining(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder { - _joining(optional: association.sqlAssociation) + _joining(optional: association._sqlAssociation) } /// Creates a request that joins an association. The columns of the /// associated record are not selected. The returned request requires /// that the associated database table contains a matching row. public func joining(required association: A) -> Self where A.OriginRowDecoder == RowDecoder { - _joining(required: association.sqlAssociation) + _joining(required: association._sqlAssociation) } } // MARK: - DerivableRequest -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// /// The base protocol for all requests that can be refined. -/// -/// :nodoc: public protocol DerivableRequest: FilteredRequest, JoinableRequest, OrderedRequest, SelectionRequest, TableRequest { } diff --git a/GRDB/QueryInterface/SQL/Column.swift b/GRDB/QueryInterface/SQL/Column.swift index d3872461f..d2282635f 100644 --- a/GRDB/QueryInterface/SQL/Column.swift +++ b/GRDB/QueryInterface/SQL/Column.swift @@ -25,16 +25,14 @@ public protocol ColumnExpression: SQLExpression { } extension ColumnExpression { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) -> String { - name.quotedDatabaseIdentifier + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + _SQLQualifiedColumn(name, alias: alias) } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - QualifiedColumn(name, alias: alias) + public func _accept(_ visitor: inout Visitor) throws { + try visitor.visit(self) } } @@ -63,8 +61,10 @@ public struct Column: ColumnExpression { } /// A qualified column in the database, as in `SELECT t.a FROM t` -struct QualifiedColumn: ColumnExpression { - var name: String +/// +/// :nodoc: +public struct _SQLQualifiedColumn: ColumnExpression { + public var name: String let alias: TableAlias /// Creates a column given its name. @@ -73,17 +73,16 @@ struct QualifiedColumn: ColumnExpression { self.alias = alias } - func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) -> String { - if let qualifier = context.qualifier(for: alias) { - return qualifier.quotedDatabaseIdentifier + "." + name.quotedDatabaseIdentifier - } - return name.quotedDatabaseIdentifier - } - - func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + /// :nodoc: + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { // Never requalify self } + + /// :nodoc: + public func _accept(_ visitor: inout Visitor) throws { + try visitor.visit(self) + } } /// Support for column enums: diff --git a/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift b/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift index 5af8e7122..add8b2689 100644 --- a/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift @@ -1,14 +1,12 @@ /// SQLCollatedExpression taints an expression so that every derived expression /// is eventually evaluated using an SQLite collation. /// -/// You create one by calling the SQLSpecificExpressible.collating() method. +/// You create one by calling the `collating()` method: /// -/// let email: SQLCollatedExpression = Column("email").collating(.nocase) +/// let email = Column("email").collating(.nocase) /// /// // SELECT * FROM player WHERE email = 'arthur@example.com' COLLATE NOCASE /// Player.filter(email == "arthur@example.com") -/// -/// :nodoc: public struct SQLCollatedExpression { /// The tainted expression public let expression: SQLExpression @@ -25,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() @@ -37,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 @@ -50,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() @@ -62,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) } #endif @@ -72,28 +70,24 @@ public struct SQLCollatedExpression { } var sqlExpression: SQLExpression { - SQLExpressionCollate(expression, collationName: collationName) + _SQLExpressionCollate(expression, collationName: collationName) } } /// :nodoc: extension SQLCollatedExpression: SQLOrderingTerm { - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public var reversed: SQLOrderingTerm { + public var _reversed: SQLOrderingTerm { desc } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func orderingTermSQL(_ context: SQLGenerationContext) throws -> String { - try sqlExpression.orderingTermSQL(context) + public func _qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { + SQLCollatedExpression(expression._qualifiedExpression(with: alias), collationName: collationName) } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { - SQLCollatedExpression(expression.qualifiedExpression(with: alias), collationName: collationName) + public func _accept(_ visitor: inout Visitor) throws { + try visitor.visit(self) } } diff --git a/GRDB/QueryInterface/SQL/SQLCollection.swift b/GRDB/QueryInterface/SQL/SQLCollection.swift index 41e924d4b..0e1cff021 100644 --- a/GRDB/QueryInterface/SQL/SQLCollection.swift +++ b/GRDB/QueryInterface/SQL/SQLCollection.swift @@ -1,24 +1,21 @@ // MARK: - SQLCollection -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// -/// SQLCollection is the protocol for types that can be checked for inclusion. +/// Implementation details of SQLCollection. /// /// :nodoc: -public protocol SQLCollection { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// Returns an SQL string that represents the collection. - func collectionSQL(_ context: SQLGenerationContext) throws -> String +public protocol _SQLCollection { + /// Returns a qualified collection + func _qualifiedCollection(with alias: TableAlias) -> SQLCollection - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// + /// Accepts a visitor + func _accept(_ visitor: inout Visitor) throws +} + +/// SQLCollection is the protocol for types that can be checked for inclusion. +public protocol SQLCollection: _SQLCollection { /// Returns an expression that check whether the collection contains /// the expression. func contains(_ value: SQLExpressible) -> SQLExpression - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - func qualifiedCollection(with alias: TableAlias) -> SQLCollection } @@ -26,30 +23,24 @@ public protocol SQLCollection { /// :nodoc: extension SQLCollection { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// Returns a SQLExpressionContains which applies the `IN` SQL operator. + /// Returns an expression which applies the `IN` SQL operator. public func contains(_ value: SQLExpressible) -> SQLExpression { - SQLExpressionContains(value, self) + _SQLExpressionContains(value, self) } } -// MARK: - SQLExpressionsArray +// MARK: - _SQLExpressionsArray -/// SQLExpressionsArray wraps an array of expressions +/// _SQLExpressionsArray wraps an array of expressions /// -/// SQLExpressionsArray([1, 2, 3]) -struct SQLExpressionsArray: SQLCollection { +/// _SQLExpressionsArray([1, 2, 3]) +/// +/// :nodoc: +public struct _SQLExpressionsArray: SQLCollection { let expressions: [SQLExpression] - func collectionSQL(_ context: SQLGenerationContext) throws -> String { - try expressions - .map { try $0.expressionSQL(context, wrappedInParenthesis: false) } - .joined(separator: ", ") - } - - func contains(_ value: SQLExpressible) -> SQLExpression { + public func contains(_ value: SQLExpressible) -> SQLExpression { guard let expression = expressions.first else { // [].contains(Column("name")) => 0 return false.databaseValue @@ -59,10 +50,16 @@ struct SQLExpressionsArray: SQLCollection { return value == expression } // ["foo", "bar"].contains(Column("name")) => name IN ('foo', 'bar') - return SQLExpressionContains(value, self) + return _SQLExpressionContains(value, self) } - func qualifiedCollection(with alias: TableAlias) -> SQLCollection { - SQLExpressionsArray(expressions: expressions.map { $0.qualifiedExpression(with: alias) }) + /// :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) } } diff --git a/GRDB/QueryInterface/SQL/SQLCollectionVisitor.swift b/GRDB/QueryInterface/SQL/SQLCollectionVisitor.swift new file mode 100644 index 000000000..a1c95bfe1 --- /dev/null +++ b/GRDB/QueryInterface/SQL/SQLCollectionVisitor.swift @@ -0,0 +1,5 @@ +/// :nodoc: +public protocol _SQLCollectionVisitor { + mutating func visit(_ collection: _SQLExpressionsArray) throws + mutating func visit(_ request: Request) throws +} diff --git a/GRDB/QueryInterface/SQL/SQLExpressible.swift b/GRDB/QueryInterface/SQL/SQLExpressible.swift index dbe6b9e74..82a14245d 100644 --- a/GRDB/QueryInterface/SQL/SQLExpressible.swift +++ b/GRDB/QueryInterface/SQL/SQLExpressible.swift @@ -1,26 +1,18 @@ // MARK: - SQLExpressible -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// The protocol for all types that can be used as SQL expression. /// -/// The protocol for all types that can be turned into an SQL expression. -/// -/// It is adopted by protocols like DatabaseValueConvertible, and types -/// like Column. +/// It is adopted by protocols like `DatabaseValueConvertible`, and types +/// like `Column`. /// /// See https://github.com/groue/GRDB.swift/#the-query-interface -/// -/// :nodoc: public protocol SQLExpressible { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// Returns an SQLExpression + /// Returns an SQL expression. var sqlExpression: SQLExpression { get } } // MARK: - SQLSpecificExpressible -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// /// SQLSpecificExpressible is a protocol for all database-specific types that can /// be turned into an SQL expression. Types whose existence is not purely /// dedicated to the database should adopt the SQLExpressible protocol instead. @@ -55,45 +47,22 @@ public protocol SQLSpecificExpressible: SQLExpressible { // MARK: - SQLExpressible & SQLOrderingTerm extension SQLExpressible where Self: SQLOrderingTerm { - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public var reversed: SQLOrderingTerm { - SQLOrdering.desc(sqlExpression) - } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// :nodoc: - public func orderingTermSQL(_ context: SQLGenerationContext) throws -> String { - try sqlExpression.expressionSQL(context, wrappedInParenthesis: false) + public var _reversed: SQLOrderingTerm { + _SQLOrdering.desc(sqlExpression) } } // MARK: - SQLExpressible & SQLSelectable extension SQLExpressible where Self: SQLSelectable { - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func resultColumnSQL(_ context: SQLGenerationContext) throws -> String { - try sqlExpression.expressionSQL(context, wrappedInParenthesis: false) + public func _count(distinct: Bool) -> _SQLCount? { + sqlExpression._count(distinct: distinct) } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func countedSQL(_ context: SQLGenerationContext) throws -> String { - try sqlExpression.expressionSQL(context, wrappedInParenthesis: false) - } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// :nodoc: - public func count(distinct: Bool) -> SQLCount? { - sqlExpression.count(distinct: distinct) - } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// :nodoc: - public func columnCount(_ db: Database) throws -> Int { + 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 c0a31a8ad..965a45bd0 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift @@ -10,236 +10,245 @@ extension SQLExpression { } } -// MARK: - SQLExpressionUnary +// MARK: - _SQLExpressionUnary -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// /// SQLUnaryOperator is a SQLite unary operator. -/// -/// :nodoc: -public struct SQLUnaryOperator: Hashable { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// +struct SQLUnaryOperator: Hashable { /// The SQL operator - public let sql: String + let sql: String - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// If true GRDB puts a white space between the operator and the operand. - public let needsRightSpace: Bool + let needsRightSpace: Bool - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// Creates an unary operator /// /// SQLUnaryOperator("~", needsRightSpace: false) - public init(_ sql: String, needsRightSpace: Bool) { + init(_ sql: String, needsRightSpace: Bool) { self.sql = sql self.needsRightSpace = needsRightSpace } + + /// The `-` unary operator + static let minus = SQLUnaryOperator("-", needsRightSpace: false) } -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// -/// 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 { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// The unary operator - public let op: SQLUnaryOperator +public struct _SQLExpressionUnary: SQLExpression { + let op: SQLUnaryOperator + let expression: SQLExpression - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// The operand - public let expression: SQLExpression - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// Creates an expression made of an unary operator and - /// an operand expression. - /// - /// // NOT favorite - /// SQLExpressionUnary(.not, Column("favorite")) - public init(_ op: SQLUnaryOperator, _ value: SQLExpressible) { + init(_ op: SQLUnaryOperator, _ value: SQLExpressible) { self.op = op self.expression = value.sqlExpression } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - if wrappedInParenthesis { - return try "(\(expressionSQL(context, wrappedInParenthesis: false)))" - } - return try op.sql - + (op.needsRightSpace ? " " : "") - + expression.expressionSQL(context, wrappedInParenthesis: true) + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + _SQLExpressionUnary(op, expression._qualifiedExpression(with: alias)) } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLExpressionUnary(op, expression.qualifiedExpression(with: alias)) + public func _accept(_ visitor: inout Visitor) throws { + try visitor.visit(self) } } -// MARK: - SQLExpressionBinary +// MARK: - _SQLExpressionBinary -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// /// SQLBinaryOperator is an SQLite binary operator, such as >, =, etc. -/// -/// :nodoc: -public struct SQLBinaryOperator: Hashable { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// +struct SQLBinaryOperator: Hashable { /// The SQL operator - public let sql: String + let sql: String - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// The SQL for the negated operator, if any - public let negatedSQL: String? + let negatedSQL: String? - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// Creates a binary operator /// /// SQLBinaryOperator("-") /// SQLBinaryOperator("IS", negated: "IS NOT") - public init(_ sql: String, negated: String? = nil) { + init(_ sql: String, negated: String? = nil) { self.sql = sql self.negatedSQL = negated } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// Returns the negated binary operator, if any /// /// let operator = SQLBinaryOperator("IS", negated: "IS NOT") /// operator.negated!.sql // IS NOT - public var negated: SQLBinaryOperator? { + var negated: SQLBinaryOperator? { guard let negatedSQL = negatedSQL else { return nil } return SQLBinaryOperator(negatedSQL, negated: sql) } + + /// The `<` binary operator + static let lessThan = SQLBinaryOperator("<") + + /// The `<=` binary operator + static let lessThanOrEqual = SQLBinaryOperator("<=") + + /// The `>` binary operator + static let greaterThan = SQLBinaryOperator(">") + + /// The `>=` binary operator + static let greaterThanOrEqual = SQLBinaryOperator(">=") + + /// The `-` binary operator + static let subtract = SQLBinaryOperator("-") + + /// The `/` binary operator + static let divide = SQLBinaryOperator("/") + + /// The `LIKE` binary operator + static let like = SQLBinaryOperator("LIKE") + + /// The `MATCH` binary operator + static let match = SQLBinaryOperator("MATCH") } -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// -/// 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 { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// The left operand - public let lhs: SQLExpression +public struct _SQLExpressionBinary: SQLExpression { + let lhs: SQLExpression + let op: SQLBinaryOperator + let rhs: SQLExpression - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// The operator - public let op: SQLBinaryOperator - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// The right operand - public let rhs: SQLExpression - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// Creates an expression made of two expressions joined with a /// binary operator. /// /// // length * width - /// SQLExpressionBinary(.subtract, Column("score"), Column("malus")) - public init(_ op: SQLBinaryOperator, _ lhs: SQLExpressible, _ rhs: SQLExpressible) { + /// _SQLExpressionBinary(.subtract, Column("score"), Column("malus")) + init(_ op: SQLBinaryOperator, _ lhs: SQLExpressible, _ rhs: SQLExpressible) { self.lhs = lhs.sqlExpression self.op = op self.rhs = rhs.sqlExpression } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - if wrappedInParenthesis { - return try "(\(expressionSQL(context, wrappedInParenthesis: false)))" - } - return try """ - \(lhs.expressionSQL(context, wrappedInParenthesis: true)) \ - \(op.sql) \ - \(rhs.expressionSQL(context, wrappedInParenthesis: true)) - """ - } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// :nodoc: - public var negated: SQLExpression { + public var _negated: SQLExpression { if let negatedOp = op.negated { - return SQLExpressionBinary(negatedOp, lhs, rhs) + return _SQLExpressionBinary(negatedOp, lhs, rhs) } else { - return SQLExpressionNot(self) + return _SQLExpressionNot(self) } } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLExpressionBinary(op, lhs.qualifiedExpression(with: alias), rhs.qualifiedExpression(with: alias)) + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + _SQLExpressionBinary(op, lhs._qualifiedExpression(with: alias), rhs._qualifiedExpression(with: alias)) + } + + /// :nodoc: + public func _accept(_ visitor: inout Visitor) throws { + try visitor.visit(self) } } -// MARK: - SQLExpressionBinaryReduce +// MARK: - _SQLExpressionAssociativeBinary -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// /// SQLAssociativeBinaryOperator is an SQLite associative binary operator, such -/// as +, *, AND, etc. +/// as `+`, `*`, `AND`, etc. /// -/// :nodoc: +/// Use it with the `joined(operator:)` method. For example: +/// +/// // SELECT score + bonus + 1000 FROM player +/// let values = [ +/// scoreColumn, +/// bonusColumn, +/// 1000.databaseValue] +/// Player.select(values.joined(operator: .add)) public struct SQLAssociativeBinaryOperator: Hashable { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// The SQL operator - public let sql: String + let sql: String - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// The neutral value - public let neutralValue: DatabaseValue + let neutralValue: DatabaseValue - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// 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 + /// `+` and `*` are not stricly associative when applied to floating /// point values. - public let strictlyAssociative: Bool + let strictlyAssociative: Bool - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// Creates a binary operator - public init(sql: String, neutralValue: DatabaseValue, strictlyAssociative: Bool) { + init(sql: String, neutralValue: DatabaseValue, strictlyAssociative: Bool) { self.sql = sql self.neutralValue = neutralValue self.strictlyAssociative = strictlyAssociative } + + /// The `+` binary operator + /// + /// For example: + /// + /// // score + bonus + /// [Column("score"), Column("bonus")].joined(operator: .add) + public static let add = SQLAssociativeBinaryOperator( + sql: "+", + neutralValue: 0.databaseValue, + strictlyAssociative: false) + + /// The `*` binary operator + /// + /// For example: + /// + /// // score * factor + /// [Column("score"), Column("factor")].joined(operator: .multiply) + public static let multiply = SQLAssociativeBinaryOperator( + sql: "*", + neutralValue: 1.databaseValue, + strictlyAssociative: false) + + /// The `AND` binary operator + /// + /// For example: + /// + /// // isBlue AND isTall + /// [Column("isBlue"), Column("isTall")].joined(operator: .and) + public static let and = SQLAssociativeBinaryOperator( + sql: "AND", + neutralValue: true.databaseValue, + strictlyAssociative: true) + + /// The `OR` binary operator + /// + /// For example: + /// + /// // isBlue OR isTall + /// [Column("isBlue"), Column("isTall")].joined(operator: .or) + public static let or = SQLAssociativeBinaryOperator( + sql: "OR", + neutralValue: false.databaseValue, + strictlyAssociative: true) + + /// The `||` string concatenation operator + /// + /// For example: + /// + /// // firstName || ' ' || lastName + /// [Column("firstName"), " ", Column("lastName")].joined(operator: .concat) + public static let concat = SQLAssociativeBinaryOperator( + sql: "||", + neutralValue: "".databaseValue, + strictlyAssociative: true) } -/// SQLExpressionBinary is an expression made of two expressions joined with a -/// binary operator. +/// `_SQLExpressionAssociativeBinary` is an expression made of several +/// expressions joined with an associative binary operator. /// -/// SQLExpressionBinary(.multiply, Column("length"), Column("width")) -struct SQLExpressionBinaryReduce: SQLExpression { +/// :nodoc: +public struct _SQLExpressionAssociativeBinary: SQLExpression { let expressions: [SQLExpression] let op: SQLAssociativeBinaryOperator @@ -247,14 +256,14 @@ struct SQLExpressionBinaryReduce: SQLExpression { /// binary operator. /// /// // length * width - /// SQLExpressionBinaryReduce(.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 { self.expressions = expressions.flatMap { expression -> [SQLExpression] in - if let reduce = expression as? SQLExpressionBinaryReduce, reduce.op == op { + if let reduce = expression as? _SQLExpressionAssociativeBinary, reduce.op == op { return reduce.expressions } else { return [expression] @@ -265,72 +274,26 @@ struct SQLExpressionBinaryReduce: SQLExpression { } } - func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - guard let first = expressions.first else { - return try op.neutralValue.expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis) - } - if expressions.count == 1 { - return try first.expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis) - } - let expressionSQLs = try expressions.map { try $0.expressionSQL(context, wrappedInParenthesis: true) } - let joiner = " \(op.sql) " - if wrappedInParenthesis { - return "(\(expressionSQLs.joined(separator: joiner)))" - } else { - return expressionSQLs.joined(separator: joiner) - } + /// :nodoc: + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + _SQLExpressionAssociativeBinary(op, expressions.map { $0._qualifiedExpression(with: alias) }) } - func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLExpressionBinaryReduce(op, expressions.map { $0.qualifiedExpression(with: alias) }) - } - - func matchedRowIds(rowIdName: String?) -> Set? { - switch op { - case .and: - let matchedRowIds = expressions.compactMap { - $0.matchedRowIds(rowIdName: rowIdName) - } - guard let first = matchedRowIds.first else { - return nil - } - return matchedRowIds.suffix(from: 1).reduce(into: first) { $0.formIntersection($1) } - case .or: - if expressions.isEmpty { - return [] - } - var result: Set = [] - for expr in expressions { - guard let matchedRowIds = expr.matchedRowIds(rowIdName: rowIdName) else { - return nil - } - result.formUnion(matchedRowIds) - } - return result + /// :nodoc: + public func _accept(_ visitor: inout Visitor) throws { + switch expressions.count { + case 0: + try op.neutralValue._accept(&visitor) + case 1: + try expressions[0]._accept(&visitor) default: - return nil + try visitor.visit(self) } } - - var truthComponents: [SQLExpression] { - guard let first = expressions.first else { - return op.neutralValue.truthComponents - } - - if expressions.count == 1 { - return first.truthComponents - } - - if op == .and { - return expressions.flatMap(\.truthComponents) - } - - return [self] - } } extension Sequence where Element == SQLExpression { - /// Returns an expression by joining all elements with an SQL + /// Returns an expression by joining all elements with an associative SQL /// binary operator. /// /// For example: @@ -347,27 +310,16 @@ extension Sequence where Element == SQLExpression { /// /// When the sequence is empty, `joined(operator:)` returns the neutral /// value of the operator. It is 0 (zero) for `.add`, 1 for ‘.multiply`, - /// false for `.or`, true for `.and`... - /// and `joined(operator: .or)` returns false: - /// When the sequence is empty, `joined(operator: .and)` returns true, - /// and `joined(operator: .or)` returns false: - /// - /// // SELECT 0 FROM player - /// Player.select([].joined(operator: .add)) - /// - /// // SELECT * FROM player WHERE 1 - /// Player.filter([].joined(operator: .and)) - /// - /// // SELECT * FROM player WHERE 0 - /// Player.filter([].joined(operator: .or)) + /// false for `.or`, and true for `.and`. public func joined(operator: SQLAssociativeBinaryOperator) -> SQLExpression { - SQLExpressionBinaryReduce(`operator`, Array(self)) + _SQLExpressionAssociativeBinary(`operator`, Array(self)) } } -// MARK: - SQLExpressionEqual +// MARK: - _SQLExpressionEqual -struct SQLExpressionEqual: SQLExpression { +/// :nodoc: +public struct _SQLExpressionEqual: SQLExpression { var lhs: SQLExpression var rhs: SQLExpression var op: Operator @@ -394,67 +346,32 @@ struct SQLExpressionEqual: SQLExpression { } } - func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - if wrappedInParenthesis { - return try "(\(expressionSQL(context, wrappedInParenthesis: false)))" - } - return try """ - \(lhs.expressionSQL(context, wrappedInParenthesis: true)) \ - \(op.rawValue) \ - \(rhs.expressionSQL(context, wrappedInParenthesis: true)) - """ + /// :nodoc: + public var _negated: SQLExpression { + _SQLExpressionEqual(op.negated, lhs, rhs) } - var negated: SQLExpression { - SQLExpressionEqual(op.negated, lhs, rhs) + /// :nodoc: + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + _SQLExpressionEqual(op, lhs._qualifiedExpression(with: alias), rhs._qualifiedExpression(with: alias)) } - func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLExpressionEqual(op, lhs.qualifiedExpression(with: alias), rhs.qualifiedExpression(with: alias)) - } - - func matchedRowIds(rowIdName: String?) -> Set? { - // FIXME: this implementation ignores column aliases - switch op { - case .equal, .is: - // Look for `id ==/IS 1`, `rowid ==/IS 1`, `1 ==/IS id`, `1 ==/IS rowid` - func matchedRowIds(column: ColumnExpression, dbValue: DatabaseValue) -> Set? { - var rowIdNames = [Column.rowID.name.lowercased()] - if let rowIdName = rowIdName { - rowIdNames.append(rowIdName.lowercased()) - } - guard rowIdNames.contains(column.name.lowercased()) else { - return nil - } - if let rowId = Int64.fromDatabaseValue(dbValue) { - return [rowId] - } else { - return [] - } - } - switch (lhs, rhs) { - case let (column as ColumnExpression, dbValue as DatabaseValue): - return matchedRowIds(column: column, dbValue: dbValue) - case let (dbValue as DatabaseValue, column as ColumnExpression): - return matchedRowIds(column: column, dbValue: dbValue) - default: - return nil - } - - case .notEqual, .isNot: - return nil - } + /// :nodoc: + public func _accept(_ visitor: inout Visitor) throws { + try visitor.visit(self) } } -// 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])) -struct SQLExpressionContains: SQLExpression { +/// _SQLExpressionContains(Column("id"), _SQLExpressionsArray([1,2,3])) +/// +/// :nodoc: +public struct _SQLExpressionContains: SQLExpression { let expression: SQLExpression let collection: SQLCollection let isNegated: Bool @@ -465,65 +382,35 @@ struct SQLExpressionContains: SQLExpression { self.isNegated = negated } - func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - if wrappedInParenthesis { - return try "(\(expressionSQL(context, wrappedInParenthesis: false)))" - } - return try """ - \(expression.expressionSQL(context, wrappedInParenthesis: true)) \ - \(isNegated ? "NOT IN" : "IN") \ - (\(collection.collectionSQL(context))) - """ + /// :nodoc: + public var _negated: SQLExpression { + _SQLExpressionContains(expression, collection, negated: !isNegated) } - var negated: SQLExpression { - SQLExpressionContains(expression, collection, negated: !isNegated) - } - - func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - return SQLExpressionContains( - expression.qualifiedExpression(with: alias), - collection.qualifiedCollection(with: alias), + /// :nodoc: + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return _SQLExpressionContains( + expression._qualifiedExpression(with: alias), + collection._qualifiedCollection(with: alias), negated: isNegated) } - func matchedRowIds(rowIdName: String?) -> Set? { - // FIXME: this implementation ignores column aliases - // Look for `id IN (1, 2, 3)` - guard let column = expression as? ColumnExpression, - let array = collection as? SQLExpressionsArray else - { - return nil - } - - var rowIdNames = [Column.rowID.name.lowercased()] - if let rowIdName = rowIdName { - rowIdNames.append(rowIdName.lowercased()) - } - - guard rowIdNames.contains(column.name.lowercased()) else { - return nil - } - - var rowIDs: Set = [] - for expression in array.expressions { - guard let dbValue = expression as? DatabaseValue else { return nil } - if let rowId = Int64.fromDatabaseValue(dbValue) { - rowIDs.insert(rowId) - } - } - return rowIDs + /// :nodoc: + public func _accept(_ visitor: inout Visitor) throws { + try visitor.visit(self) } } -// 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) -struct SQLExpressionBetween: SQLExpression { +/// _SQLExpressionBetween(Column("id"), 1.databaseValue, 3.databaseValue) +/// +/// :nodoc: +public struct _SQLExpressionBetween: SQLExpression { let expression: SQLExpression let lowerBound: SQLExpression let upperBound: SQLExpression @@ -536,123 +423,62 @@ struct SQLExpressionBetween: SQLExpression { self.isNegated = negated } - func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - if wrappedInParenthesis { - return try "(\(expressionSQL(context, wrappedInParenthesis: false)))" - } - return try """ - \(expression.expressionSQL(context, wrappedInParenthesis: true)) \ - \(isNegated ? "NOT BETWEEN" : "BETWEEN") \ - \(lowerBound.expressionSQL(context, wrappedInParenthesis: true)) \ - AND \ - \(upperBound.expressionSQL(context, wrappedInParenthesis: true)) - """ + /// :nodoc: + public var _negated: SQLExpression { + _SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated) } - var negated: SQLExpression { - SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated) - } - - func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLExpressionBetween( - expression.qualifiedExpression(with: alias), - lowerBound.qualifiedExpression(with: alias), - upperBound.qualifiedExpression(with: alias), + /// :nodoc: + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + _SQLExpressionBetween( + expression._qualifiedExpression(with: alias), + lowerBound._qualifiedExpression(with: alias), + upperBound._qualifiedExpression(with: alias), negated: isNegated) } -} - -// MARK: - SQLExpressionFunction - -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// -/// SQLFunctionName is an SQL function name. -public struct SQLFunctionName: Hashable { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// The SQL function name - /// - /// :nodoc: - public var sql: String - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// Creates a function name - /// - /// SQLFunctionName("ABS") - /// /// :nodoc: - public init(_ sql: String) { - self.sql = sql + public func _accept(_ visitor: inout Visitor) throws { + try visitor.visit(self) } } -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// -/// SQLExpressionFunction is an SQL function call. -/// -/// // ABS(-1) -/// SQLExpressionFunction(.abs, [-1.databaseValue]) -/// +// MARK: - _SQLExpressionFunction + /// :nodoc: -public struct SQLExpressionFunction: SQLExpression { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// The function name - public let functionName: SQLFunctionName +public struct _SQLExpressionFunction: SQLExpression { + let function: String + let arguments: [SQLExpression] - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// The function arguments - public let arguments: [SQLExpression] - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// Creates an SQL function call - /// - /// // ABS(-1) - /// SQLExpressionFunction(.abs, arguments: [-1.databaseValue]) - public init(_ functionName: SQLFunctionName, arguments: [SQLExpression]) { - self.functionName = functionName + init(_ function: String, arguments: [SQLExpression]) { + self.function = function self.arguments = arguments } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// Creates an SQL function call - /// - /// // ABS(-1) - /// SQLExpressionFunction(.abs, arguments: -1) - public init(_ functionName: SQLFunctionName, arguments: SQLExpressible...) { - self.init(functionName, arguments: arguments.map(\.sqlExpression)) + init(_ function: String, arguments: SQLExpressible...) { + self.init(function, arguments: arguments.map(\.sqlExpression)) } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - var sql = functionName.sql - sql += "(" - sql += try arguments - .map { try $0.expressionSQL(context, wrappedInParenthesis: false) } - .joined(separator: ", ") - sql += ")" - return sql + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + _SQLExpressionFunction(function, arguments: arguments.map { $0._qualifiedExpression(with: alias) }) } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLExpressionFunction(functionName, arguments: arguments.map { $0.qualifiedExpression(with: alias) }) + public func _accept(_ visitor: inout Visitor) throws { + try visitor.visit(self) } } -// 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")) -struct SQLExpressionCount: SQLExpression { +/// _SQLExpressionCount(Column("name")) +/// +/// :nodoc: +public struct _SQLExpressionCount: SQLExpression { /// The counted value let counted: SQLSelectable @@ -660,43 +486,51 @@ struct SQLExpressionCount: SQLExpression { self.counted = counted } - func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - try "COUNT(" + counted.countedSQL(context) + ")" + /// :nodoc: + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + _SQLExpressionCount(counted._qualifiedSelectable(with: alias)) } - func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLExpressionCount(counted.qualifiedSelectable(with: alias)) + /// :nodoc: + public func _accept(_ visitor: inout Visitor) throws { + try visitor.visit(self) } } -// 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")) -struct SQLExpressionCountDistinct: SQLExpression { +/// _SQLExpressionCountDistinct(Column("name")) +/// +/// :nodoc: +public struct _SQLExpressionCountDistinct: SQLExpression { let counted: SQLExpression init(_ counted: SQLExpression) { self.counted = counted } - func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - try "COUNT(DISTINCT " + counted.expressionSQL(context, wrappedInParenthesis: false) + ")" + /// :nodoc: + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + _SQLExpressionCountDistinct(counted._qualifiedExpression(with: alias)) } - func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLExpressionCountDistinct(counted.qualifiedExpression(with: alias)) + /// :nodoc: + public func _accept(_ visitor: inout Visitor) throws { + try visitor.visit(self) } } -// 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`. -struct SQLExpressionIsEmpty: SQLExpression { +/// +/// :nodoc: +public struct _SQLExpressionIsEmpty: SQLExpression { var countExpression: SQLExpression var isEmpty: Bool @@ -706,56 +540,51 @@ struct SQLExpressionIsEmpty: SQLExpression { self.isEmpty = isEmpty } - var negated: SQLExpression { - SQLExpressionIsEmpty(countExpression, isEmpty: !isEmpty) + /// :nodoc: + public var _negated: SQLExpression { + _SQLExpressionIsEmpty(countExpression, isEmpty: !isEmpty) } - func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - if wrappedInParenthesis { - return try "(\(expressionSQL(context, wrappedInParenthesis: false)))" - } - return try """ - \(countExpression.expressionSQL(context, wrappedInParenthesis: true)) \ - \(isEmpty ? "= 0" : "> 0") - """ + /// :nodoc: + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + _SQLExpressionIsEmpty(countExpression._qualifiedExpression(with: alias), isEmpty: isEmpty) } - 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: - TableMatchExpression +// MARK: - _SQLExpressionTableMatch -struct TableMatchExpression: SQLExpression { +/// :nodoc: +public struct _SQLExpressionTableMatch: SQLExpression { var alias: TableAlias var pattern: SQLExpression - func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - if wrappedInParenthesis { - return try "(\(expressionSQL(context, wrappedInParenthesis: false)))" - } - return try """ - \(context.resolvedName(for: alias).quotedDatabaseIdentifier) \ - MATCH \ - \(pattern.expressionSQL(context, wrappedInParenthesis: true)) - """ + /// :nodoc: + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + _SQLExpressionTableMatch( + alias: self.alias, + pattern: pattern._qualifiedExpression(with: alias)) } - func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - TableMatchExpression( - 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") -struct SQLExpressionCollate: SQLExpression { +/// _SQLExpressionCollate(Column("email") == "arthur@example.com", "NOCASE") +/// +/// :nodoc: +public struct _SQLExpressionCollate: SQLExpression { let expression: SQLExpression let collationName: Database.CollationName @@ -764,68 +593,67 @@ struct SQLExpressionCollate: SQLExpression { self.collationName = collationName } - func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - if wrappedInParenthesis { - return try "(\(expressionSQL(context, wrappedInParenthesis: false)))" - } - return try """ - \(expression.expressionSQL(context, wrappedInParenthesis: false)) \ - COLLATE \ - \(collationName.rawValue) - """ + /// :nodoc: + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + _SQLExpressionCollate(expression._qualifiedExpression(with: alias), collationName: collationName) } - func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLExpressionCollate(expression.qualifiedExpression(with: alias), collationName: collationName) + /// :nodoc: + public func _accept(_ visitor: inout Visitor) throws { + try visitor.visit(self) } } -// MARK: - FastPrimaryKeyExpression +// MARK: - _SQLExpressionFastPrimaryKey -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// -/// FastPrimaryKeyExpression 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). -struct FastPrimaryKeyExpression: 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("FastPrimaryKeyExpression was not qualified.") +/// +/// :nodoc: +public struct _SQLExpressionFastPrimaryKey: SQLExpression { + /// :nodoc: + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + _SQLExpressionQualifiedFastPrimaryKey(alias: alias) } - func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - QualifiedFastPrimaryKeyExpression(alias: alias) + /// :nodoc: + public func _accept(_ visitor: inout Visitor) throws { + try visitor.visit(self) } } -struct QualifiedFastPrimaryKeyExpression: SQLExpression { +/// :nodoc: +public struct _SQLExpressionQualifiedFastPrimaryKey: SQLExpression { let alias: TableAlias - func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - let column: Column - let primaryKey = try context.db.primaryKey(alias.tableName) - if let rowIDColumn = primaryKey.rowIDColumn { - // Prefer the user-provided name of the row id - column = Column(rowIDColumn) - } else if primaryKey.tableHasRowID { - // Prefer the row id - column = .rowID - } else if primaryKey.columns.count == 1 { - // WITHOUT ROWID table: use primary key column - column = Column(primaryKey.columns[0]) - } else { - fatalError("Not implemented: WITHOUT ROWID table with a multi-columns primary key") - } - return try column - .qualifiedExpression(with: alias) - .expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis) - } - - func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + /// :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) + if let rowIDColumn = primaryKey.rowIDColumn { + // Prefer the user-provided name of the row id + return rowIDColumn + } else if primaryKey.tableHasRowID { + // Prefer the row id + return Column.rowID.name + } else if primaryKey.columns.count == 1 { + // WITHOUT ROWID table: use primary key column + return primaryKey.columns[0] + } else { + fatalError("Not implemented: WITHOUT ROWID table with a multi-columns primary key") + } + } } diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index b56342be2..7e960fa68 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -1,25 +1,9 @@ // MARK: - SQLExpression -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// -/// SQLExpression is the protocol for types that represent an SQL expression, as -/// described at https://www.sqlite.org/lang_expr.html +/// Implementation details of SQLExpression. /// /// :nodoc: -public protocol SQLExpression: SQLSpecificExpressible, SQLSelectable, SQLOrderingTerm { - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// 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 - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// +public protocol _SQLExpression { /// Returns the expression, negated. This property fuels the `!` operator. /// /// The default implementation returns the expression prefixed by `NOT`. @@ -32,92 +16,44 @@ public protocol SQLExpression: SQLSpecificExpressible, SQLSelectable, SQLOrderin /// /// let expression = [1,2,3].contains(Column("id")) // id IN (1,2,3) /// expression.negated // id NOT IN (1,2,3) - var negated: SQLExpression { get } + var _negated: SQLExpression { get } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// Returns the rowIds matched by the expression. - func matchedRowIds(rowIdName: String?) -> Set? // FIXME: this method should take TableAlias in account + /// Returns a qualified expression + func _qualifiedExpression(with alias: TableAlias) -> SQLExpression - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - func qualifiedExpression(with alias: TableAlias) -> SQLExpression - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// The elements of the returned array, when joined with the AND operator, - /// are guaranteed to have the same truth value as the receiver. - /// - /// Those truth components allow easier introspection of the expression. - /// For example: - /// - /// // No change: - /// // [Column("a")] - /// Column("a").truthComponents - /// - /// // Erase a SQLExpressionBinaryReduce `and` expression: - /// // [Column("a"), Column("b")] - /// [Column("a"), Column("b")].joined(operator: .and).truthComponents - /// - /// // Erase a SQLExpressionBinaryReduce `or` expression: - /// // [Column("a")] - /// [Column("a")].joined(operator: .or).truthComponents - var truthComponents: [SQLExpression] { get } + /// Accepts a visitor + func _accept(_ visitor: inout Visitor) throws } +/// SQLExpression is the protocol for types that represent an SQL expression, as +/// described at https://www.sqlite.org/lang_expr.html +public protocol SQLExpression: _SQLExpression, SQLSpecificExpressible, SQLSelectable, SQLOrderingTerm { } + extension SQLExpression { - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// The default implementation returns the expression prefixed by `NOT`. /// /// let column = Column("favorite") /// column.negated // NOT favorite /// /// :nodoc: - public var negated: SQLExpression { - SQLExpressionNot(self) + public var _negated: SQLExpression { + _SQLExpressionNot(self) } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// The default implementation returns nil - /// /// :nodoc: - public func matchedRowIds(rowIdName: String?) -> Set? { - nil + public func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { + _qualifiedExpression(with: alias) } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// The default implementation returns qualifiedExpression(with:) - /// /// :nodoc: - public func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { - qualifiedExpression(with: alias) + public func _qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { + _qualifiedExpression(with: alias) } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// The default implementation returns qualifiedExpression(with:) - /// - /// :nodoc: - public func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { - qualifiedExpression(with: alias) - } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// The default implementation returns [self] - /// - /// :nodoc: - public var truthComponents: [SQLExpression] { [self] } } // SQLExpression: SQLExpressible extension SQLExpression { - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public var sqlExpression: SQLExpression { self @@ -127,10 +63,8 @@ extension SQLExpression { // SQLExpression: SQLSelectable extension SQLExpression { - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func count(distinct: Bool) -> SQLCount? { + public func _count(distinct: Bool) -> _SQLCount? { if distinct { // SELECT DISTINCT expr FROM tableName ... // -> @@ -145,27 +79,23 @@ extension SQLExpression { } } -// MARK: - SQLExpressionNot +// MARK: - _SQLExpressionNot -struct SQLExpressionNot: SQLExpression { +/// :nodoc: +public struct _SQLExpressionNot: SQLExpression { let expression: SQLExpression init(_ expression: SQLExpression) { self.expression = expression } - func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - if wrappedInParenthesis { - return try "(\(expressionSQL(context, wrappedInParenthesis: false)))" - } - return try "NOT \(expression.expressionSQL(context, wrappedInParenthesis: true))" + /// :nodoc: + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + _SQLExpressionNot(expression._qualifiedExpression(with: alias)) } - var negated: SQLExpression { - expression - } - - func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLExpressionNot(expression.qualifiedExpression(with: alias)) + /// :nodoc: + public func _accept(_ visitor: inout Visitor) throws { + try visitor.visit(self) } } diff --git a/GRDB/QueryInterface/SQL/SQLExpressionVisitor.swift b/GRDB/QueryInterface/SQL/SQLExpressionVisitor.swift new file mode 100644 index 000000000..aa9f18098 --- /dev/null +++ b/GRDB/QueryInterface/SQL/SQLExpressionVisitor.swift @@ -0,0 +1,33 @@ +/// :nodoc: +public protocol _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 + mutating func visit(_ expr: _SQLExpressionBinary) throws + /// - precondition: expr.expressions.count > 1 + mutating func visit(_ expr: _SQLExpressionAssociativeBinary) throws + /// Has a default implementation + 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 + mutating func visit(_ request: Request) throws +} + +/// :nodoc: +extension _SQLExpressionVisitor { + /// Default implementation just forwards the collated expression + mutating func visit(_ expr: _SQLExpressionCollate) throws { + try expr.expression._accept(&self) + } +} diff --git a/GRDB/QueryInterface/SQL/SQLFunctions.swift b/GRDB/QueryInterface/SQL/SQLFunctions.swift index 63b0bb615..f312068c8 100644 --- a/GRDB/QueryInterface/SQL/SQLFunctions.swift +++ b/GRDB/QueryInterface/SQL/SQLFunctions.swift @@ -5,40 +5,30 @@ extension DatabaseFunction { /// /// See https://github.com/groue/GRDB.swift/#sql-functions public func callAsFunction(_ arguments: SQLExpressible...) -> SQLExpression { - SQLExpressionFunction(SQLFunctionName(name), arguments: arguments.map(\.sqlExpression)) + _SQLExpressionFunction(name, arguments: arguments.map(\.sqlExpression)) } } // MARK: - ABS(...) -extension SQLFunctionName { - /// The `ABS` function name - public static let abs = SQLFunctionName("ABS") -} - /// Returns an expression that evaluates the `ABS` SQL function. /// /// // ABS(amount) /// abs(Column("amount")) public func abs(_ value: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionFunction(.abs, arguments: value) + _SQLExpressionFunction("ABS", arguments: value) } // MARK: - AVG(...) -extension SQLFunctionName { - /// The `AVG` function name - public static let avg = SQLFunctionName("AVG") -} - /// Returns an expression that evaluates the `AVG` SQL function. /// /// // AVG(length) /// average(Column("length")) public func average(_ value: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionFunction(.avg, arguments: value) + _SQLExpressionFunction("AVG", arguments: value) } @@ -49,7 +39,7 @@ public func average(_ value: SQLSpecificExpressible) -> SQLExpression { /// // COUNT(email) /// count(Column("email")) public func count(_ counted: SQLSelectable) -> SQLExpression { - SQLExpressionCount(counted) + _SQLExpressionCount(counted) } @@ -60,87 +50,62 @@ 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) } // MARK: - IFNULL(...) -extension SQLFunctionName { - /// The `IFNULL` function name - public static let ifNull = SQLFunctionName("IFNULL") -} - /// Returns an expression that evaluates the `IFNULL` SQL function. /// /// // IFNULL(name, 'Anonymous') /// Column("name") ?? "Anonymous" public func ?? (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - SQLExpressionFunction(.ifNull, arguments: lhs, rhs) + _SQLExpressionFunction("IFNULL", arguments: lhs, rhs) } // MARK: - LENGTH(...) -extension SQLFunctionName { - /// The `LENGTH` function name - public static let length = SQLFunctionName("LENGTH") -} - /// Returns an expression that evaluates the `LENGTH` SQL function. /// /// // LENGTH(name) /// length(Column("name")) public func length(_ value: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionFunction(.length, arguments: value) + _SQLExpressionFunction("LENGTH", arguments: value) } // MARK: - MAX(...) -extension SQLFunctionName { - /// The `MAX` function name - public static let max = SQLFunctionName("MAX") -} - /// Returns an expression that evaluates the `MAX` SQL function. /// /// // MAX(score) /// max(Column("score")) public func max(_ value: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionFunction(.max, arguments: value) + _SQLExpressionFunction("MAX", arguments: value) } // MARK: - MIN(...) -extension SQLFunctionName { - /// The `MIN` function name - public static let min = SQLFunctionName("MIN") -} - /// Returns an expression that evaluates the `MIN` SQL function. /// /// // MIN(score) /// min(Column("score")) public func min(_ value: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionFunction(.min, arguments: value) + _SQLExpressionFunction("MIN", arguments: value) } // MARK: - SUM(...) -extension SQLFunctionName { - /// The `SUM` function name - public static let sum = SQLFunctionName("SUM") -} - /// Returns an expression that evaluates the `SUM` SQL function. /// /// // SUM(amount) /// sum(Column("amount")) public func sum(_ value: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionFunction(.sum, arguments: value) + _SQLExpressionFunction("SUM", arguments: value) } @@ -266,26 +231,19 @@ public enum SQLDateModifier: SQLExpression { } } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - try rawValue.databaseValue.expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis) + public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { + self } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - self + public func _accept(_ visitor: inout Visitor) throws { + try rawValue.databaseValue._accept(&visitor) } } // MARK: JULIANDAY(...) -extension SQLFunctionName { - /// The `JULIANDAY` function name - public static let julianDay = SQLFunctionName("JULIANDAY") -} - /// Returns an expression that evaluates the `JULIANDAY` SQL function. /// /// // JULIANDAY(date) @@ -296,16 +254,11 @@ extension SQLFunctionName { /// /// 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) } // MARK: DATETIME(...) -extension SQLFunctionName { - /// The `DATETIME` function name - public static let dateTime = SQLFunctionName("DATETIME") -} - /// Returns an expression that evaluates the `DATETIME` SQL function. /// /// // DATETIME(date) @@ -316,5 +269,5 @@ extension SQLFunctionName { /// /// 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) } diff --git a/GRDB/QueryInterface/SQL/SQLOperators.swift b/GRDB/QueryInterface/SQL/SQLOperators.swift index f60fad939..d6dbda147 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. @@ -61,7 +61,7 @@ public func == (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression { if rhs { return lhs.sqlExpression } else { - return lhs.sqlExpression.negated + return lhs.sqlExpression._negated } } @@ -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. @@ -104,7 +104,7 @@ public func == (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression { if lhs { return rhs.sqlExpression } else { - return rhs.sqlExpression.negated + return rhs.sqlExpression._negated } } @@ -126,7 +126,7 @@ public func == (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// // name IS NOT NULL /// Column("name") != nil public func != (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { - isEqual(lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null).negated + isEqual(lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null)._negated } /// An SQL expression that compares two expressions with the `<>` SQL operator. @@ -139,7 +139,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpress /// // name IS NOT NULL /// Column("name").collating(.nocase) != nil public func != (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpression { - SQLExpressionCollate(lhs.expression != rhs, collationName: lhs.collationName) + _SQLExpressionCollate(lhs.expression != rhs, collationName: lhs.collationName) } /// An SQL expression that checks the boolean value of an expression. @@ -153,7 +153,7 @@ public func != (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpressi /// Column("validated") != false public func != (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression { if rhs { - return lhs.sqlExpression.negated + return lhs.sqlExpression._negated } else { return lhs.sqlExpression } @@ -169,7 +169,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression { /// // name IS NOT NULL /// nil != Column("name") public func != (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { - isEqual(lhs?.sqlExpression ?? DatabaseValue.null, rhs.sqlExpression).negated + isEqual(lhs?.sqlExpression ?? DatabaseValue.null, rhs.sqlExpression)._negated } /// An SQL expression that compares two expressions with the `<>` SQL operator. @@ -182,7 +182,7 @@ public func != (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpress /// // name IS NOT NULL /// nil != Column("name").collating(.nocase) public func != (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression { - SQLExpressionCollate(lhs != rhs.expression, collationName: rhs.collationName) + _SQLExpressionCollate(lhs != rhs.expression, collationName: rhs.collationName) } /// An SQL expression that checks the boolean value of an expression. @@ -196,7 +196,7 @@ public func != (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpressi /// false != Column("validated") public func != (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression { if lhs { - return rhs.sqlExpression.negated + return rhs.sqlExpression._negated } else { return rhs.sqlExpression } @@ -207,7 +207,7 @@ public func != (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression { /// // email <> login /// Column("email") != Column("login") public func != (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - isEqual(lhs.sqlExpression, rhs.sqlExpression).negated + isEqual(lhs.sqlExpression, rhs.sqlExpression)._negated } /// An SQL expression that compares two expressions with the `IS` SQL operator. @@ -215,7 +215,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. @@ -223,7 +223,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. @@ -232,9 +232,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) } } @@ -243,7 +243,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. @@ -251,7 +251,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. @@ -259,7 +259,7 @@ public func === (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQ /// // name IS NOT 'Arthur' /// Column("name") !== "Arthur" public func !== (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { - SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null) + _SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null) } /// An SQL expression that compares two expressions with the `IS NOT` SQL operator. @@ -267,7 +267,7 @@ public func !== (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpres /// // name IS NOT 'Arthur' COLLATE NOCASE /// Column("name").collating(.nocase) !== "Arthur" public func !== (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpression { - SQLExpressionCollate(lhs.expression !== rhs, collationName: lhs.collationName) + _SQLExpressionCollate(lhs.expression !== rhs, collationName: lhs.collationName) } /// An SQL expression that compares two expressions with the `IS NOT` SQL operator. @@ -276,9 +276,9 @@ public func !== (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpress /// "Arthur" !== Column("name") public func !== (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { if let lhs = lhs { - return SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs.sqlExpression) + return _SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs.sqlExpression) } else { - return SQLExpressionEqual(.isNot, rhs.sqlExpression, DatabaseValue.null) + return _SQLExpressionEqual(.isNot, rhs.sqlExpression, DatabaseValue.null) } } @@ -287,7 +287,7 @@ public func !== (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpres /// // name IS NOT 'Arthur' COLLATE NOCASE /// "Arthur" !== Column("name").collating(.nocase) public func !== (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression { - SQLExpressionCollate(lhs !== rhs.expression, collationName: rhs.collationName) + _SQLExpressionCollate(lhs !== rhs.expression, collationName: rhs.collationName) } /// An SQL expression that compares two expressions with the `IS NOT` SQL operator. @@ -295,31 +295,17 @@ public func !== (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpress /// // email IS NOT login /// Column("email") !== Column("login") public func !== (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs.sqlExpression) + _SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs.sqlExpression) } // MARK: - Comparison Operators (<, >, <=, >=) -extension SQLBinaryOperator { - /// The `<` binary operator - static let lessThan = SQLBinaryOperator("<") - - /// The `<=` binary operator - static let lessThanOrEqual = SQLBinaryOperator("<=") - - /// The `>` binary operator - static let greaterThan = SQLBinaryOperator(">") - - /// The `>=` binary operator - static let greaterThanOrEqual = SQLBinaryOperator(">=") -} - /// An SQL expression that compares two expressions with the `<` SQL operator. /// /// // 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. @@ -327,7 +313,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. @@ -335,7 +321,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. @@ -343,7 +329,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. @@ -351,7 +337,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. @@ -359,7 +345,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. @@ -367,7 +353,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. @@ -375,7 +361,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. @@ -383,7 +369,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. @@ -391,7 +377,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. @@ -399,7 +385,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. @@ -407,7 +393,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. @@ -415,7 +401,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. @@ -423,7 +409,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. @@ -431,7 +417,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. @@ -439,7 +425,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. @@ -447,7 +433,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. @@ -455,7 +441,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. @@ -463,7 +449,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. @@ -471,7 +457,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) @@ -500,7 +486,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. @@ -508,7 +494,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) } } @@ -528,7 +514,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) } } @@ -539,7 +525,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 @@ -548,7 +534,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) } } @@ -559,7 +545,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 @@ -568,56 +554,19 @@ 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) } } // MARK: - Arithmetic Operators (+, -, *, /) -extension SQLBinaryOperator { - /// The `-` binary operator - static let subtract = SQLBinaryOperator("-") - - /// The `/` binary operator - static let divide = SQLBinaryOperator("/") -} - -extension SQLAssociativeBinaryOperator { - /// The `+` binary operator - /// - /// For example: - /// - /// // score + bonus - /// [Column("score"), Column("bonus")].joined(operator: .add) - public static let add = SQLAssociativeBinaryOperator( - sql: "+", - neutralValue: 0.databaseValue, - strictlyAssociative: false) - - /// The `*` binary operator - /// - /// For example: - /// - /// // score * factor - /// [Column("score"), Column("factor")].joined(operator: .multiply) - public static let multiply = SQLAssociativeBinaryOperator( - sql: "*", - neutralValue: 1.databaseValue, - strictlyAssociative: false) -} - -extension SQLUnaryOperator { - /// The `-` unary operator - static let minus = SQLUnaryOperator("-", needsRightSpace: false) -} - /// An SQL arithmetic multiplication. /// /// // width * 2 /// Column("width") * 2 public func * (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - SQLExpressionBinaryReduce(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) + _SQLExpressionAssociativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic multiplication. @@ -625,7 +574,7 @@ public func * (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// // 2 * width /// 2 * Column("width") public func * (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionBinaryReduce(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) + _SQLExpressionAssociativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic multiplication. @@ -633,7 +582,7 @@ public func * (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// // width * height /// Column("width") * Column("height") public func * (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionBinaryReduce(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) + _SQLExpressionAssociativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic division. @@ -641,7 +590,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. @@ -649,7 +598,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. @@ -657,7 +606,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. @@ -665,7 +614,7 @@ public func / (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// // width + 2 /// Column("width") + 2 public func + (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - SQLExpressionBinaryReduce(.add, [lhs.sqlExpression, rhs.sqlExpression]) + _SQLExpressionAssociativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic addition. @@ -673,7 +622,7 @@ public func + (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// // 2 + width /// 2 + Column("width") public func + (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionBinaryReduce(.add, [lhs.sqlExpression, rhs.sqlExpression]) + _SQLExpressionAssociativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic addition. @@ -681,7 +630,7 @@ public func + (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// // width + height /// Column("width") + Column("height") public func + (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionBinaryReduce(.add, [lhs.sqlExpression, rhs.sqlExpression]) + _SQLExpressionAssociativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) } /// A negated SQL arithmetic expression. @@ -689,7 +638,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. @@ -697,7 +646,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. @@ -705,7 +654,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. @@ -713,42 +662,18 @@ 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) } // MARK: - Logical Operators (AND, OR, NOT) -extension SQLAssociativeBinaryOperator { - /// The `AND` binary operator - /// - /// For example: - /// - /// // isBlue AND isTall - /// [Column("isBlue"), Column("isTall")].joined(operator: .and) - public static let and = SQLAssociativeBinaryOperator( - sql: "AND", - neutralValue: true.databaseValue, - strictlyAssociative: true) - - /// The `OR` binary operator - /// - /// For example: - /// - /// // isBlue OR isTall - /// [Column("isBlue"), Column("isTall")].joined(operator: .or) - public static let or = SQLAssociativeBinaryOperator( - sql: "OR", - neutralValue: false.databaseValue, - strictlyAssociative: true) -} - /// A logical SQL expression with the `AND` SQL operator. /// /// // favorite AND 0 /// Column("favorite") && false public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - SQLExpressionBinaryReduce(.and, [lhs.sqlExpression, rhs.sqlExpression]) + _SQLExpressionAssociativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `AND` SQL operator. @@ -756,7 +681,7 @@ public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// // 0 AND favorite /// false && Column("favorite") public func && (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionBinaryReduce(.and, [lhs.sqlExpression, rhs.sqlExpression]) + _SQLExpressionAssociativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `AND` SQL operator. @@ -764,7 +689,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 { - SQLExpressionBinaryReduce(.and, [lhs.sqlExpression, rhs.sqlExpression]) + _SQLExpressionAssociativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -772,7 +697,7 @@ public func && (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// // favorite OR 1 /// Column("favorite") || true public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - SQLExpressionBinaryReduce(.or, [lhs.sqlExpression, rhs.sqlExpression]) + _SQLExpressionAssociativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -780,7 +705,7 @@ public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// // 0 OR favorite /// true || Column("favorite") public func || (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionBinaryReduce(.or, [lhs.sqlExpression, rhs.sqlExpression]) + _SQLExpressionAssociativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -788,7 +713,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 { - SQLExpressionBinaryReduce(.or, [lhs.sqlExpression, rhs.sqlExpression]) + _SQLExpressionAssociativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) } /// A negated logical SQL expression with the `NOT` SQL operator. @@ -801,16 +726,11 @@ public func || (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// // id NOT BETWEEN 1 AND 10 /// !((1...10).contains(Column("id"))) public prefix func ! (value: SQLSpecificExpressible) -> SQLExpression { - value.sqlExpression.negated + value.sqlExpression._negated } // MARK: - Like Operator -extension SQLBinaryOperator { - /// The `LIKE` binary operator - static let like = SQLBinaryOperator("LIKE") -} - /// :nodoc: extension SQLSpecificExpressible { @@ -819,28 +739,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) } } - -// MARK: - Concat Operator - -extension SQLAssociativeBinaryOperator { - /// The `||` string concatenation operator - /// - /// For example: - /// - /// // firstName || ' ' || lastName - /// [Column("firstName"), " ", Column("lastName")].joined(operator: .concat) - public static let concat = SQLAssociativeBinaryOperator( - sql: "||", - neutralValue: "".databaseValue, - strictlyAssociative: true) -} - -// MARK: - Match Operator - -extension SQLBinaryOperator { - /// The `MATCH` binary operator - static let match = SQLBinaryOperator("MATCH") -} diff --git a/GRDB/QueryInterface/SQL/SQLOrdering.swift b/GRDB/QueryInterface/SQL/SQLOrdering.swift index 9deca0855..71e599d6b 100644 --- a/GRDB/QueryInterface/SQL/SQLOrdering.swift +++ b/GRDB/QueryInterface/SQL/SQLOrdering.swift @@ -1,29 +1,28 @@ // MARK: - SQLOrderingTerm -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// Implementation details of SQLOrderingTerm. /// +/// :nodoc: +public protocol _SQLOrderingTerm { + /// The ordering term, reversed + var _reversed: SQLOrderingTerm { get } + + /// Returns a qualified ordering + func _qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm + + /// Accepts a visitor + func _accept(_ visitor: inout Visitor) throws +} + /// 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 protocol SQLOrderingTerm { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// The ordering term, reversed - var reversed: SQLOrderingTerm { get } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// Returns an SQL string that represents the ordering term. - func orderingTermSQL(_ context: SQLGenerationContext) throws -> String - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm -} - -// MARK: - SQLOrdering - -enum SQLOrdering: SQLOrderingTerm { +public enum _SQLOrdering: SQLOrderingTerm { case asc(SQLExpression) case desc(SQLExpression) #if GRDBCUSTOMSQLITE @@ -31,48 +30,40 @@ enum SQLOrdering: SQLOrderingTerm { case descNullsFirst(SQLExpression) #endif - var reversed: SQLOrderingTerm { + /// :nodoc: + public var _reversed: SQLOrderingTerm { switch self { case .asc(let expression): - return SQLOrdering.desc(expression) + return _SQLOrdering.desc(expression) case .desc(let expression): - return SQLOrdering.asc(expression) + return _SQLOrdering.asc(expression) #if GRDBCUSTOMSQLITE case .ascNullsLast(let expression): - return SQLOrdering.descNullsFirst(expression) + return _SQLOrdering.descNullsFirst(expression) case .descNullsFirst(let expression): - return SQLOrdering.ascNullsLast(expression) + return _SQLOrdering.ascNullsLast(expression) #endif } } - func orderingTermSQL(_ context: SQLGenerationContext) throws -> String { + /// :nodoc: + public func _qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { switch self { case .asc(let expression): - return try expression.expressionSQL(context, wrappedInParenthesis: false) + " ASC" + return _SQLOrdering.asc(expression._qualifiedExpression(with: alias)) case .desc(let expression): - return try expression.expressionSQL(context, wrappedInParenthesis: false) + " DESC" + return _SQLOrdering.desc(expression._qualifiedExpression(with: alias)) #if GRDBCUSTOMSQLITE case .ascNullsLast(let expression): - return try expression.expressionSQL(context, wrappedInParenthesis: false) + " ASC NULLS LAST" + return _SQLOrdering.ascNullsLast(expression._qualifiedExpression(with: alias)) case .descNullsFirst(let expression): - return try expression.expressionSQL(context, wrappedInParenthesis: false) + " DESC NULLS FIRST" + return _SQLOrdering.descNullsFirst(expression._qualifiedExpression(with: alias)) #endif } } - func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { - switch self { - case .asc(let expression): - return SQLOrdering.asc(expression.qualifiedExpression(with: alias)) - case .desc(let expression): - return SQLOrdering.desc(expression.qualifiedExpression(with: alias)) - #if GRDBCUSTOMSQLITE - case .ascNullsLast(let expression): - return SQLOrdering.ascNullsLast(expression.qualifiedExpression(with: alias)) - case .descNullsFirst(let expression): - return SQLOrdering.descNullsFirst(expression.qualifiedExpression(with: alias)) - #endif - } + /// :nodoc: + public func _accept(_ visitor: inout Visitor) throws { + try visitor.visit(self) } } diff --git a/GRDB/QueryInterface/SQL/SQLOrderingVisitor.swift b/GRDB/QueryInterface/SQL/SQLOrderingVisitor.swift new file mode 100644 index 000000000..add6af231 --- /dev/null +++ b/GRDB/QueryInterface/SQL/SQLOrderingVisitor.swift @@ -0,0 +1,6 @@ +/// :nodoc: +public protocol _SQLOrderingVisitor: _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 de43fd3c0..83e5a128e 100644 --- a/GRDB/QueryInterface/SQL/SQLQuery.swift +++ b/GRDB/QueryInterface/SQL/SQLQuery.swift @@ -119,16 +119,16 @@ extension SQLQuery { let selection = try relation.selectionPromise.resolve(db) GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") if selection.count == 1 { - guard let count = selection[0].count(distinct: isDistinct) else { + guard let count = selection[0]._count(distinct: isDistinct) else { return trivialCountQuery } var countQuery = self.unordered() 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 countQuery } else { @@ -141,7 +141,7 @@ extension SQLQuery { // SELECT expr1, expr2, ... FROM tableName ... // -> // SELECT COUNT(*) FROM tableName ... - return self.unordered().select(SQLExpressionCount(AllColumns())) + return self.unordered().select(_SQLExpressionCount(AllColumns())) } } @@ -149,7 +149,7 @@ extension SQLQuery { private var trivialCountQuery: SQLQuery { let relation = SQLRelation( source: .subquery(unordered()), - selectionPromise: DatabasePromise(value: [SQLExpressionCount(AllColumns())])) + selectionPromise: DatabasePromise(value: [_SQLExpressionCount(AllColumns())])) return SQLQuery(relation: relation) } } diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 967a55a8b..99e0ebbff 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -258,7 +258,7 @@ extension SQLRelation { /// /// At low-level, this gives: /// - /// let sqlAssociation = Origin.destination.sqlAssociation + /// let sqlAssociation = Origin.destination._sqlAssociation /// let origin = Origin.all().query.relation /// let relation = origin.appending(sqlAssociation, kind: .oneRequired) /// let query = SQLQuery(relation: relation) @@ -421,7 +421,7 @@ extension SQLRelation { var reversed: Element { switch self { case .terms(let terms): - return .terms(terms.map { $0.map(\.reversed) }) + return .terms(terms.map { $0.map(\._reversed) }) case .ordering(let ordering): return .ordering(ordering.reversed) } @@ -430,7 +430,7 @@ extension SQLRelation { func qualified(with alias: TableAlias) -> Element { switch self { case .terms(let terms): - return .terms(terms.map { $0.map { $0.qualifiedOrdering(with: alias) } }) + return .terms(terms.map { $0.map { $0._qualifiedOrdering(with: alias) } }) case .ordering(let ordering): return .ordering(ordering.qualified(with: alias)) } @@ -629,7 +629,7 @@ extension JoinMapping { /// the AND operator and qualified with the right table. func joinExpressions(leftAlias: TableAlias) -> [SQLExpression] { map { - Column($0.right) == QualifiedColumn($0.left, alias: leftAlias) + Column($0.right) == _SQLQualifiedColumn($0.left, alias: leftAlias) } } } diff --git a/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift index 4b0d2f752..4474ab419 100644 --- a/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift +++ b/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift @@ -19,23 +19,11 @@ public struct AllColumns { } extension AllColumns: SQLSelectable { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func resultColumnSQL(_ context: SQLGenerationContext) -> String { - "*" - } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// :nodoc: - public func countedSQL(_ context: SQLGenerationContext) -> String { - "*" - } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// :nodoc: - public func count(distinct: Bool) -> SQLCount? { + public func _count(distinct: Bool) -> _SQLCount? { // SELECT DISTINCT * FROM tableName ... if distinct { + // Can't count return nil } @@ -45,61 +33,60 @@ extension AllColumns: SQLSelectable { return .all } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { - QualifiedAllColumns(alias: alias) + public func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { + _SQLQualifiedAllColumns(alias: alias) } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func columnCount(_ db: Database) throws -> Int { + public func _columnCount(_ db: Database) throws -> Int { fatalError("Can't compute number of columns without an alias") } + + /// :nodoc: + public func _accept(_ visitor: inout Visitor) throws { + try visitor.visit(self) + } } -// MARK: - QualifiedAllColumns +// MARK: - _SQLQualifiedAllColumns -/// QualifiedAllColumns is the `t.*` in `SELECT t.*`. -struct QualifiedAllColumns { - private let alias: TableAlias +/// _SQLQualifiedAllColumns is the `t.*` in `SELECT t.*`. +/// +/// :nodoc: +public struct _SQLQualifiedAllColumns { + let alias: TableAlias init(alias: TableAlias) { self.alias = alias } } -extension QualifiedAllColumns: SQLSelectable { - func resultColumnSQL(_ context: SQLGenerationContext) -> String { - if let qualifier = context.qualifier(for: alias) { - return qualifier.quotedDatabaseIdentifier + ".*" - } - return "*" - } +extension _SQLQualifiedAllColumns: SQLSelectable { + /// :nodoc: + public func _count(distinct: Bool) -> _SQLCount? { nil } - func countedSQL(_ context: SQLGenerationContext) -> String { - if context.qualifier(for: alias) != nil { - // SELECT COUNT(t.*) is invalid SQL - fatalError("Not implemented, or invalid query") - } - return "*" - } - - func count(distinct: Bool) -> SQLCount? { nil } - - func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { + /// :nodoc: + public func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { // Never requalify return self } - func columnCount(_ db: Database) throws -> Int { + /// :nodoc: + public func _columnCount(_ db: Database) throws -> Int { try db.columns(in: alias.tableName).count } + + /// :nodoc: + public func _accept(_ visitor: inout Visitor) throws { + try visitor.visit(self) + } } -// MARK: - SQLAliasedExpression +// MARK: - _SQLAliasedExpression -struct SQLAliasedExpression: SQLSelectable { +/// :nodoc: +public struct _SQLAliasedExpression: SQLSelectable { let expression: SQLExpression let name: String @@ -108,21 +95,21 @@ struct SQLAliasedExpression: SQLSelectable { self.name = name } - func resultColumnSQL(_ context: SQLGenerationContext) throws -> String { - try expression.resultColumnSQL(context) + " AS " + name.quotedDatabaseIdentifier + /// :nodoc: + public func _count(distinct: Bool) -> _SQLCount? { + expression._count(distinct: distinct) } - func countedSQL(_ context: SQLGenerationContext) throws -> String { - try expression.countedSQL(context) + /// :nodoc: + public func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { + _SQLAliasedExpression(expression._qualifiedExpression(with: alias), name: name) } - func count(distinct: Bool) -> SQLCount? { - expression.count(distinct: distinct) - } + /// :nodoc: + public func _columnCount(_ db: Database) throws -> Int { 1 } - func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { - SQLAliasedExpression(expression.qualifiedExpression(with: alias), name: name) + /// :nodoc: + public func _accept(_ visitor: inout Visitor) throws { + try visitor.visit(self) } - - func columnCount(_ db: Database) throws -> Int { 1 } } diff --git a/GRDB/QueryInterface/SQL/SQLSelectable.swift b/GRDB/QueryInterface/SQL/SQLSelectable.swift index e7ef0c34d..3e04252a2 100644 --- a/GRDB/QueryInterface/SQL/SQLSelectable.swift +++ b/GRDB/QueryInterface/SQL/SQLSelectable.swift @@ -1,41 +1,35 @@ // MARK: - SQLSelectable -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// Implementation details of SQLSelectable. /// +/// :nodoc: +public protocol _SQLSelectable { + /// 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 a qualified selectable + func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable + + /// Accepts a visitor + func _accept(_ visitor: inout Visitor) throws +} + /// SQLSelectable is the protocol for types that can be selected, as /// described at https://www.sqlite.org/syntax/result-column.html /// /// :nodoc: -public protocol SQLSelectable { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - func resultColumnSQL(_ context: SQLGenerationContext) throws -> String - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - func countedSQL(_ context: SQLGenerationContext) throws -> String - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - func count(distinct: Bool) -> SQLCount? - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - func columnCount(_ db: Database) throws -> Int - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable -} +public protocol SQLSelectable: _SQLSelectable { } // MARK: - Counting -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// /// :nodoc: -public enum SQLCount { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// Represents COUNT(*) +public enum _SQLCount { + /// Represents `COUNT(*)` case all - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// Represents COUNT(DISTINCT expression) + /// Represents `COUNT(DISTINCT expression)` case distinct(SQLExpression) } diff --git a/GRDB/QueryInterface/SQL/SQLSelectableVisitor.swift b/GRDB/QueryInterface/SQL/SQLSelectableVisitor.swift new file mode 100644 index 000000000..760645781 --- /dev/null +++ b/GRDB/QueryInterface/SQL/SQLSelectableVisitor.swift @@ -0,0 +1,7 @@ +/// :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 de005629d..d18d6b465 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) } #endif } @@ -50,7 +50,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 new file mode 100644 index 000000000..af0d9ae35 --- /dev/null +++ b/GRDB/QueryInterface/SQLGeneration/SQLCollectionGenerator.swift @@ -0,0 +1,26 @@ +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(_ request: Request) throws { + resultSQL = try request.requestSQL(context, forSingleResult: false) + } +} diff --git a/GRDB/QueryInterface/SQLGeneration/SQLExpressionGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLExpressionGenerator.swift new file mode 100644 index 000000000..b0709d172 --- /dev/null +++ b/GRDB/QueryInterface/SQLGeneration/SQLExpressionGenerator.swift @@ -0,0 +1,188 @@ +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: _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))" + } + } + + mutating func visit(_ request: Request) 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 164145c87..1e8f30d90 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -342,27 +342,39 @@ public class TableAlias: Hashable { /// Returns a qualified value that is able to resolve ambiguities in /// joined queries. public subscript(_ selectable: SQLSelectable) -> SQLSelectable { - selectable.qualifiedSelectable(with: self) + selectable._qualifiedSelectable(with: self) } /// Returns a qualified expression that is able to resolve ambiguities in /// joined queries. public subscript(_ expression: SQLExpression) -> SQLExpression { - expression.qualifiedExpression(with: self) + expression._qualifiedExpression(with: self) } /// Returns a qualified ordering that is able to resolve ambiguities in /// joined queries. public subscript(_ ordering: SQLOrderingTerm) -> SQLOrderingTerm { - ordering.qualifiedOrdering(with: self) + ordering._qualifiedOrdering(with: self) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// An expression that evaluates to true if the record refered by this /// `TableAlias` exists. + /// + /// For example, here is how filter books and only keep those that are not + /// associated to any author: + /// + /// let books: [Book] = try dbQueue.read { db in + /// let authorAlias = TableAlias() + /// let request = Book + /// .joining(optional: Book.author.aliased(authorAlias)) + /// .filter(!authorAlias.exists) + /// return try request.fetchAll(db) + /// } + public var exists: SQLExpression { - QualifiedFastPrimaryKeyExpression(alias: self) != nil + _SQLExpressionQualifiedFastPrimaryKey(alias: self) != nil } /// :nodoc: diff --git a/GRDB/QueryInterface/SQLGeneration/SQLOrderingGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLOrderingGenerator.swift new file mode 100644 index 000000000..59634b44a --- /dev/null +++ b/GRDB/QueryInterface/SQLGeneration/SQLOrderingGenerator.swift @@ -0,0 +1,123 @@ +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: _SQLOrderingVisitor { + let context: SQLGenerationContext + var resultSQL = "" + + // MARK: - _SQLOrderingVisitor + + 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" + #if GRDBCUSTOMSQLITE + 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" + #endif + } + } + + 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: _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) + } + + mutating func visit(_ expr: Request) throws { + resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) + } +} diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index f9d899ba1..3c713b25b 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -46,10 +46,10 @@ struct SQLQueryGenerator: Refinable { // `HAVING MAX(year) < 2000` INTO `HAVING MAX(book.year) < 2000`. if let alias = relation.source.alias { groupPromise = query.groupPromise?.map { - $0.map { $0.qualifiedExpression(with: alias) } + $0.map { $0._qualifiedExpression(with: alias) } } havingExpressionsPromise = query.havingExpressionsPromise.map { - $0.map { $0.qualifiedExpression(with: alias) } + $0.map { $0._qualifiedExpression(with: alias) } } } else { groupPromise = query.groupPromise @@ -175,26 +175,20 @@ struct SQLQueryGenerator: Refinable { // Can we intersect the region with rowIds? // // Give up unless request feeds from a single database table - guard case .table(tableName: let tableName, alias: _) = relation.source else { + guard case let .table(tableName: tableName, alias: alias) = relation.source else { // TODO: try harder return selectedRegion } - // Give up unless primary key is rowId - let primaryKeyInfo = try db.primaryKey(tableName) - guard primaryKeyInfo.isRowID else { - return selectedRegion - } - - // The filters knows better - let filters = try relation.filtersPromise.resolve(db) - guard let rowIds = filters.joined(operator: .and).matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else { + // The filter knows better + let filter = try relation.filtersPromise.resolve(db).joined(operator: .and) + guard let rowIDs = try filter.identifyingRowIDs(db, for: alias) else { return selectedRegion } // Database regions are case-sensitive: use the canonical table name let canonicalTableName = try db.canonicalTableName(tableName) - return selectedRegion.tableIntersection(canonicalTableName, rowIds: rowIds) + return selectedRegion.tableIntersection(canonicalTableName, rowIds: rowIDs) } /// If true, executing this query yields at most one row. @@ -206,89 +200,26 @@ struct SQLQueryGenerator: Refinable { groupExpressions: [SQLExpression]) throws -> Bool { - if relation.allAliases.count > 1 { - // Don't expect single results as soon as several tables are involved + if relation.joins.isEmpty == false { + // Don't expect single results as soon as there is a join return false } // Do we filter on a unique key? if case let .table(tableName, sourceAlias) = relation.source { - let filteredColumns = filters.flatMap(\.truthComponents).compactMap { expression -> String? in - guard let equalExpression = expression as? SQLExpressionEqual, - (equalExpression.op == .equal || equalExpression.op == .is) else - { - // Not Column("foo") == value - return nil - } - - if equalExpression.lhs is DatabaseValue, - let qualifiedColumn = equalExpression.rhs as? QualifiedColumn, - qualifiedColumn.alias == sourceAlias - { - // value == Column("foo") - return qualifiedColumn.name - } - - if equalExpression.rhs is DatabaseValue, - let qualifiedColumn = equalExpression.lhs as? QualifiedColumn, - qualifiedColumn.alias == sourceAlias - { - // Column("foo") == value - return qualifiedColumn.name - } - - return nil - } - if try db.table(tableName, hasUniqueKey: filteredColumns) { + let identifyingColums = try filters + .joined(operator: .and) + .identifyingColums(db, for: sourceAlias) + if try db.table(tableName, hasUniqueKey: identifyingColums) { // Filter by unique key: guaranteed single row! return true } } // Do we aggregate without grouping? - if groupExpressions.isEmpty { - // https://www.sqlite.org/lang_aggfunc.html#groupconcat - let aggregateFunctionNames: Set = [ - "AVG", "COUNT", "GROUP_CONCAT", "MAX", "MIN", "SUM", "TOTAL" - ] - for selectable in selection { - switch selectable { - case is SQLExpressionCount: - // Selection contains COUNT(...): guaranteed single row! - return true - case is SQLExpressionCountDistinct: - // Selection contains COUNT(DISTINCT ...): guaranteed single row! - return true - case let expression as SQLExpressionFunction: - let functionName = expression.functionName.sql.uppercased() - guard aggregateFunctionNames.contains(functionName) else { - // Not an aggregate function. - // (We miss custom aggregates) - continue - } - guard expression.arguments.allSatisfy({ $0 is QualifiedColumn }) else { - // Aggregate function argument is not a column. - // (We miss expressions such as `max(column + 1)`) - continue - } - if functionName == "GROUP_CONCAT" { - switch expression.arguments.count { - case 1, 2: - // Selection contains an aggregate function: guaranteed single row! - return true - default: - break - } - } else if expression.arguments.count == 1 { - // Selection contains an aggregate function: guaranteed single row! - return true - } - default: - // Not an aggregate - // (We miss expressions such as `max(column) + 1`) - break - } - } + if groupExpressions.isEmpty && selection.contains(where: { $0.isAggregate() }) { + // Selection contains an aggregate function: guaranteed single row! + return true } return false @@ -349,7 +280,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 = FastPrimaryKeyExpression() + let primaryKey = _SQLExpressionFastPrimaryKey() var sql = "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE " sql += try alias[primaryKey].expressionSQL(context, wrappedInParenthesis: false) @@ -455,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 = FastPrimaryKeyExpression() + let primaryKey = _SQLExpressionFastPrimaryKey() // UPDATE table... var sql = "UPDATE " @@ -505,34 +436,19 @@ struct SQLQueryGenerator: Refinable { return .nonUnique } - // FastPrimaryKeyExpression? + var groupingColumns: Set = [] for expression in groupExpressions { - if - let column = expression as? QualifiedFastPrimaryKeyExpression, - column.alias == alias { - return .unique + guard let column = try expression.column(db, for: alias, acceptsBijection: true) else { + // Grouping by something which is not a column: assume non + // unique grouping. + return .nonUnique } - } - - // Grouping by something which is not a column: assume non - // unique grouping. - // SELECT * FROM player GROUP BY (score + bonus) - let qualifiedColumns = groupExpressions.compactMap { $0 as? QualifiedColumn } - if qualifiedColumns.count != groupExpressions.count { - return .nonUnique - } - - // Grouping by some column(s) which do not come from the main table: - // assume non unique grouping. - // SELECT * FROM player JOIN team ... GROUP BY team.id - guard qualifiedColumns.allSatisfy({ $0.alias == alias }) else { - return .nonUnique + groupingColumns.insert(column) } // Grouping by some column(s) which are unique // SELECT * FROM player GROUP BY id - let columnNames = qualifiedColumns.map(\.name) - if try db.table(tableName, hasUniqueKey: columnNames) { + if try db.table(tableName, hasUniqueKey: groupingColumns) { return .unique } @@ -654,10 +570,10 @@ private struct SQLQualifiedRelation { joins = relation.children.compactMapValues { SQLQualifiedJoin($0) } if let sourceAlias = source.alias { sourceSelectionPromise = relation.selectionPromise.map { - $0.map { $0.qualifiedSelectable(with: sourceAlias) } + $0.map { $0._qualifiedSelectable(with: sourceAlias) } } filtersPromise = relation.filtersPromise.map { - $0.map { $0.qualifiedExpression(with: sourceAlias) } + $0.map { $0._qualifiedExpression(with: sourceAlias) } } sourceOrdering = relation.ordering.qualified(with: sourceAlias) } else { @@ -686,7 +602,7 @@ private struct SQLQualifiedRelation { // The number of columns in source selection. Columns selected by joined // relations are appended after. let sourceSelectionWidth = try sourceSelectionPromise.resolve(db).reduce(0) { - try $0 + $1.columnCount(db) + try $0 + $1._columnCount(db) } // Recursively build adapters for each joined relation with a selection. @@ -731,7 +647,9 @@ private struct SQLQualifiedRelation { func selectOnly(_ selection: [SQLSelectable]) -> Self { let sourceSelectionPromise: DatabasePromise<[SQLSelectable]> if let sourceAlias = source.alias { - sourceSelectionPromise = DatabasePromise(value: selection.map { $0.qualifiedSelectable(with: sourceAlias) }) + sourceSelectionPromise = DatabasePromise(value: selection.map { + $0._qualifiedSelectable(with: sourceAlias) + }) } else { sourceSelectionPromise = DatabasePromise(value: selection) } @@ -877,7 +795,7 @@ private struct SQLQualifiedJoin: Refinable { if joinExpressions.isEmpty == false { let joiningSQL = try joinExpressions .joined(operator: .and) - .qualifiedExpression(with: rightAlias) + ._qualifiedExpression(with: rightAlias) .expressionSQL(context, wrappedInParenthesis: false) sql += " ON \(joiningSQL)" } @@ -890,3 +808,602 @@ private struct SQLQualifiedJoin: Refinable { return sql } } + +// 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: _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: _SQLExpressionContains) throws { + // TODO: visit the collection + try setNotConstant() // Don't know - assume not constant + } + + 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) + } + + mutating func visit(_ request: Request) throws where Request: SQLRequestProtocol { + 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: _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: _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) + } + } + + mutating func visit(_ request: Request) throws where Request: SQLRequestProtocol { } +} + +// 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 -- [] + /// + /// 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: _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: _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 { } + + mutating func visit(_ request: Request) throws where Request: SQLRequestProtocol { } +} + +// 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 0 -- nil + /// WHERE id IS NULL -- [] + /// WHERE id = 1 -- [1] + /// WHERE id = 1 AND b = 2 -- [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 > 1 -- nil + /// + /// 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 { } + + mutating func visit(_ column: Column) throws where Column: ColumnExpression { } + + mutating func visit(_ column: _SQLQualifiedColumn) 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: _SQLExpressionContains) throws { + if + let array = expr.collection as? _SQLExpressionsArray, + let column = try expr.expression.column(db, for: alias), + try db.columnIsRowID(column, of: alias.tableName) + { + rowIDs = Set(array.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 { + 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 { + 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 { } + + mutating func visit(_ request: Request) throws where Request: SQLRequestProtocol { } +} + +// 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(_ 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: _SQLExpressionContains) throws { + try expr.expression._accept(&self) + } + + 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) + } + + mutating func visit(_ request: Request) throws { } +} diff --git a/GRDB/QueryInterface/SQLGeneration/SQLSelectableCountGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLSelectableCountGenerator.swift new file mode 100644 index 000000000..b7bc07459 --- /dev/null +++ b/GRDB/QueryInterface/SQLGeneration/SQLSelectableCountGenerator.swift @@ -0,0 +1,130 @@ +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: _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) + } + + mutating func visit(_ expr: Request) throws { + resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) + } +} diff --git a/GRDB/QueryInterface/SQLGeneration/SQLSelectableResultColumnGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLSelectableResultColumnGenerator.swift new file mode 100644 index 000000000..d04e8d392 --- /dev/null +++ b/GRDB/QueryInterface/SQLGeneration/SQLSelectableResultColumnGenerator.swift @@ -0,0 +1,129 @@ +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: _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) + } + + mutating func visit(_ expr: Request) throws { + resultSQL = try expr.expressionSQL(context, wrappedInParenthesis: false) + } +} diff --git a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift index 868b75eab..e9d6b34fe 100644 --- a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift @@ -57,7 +57,7 @@ extension SQLInterpolation { { let alias = TableAlias(name: tableAlias ?? T.databaseTableName) elements.append(contentsOf: T.databaseSelection - .map { CollectionOfOne(.selectable($0.qualifiedSelectable(with: alias))) } + .map { CollectionOfOne(.selectable($0._qualifiedSelectable(with: alias))) } .joined(separator: CollectionOfOne(.sql(", ")))) } diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index a9713e549..a225f549a 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -202,7 +202,7 @@ extension TableRecord { Pivot.RowDecoder == Target.OriginRowDecoder { let association = HasManyThroughAssociation( - sqlAssociation: target.sqlAssociation.through(pivot.sqlAssociation)) + sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation)) if let key = key { return association.forKey(key) @@ -349,7 +349,7 @@ extension TableRecord { Pivot.RowDecoder == Target.OriginRowDecoder { let association = HasOneThroughAssociation( - sqlAssociation: target.sqlAssociation.through(pivot.sqlAssociation)) + sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation)) if let key = key { return association.forKey(key) @@ -486,10 +486,10 @@ extension TableRecord where Self: EncodableRecord { -> QueryInterfaceRequest where A.OriginRowDecoder == Self { - switch association.sqlAssociation.pivot.condition { + switch association._sqlAssociation.pivot.condition { case let .foreignKey(request: foreignKeyRequest, originIsLeft: originIsLeft): let destinationRelation = association - .sqlAssociation + ._sqlAssociation .map(\.pivot.relation, { pivotRelation in pivotRelation.filter { db in // Filter the pivot on self diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index 2eb623df6..61a24dd5c 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -135,7 +135,7 @@ extension TableRecord { public static func numberOfSelectedColumns(_ db: Database) throws -> Int { let alias = TableAlias(tableName: databaseTableName) return try databaseSelection - .map { try $0.qualifiedSelectable(with: alias).columnCount(db) } + .map { try $0._qualifiedSelectable(with: alias)._columnCount(db) } .reduce(0, +) } } diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index 789a52cb9..8f27fc9af 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -21,19 +21,13 @@ public func databaseQuestionMarks(count: Int) -> String { repeatElement("?", count: count).joined(separator: ",") } -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// /// This protocol is an implementation detail of GRDB. Don't use it. /// /// :nodoc: public protocol _OptionalProtocol { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// :nodoc: associatedtype Wrapped } -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// /// This conformance is an implementation detail of GRDB. Don't rely on it. /// /// :nodoc: diff --git a/GRDB/ValueObservation/ValueReducer/Fetch.swift b/GRDB/ValueObservation/ValueReducer/Fetch.swift index 9d0af1f0f..a15ff071c 100644 --- a/GRDB/ValueObservation/ValueReducer/Fetch.swift +++ b/GRDB/ValueObservation/ValueReducer/Fetch.swift @@ -1,6 +1,4 @@ extension ValueReducers { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// A reducer which passes raw fetched values through. /// /// :nodoc: @@ -8,8 +6,7 @@ extension ValueReducers { private let _fetch: (Database) throws -> Value public let isSelectedRegionDeterministic: Bool - /// Creates a ValueReducers.Fetch reducer, which passes raw fetched - /// values through. + /// Creates a reducer, which passes raw fetched values through. /// /// - parameter isSelectedRegionDeterministic: When true, the fetching /// function is assumed to always fetch from the same database region. diff --git a/GRDB/ValueObservation/ValueReducer/Map.swift b/GRDB/ValueObservation/ValueReducer/Map.swift index b6d10283f..86bc42421 100644 --- a/GRDB/ValueObservation/ValueReducer/Map.swift +++ b/GRDB/ValueObservation/ValueReducer/Map.swift @@ -10,12 +10,10 @@ extension ValueObservation { } extension ValueReducers { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// A reducer whose values consist of those in a `Base` reducer + /// passed through a transform function. /// - /// A _ValueReducer whose values consist of those in a Base _ValueReducer passed - /// through a transform function. - /// - /// See _ValueReducer.map(_:) + /// See `ValueObservation.map(_:)` /// /// :nodoc: public struct Map: _ValueReducer { diff --git a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift b/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift index da962ee50..4dbea9367 100644 --- a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift +++ b/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift @@ -9,9 +9,7 @@ extension ValueObservation where Reducer.Value: Equatable { } extension ValueReducers { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// See _ValueReducer.removeDuplicates() + /// See `ValueObservation.removeDuplicates()` /// /// :nodoc: public struct RemoveDuplicates: _ValueReducer where Base.Value: Equatable { diff --git a/GRDB/ValueObservation/ValueReducer/Trace.swift b/GRDB/ValueObservation/ValueReducer/Trace.swift index 8628f2e5d..ed23b7900 100644 --- a/GRDB/ValueObservation/ValueReducer/Trace.swift +++ b/GRDB/ValueObservation/ValueReducer/Trace.swift @@ -1,6 +1,4 @@ extension ValueReducers { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public struct Trace: _ValueReducer { var base: Base diff --git a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift index e8fd90982..de5c09075 100644 --- a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift +++ b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift @@ -1,5 +1,3 @@ -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// /// The _ValueReducer protocol supports ValueObservation. public protocol _ValueReducer { /// The type of fetched database values diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 1bf355df9..6b3f9ed00 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -254,8 +254,6 @@ 5656A8922295BD56001FF3FF /* SQLSpecificExpressible+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84B2295BD56001FF3FF /* SQLSpecificExpressible+QueryInterface.swift */; }; 5656A8932295BD56001FF3FF /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84C2295BD56001FF3FF /* SQLFunctions.swift */; }; 5656A8942295BD56001FF3FF /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84C2295BD56001FF3FF /* SQLFunctions.swift */; }; - 5656A8952295BD56001FF3FF /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84D2295BD56001FF3FF /* SQLCollatedExpression.swift */; }; - 5656A8962295BD56001FF3FF /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84D2295BD56001FF3FF /* SQLCollatedExpression.swift */; }; 5656A8972295BD56001FF3FF /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84E2295BD56001FF3FF /* SQLRelation.swift */; }; 5656A8982295BD56001FF3FF /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84E2295BD56001FF3FF /* SQLRelation.swift */; }; 5656A8992295BD56001FF3FF /* SQLSelectable+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84F2295BD56001FF3FF /* SQLSelectable+QueryInterface.swift */; }; @@ -503,6 +501,30 @@ 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 /* SQLOrderingVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE524B0E94C007513FC /* SQLOrderingVisitor.swift */; }; + 56F34FE724B0E94C007513FC /* SQLOrderingVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FE524B0E94C007513FC /* SQLOrderingVisitor.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 */; }; 56F409282465C8F500A7A152 /* SQLRequestProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F409262465C8F500A7A152 /* SQLRequestProtocol.swift */; }; @@ -902,7 +924,6 @@ 5656A84A2295BD56001FF3FF /* Column.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Column.swift; sourceTree = ""; }; 5656A84B2295BD56001FF3FF /* SQLSpecificExpressible+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLSpecificExpressible+QueryInterface.swift"; sourceTree = ""; }; 5656A84C2295BD56001FF3FF /* SQLFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunctions.swift; sourceTree = ""; }; - 5656A84D2295BD56001FF3FF /* SQLCollatedExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollatedExpression.swift; sourceTree = ""; }; 5656A84E2295BD56001FF3FF /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = ""; }; 5656A84F2295BD56001FF3FF /* SQLSelectable+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLSelectable+QueryInterface.swift"; sourceTree = ""; }; 5656A8502295BD56001FF3FF /* SQLQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQuery.swift; sourceTree = ""; }; @@ -1088,6 +1109,18 @@ 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 /* SQLOrderingVisitor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOrderingVisitor.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 = ""; }; 56F409262465C8F500A7A152 /* SQLRequestProtocol.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestProtocol.swift; sourceTree = ""; }; 56FBFED52210731000945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = ""; }; @@ -1341,7 +1374,6 @@ 56300B5C1C53C38F005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( - 5653EB5620961F8900F46237 /* Association */, 56B6EF5E208CB746002F0ACB /* ColumnExpressionTests.swift */, 56EA63C7209C7F1E009715B8 /* DerivableRequestTests.swift */, 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, @@ -1350,9 +1382,12 @@ 563EF45521631E3E007DAACD /* QueryInterfacePromiseTests.swift */, 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */, 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */, + 56F34FBD24B094D1007513FC /* SQLExpressionIsConstantTests.swift */, + 56F34FC524B0A0C8007513FC /* SQLIdentifyingColumnsTests.swift */, 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */, 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */, 5698AC7F1DA380A20056AF8C /* VirtualTableModuleTests.swift */, + 5653EB5620961F8900F46237 /* Association */, ); name = QueryInterface; sourceTree = ""; @@ -1484,8 +1519,13 @@ 5656A8292295BD56001FF3FF /* SQLGeneration */ = { isa = PBXGroup; children = ( + 56F34FFB24B0FB43007513FC /* SQLCollectionGenerator.swift */, + 56F34F9F24B06A29007513FC /* SQLExpressionGenerator.swift */, 5656A82B2295BD56001FF3FF /* SQLGenerationContext.swift */, + 56F34FED24B0EEA6007513FC /* SQLOrderingGenerator.swift */, 5656A82A2295BD56001FF3FF /* SQLQueryGenerator.swift */, + 56F34FDB24B0E53F007513FC /* SQLSelectableCountGenerator.swift */, + 56F34FDA24B0E53E007513FC /* SQLSelectableResultColumnGenerator.swift */, ); path = SQLGeneration; sourceTree = ""; @@ -1530,19 +1570,23 @@ 5656A84A2295BD56001FF3FF /* Column.swift */, 5656A8A52295BF44001FF3FF /* DatabasePromise.swift */, 5656A8412295BD56001FF3FF /* SQLAssociation.swift */, - 5656A84D2295BD56001FF3FF /* SQLCollatedExpression.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 /* SQLOrderingVisitor.swift */, 5656A8502295BD56001FF3FF /* SQLQuery.swift */, 5656A84E2295BD56001FF3FF /* SQLRelation.swift */, 5656A8492295BD56001FF3FF /* SQLSelectable.swift */, 5656A84F2295BD56001FF3FF /* SQLSelectable+QueryInterface.swift */, + 56F34FCD24B0DE0B007513FC /* SQLSelectableVisitor.swift */, 5656A84B2295BD56001FF3FF /* SQLSpecificExpressible+QueryInterface.swift */, ); path = SQL; @@ -2245,6 +2289,8 @@ 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 */, @@ -2274,6 +2320,7 @@ F3BA800B1CFB286D003DC1BA /* Database.swift in Sources */, F3BA80341CFB28A4003DC1BA /* Record.swift in Sources */, 56C0539422ACEECD0029D27D /* Fetch.swift in Sources */, + 56F34FE724B0E94C007513FC /* SQLOrderingVisitor.swift in Sources */, 56E9FAC52210468500C703A8 /* SQLInterpolation.swift in Sources */, 563EF421215F8A76007DAACD /* OrderedDictionary.swift in Sources */, F3BA80161CFB2876003DC1BA /* Row.swift in Sources */, @@ -2281,6 +2328,7 @@ 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 */, @@ -2289,6 +2337,7 @@ 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 */, @@ -2304,6 +2353,7 @@ 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 */, @@ -2316,6 +2366,9 @@ 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 */, F3BA800C1CFB286F003DC1BA /* DatabaseError.swift in Sources */, @@ -2366,7 +2419,7 @@ 5656A8662295BD56001FF3FF /* BelongsToAssociation.swift in Sources */, F3BA800E1CFB2876003DC1BA /* DatabaseQueue.swift in Sources */, F3BA80191CFB2876003DC1BA /* Statement.swift in Sources */, - 5656A8962295BD56001FF3FF /* SQLCollatedExpression.swift in Sources */, + 56F34FCF24B0DE0C007513FC /* SQLSelectableVisitor.swift in Sources */, 56B964A21DA51B4C0002DA19 /* FTS5.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -2559,7 +2612,9 @@ 566A84442041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, F3BA81171CFB305E003DC1BA /* QueryInterfaceExpressionsTests.swift in Sources */, 569BBA2C228DE53200478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, + 56F34FC024B094D2007513FC /* SQLExpressionIsConstantTests.swift in Sources */, 5670329C212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, + 56F34FC724B0A0C9007513FC /* SQLIdentifyingColumnsTests.swift in Sources */, F3BA810B1CFB3056003DC1BA /* Row+FoundationTests.swift in Sources */, 5698AC901DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, 56043297228F00A9009D3FE2 /* OrderedDictionaryTests.swift in Sources */, @@ -2601,6 +2656,8 @@ 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 */, @@ -2630,6 +2687,7 @@ F3BA80671CFB2E55003DC1BA /* Database.swift in Sources */, F3BA80901CFB2E7A003DC1BA /* Record.swift in Sources */, 56C0539322ACEECD0029D27D /* Fetch.swift in Sources */, + 56F34FE624B0E94C007513FC /* SQLOrderingVisitor.swift in Sources */, 56E9FAC42210468500C703A8 /* SQLInterpolation.swift in Sources */, 563EF420215F8A76007DAACD /* OrderedDictionary.swift in Sources */, F3BA80721CFB2E55003DC1BA /* Row.swift in Sources */, @@ -2637,6 +2695,7 @@ 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 */, @@ -2645,6 +2704,7 @@ 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 */, @@ -2660,6 +2720,7 @@ 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 */, @@ -2672,6 +2733,9 @@ 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 */, F3BA80681CFB2E55003DC1BA /* DatabaseError.swift in Sources */, @@ -2722,7 +2786,7 @@ 5656A8652295BD56001FF3FF /* BelongsToAssociation.swift in Sources */, F3BA806A1CFB2E55003DC1BA /* DatabaseQueue.swift in Sources */, F3BA80751CFB2E55003DC1BA /* Statement.swift in Sources */, - 5656A8952295BD56001FF3FF /* SQLCollatedExpression.swift in Sources */, + 56F34FCE24B0DE0B007513FC /* SQLSelectableVisitor.swift in Sources */, 56B9649F1DA51B4C0002DA19 /* FTS5.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -2915,7 +2979,9 @@ 566A84432041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */, 569BBA2B228DE53200478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, + 56F34FBF24B094D2007513FC /* SQLExpressionIsConstantTests.swift in Sources */, 5670329B212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, + 56F34FC624B0A0C9007513FC /* SQLIdentifyingColumnsTests.swift in Sources */, F3BA81131CFB305B003DC1BA /* DatabaseMigratorTests.swift in Sources */, F3BA81381CFB3064003DC1BA /* RecordSubClassTests.swift in Sources */, 56043296228F00A9009D3FE2 /* OrderedDictionaryTests.swift in Sources */, diff --git a/TODO.md b/TODO.md index 31f079b26..b420b5e27 100644 --- a/TODO.md +++ b/TODO.md @@ -2,7 +2,6 @@ - [ ] SQLCipher: sqlite3_rekey is discouraged (https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320) - [ ] Write regression tests for #156 and #157 -- [ ] Fix matchingRowIds (todo: what is the problem, already?) - [ ] deprecate ScopeAdapter(base, scopes), because base.addingScopes has a better implementation - [ ] https://github.com/groue/GRDB.swift/issues/514 - [ ] Test NOT TESTED methods diff --git a/Tests/GRDBTests/DatabaseRegionTests.swift b/Tests/GRDBTests/DatabaseRegionTests.swift index 6d9be0adc..614c5fe1f 100644 --- a/Tests/GRDBTests/DatabaseRegionTests.swift +++ b/Tests/GRDBTests/DatabaseRegionTests.swift @@ -294,7 +294,6 @@ class DatabaseRegionTests : GRDBTestCase { let request = Record.filter(Column("id") >= 1) try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)") } - do { let request = Record.filter((Column("id") == 1) || (Column("a") == "foo")) try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)") @@ -306,22 +305,18 @@ class DatabaseRegionTests : GRDBTestCase { let request = Record.filter(Column("id") == nil) try XCTAssertEqual(request.databaseRegion(db).description, "empty") } - do { let request = Record.filter(Column("id") === nil) try XCTAssertEqual(request.databaseRegion(db).description, "empty") } - do { let request = Record.filter(nil == Column("id")) try XCTAssertEqual(request.databaseRegion(db).description, "empty") } - do { let request = Record.filter(nil === Column("id")) try XCTAssertEqual(request.databaseRegion(db).description, "empty") } - do { let request = Record.filter((Column("id") == 1) && (Column("id") == 2)) try XCTAssertEqual(request.databaseRegion(db).description, "empty") @@ -392,6 +387,14 @@ class DatabaseRegionTests : GRDBTestCase { let request = Record.filter([1, 2, 3].contains(Column.rowID)) try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1,2,3]") } + do { + let request = Record.filter([1, 2, 3].contains(Column("id")) || [2, 3, 4].contains(Column.rowID)) + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1,2,3,4]") + } + do { + let request = Record.filter([1, 2, 3].contains(Column("id")) && [2, 3, 4].contains(Column.rowID)) + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[2,3]") + } do { let request = Record.filter(keys: [1, 2, 3]) try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1,2,3]") diff --git a/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift b/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift index e14d3df46..90382e54c 100644 --- a/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift @@ -267,6 +267,24 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase { GROUP BY "id") """) } + do { + try Player.all().group(Column.rowID + 1).deleteAll(db) + XCTAssertEqual(self.lastSQLQuery, """ + DELETE FROM "player" WHERE "id" IN (\ + SELECT "id" \ + FROM "player" \ + GROUP BY "rowid" + 1) + """) + } + do { + try Player.all().group(-Column("id")).deleteAll(db) + XCTAssertEqual(self.lastSQLQuery, """ + DELETE FROM "player" WHERE "id" IN (\ + SELECT "id" \ + FROM "player" \ + GROUP BY -"id") + """) + } do { try Player.all().group(Column.rowID).deleteAll(db) XCTAssertEqual(self.lastSQLQuery, """ diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index 1c41769e0..9ea55cc2a 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -809,6 +809,10 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { XCTAssertEqual( sql(dbQueue, tableRequest.filter(!Col.age)), "SELECT * FROM \"readers\" WHERE NOT \"age\"") + // Make sure NOT NOT "hack" is available in order to produce 0 or 1 + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(!Col.age))), + "SELECT * FROM \"readers\" WHERE NOT (NOT \"age\")") XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.age && true)), "SELECT * FROM \"readers\" WHERE \"age\" AND 1") @@ -1261,7 +1265,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { "SELECT avgOf(\"age\", 1, 2) FROM \"readers\"") } - // MARK: - FastPrimaryKeyExpression + // MARK: - _SQLExpressionFastPrimaryKey func testFastPrimaryKeyExpression() throws { struct IntegerPrimaryKeyRecord: TableRecord { } @@ -1280,19 +1284,19 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { CREATE TABLE compoundPrimaryKeyRecord (a INTEGER, b INTEGER, PRIMARY KEY (a, b)); """) - try assertEqualSQL(db, IntegerPrimaryKeyRecord.select(FastPrimaryKeyExpression()), """ + try assertEqualSQL(db, IntegerPrimaryKeyRecord.select(_SQLExpressionFastPrimaryKey()), """ SELECT "id" FROM "integerPrimaryKeyRecord" """) - try assertEqualSQL(db, UUIDRecord.select(FastPrimaryKeyExpression()), """ + try assertEqualSQL(db, UUIDRecord.select(_SQLExpressionFastPrimaryKey()), """ SELECT "rowid" FROM "uuidRecord" """) - try assertEqualSQL(db, UUIDRecordWithoutRowID.select(FastPrimaryKeyExpression()), """ + try assertEqualSQL(db, UUIDRecordWithoutRowID.select(_SQLExpressionFastPrimaryKey()), """ SELECT "uuid" FROM "uuidRecordWithoutRowID" """) - try assertEqualSQL(db, RowIDRecord.select(FastPrimaryKeyExpression()), """ + try assertEqualSQL(db, RowIDRecord.select(_SQLExpressionFastPrimaryKey()), """ SELECT "rowid" FROM "rowIDRecord" """) - try assertEqualSQL(db, CompoundPrimaryKeyRecord.select(FastPrimaryKeyExpression()), """ + try assertEqualSQL(db, CompoundPrimaryKeyRecord.select(_SQLExpressionFastPrimaryKey()), """ SELECT "rowid" FROM "compoundPrimaryKeyRecord" """) } diff --git a/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift b/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift index e153f7df0..6241ab94d 100644 --- a/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift @@ -1,83 +1,11 @@ import XCTest import GRDB -// Tests for sample code in Documentation/ExtendingGRDB.md - -// STRFTIME - -extension SQLFunctionName { - /// The `STRFTIME` SQL function - static let strftime = SQLFunctionName("STRFTIME") -} - -/// Returns an expression that evaluates the `STRFTIME` SQL function. -/// -/// // STRFTIME('%Y', date) -/// strftime("%Y", Column("date")) -func strftime(_ format: String, _ date: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionFunction(.strftime, arguments: format, date) -} - - -// MATCH - -extension SQLBinaryOperator { - /// The `MATCH` binary operator - static let match = SQLBinaryOperator("MATCH") -} - -func ~= (_ lhs: SQLExpressible, _ rhs: Column) -> SQLExpression { - SQLExpressionBinary(.match, rhs, lhs) -} - - -// CAST - private func cast(_ value: T, as type: Database.ColumnType) -> SQLExpression { SQLLiteral("CAST(\(value) AS \(sql: type.rawValue))").sqlExpression } - class QueryInterfaceExtensibilityTests: GRDBTestCase { - - func testStrftime() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try db.create(table: "records") { t in - t.column("date", .datetime) - } - struct Record : TableRecord { - static let databaseTableName = "records" - } - - let date = Date(timeIntervalSince1970: 0) - try db.execute(sql: "INSERT INTO records (date) VALUES (?)", arguments: [date]) - - let request = Record.select(strftime("%Y", Column("date"))) - let year = try Int.fetchOne(db, request) - XCTAssertEqual(year, 1970) - XCTAssertEqual(self.lastSQLQuery, "SELECT STRFTIME('%Y', \"date\") FROM \"records\" LIMIT 1") - } - } - - func testMatch() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try db.execute(sql: "CREATE VIRTUAL TABLE records USING fts3(content TEXT)") - struct Record : TableRecord { - static let databaseTableName = "records" - } - - try db.execute(sql: "INSERT INTO records (content) VALUES (?)", arguments: ["foo"]) - try db.execute(sql: "INSERT INTO records (content) VALUES (?)", arguments: ["foo bar"]) - try db.execute(sql: "INSERT INTO records (content) VALUES (?)", arguments: ["bar"]) - - let request = Record.filter("foo" ~= Column("content")) - let count = try request.fetchCount(db) - XCTAssertEqual(count, 2) - } - } - func testCast() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in diff --git a/Tests/GRDBTests/QueryInterfaceRequestTests.swift b/Tests/GRDBTests/QueryInterfaceRequestTests.swift index f5e7c3831..d2571b11f 100644 --- a/Tests/GRDBTests/QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/QueryInterfaceRequestTests.swift @@ -858,4 +858,69 @@ class QueryInterfaceRequestTests: GRDBTestCase { sql(dbQueue, tableRequest.limit(1, offset: 2).limit(3)), "SELECT * FROM \"readers\" LIMIT 3") } + + // MARK: - FetchOne Optimization + + func testFetchOneLimitOptimization() throws { + // Test that we avoid emitting "LIMIT 1" when possible + let dbQueue = try makeDatabaseQueue() + try dbQueue.read { db in + do { + _ = try Row.fetchOne(db, tableRequest.filter(key: 1)) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\" WHERE \"id\" = 1") + } + do { + _ = try Row.fetchOne(db, tableRequest.filter(Column("id") == 1)) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\" WHERE \"id\" = 1") + } + do { + _ = try Row.fetchOne(db, tableRequest.filter(Column("id") == nil)) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\" WHERE \"id\" IS NULL") + } + do { + _ = try Row.fetchOne(db, tableRequest.filter(Column("name") == "Arthur")) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\" WHERE \"name\" = \'Arthur\' LIMIT 1") + } + do { + _ = try Row.fetchOne(db, tableRequest.filter(Column("id") == 1 && Column("name") == "Arthur")) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\" WHERE (\"id\" = 1) AND (\"name\" = \'Arthur\')") + } + do { + _ = try Row.fetchOne(db, tableRequest.filter(Column("id") == 1).filter(Column("name") == "Arthur")) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\" WHERE (\"id\" = 1) AND (\"name\" = \'Arthur\')") + } + do { + _ = try Row.fetchOne(db, tableRequest.filter(Column("id"))) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\" WHERE \"id\" LIMIT 1") + } + do { + _ = try Row.fetchOne(db, tableRequest.filter(Column("id") != 1)) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\" WHERE \"id\" <> 1 LIMIT 1") + } + do { + _ = try Row.fetchOne(db, tableRequest.filter(Column("id") == 1 && Column("id") == 2)) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\" WHERE (\"id\" = 1) AND (\"id\" = 2)") + } + do { + _ = try Row.fetchOne(db, tableRequest.filter(Column("id") == 1 || Column("id") == 2)) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\" WHERE (\"id\" = 1) OR (\"id\" = 2) LIMIT 1") + } + do { + _ = try Row.fetchOne(db, tableRequest.select(max(Column("id")))) + XCTAssertEqual(lastSQLQuery, "SELECT MAX(\"id\") FROM \"readers\"") + } + do { + _ = try Row.fetchOne(db, tableRequest.select(min(Column("score")).forKey("minScore"), max(Column("score")).forKey("maxScore"))) + XCTAssertEqual(lastSQLQuery, "SELECT MIN(\"score\") AS \"minScore\", MAX(\"score\") AS \"maxScore\" FROM \"readers\"") + } + do { + _ = try Row.fetchOne(db, tableRequest.select(max(Column("score") + 1))) + XCTAssertEqual(lastSQLQuery, "SELECT MAX(\"score\" + 1) FROM \"readers\"") + } + do { + _ = try Row.fetchOne(db, tableRequest.select(max(Column("score")) + 1)) + XCTAssertEqual(lastSQLQuery, "SELECT MAX(\"score\") + 1 FROM \"readers\"") + } + } + } } diff --git a/Tests/GRDBTests/SQLExpressionIsConstantTests.swift b/Tests/GRDBTests/SQLExpressionIsConstantTests.swift new file mode 100644 index 000000000..fa3faf4f4 --- /dev/null +++ b/Tests/GRDBTests/SQLExpressionIsConstantTests.swift @@ -0,0 +1,47 @@ +import XCTest +@testable import GRDB + +class SQLExpressionIsConstantTests: XCTestCase { + func testIsConstant() { + XCTAssertTrue(1.databaseValue.isConstantInRequest) + + XCTAssertFalse(Column("a").isConstantInRequest) + + XCTAssertFalse(Column("a")._qualifiedExpression(with: TableAlias()).isConstantInRequest) + + XCTAssertTrue(SQLDateModifier.day(1).isConstantInRequest) + + XCTAssertTrue((1...3).contains(1.databaseValue).isConstantInRequest) + XCTAssertFalse((1...3).contains(Column("a")).isConstantInRequest) + + XCTAssertTrue("foo".databaseValue.collating(.binary).sqlExpression.isConstantInRequest) + XCTAssertFalse(Column("a").collating(.binary).sqlExpression.isConstantInRequest) + + 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) + + 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((1.databaseValue == 2.databaseValue).isConstantInRequest) + XCTAssertFalse((Column("a") == 2.databaseValue).isConstantInRequest) + XCTAssertFalse((1.databaseValue == Column("a")).isConstantInRequest) + + XCTAssertFalse(_SQLExpressionFastPrimaryKey().isConstantInRequest) + + XCTAssertFalse(_SQLExpressionFastPrimaryKey()._qualifiedExpression(with: TableAlias()).isConstantInRequest) + + XCTAssertTrue(length("foo".databaseValue).isConstantInRequest) + XCTAssertFalse(length(Column("a")).isConstantInRequest) + + XCTAssertTrue((!(true.databaseValue)).isConstantInRequest) + XCTAssertFalse((!Column("a")).isConstantInRequest) + + XCTAssertTrue((-(1.databaseValue)).isConstantInRequest) + XCTAssertFalse((Column("a")).isConstantInRequest) + } +} diff --git a/Tests/GRDBTests/SQLIdentifyingColumnsTests.swift b/Tests/GRDBTests/SQLIdentifyingColumnsTests.swift new file mode 100644 index 000000000..d80a333d4 --- /dev/null +++ b/Tests/GRDBTests/SQLIdentifyingColumnsTests.swift @@ -0,0 +1,30 @@ +import XCTest +@testable import GRDB + +class SQLIdentifyingColumnsTests: GRDBTestCase { + func testIdentifyingColumns() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "t") { t in + t.autoIncrementedPrimaryKey("id") + } + 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((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), []) + } + } +}