From 920417beb32cc95db5548bd8fdd8e35be885fe40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 14 Feb 2021 16:23:15 +0100 Subject: [PATCH] Replace protocols with enums --- GRDB.xcodeproj/project.pbxproj | 100 +- GRDB/Core/Database+Schema.swift | 18 + GRDB/Core/DatabaseValue.swift | 68 +- GRDB/Core/DatabaseValueConvertible.swift | 3 +- GRDB/Core/FetchRequest.swift | 121 +- GRDB/Core/SQLLiteral.swift | 165 +- GRDB/Core/SQLRequest.swift | 19 +- ...aseValueConvertible+RawRepresentable.swift | 36 +- GRDB/Fixit/GRDB-5.0.swift | 5 +- GRDB/QueryInterface/FTS3+QueryInterface.swift | 4 +- GRDB/QueryInterface/FTS5+QueryInterface.swift | 2 +- GRDB/QueryInterface/ForeignKey.swift | 1 - .../Request/Association/Association.swift | 6 +- .../Association/AssociationAggregate.swift | 12 +- .../Request/CommonTableExpression.swift | 24 +- .../Request/QueryInterfaceRequest.swift | 65 +- .../Request/RequestProtocols.swift | 6 +- GRDB/QueryInterface/SQL/Column.swift | 48 +- .../SQL/SQLCollatedExpression.swift | 51 +- GRDB/QueryInterface/SQL/SQLCollection.swift | 180 +- GRDB/QueryInterface/SQL/SQLExpressible.swift | 46 - .../SQL/SQLExpression+QueryInterface.swift | 1207 ------------- GRDB/QueryInterface/SQL/SQLExpression.swift | 1537 +++++++++++++++-- .../SQL/SQLForeignKeyRequest.swift | 2 +- GRDB/QueryInterface/SQL/SQLFunctions.swift | 26 +- GRDB/QueryInterface/SQL/SQLOperators.swift | 154 +- GRDB/QueryInterface/SQL/SQLOrdering.swift | 204 ++- GRDB/QueryInterface/SQL/SQLQuery.swift | 25 +- GRDB/QueryInterface/SQL/SQLRelation.swift | 47 +- GRDB/QueryInterface/SQL/SQLRowValue.swift | 70 - .../SQL/SQLSelectable+QueryInterface.swift | 168 -- GRDB/QueryInterface/SQL/SQLSelectable.swift | 80 - GRDB/QueryInterface/SQL/SQLSelection.swift | 334 ++++ ...QLSpecificExpressible+QueryInterface.swift | 118 -- GRDB/QueryInterface/SQL/SQLSubquery.swift | 116 ++ .../SQLGeneration/SQLGenerationContext.swift | 29 +- .../SQLGeneration/SQLQueryGenerator.swift | 116 +- .../SQLInterpolation+QueryInterface.swift | 52 +- .../TableRecord+Association.swift | 4 +- .../TableRecord+QueryInterfaceRequest.swift | 2 +- GRDB/Record/TableRecord.swift | 2 +- GRDBCustom.xcodeproj/project.pbxproj | 48 +- ...atabaseValueConvertibleEscapingTests.swift | 28 +- .../QueryInterfaceExpressionsTests.swift | 10 +- ...ntable+DatabaseValueConvertibleTests.swift | 2 + .../SQLExpressionIsConstantTests.swift | 370 ++-- .../GRDBTests/SQLExpressionLiteralTests.swift | 4 +- .../SQLIdentifyingColumnsTests.swift | 28 +- Tests/GRDBTests/SQLLiteralTests.swift | 2 +- 49 files changed, 2740 insertions(+), 3025 deletions(-) delete mode 100644 GRDB/QueryInterface/SQL/SQLExpressible.swift delete mode 100644 GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift delete mode 100644 GRDB/QueryInterface/SQL/SQLRowValue.swift delete mode 100644 GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift delete mode 100644 GRDB/QueryInterface/SQL/SQLSelectable.swift create mode 100644 GRDB/QueryInterface/SQL/SQLSelection.swift delete mode 100644 GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift create mode 100644 GRDB/QueryInterface/SQL/SQLSubquery.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 9eb23e130..e56b05cb3 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -415,12 +415,6 @@ 5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475991D97D8A000FF74B8 /* SQLCollection.swift */; }; 5664759D1D97D8A000FF74B8 /* SQLCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475991D97D8A000FF74B8 /* SQLCollection.swift */; }; 566475A01D97D8A000FF74B8 /* SQLCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475991D97D8A000FF74B8 /* SQLCollection.swift */; }; - 566475A21D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */; }; - 566475A51D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */; }; - 566475A81D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */; }; - 566475BA1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */; }; - 566475BD1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */; }; - 566475C01D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */; }; 566475CC1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */; }; 566475CF1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */; }; 566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */; }; @@ -533,6 +527,18 @@ 568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLQueryGenerator.swift */; }; 568D13202207213E00674B58 /* SQLQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLQueryGenerator.swift */; }; 568D13212207213F00674B58 /* SQLQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLQueryGenerator.swift */; }; + 568ECA8A25D7013000B71526 /* SQLSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA8925D7013000B71526 /* SQLSelection.swift */; }; + 568ECA8B25D7013000B71526 /* SQLSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA8925D7013000B71526 /* SQLSelection.swift */; }; + 568ECA8C25D7013000B71526 /* SQLSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA8925D7013000B71526 /* SQLSelection.swift */; }; + 568ECA8D25D7013000B71526 /* SQLSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA8925D7013000B71526 /* SQLSelection.swift */; }; + 568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */; }; + 568ECAA025D7E53E00B71526 /* SQLOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */; }; + 568ECAA125D7E53E00B71526 /* SQLOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */; }; + 568ECAA225D7E53E00B71526 /* SQLOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */; }; + 568ECB1825D9161600B71526 /* SQLSubquery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB1725D9161500B71526 /* SQLSubquery.swift */; }; + 568ECB1925D9161600B71526 /* SQLSubquery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB1725D9161500B71526 /* SQLSubquery.swift */; }; + 568ECB1A25D9161600B71526 /* SQLSubquery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB1725D9161500B71526 /* SQLSubquery.swift */; }; + 568ECB1B25D9161600B71526 /* SQLSubquery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB1725D9161500B71526 /* SQLSubquery.swift */; }; 5690C32A1D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */; }; 5690C33B1D23E7D200E59934 /* FoundationDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3361D23E7D200E59934 /* FoundationDateTests.swift */; }; 5690C3401D23E82A00E59934 /* Data.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C33F1D23E82A00E59934 /* Data.swift */; }; @@ -727,18 +733,9 @@ 56CEB5451EAA359A00BFAF62 /* Column.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5401EAA359A00BFAF62 /* Column.swift */; }; 56CEB5481EAA359A00BFAF62 /* Column.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5401EAA359A00BFAF62 /* Column.swift */; }; 56CEB54B1EAA359A00BFAF62 /* Column.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5401EAA359A00BFAF62 /* Column.swift */; }; - 56CEB54C1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */; }; - 56CEB54F1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */; }; - 56CEB5521EAA359A00BFAF62 /* SQLExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */; }; 56CEB5531EAA359A00BFAF62 /* SQLExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */; }; 56CEB5561EAA359A00BFAF62 /* SQLExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */; }; 56CEB5591EAA359A00BFAF62 /* SQLExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */; }; - 56CEB55A1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */; }; - 56CEB55D1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */; }; - 56CEB5601EAA359A00BFAF62 /* SQLOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */; }; - 56CEB5611EAA359A00BFAF62 /* SQLSelectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */; }; - 56CEB5641EAA359A00BFAF62 /* SQLSelectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */; }; - 56CEB5671EAA359A00BFAF62 /* SQLSelectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */; }; 56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */; }; 56D496551D812F83008276D7 /* FoundationDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */; }; 56D496571D81303E008276D7 /* FoundationDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */; }; @@ -822,10 +819,6 @@ 56D51D001EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; 56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; 56D51D061EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; - 56D8B3FF257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */; }; - 56D8B400257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */; }; - 56D8B401257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */; }; - 56D8B402257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */; }; 56D91AA22205E03700770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA12205E03700770D8D /* SQLRelation.swift */; }; 56D91AA32205E03700770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA12205E03700770D8D /* SQLRelation.swift */; }; 56D91AA42205E03700770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA12205E03700770D8D /* SQLRelation.swift */; }; @@ -887,9 +880,6 @@ 56FBFED92210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; }; 56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; }; 56FBFEDB2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; }; - 56FC98781D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; }; - 56FC987B1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; }; - 56FC987E1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; }; 56FDECE31BB32DFD009AD709 /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; }; 56FEB8F8248403000081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */; }; 56FEB8F9248403010081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */; }; @@ -936,13 +926,11 @@ AAA4DC9A230F1E0600C74B15 /* FTS5TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */; }; AAA4DC9B230F1E0600C74B15 /* SerializedDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */; }; AAA4DC9C230F1E0600C74B15 /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84192041146100E50BFD /* DatabaseSnapshot.swift */; }; - AAA4DC9D230F1E0600C74B15 /* SQLExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */; }; AAA4DC9E230F1E0600C74B15 /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; AAA4DC9F230F1E0600C74B15 /* NSString.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1521C672E4000235C62 /* NSString.swift */; }; AAA4DCA0230F1E0600C74B15 /* Database+Statements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91081FA4C3960012D5B0 /* Database+Statements.swift */; }; AAA4DCA1230F1E0600C74B15 /* UUID.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C22F1D1914540096E9D4 /* UUID.swift */; }; AAA4DCA2230F1E0600C74B15 /* DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */; }; - AAA4DCA3230F1E0600C74B15 /* SQLSpecificExpressible+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */; }; AAA4DCA4230F1E0600C74B15 /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; AAA4DCA5230F1E0600C74B15 /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; }; AAA4DCA6230F1E0600C74B15 /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; @@ -967,7 +955,6 @@ AAA4DCBA230F1E0600C74B15 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; }; AAA4DCBB230F1E0600C74B15 /* DatabaseValueConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */; }; AAA4DCBC230F1E0600C74B15 /* DatabaseCollation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91121FA4C3F50012D5B0 /* DatabaseCollation.swift */; }; - AAA4DCBD230F1E0600C74B15 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; }; AAA4DCBE230F1E0600C74B15 /* Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238761B9C75030082EB20 /* Row.swift */; }; AAA4DCC1230F1E0600C74B15 /* Inflections.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF4492161F179007DAACD /* Inflections.swift */; }; AAA4DCC2230F1E0600C74B15 /* FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */; }; @@ -1001,15 +988,12 @@ AAA4DCE0230F1E0600C74B15 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */; }; AAA4DCE2230F1E0600C74B15 /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */; }; AAA4DCE3230F1E0600C74B15 /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3421A95A5C00DC7A68 /* Map.swift */; }; - AAA4DCE4230F1E0600C74B15 /* SQLSelectable+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */; }; AAA4DCE5230F1E0600C74B15 /* SQLLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAD7221053DC00C703A8 /* SQLLiteral.swift */; }; AAA4DCE6230F1E0600C74B15 /* SQLForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAF920944C7B00F46237 /* SQLForeignKeyRequest.swift */; }; AAA4DCE7230F1E0600C74B15 /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; AAA4DCEA230F1E0600C74B15 /* DatabaseValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238751B9C75030082EB20 /* DatabaseValue.swift */; }; - AAA4DCEB230F1E0600C74B15 /* SQLOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */; }; AAA4DCEC230F1E0600C74B15 /* Database+Schema.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91221FA4CF810012D5B0 /* Database+Schema.swift */; }; AAA4DCED230F1E0600C74B15 /* StatementAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */; }; - AAA4DCEE230F1E0600C74B15 /* SQLSelectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */; }; AAA4DCEF230F1E0600C74B15 /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA12205E03700770D8D /* SQLRelation.swift */; }; AAA4DCF0230F1E0600C74B15 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; AAA4DCF1230F1E0600C74B15 /* RemoveDuplicates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* RemoveDuplicates.swift */; }; @@ -1405,8 +1389,6 @@ 565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NumericOverflowTests.swift; sourceTree = ""; }; 565F03C11CE5D3AA00DE108F /* RowAdapterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowAdapterTests.swift; sourceTree = ""; }; 566475991D97D8A000FF74B8 /* SQLCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollection.swift; sourceTree = ""; }; - 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLSelectable+QueryInterface.swift"; sourceTree = ""; }; - 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLSpecificExpressible+QueryInterface.swift"; sourceTree = ""; }; 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunctions.swift; sourceTree = ""; }; 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperators.swift; sourceTree = ""; }; 5665F85C203EE6030084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = ""; }; @@ -1455,6 +1437,9 @@ 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationScheduler.swift; sourceTree = ""; }; 5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 568D13182207213E00674B58 /* SQLQueryGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQueryGenerator.swift; sourceTree = ""; }; + 568ECA8925D7013000B71526 /* SQLSelection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelection.swift; sourceTree = ""; }; + 568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOrdering.swift; sourceTree = ""; }; + 568ECB1725D9161500B71526 /* SQLSubquery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSubquery.swift; sourceTree = ""; }; 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateComponentsTests.swift; sourceTree = ""; }; 5690C3361D23E7D200E59934 /* FoundationDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateTests.swift; sourceTree = ""; }; 5690C33F1D23E82A00E59934 /* Data.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Data.swift; sourceTree = ""; }; @@ -1571,13 +1556,9 @@ 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FTS3+QueryInterface.swift"; sourceTree = ""; }; 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FTS5+QueryInterface.swift"; sourceTree = ""; }; 56CEB5401EAA359A00BFAF62 /* Column.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Column.swift; sourceTree = ""; }; - 56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpressible.swift; sourceTree = ""; }; 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpression.swift; sourceTree = ""; }; - 56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOrdering.swift; sourceTree = ""; }; - 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectable.swift; sourceTree = ""; }; 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = ""; }; - 56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRowValue.swift; sourceTree = ""; }; 56D91AA12205E03700770D8D /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = ""; }; 56D91AA82205F2F000770D8D /* DatabasePromise.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePromise.swift; sourceTree = ""; }; 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQuery.swift; sourceTree = ""; }; @@ -1604,7 +1585,6 @@ 56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLIdentifyingColumnsTests.swift; sourceTree = ""; }; 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = ""; }; 56FBFED82210731A00945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = ""; }; - 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = ""; }; 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = ""; }; 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseTraceTests.swift; sourceTree = ""; }; 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = ""; }; @@ -2052,19 +2032,15 @@ 5656A81D2295B12F001FF3FF /* SQLAssociation.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, - 56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */, 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */, - 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */, 5653EAF920944C7B00F46237 /* SQLForeignKeyRequest.swift */, 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */, 566475CB1D981D5E00FF74B8 /* SQLOperators.swift */, - 56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */, + 568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */, 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */, 56D91AA12205E03700770D8D /* SQLRelation.swift */, - 56D8B3FE257D0FAA008AA1F7 /* SQLRowValue.swift */, - 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */, - 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */, - 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */, + 568ECA8925D7013000B71526 /* SQLSelection.swift */, + 568ECB1725D9161500B71526 /* SQLSubquery.swift */, ); path = SQL; sourceTree = ""; @@ -2876,11 +2852,11 @@ 565490E41D5AE252005622CB /* TableRecord.swift in Sources */, 564CE5AE21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */, 565490CF1D5AE252005622CB /* NSNumber.swift in Sources */, - 566475C01D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 56CEB51F1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, 56D91AA42205E03700770D8D /* SQLRelation.swift in Sources */, 565490E21D5AE252005622CB /* Record.swift in Sources */, 565490C11D5AE236005622CB /* FetchRequest.swift in Sources */, + 568ECB1A25D9161600B71526 /* SQLSubquery.swift in Sources */, 5613ED4621A95B2C00DC7A68 /* ValueReducer.swift in Sources */, 5698AD1C1DAAD17F0056AF8C /* FTS5Tokenizer.swift in Sources */, 56CEB5171EAA324B00BFAF62 /* FTS3+QueryInterface.swift in Sources */, @@ -2891,21 +2867,18 @@ 564CE59F21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */, 56F5ABDA1D814330001F60CB /* NSData.swift in Sources */, 564F9C341F07611900877A00 /* DatabaseFunction.swift in Sources */, - 566475A81D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5659F4961EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 56172950223533F40006E219 /* EncodableRecord.swift in Sources */, 56AE64142229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */, 5613ED3721A95A5C00DC7A68 /* Map.swift in Sources */, 5659F48E1EA8D94E004A4992 /* Utils.swift in Sources */, 564CE43321AA901800652B19 /* ValueObserver.swift in Sources */, - 56CEB5671EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 563B8FC724A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */, 565490B91D5AE236005622CB /* DatabasePool.swift in Sources */, 563B06AD217EF0CC00B38F35 /* ValueObservation.swift in Sources */, 5674A6EF1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 565490D81D5AE252005622CB /* DatabaseMigrator.swift in Sources */, 5656A8AF2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */, - 56CEB5601EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, 565490C21D5AE236005622CB /* Row.swift in Sources */, 565490C71D5AE236005622CB /* StatementColumnConvertible.swift in Sources */, 565490D91D5AE252005622CB /* Migration.swift in Sources */, @@ -2925,6 +2898,7 @@ 565490BF1D5AE236005622CB /* DatabaseValueConvertible.swift in Sources */, 566B91191FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 56CEB5591EAA359A00BFAF62 /* SQLExpression.swift in Sources */, + 568ECA8C25D7013000B71526 /* SQLSelection.swift in Sources */, 5674A6FF1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, 56E9FAD9221053DD00C703A8 /* SQLLiteral.swift in Sources */, 563082E62430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */, @@ -2953,9 +2927,9 @@ 56CEB54B1EAA359A00BFAF62 /* Column.swift in Sources */, 565490CC1D5AE252005622CB /* (null) in Sources */, 566B91291FA4CF810012D5B0 /* Database+Schema.swift in Sources */, + 568ECAA125D7E53E00B71526 /* SQLOrdering.swift in Sources */, 5671FC261DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 5653EC142098738B00F46237 /* SQLGenerationContext.swift in Sources */, - 56CEB5521EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 563B8F94249E6171007A48C9 /* Trace.swift in Sources */, 568D13212207213F00674B58 /* SQLQueryGenerator.swift in Sources */, 565490DB1D5AE252005622CB /* SQLCollatedExpression.swift in Sources */, @@ -2969,7 +2943,6 @@ 566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, 565490B61D5AE236005622CB /* Configuration.swift in Sources */, 565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */, - 56FC987E1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, 569BBA50229170FA00478429 /* Inflections+English.swift in Sources */, 563B8FB724A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */, 566B91391FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, @@ -2988,7 +2961,6 @@ 565490D61D5AE252005622CB /* StandardLibrary.swift in Sources */, 565490B81D5AE236005622CB /* DatabaseError.swift in Sources */, 56DAA2E11DE9C827006E10C8 /* Cursor.swift in Sources */, - 56D8B401257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */, 5653EB0520944C7C00F46237 /* BelongsToAssociation.swift in Sources */, 5644DE6F20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */, 56A2FA3C24424F4800E97D23 /* Export.swift in Sources */, @@ -3024,6 +2996,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 568ECAA025D7E53E00B71526 /* SQLOrdering.swift in Sources */, 5636E9BF1D22574100B9B05F /* FetchRequest.swift in Sources */, 563EF42E2161180D007DAACD /* AssociationAggregate.swift in Sources */, 56BB6EAC1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, @@ -3044,6 +3017,7 @@ 5605F1641C672E4000235C62 /* Date.swift in Sources */, 566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 564CE43221AA901800652B19 /* ValueObserver.swift in Sources */, + 568ECA8B25D7013000B71526 /* SQLSelection.swift in Sources */, 56AACAA922ACED7100A40F2A /* Fetch.swift in Sources */, 5605F1721C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 56CEB5141EAA324B00BFAF62 /* FTS3+QueryInterface.swift in Sources */, @@ -3064,13 +3038,11 @@ 563B8FB624A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */, 560A37A81C8FF6E500949E71 /* SerializedDatabase.swift in Sources */, 566A841B2041146100E50BFD /* DatabaseSnapshot.swift in Sources */, - 56CEB54F1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 56A238941B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */, 5605F16A1C672E4000235C62 /* NSString.swift in Sources */, 566B910C1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 56A8C2331D1914540096E9D4 /* UUID.swift in Sources */, 560D92411C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */, - 566475BD1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 56A238A51B9C753B0082EB20 /* Record.swift in Sources */, 5671FC231DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, @@ -3099,7 +3071,6 @@ 5674A7001F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, 5674A6E91F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, 566B91161FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, - 56FC987B1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, 56A238881B9C75030082EB20 /* Row.swift in Sources */, 563EF44B2161F179007DAACD /* Inflections.swift in Sources */, 56CEB4F41EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, @@ -3122,8 +3093,8 @@ 5653EB0D20944C7C00F46237 /* HasManyAssociation.swift in Sources */, 567ECE502222E431009245CA /* GRDB-5.0.swift in Sources */, 566AD8B51D5318F4002EC1A8 /* TableDefinition.swift in Sources */, - 56D8B400257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */, 5698AD241DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, + 568ECB1925D9161600B71526 /* SQLSubquery.swift in Sources */, 56FBFED92210731A00945324 /* SQLRequest.swift in Sources */, 5644DE6E20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */, C96C0F2C2084A459006B2981 /* SQLiteDateParser.swift in Sources */, @@ -3137,16 +3108,13 @@ 5613ED4521A95B2C00DC7A68 /* ValueReducer.swift in Sources */, 560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */, 5613ED3621A95A5C00DC7A68 /* Map.swift in Sources */, - 566475A51D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 56E9FAD8221053DD00C703A8 /* SQLLiteral.swift in Sources */, 56781B0C243F86E600650A83 /* Refinable.swift in Sources */, 5653EB0720944C7C00F46237 /* SQLForeignKeyRequest.swift in Sources */, 5657AABC1D107001006283EF /* NSData.swift in Sources */, 56A238861B9C75030082EB20 /* DatabaseValue.swift in Sources */, - 56CEB55D1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, 566B91261FA4CF810012D5B0 /* Database+Schema.swift in Sources */, 566B912E1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, - 56CEB5641EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56D91AA32205E03700770D8D /* SQLRelation.swift in Sources */, 564F9C311F07611600877A00 /* DatabaseFunction.swift in Sources */, 564CE59E21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */, @@ -3611,6 +3579,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 568ECAA225D7E53E00B71526 /* SQLOrdering.swift in Sources */, AAA4DC77230F1E0600C74B15 /* FetchRequest.swift in Sources */, AAA4DC78230F1E0600C74B15 /* AssociationAggregate.swift in Sources */, AAA4DC79230F1E0600C74B15 /* SchedulingWatchdog.swift in Sources */, @@ -3631,6 +3600,7 @@ AAA4DC87230F1E0600C74B15 /* Date.swift in Sources */, AAA4DC89230F1E0600C74B15 /* TransactionObserver.swift in Sources */, AAA4DC8A230F1E0600C74B15 /* ValueObserver.swift in Sources */, + 568ECA8D25D7013000B71526 /* SQLSelection.swift in Sources */, AAA4DC8B230F1E0600C74B15 /* Fetch.swift in Sources */, AAA4DC8C230F1E0600C74B15 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, AAA4DC8D230F1E0600C74B15 /* FTS3+QueryInterface.swift in Sources */, @@ -3651,13 +3621,11 @@ 563B8FB824A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */, AAA4DC9B230F1E0600C74B15 /* SerializedDatabase.swift in Sources */, AAA4DC9C230F1E0600C74B15 /* DatabaseSnapshot.swift in Sources */, - AAA4DC9D230F1E0600C74B15 /* SQLExpressible.swift in Sources */, AAA4DC9E230F1E0600C74B15 /* DatabaseMigrator.swift in Sources */, AAA4DC9F230F1E0600C74B15 /* NSString.swift in Sources */, AAA4DCA0230F1E0600C74B15 /* Database+Statements.swift in Sources */, AAA4DCA1230F1E0600C74B15 /* UUID.swift in Sources */, AAA4DCA2230F1E0600C74B15 /* DatabaseValueConvertible.swift in Sources */, - AAA4DCA3230F1E0600C74B15 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, AAA4DCA4230F1E0600C74B15 /* Record.swift in Sources */, AAA4DCA5230F1E0600C74B15 /* FTS3TokenizerDescriptor.swift in Sources */, AAA4DCA6230F1E0600C74B15 /* FetchableRecord+TableRecord.swift in Sources */, @@ -3686,7 +3654,6 @@ AAA4DCBA230F1E0600C74B15 /* FetchableRecord+Decodable.swift in Sources */, AAA4DCBB230F1E0600C74B15 /* DatabaseValueConvertible+Decodable.swift in Sources */, AAA4DCBC230F1E0600C74B15 /* DatabaseCollation.swift in Sources */, - AAA4DCBD230F1E0600C74B15 /* SQLExpression+QueryInterface.swift in Sources */, AAA4DCBE230F1E0600C74B15 /* Row.swift in Sources */, AAA4DCC1230F1E0600C74B15 /* Inflections.swift in Sources */, AAA4DCC2230F1E0600C74B15 /* FetchableRecord.swift in Sources */, @@ -3709,8 +3676,8 @@ AAA4DCD2230F1E0600C74B15 /* HasManyAssociation.swift in Sources */, AAA4DCD3230F1E0600C74B15 /* GRDB-5.0.swift in Sources */, AAA4DCD4230F1E0600C74B15 /* TableDefinition.swift in Sources */, - 56D8B402257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */, AAA4DCD5230F1E0600C74B15 /* FTS5WrapperTokenizer.swift in Sources */, + 568ECB1B25D9161600B71526 /* SQLSubquery.swift in Sources */, AAA4DCD6230F1E0600C74B15 /* SQLRequest.swift in Sources */, AAA4DCD7230F1E0600C74B15 /* DatabaseValueConversion.swift in Sources */, AAA4DCD8230F1E0600C74B15 /* SQLiteDateParser.swift in Sources */, @@ -3724,16 +3691,13 @@ AAA4DCE0230F1E0600C74B15 /* ValueReducer.swift in Sources */, AAA4DCE2230F1E0600C74B15 /* StatementColumnConvertible.swift in Sources */, AAA4DCE3230F1E0600C74B15 /* Map.swift in Sources */, - AAA4DCE4230F1E0600C74B15 /* SQLSelectable+QueryInterface.swift in Sources */, AAA4DCE5230F1E0600C74B15 /* SQLLiteral.swift in Sources */, 56781B0E243F86E600650A83 /* Refinable.swift in Sources */, AAA4DCE6230F1E0600C74B15 /* SQLForeignKeyRequest.swift in Sources */, AAA4DCE7230F1E0600C74B15 /* NSData.swift in Sources */, AAA4DCEA230F1E0600C74B15 /* DatabaseValue.swift in Sources */, - AAA4DCEB230F1E0600C74B15 /* SQLOrdering.swift in Sources */, AAA4DCEC230F1E0600C74B15 /* Database+Schema.swift in Sources */, AAA4DCED230F1E0600C74B15 /* StatementAuthorizer.swift in Sources */, - AAA4DCEE230F1E0600C74B15 /* SQLSelectable.swift in Sources */, AAA4DCEF230F1E0600C74B15 /* SQLRelation.swift in Sources */, AAA4DCF0230F1E0600C74B15 /* DatabaseFunction.swift in Sources */, AAA4DCF1230F1E0600C74B15 /* RemoveDuplicates.swift in Sources */, @@ -3972,6 +3936,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */, 563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */, 56D91AB02205F8AC00770D8D /* SQLQuery.swift in Sources */, 5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */, @@ -3992,11 +3957,11 @@ 56CEB4F11EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 56D91AA22205E03700770D8D /* SQLRelation.swift in Sources */, 56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */, + 568ECA8A25D7013000B71526 /* SQLSelection.swift in Sources */, 56AACAA822ACED7100A40F2A /* Fetch.swift in Sources */, 5605F18D1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */, 566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 566475D31D981D5E00FF74B8 /* SQLOperators.swift in Sources */, - 56CEB5611EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56CEB4FA1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 563082E42430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */, 564CE59D21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */, @@ -4016,7 +3981,6 @@ 5659F4981EA8D989004A4992 /* Pool.swift in Sources */, 56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */, 5674A6F41F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, - 56CEB54C1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 567404881CEF84C8003ED5CC /* RowAdapter.swift in Sources */, 5653EB0320944C7C00F46237 /* BelongsToAssociation.swift in Sources */, @@ -4034,11 +3998,9 @@ 56A8C2301D1914540096E9D4 /* UUID.swift in Sources */, 56CEB5011EAA2F4D00BFAF62 /* FTS4.swift in Sources */, 56AE64122229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */, - 56CEB55A1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, 56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */, 56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */, 56D51D001EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, - 566475BA1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 5653EB0920944C7C00F46237 /* Association.swift in Sources */, 56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */, 5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, @@ -4058,7 +4020,6 @@ 5656A8AD2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */, 5690C3401D23E82A00E59934 /* Data.swift in Sources */, 5659F4881EA8D94E004A4992 /* Utils.swift in Sources */, - 56FC98781D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, 566BE71E2342542F00A8254B /* LockedBox.swift in Sources */, 56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */, 5611620825757583007AAF99 /* JoinAssociation.swift in Sources */, @@ -4070,10 +4031,10 @@ 56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, 56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */, 563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */, - 56D8B3FF257D0FAA008AA1F7 /* SQLRowValue.swift in Sources */, 564CE43121AA901800652B19 /* ValueObserver.swift in Sources */, 5605F1651C672E4000235C62 /* NSNull.swift in Sources */, 56CEB5191EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, + 568ECB1825D9161600B71526 /* SQLSubquery.swift in Sources */, 5674A6FB1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, 5653EB0620944C7C00F46237 /* SQLForeignKeyRequest.swift in Sources */, 56E9FACB221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */, @@ -4092,7 +4053,6 @@ 5605F1731C672E4000235C62 /* StandardLibrary.swift in Sources */, 5653EC122098738B00F46237 /* SQLGenerationContext.swift in Sources */, 560D92471C672C4B00F4F92B /* PersistableRecord.swift in Sources */, - 566475A21D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5674A6E41F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, 5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */, 5644DE6D20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */, diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 70c70c713..5b8effbb0 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -669,6 +669,24 @@ public struct PrimaryKeyInfo { return tableHasRowID } } + + /// The name of the fastest primary key column + /// + /// Returns nil for WITHOUT ROWID tables with a multi-columns primary key + var fastPrimaryKeyColumn: String? { + if let rowIDColumn = rowIDColumn { + // Prefer the user-provided name of the rowid + return rowIDColumn + } else if tableHasRowID { + // Prefer the rowid + return Column.rowID.name + } else if columns.count == 1 { + // WITHOUT ROWID table: use primary key column + return columns[0] + } else { + return nil + } + } } /// You get foreign keys from table names, with the diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index 47b7552bd..60e75ca47 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -5,7 +5,7 @@ import Foundation /// DatabaseValue is the intermediate type between SQLite and your values. /// /// See https://www.sqlite.org/datatype3.html -public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLExpression { +public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLSpecificExpressible { /// The SQLite storage public let storage: Storage @@ -137,69 +137,6 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon fatalError("Unexpected SQLite column type: \(type)") } } - - // MARK: SQLExpression - - /// :nodoc: - public func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - if isNull { - // fast path for NULL - return "NULL" - } else if context.append(arguments: [self]) { - // Use statement arguments - return "?" - } else { - // Quoting needed: just use SQLite, which knows better. - return try String.fetchOne(context.db, sql: "SELECT QUOTE(?)", arguments: [self])! - } - } - - /// :nodoc: - public func _identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set? { - if isNull || self == false.databaseValue { - // Those requests select no row: - // - WHERE NULL - // - WHERE 0 - return [] - } - return nil - } - - // Specific boolean checks for null, true, and false - /// :nodoc: - public func _is(_ test: _SQLBooleanTest) -> SQLExpression { - switch storage { - case .null: - return DatabaseValue.null - - case .int64(let int64) where int64 == 0 || int64 == 1: - switch test { - case .true: - return (int64 == 1).sqlExpression - case .false, .falsey: - return (int64 == 0).sqlExpression - } - - default: - switch test { - case .true: - return SQLExpressionEqual(.equal, self, true.sqlExpression) - case .false: - return SQLExpressionEqual(.equal, self, false.sqlExpression) - case .falsey: - return SQLExpressionNot(self) - } - } - } - - /// :nodoc: - public var _isConstantInRequest: Bool { true } - - /// :nodoc: - public var _isTrue: Bool { self == true.databaseValue } - - /// :nodoc: - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { self } } // MARK: - Hashable & Equatable @@ -276,9 +213,8 @@ extension DatabaseValue { // SQLExpressible extension DatabaseValue { - /// :nodoc: public var sqlExpression: SQLExpression { - self + .databaseValue(self) } } diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 8ba472cec..d0089929e 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -23,9 +23,8 @@ public protocol DatabaseValueConvertible: SQLExpressible { } extension DatabaseValueConvertible { - /// :nodoc: public var sqlExpression: SQLExpression { - databaseValue + .databaseValue(databaseValue) } } diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index 85c0b3a4d..1c4ae00b5 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -1,53 +1,5 @@ // MARK: - FetchRequest -/// Implementation details of `FetchRequest`. -/// -/// :nodoc: -public protocol _FetchRequest { - /// The number of columns selected by the request. - /// - /// This method makes it possible to find the columns of a CTE in a request - /// that includes a CTE association: - /// - /// // WITH cte AS (SELECT 1 AS a, 2 AS b) - /// // SELECT player.*, cte.* - /// // FROM player - /// // JOIN cte - /// let cte = CommonTableExpression(named: "cte", sql: "SELECT 1 AS a, 2 AS b") - /// let request = Player - /// .with(cte) - /// .including(required: Player.association(to: cte)) - /// let row = try Row.fetchOne(db, request)! - /// - /// // We know that "SELECT 1 AS a, 2 AS b" selects two columns, - /// // so we can find cte columns in the row: - /// row.scopes["cte"] // [a:1, b:2] - /// - /// :nodoc: - func _selectedColumnCount(_ db: Database) throws -> Int - - /// Returns the request SQL. - /// - /// This method makes it possible to embed a request as a subquery: - /// - /// // SELECT * - /// // FROM "player" - /// // WHERE "score" = (SELECT MAX("score") FROM "player") - /// let maxScore = Player.select(max(Column("score"))) - /// let players = try Player - /// .filter(Column("score") == maxScore) - /// .fetchAll(db) - /// - /// - parameter context: An SQL generation context. - /// - parameter singleResult: A hint that a single result row will be - /// consumed. Implementations can optionally use it to optimize the - /// generated SQL, for example by adding a `LIMIT 1` SQL clause. - /// - returns: An SQL string. - /// - /// :nodoc: - func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String -} - /// The protocol for all requests that fetch database rows, and tell how those /// rows should be interpreted. /// @@ -58,7 +10,7 @@ public protocol _FetchRequest { /// try request.fetchSet(db) // Set /// try request.fetchOne(db) // Player? /// try request.fetchCount(db) // Int -public protocol FetchRequest: _FetchRequest, DatabaseRegionConvertible, SQLExpression, SQLCollection { +public protocol FetchRequest: SQLSubqueryable, DatabaseRegionConvertible { /// The type that tells how fetched database rows should be interpreted. associatedtype RowDecoder @@ -84,45 +36,12 @@ public protocol FetchRequest: _FetchRequest, DatabaseRegionConvertible, SQLExpre } extension FetchRequest { - // MARK: DatabaseRegionConvertible - /// Returns the database region that the request feeds from. /// /// - parameter db: A database connection. public func databaseRegion(_ db: Database) throws -> DatabaseRegion { try makePreparedRequest(db, forSingleResult: false).statement.databaseRegion } - - // MARK: SQLCollection - - /// :nodoc: - public var _collectionExpressions: [SQLExpression]? { nil } - - /// :nodoc: - public func _collectionSQL(_ context: SQLGenerationContext) throws -> String { - try "(" - + _requestSQL(context, forSingleResult: false) - + ")" - } - - public func contains(_ value: SQLExpressible) -> SQLExpression { - SQLExpressionContains(value, self) - } - - /// :nodoc: - public func _qualifiedCollection(with alias: TableAlias) -> SQLCollection { self } - - // MARK: SQLExpression - - /// :nodoc: - public func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - try "(" - + _requestSQL(context, forSingleResult: false) - + ")" - } - - /// :nodoc: - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { self } } // MARK: - PreparedRequest @@ -174,6 +93,10 @@ public struct AdaptedFetchRequest: FetchRequest { self.adapter = adapter } + public var sqlSubquery: SQLSubquery { + base.sqlSubquery + } + public func fetchCount(_ db: Database) throws -> Int { try base.fetchCount(db) } @@ -193,16 +116,6 @@ public struct AdaptedFetchRequest: FetchRequest { return preparedRequest } - - /// :nodoc: - public func _selectedColumnCount(_ db: Database) throws -> Int { - try base._selectedColumnCount(db) - } - - /// :nodoc: - public func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { - try base._requestSQL(context, forSingleResult: singleResult) - } } // MARK: - AnyFetchRequest @@ -222,9 +135,8 @@ public struct AnyFetchRequest: FetchRequest { AnyFetchRequest(request: request) } - /// :nodoc: - public func _selectedColumnCount(_ db: Database) throws -> Int { - try request._selectedColumnCount(db) + public var sqlSubquery: SQLSubquery { + request.sqlSubquery } public func fetchCount(_ db: Database) throws -> Int { @@ -238,11 +150,6 @@ public struct AnyFetchRequest: FetchRequest { { try request.makePreparedRequest(db, forSingleResult: singleResult) } - - /// :nodoc: - public func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { - try request._requestSQL(context, forSingleResult: singleResult) - } } extension AnyFetchRequest { @@ -258,7 +165,7 @@ extension AnyFetchRequest { private class FetchRequestEraser: FetchRequest { typealias RowDecoder = Void - func _selectedColumnCount(_ db: Database) throws -> Int { + var sqlSubquery: SQLSubquery { fatalError("subclass must override") } @@ -269,10 +176,6 @@ private class FetchRequestEraser: FetchRequest { func fetchCount(_ db: Database) throws -> Int { fatalError("subclass must override") } - - func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { - fatalError("subclass must override") - } } private final class ConcreteFetchRequestEraser: FetchRequestEraser { @@ -282,8 +185,8 @@ private final class ConcreteFetchRequestEraser: FetchRequ self.request = request } - override func _selectedColumnCount(_ db: Database) throws -> Int { - try request._selectedColumnCount(db) + override var sqlSubquery: SQLSubquery { + request.sqlSubquery } override func fetchCount(_ db: Database) throws -> Int { @@ -293,8 +196,4 @@ private final class ConcreteFetchRequestEraser: FetchRequ override func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { try request.makePreparedRequest(db, forSingleResult: singleResult) } - - override func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { - try request._requestSQL(context, forSingleResult: singleResult) - } } diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index 4e4b4f1d4..3697893cb 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -16,11 +16,11 @@ public struct SQLLiteral { // Can't be qualified with a table alias case sql(String, StatementArguments = StatementArguments()) // Does not need to be qualified with a table alias - case subquery(DatabasePromise<_FetchRequest>) + case subquery(SQLSubquery) // Cases below can be qualified with a table alias case expression(SQLExpression) - case selectable(SQLSelectable) - case orderingTerm(SQLOrderingTerm) + case selection(SQLSelection) + case ordering(SQLOrdering) var isEmpty: Bool { switch self { @@ -40,14 +40,14 @@ public struct SQLLiteral { fatalError("Not implemented: turning an SQL parameter into an SQL literal value") } return sql - case let .subquery(requestPromise): - return try requestPromise.resolve(context.db)._requestSQL(context, forSingleResult: false) + case let .subquery(subquery): + return try subquery.sql(context) case let .expression(expression): - return try expression._expressionSQL(context, wrappedInParenthesis: false) - case let .selectable(selectable): - return try selectable._resultColumnSQL(context) - case let .orderingTerm(orderingTerm): - return try orderingTerm._orderingTermSQL(context) + return try expression.sql(context) + case let .selection(selection): + return try selection.sql(context) + case let .ordering(ordering): + return try ordering.sql(context) } } @@ -60,11 +60,11 @@ public struct SQLLiteral { // Subqueries don't need table alias return self case let .expression(expression): - return .expression(expression._qualifiedExpression(with: alias)) - case let .selectable(selectable): - return .selectable(selectable._qualifiedSelectable(with: alias)) - case let .orderingTerm(orderingTerm): - return .orderingTerm(orderingTerm._qualifiedOrdering(with: alias)) + return .expression(expression.qualified(with: alias)) + case let .selection(selection): + return .selection(selection.qualified(with: alias)) + case let .ordering(ordering): + return .ordering(ordering.qualified(with: alias)) } } } @@ -95,8 +95,8 @@ public struct SQLLiteral { /// let emailLiteral = [columnLiteral, suffixLiteral].joined(separator: " || ") /// let request = User.select(emailLiteral.sqlExpression) /// let emails = try String.fetchAll(db, request) - public init(_ expression: SQLExpression) { - self.init(elements: [.expression(expression)]) + public init(_ expression: SQLSpecificExpressible) { + self.init(elements: [.expression(expression.sqlExpression)]) } /// Returns true if this literal generates an empty SQL string @@ -172,15 +172,15 @@ extension SQLLiteral { /// SQLLiteral(sql: "? + ?", arguments: [1, 2]).sqlExpression /// SQLLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]).sqlExpression public var sqlExpression: SQLExpression { - SQLExpressionLiteral(sqlLiteral: self) + .literal(self) } - var sqlSelectable: SQLSelectable { - SQLSelectionLiteral(sqlLiteral: self) + var sqlSelection: SQLSelection { + .literal(self) } - var sqlOrderingTerm: SQLOrderingTerm { - SQLOrderingLiteral(sqlLiteral: self) + var sqlOrdering: SQLOrdering { + .literal(self) } } @@ -245,124 +245,3 @@ extension SQLLiteral: ExpressibleByStringInterpolation { self.init(elements: sqlInterpolation.elements) } } - -// MARK: - SQLExpressionLiteral - -// TODO: remove public qualifier when GRDB5 fixits are removed. -/// `SQLExpressionLiteral` is an expression built from a raw SQL snippet. -/// -/// To build one, use the `SQLiteral.sqlExpression` property: -/// -/// let name = "O'Brien" -/// let column = Column("name") -/// let literal: SQLLiteral = "\(column) = \(name)" -/// let expression = literal.sqlExpression -/// -/// Such expressions can feed query interface requests: -/// -/// try dbQueue.read { db in -/// // SELECT * FROM player WHERE name = 'O''Brien' -/// let players = try Player -/// .filter(expression) -/// .fetchAll(db) -/// -/// // SELECT player.*, team.* -/// // FROM player -/// // JOIN team WHERE team.id = player.teamID -/// // WHERE player.name = 'O''Brien' -/// let players = try Player -/// .including(required: Player.team) -/// .filter(expression) -/// .fetchAll(db) -/// } -/// -/// See SQLLiteral for more information. -/// -/// :nodoc: -public struct SQLExpressionLiteral: SQLExpression { - let sqlLiteral: SQLLiteral - - // Prefer SQLLiteral.sqlExpression - fileprivate init(sqlLiteral: SQLLiteral) { - self.sqlLiteral = sqlLiteral - } - - /// :nodoc: - public func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - var resultSQL = try sqlLiteral.sql(context) - - if wrappedInParenthesis { - resultSQL = "(\(resultSQL))" - } - - return resultSQL - } - - /// :nodoc: - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - sqlLiteral.qualified(with: alias).sqlExpression - } -} - -// MARK: - SQLSelectionLiteral - -struct SQLSelectionLiteral: SQLSelectable { - let sqlLiteral: SQLLiteral - - // Prefer SQLLiteral.sqlSelectable - fileprivate init(sqlLiteral: SQLLiteral) { - self.sqlLiteral = sqlLiteral - } - - 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. \ - See SQLLiteral.sqlExpression. - """) - } - - func _count(distinct: Bool) -> _SQLCount? { nil } - - func _countedSQL(_ context: SQLGenerationContext) throws -> String { - fatalError(""" - Selection literals can't be counted. \ - To resolve this error, select one or several literal expressions instead. \ - See SQLLiteral.sqlExpression. - """) - } - - func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { - sqlLiteral.qualified(with: alias).sqlSelectable - } - - func _resultColumnSQL(_ context: SQLGenerationContext) throws -> String { - try sqlLiteral.sql(context) - } -} - -// MARK: - SQLOrderingLiteral - -struct SQLOrderingLiteral: SQLOrderingTerm { - let sqlLiteral: SQLLiteral - - // Prefer SQLLiteral.sqlOrderingTerm - fileprivate init(sqlLiteral: SQLLiteral) { - self.sqlLiteral = sqlLiteral - } - - func _orderingTermSQL(_ context: SQLGenerationContext) throws -> String { - try sqlLiteral.sql(context) - } - - func _qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { - sqlLiteral.qualified(with: alias).sqlOrderingTerm - } - - var _reversed: SQLOrderingTerm { - fatalError(""" - Ordering literals can't be reversed. \ - To resolve this error, order by expression literals instead. - """) - } -} diff --git a/GRDB/Core/SQLRequest.swift b/GRDB/Core/SQLRequest.swift index 676db3c46..423d89719 100644 --- a/GRDB/Core/SQLRequest.swift +++ b/GRDB/Core/SQLRequest.swift @@ -102,6 +102,10 @@ public struct SQLRequest { } extension SQLRequest: FetchRequest { + public var sqlSubquery: SQLSubquery { + .literal(sqlLiteral) + } + public func fetchCount(_ db: Database) throws -> Int { try SQLRequest("SELECT COUNT(*) FROM (\(self))").fetchOne(db)! } @@ -125,21 +129,6 @@ extension SQLRequest: FetchRequest { try statement.setArguments(context.arguments) return PreparedRequest(statement: statement, adapter: adapter) } - - /// :nodoc - public func _selectedColumnCount(_ db: Database) throws -> Int { - // Compile request. We can freely use the statement cache because we - // do not execute the statement or modify its arguments. - let context = SQLGenerationContext(db) - let sql = try _requestSQL(context, forSingleResult: false) - let statement = try db.cachedSelectStatement(sql: sql) - return statement.columnCount - } - - /// :nodoc: - public func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { - try sqlLiteral.sql(context) - } } extension SQLRequest: ExpressibleByStringInterpolation { diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+RawRepresentable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+RawRepresentable.swift index 2d61c9fd4..8547c7361 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+RawRepresentable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+RawRepresentable.swift @@ -1,15 +1,15 @@ -/// SQLExpressible is free for RawRepresentable types whose raw value -/// is itself SQLExpressible. -/// -/// // If the RawValue adopts SQLExpressible... -/// enum Color : Int { -/// case red -/// case white -/// case rose -/// } -/// -/// // ... then the RawRepresentable type can freely adopt SQLExpressible: -/// extension Color : SQLExpressible { /* empty */ } +extension SQLSelectable where Self: RawRepresentable, Self.RawValue: SQLSelectable { + public var sqlSelection: SQLSelection { + rawValue.sqlSelection + } +} + +extension SQLOrderingTerm where Self: RawRepresentable, Self.RawValue: SQLOrderingTerm { + public var sqlOrdering: SQLOrdering { + rawValue.sqlOrdering + } +} + extension SQLExpressible where Self: RawRepresentable, Self.RawValue: SQLExpressible { /// Returns the raw value as an SQL expression. public var sqlExpression: SQLExpression { @@ -17,8 +17,8 @@ extension SQLExpressible where Self: RawRepresentable, Self.RawValue: SQLExpress } } -/// DatabaseValueConvertible is free for RawRepresentable types whose raw value -/// is itself DatabaseValueConvertible. +/// `DatabaseValueConvertible` is free for `RawRepresentable` types whose raw +/// value is itself `DatabaseValueConvertible`. /// /// // If the RawValue adopts DatabaseValueConvertible... /// enum Color : Int { @@ -27,16 +27,14 @@ extension SQLExpressible where Self: RawRepresentable, Self.RawValue: SQLExpress /// case rose /// } /// -/// // ... then the RawRepresentable type can freely adopt DatabaseValueConvertible: -/// extension Color : DatabaseValueConvertible { /* empty */ } +/// // ... then the RawRepresentable type can freely +/// // adopt DatabaseValueConvertible: +/// extension Color: DatabaseValueConvertible { } extension DatabaseValueConvertible where Self: RawRepresentable, Self.RawValue: DatabaseValueConvertible { - - /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { rawValue.databaseValue } - /// Returns a value initialized from *dbValue*, if possible. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { RawValue.fromDatabaseValue(dbValue).flatMap { self.init(rawValue: $0) } } diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift index f3e30e209..a24fddeb6 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -195,7 +195,10 @@ extension FilteredRequest { } /// :nodoc: -extension SQLExpressionLiteral { +@available(*, unavailable, message: "Build literal expressions with SQLLiteral.sqlExpression instead.") +struct SQLExpressionLiteral: SQLSpecificExpressible { + var sqlExpression: SQLExpression { preconditionFailure() } + @available(*, unavailable, message: "Build literal expressions with SQLLiteral.sqlExpression instead.") public var sql: String { preconditionFailure() } diff --git a/GRDB/QueryInterface/FTS3+QueryInterface.swift b/GRDB/QueryInterface/FTS3+QueryInterface.swift index 036133800..948ec113e 100644 --- a/GRDB/QueryInterface/FTS3+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS3+QueryInterface.swift @@ -16,7 +16,7 @@ extension TableRequest where Self: FilteredRequest { return none() } let alias = TableAlias() - let matchExpression = SQLExpressionTableMatch(alias: alias, pattern: pattern.databaseValue) + let matchExpression = SQLExpression.tableMatch(alias, pattern.sqlExpression) 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) + .binary(.match, sqlExpression, pattern?.sqlExpression ?? .null) } } diff --git a/GRDB/QueryInterface/FTS5+QueryInterface.swift b/GRDB/QueryInterface/FTS5+QueryInterface.swift index c0c69e771..7ab62750a 100644 --- a/GRDB/QueryInterface/FTS5+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS5+QueryInterface.swift @@ -21,7 +21,7 @@ extension TableRequest where Self: FilteredRequest { return none() } let alias = TableAlias() - let matchExpression = SQLExpressionTableMatch(alias: alias, pattern: pattern.databaseValue) + let matchExpression = SQLExpression.tableMatch(alias, pattern.sqlExpression) return self.aliased(alias).filter(matchExpression) } } diff --git a/GRDB/QueryInterface/ForeignKey.swift b/GRDB/QueryInterface/ForeignKey.swift index 18e2415ed..a27a55d36 100644 --- a/GRDB/QueryInterface/ForeignKey.swift +++ b/GRDB/QueryInterface/ForeignKey.swift @@ -1,4 +1,3 @@ - /// A ForeignKey helps building associations when GRDB can't infer a foreign /// key from the database schema. /// diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index 4c453c62a..7fa7a724b 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -127,7 +127,7 @@ extension Association { /// .select { db in [Column("color") } /// var request = Player.including(required: association) public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self { - mapDestinationRelation { $0.select(selection) } + mapDestinationRelation { $0.select { try selection($0).map(\.sqlSelection) } } } /// Creates an association which appends *selection*. @@ -144,7 +144,7 @@ extension Association { /// .annotated(with: { db in [Column("name")] }) /// var request = Player.including(required: association) public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self { - mapDestinationRelation { $0.annotated(with: selection) } + mapDestinationRelation { $0.annotated { try selection($0).map(\.sqlSelection) } } } /// Creates an association with the provided *predicate promise* added to @@ -188,7 +188,7 @@ extension Association { /// .order{ _ in [Column("name")] } /// var request = Player.including(required: association) public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self { - mapDestinationRelation { $0.order(orderings) } + mapDestinationRelation { $0.order { try orderings($0).map(\.sqlOrdering) } } } /// Creates an association that reverses applied orderings. diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index 0eb305a5f..fde5a0685 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -38,7 +38,7 @@ extension AssociationToMany { /// /// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db) public var count: AssociationAggregate { - let expression = SQLExpressionCountDistinct(SQLExpressionFastPrimaryKey()) + let expression = SQLExpression.countDistinct(.fastPrimaryKey) return makeAggregate(expression).forKey("\(key.singularizedName)Count") } @@ -58,7 +58,7 @@ extension AssociationToMany { /// let teams: [Team] = try Team.having(!Team.players.isEmpty()) /// let teams: [Team] = try Team.having(Team.players.isEmpty() == false) public var isEmpty: AssociationAggregate { - let expression = SQLExpressionIsEmpty(SQLExpressionCountDistinct(SQLExpressionFastPrimaryKey())) + let expression = SQLExpression.isEmpty(.countDistinct(.fastPrimaryKey)) 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(.function("AVG", [expression.sqlExpression])) 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(.function("MAX", [expression.sqlExpression])) 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(.function("MIN", [expression.sqlExpression])) 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(.function("SUM", [expression.sqlExpression])) if let column = expression as? ColumnExpression { let name = key.singularizedName return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum") diff --git a/GRDB/QueryInterface/Request/CommonTableExpression.swift b/GRDB/QueryInterface/Request/CommonTableExpression.swift index f963e92d2..de5487bb5 100644 --- a/GRDB/QueryInterface/Request/CommonTableExpression.swift +++ b/GRDB/QueryInterface/Request/CommonTableExpression.swift @@ -36,7 +36,7 @@ extension CommonTableExpression { /// - parameter columns: The columns of the common table expression. If nil, /// the columns are the columns of the request. /// - parameter request: A request. - public init( + public init( recursive: Bool = false, named tableName: String, columns: [String]? = nil, @@ -46,7 +46,7 @@ extension CommonTableExpression { tableName: tableName, cte: SQLCTE( columns: columns, - requestPromise: DatabasePromise(value: request), + sqlSubquery: request.sqlSubquery, isRecursive: recursive)) } @@ -113,7 +113,8 @@ extension CommonTableExpression { extension CommonTableExpression { var relationForAll: SQLRelation { - .all(fromTable: tableName, selection: { _ in [AllColumns(cte: cte)] }) + let cte = self.cte + return .all(fromTable: tableName, selection: { _ in [.allCTEColumns(cte)] }) } /// Creates a request for all rows of the common table expression. @@ -157,7 +158,7 @@ extension CommonTableExpression { /// // name IN playerName /// playerNameCTE.contains(Column("name")) public func contains(_ element: SQLExpressible) -> SQLExpression { - SQLTableCollection.tableName(tableName).contains(element) + SQLCollection.table(tableName).contains(element.sqlExpression) } } @@ -174,13 +175,14 @@ struct SQLCTE { /// /// -- Column id /// WITH t(id) AS (SELECT 1) ... + /// ~~ var columns: [String]? - /// The common table expression request. + /// The common table expression subquery. /// /// WITH t AS (SELECT ...) /// ~~~~~~~~~~ - var requestPromise: DatabasePromise<_FetchRequest> + var sqlSubquery: SQLSubquery /// Whether this common table expression needs a `WITH RECURSIVE` /// sql clause. @@ -193,7 +195,7 @@ struct SQLCTE { return columns.count } - return try requestPromise.resolve(db)._selectedColumnCount(db) + return try sqlSubquery.columnsCount(db) } } @@ -214,7 +216,9 @@ extension CommonTableExpression { on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> SQLExpressible) -> JoinAssociation { - JoinAssociation(to: cte.relationForAll, condition: .expression(condition)) + JoinAssociation( + to: cte.relationForAll, + condition: .expression { condition($0, $1).sqlExpression }) } /// Creates an association to a common table expression that you can join @@ -248,7 +252,9 @@ extension CommonTableExpression { -> JoinAssociation where Destination: TableRecord { - JoinAssociation(to: Destination.relationForAll, condition: .expression(condition)) + JoinAssociation( + to: Destination.relationForAll, + condition: .expression { condition($0, $1).sqlExpression }) } /// Creates an association to a table record that you can join diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 1c952e1a6..a9b7f8ce7 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -41,6 +41,10 @@ extension QueryInterfaceRequest { extension QueryInterfaceRequest: Refinable { } extension QueryInterfaceRequest: FetchRequest { + public var sqlSubquery: SQLSubquery { + .query(query) + } + public func fetchCount(_ db: Database) throws -> Int { try query.fetchCount(db) } @@ -55,22 +59,12 @@ extension QueryInterfaceRequest: FetchRequest { let associations = query.relation.prefetchedAssociations if associations.isEmpty == false { // Eager loading of prefetched associations - preparedRequest = preparedRequest.with(\.supplementaryFetch) { db, rows in - try prefetch(db, associations: associations, from: self, into: rows) + preparedRequest = preparedRequest.with(\.supplementaryFetch) { [query] db, rows in + try prefetch(db, associations: associations, from: query, into: rows) } } return preparedRequest } - - /// :nodoc: - public func _selectedColumnCount(_ db: Database) throws -> Int { - try SQLQueryGenerator(query: query).columnsCount(db) - } - - /// :nodoc: - public func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { - try SQLQueryGenerator(query: query, forSingleResult: singleResult).requestSQL(context) - } } // MARK: - Request Derivation @@ -169,7 +163,7 @@ extension QueryInterfaceRequest: SelectionRequest { as type: RowDecoder.Type = RowDecoder.self) -> QueryInterfaceRequest { - select(sqlLiteral.sqlSelectable, as: type) + select(sqlLiteral.sqlSelection, as: type) } /// Creates a request which appends *selection promise*. @@ -500,12 +494,10 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord { /// } public struct ColumnAssignment { var column: ColumnExpression - var value: SQLExpressible + var value: SQLExpression func sql(_ context: SQLGenerationContext) throws -> String { - try column._expressionSQL(context, wrappedInParenthesis: false) - + " = " - + value.sqlExpression._expressionSQL(context, wrappedInParenthesis: false) + try column.sqlExpression.sql(context) + " = " + value.sql(context) } } @@ -522,7 +514,7 @@ extension ColumnExpression { /// try Player.updateAll(db, Column("score").set(to: 0)) /// } public func set(to value: SQLExpressible?) -> ColumnAssignment { - ColumnAssignment(column: self, value: value ?? DatabaseValue.null) + ColumnAssignment(column: self, value: value?.sqlExpression ?? .null) } } @@ -581,19 +573,19 @@ public func /= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssign // MARK: - Eager loading of hasMany associations // CAUTION: Keep this code in sync with prefetchedRegion(_:_:) -/// Append rows from prefetched associations into the `baseRows` argument. +/// Append rows from prefetched associations into the `originRows` argument. /// /// - parameter db: A database connection. /// - parameter associations: Prefetched associations. -/// - parameter baseRows: The rows that need to be extended with prefetched rows. -/// - parameter baseRequest: The request that was used to fetch `baseRows`. -private func prefetch( +/// - parameter originRows: The rows that need to be extended with prefetched rows. +/// - parameter originQuery: The query that was used to fetch `originRows`. +private func prefetch( _ db: Database, associations: [_SQLAssociation], - from baseRequest: QueryInterfaceRequest, - into baseRows: [Row]) throws + from originQuery: SQLQuery, + into originRows: [Row]) throws { - guard let firstBaseRow = baseRows.first else { + guard let firstOriginRow = originRows.first else { // No rows -> no prefetch return } @@ -606,7 +598,7 @@ private func prefetch( fatalError("Not implemented: prefetch association without any foreign key") case let .foreignKey(pivotForeignKey): - let originTable = baseRequest.query.relation.source.tableName + let originTable = originQuery.relation.source.tableName let pivotMapping = try pivotForeignKey.joinMapping(db, from: originTable) let pivotColumns = pivotMapping.map(\.right) let leftColumns = pivotMapping.map(\.left) @@ -637,7 +629,7 @@ private func prefetch( // Otherwise, we fallback to the `(a = ? AND b = ?) OR ...` // condition (the one that may fail if there are too many // base rows). - let usesCommonTableExpression = pivotMapping.count > 1 && SQLRowValue.isAvailable + let usesCommonTableExpression = pivotMapping.count > 1 && SQLExpression.rowValuesAreAvailable let prefetchRequest: QueryInterfaceRequest if usesCommonTableExpression { @@ -655,24 +647,25 @@ private func prefetch( // FROM country // JOIN passport ON passport.countryCode = country.code // AND (passport.a, passport.b) IN grdb_base - let baseRequest = baseRequest.map(\.query.relation) { baseRelation in + let originQuery = originQuery.map(\.relation) { baseRelation in // Ordering and including(all:) children are // useless, and we only need pivoting columns: baseRelation .unordered() .removingChildrenForPrefetchedAssociations() - .selectOnly(leftColumns.map(Column.init)) + .selectOnly(leftColumns.map { SQLExpression.column($0).sqlSelection }) } - let baseCTE = CommonTableExpression( + let originCTE = CommonTableExpression( named: "grdb_base", - request: baseRequest) - let pivotFilter = baseCTE.contains(SQLRowValue(pivotColumns.map(Column.init))) + request: originQuery) + let pivotRowValue = SQLExpression.rowValue(pivotColumns.map(SQLExpression.column))! + let pivotFilter = originCTE.contains(pivotRowValue) prefetchRequest = makePrefetchRequest( for: association, filteringPivotWith: pivotFilter, annotatedWith: pivotColumns) - .with(baseCTE) + .with(originCTE) } else { // HasMany: Author.including(all: Author.books) // @@ -686,7 +679,7 @@ private func prefetch( // FROM country // JOIN passport ON passport.countryCode = country.code // AND passport.citizenId IN (1, 2, 3) - let pivotFilter = pivotMapping.joinExpression(leftRows: baseRows) + let pivotFilter = pivotMapping.joinExpression(leftRows: originRows) prefetchRequest = makePrefetchRequest( for: association, @@ -696,9 +689,9 @@ private func prefetch( let prefetchedRows = try prefetchRequest.fetchAll(db) let prefetchedGroups = prefetchedRows.grouped(byDatabaseValuesOnColumns: pivotColumns.map { "grdb_\($0)" }) - let groupingIndexes = firstBaseRow.indexes(forColumns: leftColumns) + let groupingIndexes = firstOriginRow.indexes(forColumns: leftColumns) - for row in baseRows { + for row in originRows { let groupingKey = groupingIndexes.map { row.impl.databaseValue(atUncheckedIndex: $0) } let prefetchedRows = prefetchedGroups[groupingKey, default: []] row.prefetchedRows.setRows(prefetchedRows, forKeyPath: association.keyPath) diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 1a4d028aa..347206c29 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -102,7 +102,7 @@ extension SelectionRequest { /// .select(literal: SQLLiteral(sql: "email")) public func select(literal sqlLiteral: SQLLiteral) -> Self { // NOT TESTED - select(sqlLiteral.sqlSelectable) + select(sqlLiteral.sqlSelection) } /// Creates a request which appends *selection*. @@ -317,7 +317,7 @@ extension TableRequest where Self: OrderedRequest { public func orderByPrimaryKey() -> Self { let tableName = self.databaseTableName return order { db in - try db.primaryKey(tableName).columns.map { Column($0) } + try db.primaryKey(tableName).columns.map(SQLExpression.column) } } } @@ -501,7 +501,7 @@ extension OrderedRequest { /// .order(sql: "name") public func order(literal sqlLiteral: SQLLiteral) -> Self { // NOT TESTED - order(sqlLiteral.sqlOrderingTerm) + order(sqlLiteral.sqlOrdering) } } diff --git a/GRDB/QueryInterface/SQL/Column.swift b/GRDB/QueryInterface/SQL/Column.swift index 36e887501..97811b3c5 100644 --- a/GRDB/QueryInterface/SQL/Column.swift +++ b/GRDB/QueryInterface/SQL/Column.swift @@ -17,7 +17,7 @@ /// let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db) /// /// See https://github.com/groue/GRDB.swift#the-query-interface -public protocol ColumnExpression: SQLExpression { +public protocol ColumnExpression: SQLSpecificExpressible { /// The unqualified name of a database column. /// /// "score" is a valid unqualified name. "player.score" is not. @@ -25,14 +25,8 @@ public protocol ColumnExpression: SQLExpression { } extension ColumnExpression { - /// :nodoc: - public func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - name.quotedDatabaseIdentifier - } - - /// :nodoc: - public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLQualifiedColumn(name, alias: alias) + public var sqlExpression: SQLExpression { + .column(name) } } @@ -60,42 +54,6 @@ public struct Column: ColumnExpression, Equatable { } } -/// A qualified column in the database, as in `SELECT t.a FROM t` -/// -/// :nodoc: -struct SQLQualifiedColumn: ColumnExpression { - var name: String - let alias: TableAlias - - /// Creates a column given its name. - init(_ name: String, alias: TableAlias) { - self.name = name - self.alias = alias - } - - func _column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool) throws -> String? { - if alias == self.alias { - return name - } else { - return nil - } - } - - func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - if let qualifier = context.qualifier(for: alias) { - return qualifier.quotedDatabaseIdentifier - + "." - + name.quotedDatabaseIdentifier - } - return name.quotedDatabaseIdentifier - } - - func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - // Never requalify - self - } -} - /// Support for column enums: /// /// struct Player { diff --git a/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift b/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift index 531bcc21f..50ae6013c 100644 --- a/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLCollatedExpression.swift @@ -22,10 +22,10 @@ public struct SQLCollatedExpression: SQLOrderingTerm { /// Player.order(email.asc) /// /// See https://github.com/groue/GRDB.swift/#the-query-interface - public var asc: SQLOrderingTerm { - SQLOrdering.asc(sqlExpression) + public var asc: SQLOrdering { + .asc(sqlExpression) } - + /// Returns an ordering suitable for QueryInterfaceRequest.order() /// /// let email: SQLCollatedExpression = Column("email").collating(.nocase) @@ -34,10 +34,10 @@ public struct SQLCollatedExpression: SQLOrderingTerm { /// Player.order(email.desc) /// /// See https://github.com/groue/GRDB.swift/#the-query-interface - public var desc: SQLOrderingTerm { - SQLOrdering.desc(sqlExpression) + public var desc: SQLOrdering { + .desc(sqlExpression) } - + #if GRDBCUSTOMSQLITE /// Returns an ordering suitable for QueryInterfaceRequest.order() /// @@ -47,10 +47,10 @@ public struct SQLCollatedExpression: SQLOrderingTerm { /// Player.order(email.ascNullsLast) /// /// See https://github.com/groue/GRDB.swift/#the-query-interface - public var ascNullsLast: SQLOrderingTerm { - SQLOrdering.ascNullsLast(sqlExpression) + public var ascNullsLast: SQLOrdering { + .ascNullsLast(sqlExpression) } - + /// Returns an ordering suitable for QueryInterfaceRequest.order() /// /// let email: SQLCollatedExpression = Column("email").collating(.nocase) @@ -59,8 +59,8 @@ public struct SQLCollatedExpression: SQLOrderingTerm { /// Player.order(email.descNullsFirst) /// /// See https://github.com/groue/GRDB.swift/#the-query-interface - public var descNullsFirst: SQLOrderingTerm { - SQLOrdering.descNullsFirst(sqlExpression) + public var descNullsFirst: SQLOrdering { + .descNullsFirst(sqlExpression) } #elseif !GRDBCIPHER /// Returns an ordering suitable for QueryInterfaceRequest.order() @@ -72,10 +72,10 @@ public struct SQLCollatedExpression: SQLOrderingTerm { /// /// See https://github.com/groue/GRDB.swift/#the-query-interface @available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) - public var ascNullsLast: SQLOrderingTerm { - SQLOrdering.ascNullsLast(sqlExpression) + public var ascNullsLast: SQLOrdering { + .ascNullsLast(sqlExpression) } - + /// Returns an ordering suitable for QueryInterfaceRequest.order() /// /// let email: SQLCollatedExpression = Column("email").collating(.nocase) @@ -85,32 +85,21 @@ public struct SQLCollatedExpression: SQLOrderingTerm { /// /// See https://github.com/groue/GRDB.swift/#the-query-interface @available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) - public var descNullsFirst: SQLOrderingTerm { - SQLOrdering.descNullsFirst(sqlExpression) + public var descNullsFirst: SQLOrdering { + .descNullsFirst(sqlExpression) } #endif - + init(_ expression: SQLExpression, collationName: Database.CollationName) { self.expression = expression self.collationName = collationName } var sqlExpression: SQLExpression { - SQLExpressionCollate(expression, collationName: collationName) + .collated(expression, collationName) } - // MARK: SQLOrderingTerm - - /// :nodoc: - public func _orderingTermSQL(_ context: SQLGenerationContext) throws -> String { - try sqlExpression._orderingTermSQL(context) + public var sqlOrdering: SQLOrdering { + .expression(sqlExpression) } - - /// :nodoc: - public func _qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { - SQLCollatedExpression(expression._qualifiedExpression(with: alias), collationName: collationName) - } - - /// :nodoc: - public var _reversed: SQLOrderingTerm { desc } } diff --git a/GRDB/QueryInterface/SQL/SQLCollection.swift b/GRDB/QueryInterface/SQL/SQLCollection.swift index 198a8a457..17fda3812 100644 --- a/GRDB/QueryInterface/SQL/SQLCollection.swift +++ b/GRDB/QueryInterface/SQL/SQLCollection.swift @@ -1,13 +1,54 @@ -// MARK: - SQLCollection - -/// Implementation details of `SQLCollection`. +/// The right-hand side of the `IN` or `NOT IN` SQL operators /// -/// :nodoc: -public protocol _SQLCollection { +/// See https://sqlite.org/lang_expr.html#the_in_and_not_in_operators +public struct SQLCollection { + private var impl: Impl + + private enum Impl { + /// An array collection + /// + /// id IN (1, 2, 3) + /// ~~~~~~~~~ + case array([SQLExpression]) + + /// A subquery + /// + /// score IN (SELECT ...) + /// ~~~~~~~~~~~~ + case subquery(SQLSubquery) + + /// A table + /// + /// score IN table + /// ~~~~~ + case table(String) + } + + static func array(_ expressions: [SQLExpression]) -> Self { + self.init(impl: .array(expressions)) + } + + static func subquery(_ subquery: SQLSubquery) -> Self { + self.init(impl: .subquery(subquery)) + } + + static func table(_ tableName: String) -> Self { + self.init(impl: .table(tableName)) + } +} + +extension SQLCollection { /// Returns a qualified collection. - /// - /// :nodoc: - func _qualifiedCollection(with alias: TableAlias) -> SQLCollection + func qualified(with alias: TableAlias) -> SQLCollection { + switch impl { + case .subquery, + .table: + return self + + case let .array(expressions): + return .array(expressions.map { $0.qualified(with: alias) }) + } + } /// The expressions in the collection, if known. /// @@ -18,88 +59,63 @@ public protocol _SQLCollection { /// let request = Player.filter(keys: [1, 2, 3]) /// let regionObservation = DatabaseRegionObservation(tracking: request) /// let valueObservation = ValueObservation.tracking(request.fetchAll) - /// - /// :nodoc: - var _collectionExpressions: [SQLExpression]? { get } + var collectionExpressions: [SQLExpression]? { + switch impl { + case .subquery, + .table: + return nil + + case let .array(expressions): + return expressions + } + } /// Returns an SQL string that represents the collection. /// /// - parameter context: An SQL generation context which accepts /// statement arguments. - func _collectionSQL(_ context: SQLGenerationContext) throws -> String -} - -/// SQLCollection is the protocol for types that can be checked for inclusion. -public protocol SQLCollection: _SQLCollection { - /// Returns an expression that check whether the collection contains - /// the expression. - func contains(_ value: SQLExpressible) -> SQLExpression -} - -// MARK: - SQLExpressionsArray - -/// SQLExpressionsArray wraps an array of expressions -/// -/// SQLExpressionsArray([1, 2, 3]) -/// -/// :nodoc: -struct SQLExpressionsArray: SQLCollection { - let expressions: [SQLExpression] - - var _collectionExpressions: [SQLExpression]? { expressions } - - func _collectionSQL(_ context: SQLGenerationContext) throws -> String { - try "(" - + expressions - .map { try $0._expressionSQL(context, wrappedInParenthesis: false) } - .joined(separator: ", ") - + ")" - } - - func contains(_ value: SQLExpressible) -> SQLExpression { - guard let expression = expressions.first else { - return false.databaseValue - } - - // With SQLite, `expr IN (NULL)` never succeeds. - // - // We must not provide special handling of NULL, because we can not - // guess if our `expressions` array contains a value evaluates to NULL. - - if expressions.count == 1 { - // Output `expr = value` instead of `expr IN (value)`, because it - // looks nicer. And make sure we do not produce 'expr IS NULL'. - return SQLExpressionEqual(.equal, value.sqlExpression, expression) - } - - return SQLExpressionContains(value, self) - } - - func _qualifiedCollection(with alias: TableAlias) -> SQLCollection { - SQLExpressionsArray(expressions: expressions.map { $0._qualifiedExpression(with: alias) }) - } -} - -// MARK: - SQLTableCollection - -/// SQLTableCollection aims at generating `value IN table` expressions. -/// -/// :nodoc: -enum SQLTableCollection: SQLCollection { - case tableName(String) - - var _collectionExpressions: [SQLExpression]? { nil } - - func _collectionSQL(_ context: SQLGenerationContext) throws -> String { - switch self { - case let .tableName(tableName): + func sql(_ context: SQLGenerationContext) throws -> String { + switch impl { + case let .array(expressions): + return try "(" + + expressions.map { try $0.sql(context) }.joined(separator: ", ") + + ")" + + case let .subquery(subquery): + return try "(" + + subquery.sql(context) + + ")" + + case let .table(tableName): return tableName.quotedDatabaseIdentifier } } - func contains(_ value: SQLExpressible) -> SQLExpression { - return SQLExpressionContains(value, self) + /// Returns an expression that check whether the collection contains + /// the expression. + func contains(_ value: SQLExpression) -> SQLExpression { + switch impl { + case .subquery, + .table: + return .in(value, self) + + case let .array(expressions): + guard let expression = expressions.first else { + return false.sqlExpression + } + + // With SQLite, `expr IN (NULL)` never succeeds. + // + // We must not provide special handling of NULL, because we can not + // guess if our `expressions` array contains a value evaluates to NULL. + + if expressions.count == 1 { + // Output `expr = value` instead of `expr IN (value)`, because it + // looks nicer. And make sure we do not produce 'expr IS NULL'. + return .compare(.equal, value, expression) + } + + return .in(value, self) + } } - - func _qualifiedCollection(with alias: TableAlias) -> SQLCollection { self } } diff --git a/GRDB/QueryInterface/SQL/SQLExpressible.swift b/GRDB/QueryInterface/SQL/SQLExpressible.swift deleted file mode 100644 index a2e0d19ed..000000000 --- a/GRDB/QueryInterface/SQL/SQLExpressible.swift +++ /dev/null @@ -1,46 +0,0 @@ -// MARK: - SQLExpressible - -/// `SQLExpressible` is the protocol for all types that can be used as an -/// SQL expression. -/// -/// It is adopted by protocols like `DatabaseValueConvertible`, and types -/// like `Column`. -/// -/// See https://github.com/groue/GRDB.swift/#the-query-interface -public protocol SQLExpressible { - /// Returns an SQL expression. - var sqlExpression: SQLExpression { get } -} - -// MARK: - SQLSpecificExpressible - -/// 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. -/// -/// For example, Column is a type that only exists to help you build requests, -/// and it adopts SQLSpecificExpressible. -/// -/// On the other side, Int adopts SQLExpressible (via DatabaseValueConvertible). -/// -/// :nodoc: -public protocol SQLSpecificExpressible: SQLExpressible { - // SQLExpressible can be adopted by Swift standard types, and user - // types, through the DatabaseValueConvertible protocol which inherits - // from SQLExpressible. - // - // For example, Int adopts SQLExpressible through - // DatabaseValueConvertible. - // - // SQLSpecificExpressible, on the other side, is not adopted by any - // Swift standard type or any user type. It is only adopted by GRDB types, - // such as Column and SQLExpression. - // - // This separation lets us define functions and operators that do not - // spill out. The three declarations below have no chance overloading a - // Swift-defined operator, or a user-defined operator: - // - // - ==(SQLExpressible, SQLSpecificExpressible) - // - ==(SQLSpecificExpressible, SQLExpressible) - // - ==(SQLSpecificExpressible, SQLSpecificExpressible) -} diff --git a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift deleted file mode 100644 index b2f9eec47..000000000 --- a/GRDB/QueryInterface/SQL/SQLExpression+QueryInterface.swift +++ /dev/null @@ -1,1207 +0,0 @@ -// MARK: - SQLExpression - -extension SQLExpression { - /// The expression as a quoted SQL literal (not public in order to avoid abuses) - /// - /// try "foo'bar".databaseValue.quotedSQL(db) // "'foo''bar'"" - func quotedSQL(_ db: Database) throws -> String { - let context = SQLGenerationContext(db, argumentsSink: .forRawSQL) - return try _expressionSQL(context, wrappedInParenthesis: false) - } -} - -// MARK: - SQLExpressionNot - -/// :nodoc: -struct SQLExpressionNot: SQLExpression { - let expression: SQLExpression - - init(_ expression: SQLExpression) { - self.expression = expression - } - - // MARK: SQLExpression - - func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - var resultSQL = try "NOT \(expression._expressionSQL(context, wrappedInParenthesis: true))" - - if wrappedInParenthesis { - resultSQL = "(\(resultSQL))" - } - - return resultSQL - } - - func _is(_ test: _SQLBooleanTest) -> SQLExpression { - switch test { - case .true: - return SQLExpressionEqual(.equal, self, true.sqlExpression) - - case .false: - return SQLExpressionEqual(.equal, self, false.sqlExpression) - - case .falsey: - // Support `NOT (NOT expression)` as a technique to build 0 or 1 - return SQLExpressionNot(self) - } - } - - var _isConstantInRequest: Bool { expression._isConstantInRequest } - - func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLExpressionNot(expression._qualifiedExpression(with: alias)) - } - - // MARK: SQLSelectable - - var _isAggregate: Bool { expression._isAggregate } -} - -// MARK: - SQLExpressionUnary - -/// SQLUnaryOperator is a SQLite unary operator. -struct SQLUnaryOperator: Hashable { - /// The SQL operator - let sql: String - - /// If true GRDB puts a white space between the operator and the operand. - let needsRightSpace: Bool - - /// Creates an unary operator - /// - /// SQLUnaryOperator("~", needsRightSpace: false) - init(_ sql: String, needsRightSpace: Bool) { - self.sql = sql - self.needsRightSpace = needsRightSpace - } - - /// The `-` unary operator - static let minus = SQLUnaryOperator("-", needsRightSpace: false) -} - -/// SQLExpressionUnary is an expression made of an unary operator and -/// an operand expression. -/// -/// :nodoc: -struct SQLExpressionUnary: SQLExpression { - let op: SQLUnaryOperator - let expression: SQLExpression - - init(_ op: SQLUnaryOperator, _ value: SQLExpressible) { - self.op = op - self.expression = value.sqlExpression - } - - // MARK: SQLExpression - - func _column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool) throws -> String? { - if acceptsBijection && op == .minus { - return try expression._column(db, for: alias, acceptsBijection: acceptsBijection) - } - - return nil - } - - func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - var resultSQL = try op.sql - + (op.needsRightSpace ? " " : "") - + expression._expressionSQL(context, wrappedInParenthesis: true) - - if wrappedInParenthesis { - resultSQL = "(\(resultSQL))" - } - - return resultSQL - } - - var _isConstantInRequest: Bool { expression._isConstantInRequest } - - func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLExpressionUnary(op, expression._qualifiedExpression(with: alias)) - } - - // MARK: SQLSelectable - - var _isAggregate: Bool { expression._isAggregate } -} - -// MARK: - SQLExpressionBinary - -/// SQLBinaryOperator is an SQLite binary operator, such as >, =, etc. -struct SQLBinaryOperator: Hashable { - /// The SQL operator - let sql: String - - /// The SQL for the negated operator, if any - let negatedSQL: String? - - /// Creates a binary operator - /// - /// SQLBinaryOperator("-") - /// SQLBinaryOperator("LIKE", negated: "NOT LIKE") - init(_ sql: String, negated: String? = nil) { - self.sql = sql - self.negatedSQL = negated - } - - /// Returns the negated binary operator, if any - /// - /// let operator = SQLBinaryOperator("IS", negated: "IS NOT") - /// operator.negated!.sql // IS NOT - 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", negated: "NOT LIKE") - - /// The `MATCH` binary operator - static let match = SQLBinaryOperator("MATCH") -} - -/// SQLExpressionBinary is an expression made of two expressions joined with a -/// binary operator. -/// -/// SQLExpressionBinary(.multiply, Column("length"), Column("width")) -/// -/// :nodoc: -struct SQLExpressionBinary: SQLExpression { - let lhs: SQLExpression - let op: SQLBinaryOperator - let rhs: SQLExpression - - /// Creates an expression made of two expressions joined with a - /// binary operator. - /// - /// // length * width - /// SQLExpressionBinary(.subtract, Column("score"), Column("malus")) - init(_ op: SQLBinaryOperator, _ lhs: SQLExpressible, _ rhs: SQLExpressible) { - self.lhs = lhs.sqlExpression - self.op = op - self.rhs = rhs.sqlExpression - } - - // MARK: SQLExpression - - func _column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool) throws -> String? { - guard acceptsBijection && op == .subtract else { - return nil - } - - if lhs._isConstantInRequest { - return try rhs._column(db, for: alias, acceptsBijection: acceptsBijection) - } else if rhs._isConstantInRequest { - return try lhs._column(db, for: alias, acceptsBijection: acceptsBijection) - } else { - return nil - } - } - - func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - var resultSQL = try """ - \(lhs._expressionSQL(context, wrappedInParenthesis: true)) \ - \(op.sql) \ - \(rhs._expressionSQL(context, wrappedInParenthesis: true)) - """ - - if wrappedInParenthesis { - resultSQL = "(\(resultSQL))" - } - - return resultSQL - } - - func _is(_ test: _SQLBooleanTest) -> SQLExpression { - switch test { - case .true: - return SQLExpressionEqual(.equal, self, true.sqlExpression) - - case .false: - return SQLExpressionEqual(.equal, self, false.sqlExpression) - - case .falsey: - if let negatedOp = op.negated { - return SQLExpressionBinary(negatedOp, lhs, rhs) - } else { - return SQLExpressionNot(self) - } - } - } - - var _isConstantInRequest: Bool { - lhs._isConstantInRequest && rhs._isConstantInRequest - } - - func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLExpressionBinary(op, lhs._qualifiedExpression(with: alias), rhs._qualifiedExpression(with: alias)) - } - - // MARK: SQLSelectable - - var _isAggregate: Bool { - lhs._isAggregate || rhs._isAggregate - } -} - -// MARK: - SQLExpressionAssociativeBinary - -/// SQLAssociativeBinaryOperator is an SQLite associative binary operator, such -/// as `+`, `*`, `AND`, etc. -/// -/// 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 { - /// The SQL operator - let sql: String - - /// The neutral value - let neutralValue: DatabaseValue - - /// If true, (a • b) • c is strictly equal to a • (b • c). - /// - /// `AND`, `OR`, `||` (concat) are stricly associative. - /// - /// `+` and `*` are not stricly associative when applied to floating - /// point values. - let isStrictlyAssociative: Bool - - /// If true, (a • b) is a bijective function of a, and a bijective - /// function of b. - /// - /// `+` and `||` (concat) are bijective. - /// - /// `AND`, `OR` and `*` are not. - let isBijective: Bool - - /// Creates a binary operator - init(sql: String, neutralValue: DatabaseValue, strictlyAssociative: Bool, bijective: Bool) { - self.sql = sql - self.neutralValue = neutralValue - self.isStrictlyAssociative = strictlyAssociative - self.isBijective = bijective - } - - /// 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, - bijective: true) - - /// 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, - bijective: 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, - bijective: false) - - /// 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, - bijective: false) - - /// 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, - bijective: true) -} - -/// `SQLExpressionAssociativeBinary` is an expression made of several -/// expressions joined with an associative binary operator. -/// -/// :nodoc: -struct SQLExpressionAssociativeBinary: SQLExpression { - let expressions: [SQLExpression] - let op: SQLAssociativeBinaryOperator - - /// Creates an expression made of expressions joined with an associative - /// binary operator. - /// - /// // length * 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.isStrictlyAssociative { - self.expressions = expressions.flatMap { expression -> [SQLExpression] in - if let reduce = expression as? SQLExpressionAssociativeBinary, reduce.op == op { - return reduce.expressions - } else { - return [expression] - } - } - } else { - self.expressions = expressions - } - } - - // MARK: SQLExpression - - func _column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool) throws -> String? { - switch expressions.count { - case 0: - return try op.neutralValue._column(db, for: alias, acceptsBijection: acceptsBijection) - case 1: - return try expressions[0]._column(db, for: alias, acceptsBijection: acceptsBijection) - default: - guard acceptsBijection && op.isBijective else { - return nil - } - - let nonConstants = expressions.filter { $0._isConstantInRequest == false } - if nonConstants.count == 1 { - return try nonConstants[0]._column(db, for: alias, acceptsBijection: acceptsBijection) - } - - return nil - } - } - - func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - switch expressions.count { - case 0: - return try op.neutralValue._expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis) - case 1: - return try expressions[0]._expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis) - default: - let expressionSQLs = try expressions.map { - try $0._expressionSQL(context, wrappedInParenthesis: true) - } - let joiner = " \(op.sql) " - var resultSQL = expressionSQLs.joined(separator: joiner) - - if wrappedInParenthesis { - resultSQL = "(\(resultSQL))" - } - - return resultSQL - } - } - - func _identifyingColums(_ db: Database, for alias: TableAlias) throws -> Set { - switch expressions.count { - case 0: - return try op.neutralValue._identifyingColums(db, for: alias) - case 1: - return try expressions[0]._identifyingColums(db, for: alias) - default: - if op == .and { - return try expressions.reduce(into: []) { try $0.formUnion($1._identifyingColums(db, for: alias)) } - } else if op == .or { - return [] - } else { - return [] - } - } - } - - func _identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set? { - switch expressions.count { - case 0: - return try op.neutralValue._identifyingRowIDs(db, for: alias) - case 1: - return try expressions[0]._identifyingRowIDs(db, for: alias) - default: - if op == .and { - var result: Set? = nil - for expression in expressions { - if let expressionRowIDs = try expression._identifyingRowIDs(db, for: alias) { - if var rowIDs = result { - rowIDs.formIntersection(expressionRowIDs) - result = rowIDs - if rowIDs.isEmpty { - break - } - } else { - result = expressionRowIDs - } - } - } - return result - } else if op == .or { - var result: Set = [] - for expression in expressions { - if let expressionRowIDs = try expression._identifyingRowIDs(db, for: alias) { - result.formUnion(expressionRowIDs) - } else { - return nil - } - } - return result - } else { - return nil - } - } - } - - var _isConstantInRequest: Bool { - switch expressions.count { - case 0: - return op.neutralValue._isConstantInRequest - default: - return expressions.allSatisfy(\._isConstantInRequest) - } - } - - var _isTrue: Bool { - switch expressions.count { - case 0: - return op.neutralValue._isTrue - case 1: - return expressions[0]._isTrue - default: - // Could do better (1 OR x, for example) - return false - } - } - - func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLExpressionAssociativeBinary(op, expressions.map { $0._qualifiedExpression(with: alias) }) - } - - // MARK: SQLSelectable - - var _isAggregate: Bool { - switch expressions.count { - case 0: - return op.neutralValue._isAggregate - default: - return expressions.contains(where: \._isAggregate) - } - } -} - -extension Sequence where Element == SQLExpression { - /// Returns an expression by joining all elements with an associative SQL - /// binary operator. - /// - /// For example: - /// - /// // SELECT * FROM player - /// // WHERE (registered - /// // AND (score >= 1000) - /// // AND (name IS NOT NULL)) - /// let conditions = [ - /// Column("registered"), - /// Column("score") >= 1000, - /// Column("name") != nil] - /// Player.filter(conditions.joined(operator: .and)) - /// - /// 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`, and true for `.and`. - public func joined(operator: SQLAssociativeBinaryOperator) -> SQLExpression { - SQLExpressionAssociativeBinary(`operator`, Array(self)) - } -} - -// MARK: - SQLExpressionEqual - -/// :nodoc: -struct SQLExpressionEqual: SQLExpression { - var lhs: SQLExpression - var rhs: SQLExpression - var op: Operator - - init(_ op: Operator, _ lhs: SQLExpression, _ rhs: SQLExpression) { - self.lhs = lhs - self.rhs = rhs - self.op = op - } - - enum Operator: String { - case equal = "=" - case notEqual = "<>" - case `is` = "IS" - case isNot = "IS NOT" - - var negated: Operator { - switch self { - case .equal: return .notEqual - case .notEqual: return .equal - case .is: return .isNot - case .isNot: return .is - } - } - } - - // MARK: SQLExpression - - func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - var resultSQL = try """ - \(lhs._expressionSQL(context, wrappedInParenthesis: true)) \ - \(op.rawValue) \ - \(rhs._expressionSQL(context, wrappedInParenthesis: true)) - """ - - if wrappedInParenthesis { - resultSQL = "(\(resultSQL))" - } - - return resultSQL - } - - func _identifyingColums(_ db: Database, for alias: TableAlias) throws -> Set { - switch op { - case .equal, .is: - if let column = try lhs._column(db, for: alias, acceptsBijection: true), - rhs._isConstantInRequest - { - return [column] - } - - if let column = try rhs._column(db, for: alias, acceptsBijection: true), - lhs._isConstantInRequest - { - return [column] - } - - return [] - - case .notEqual, .isNot: - return [] - } - } - - func _identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set? { - switch op { - case .equal, .is: - if let column = try lhs._column(db, for: alias), - try db.columnIsRowID(column, of: alias.tableName), - let dbValue = rhs as? DatabaseValue - { - if let rowID = Int64.fromDatabaseValue(dbValue) { - return [rowID] - } else { - // We miss `rowid = '1'` here, because SQLite would interpret the '1' string as a number - return [] - } - } - - if let column = try rhs._column(db, for: alias), - try db.columnIsRowID(column, of: alias.tableName), - let dbValue = lhs as? DatabaseValue - { - if let rowID = Int64.fromDatabaseValue(dbValue) { - return [rowID] - } else { - // We miss `rowid = '1'` here, because SQLite would interpret the '1' string as a number - return [] - } - } - - return nil - - case .notEqual, .isNot: - return nil - } - } - - func _is(_ test: _SQLBooleanTest) -> SQLExpression { - switch test { - case .true: - return SQLExpressionEqual(.equal, self, true.sqlExpression) - - case .false: - return SQLExpressionEqual(.equal, self, false.sqlExpression) - - case .falsey: - return SQLExpressionEqual(op.negated, lhs, rhs) - } - } - - var _isConstantInRequest: Bool { - lhs._isConstantInRequest && rhs._isConstantInRequest - } - - func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLExpressionEqual(op, lhs._qualifiedExpression(with: alias), rhs._qualifiedExpression(with: alias)) - } - - // MARK: SQLSelectable - - var _isAggregate: Bool { - lhs._isAggregate || rhs._isAggregate - } -} - -// MARK: - SQLExpressionContains - -/// 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])) -/// -/// :nodoc: -struct SQLExpressionContains: SQLExpression { - let expression: SQLExpression - let collection: SQLCollection - let isNegated: Bool - - init(_ value: SQLExpressible, _ collection: SQLCollection, negated: Bool = false) { - self.expression = value.sqlExpression - self.collection = collection - self.isNegated = negated - } - - // MARK: SQLExpression - - func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - var resultSQL = try """ - \(expression._expressionSQL(context, wrappedInParenthesis: true)) \ - \(isNegated ? "NOT IN" : "IN") \ - \(collection._collectionSQL(context)) - """ - - if wrappedInParenthesis { - resultSQL = "(\(resultSQL))" - } - - return resultSQL - } - - func _identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set? { - if let expressions = collection._collectionExpressions, - let column = try expression._column(db, for: alias), - try db.columnIsRowID(column, of: alias.tableName) - { - return Set(expressions.compactMap { - ($0 as? DatabaseValue).flatMap { Int64.fromDatabaseValue($0) } - }) - } else { - return nil - } - } - - func _is(_ test: _SQLBooleanTest) -> SQLExpression { - switch test { - case .true: - return SQLExpressionEqual(.equal, self, true.sqlExpression) - - case .false: - return SQLExpressionEqual(.equal, self, false.sqlExpression) - - case .falsey: - return SQLExpressionContains(expression, collection, negated: !isNegated) - } - } - - var _isConstantInRequest: Bool { - guard let expressions = collection._collectionExpressions else { - return false - } - - return expression._isConstantInRequest && expressions.allSatisfy(\._isConstantInRequest) - } - - func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLExpressionContains( - expression._qualifiedExpression(with: alias), - collection._qualifiedCollection(with: alias), - negated: isNegated) - } - - // MARK: SQLSelectable - - var _isAggregate: Bool { - if expression._isAggregate { - // SELECT aggregate IN (...) - return true - } - - if let expressions = collection._collectionExpressions, - expressions.contains(where: \._isAggregate) - { - // SELECT expr IN (aggregate, ...) - return true - } - - return false - } -} - -// MARK: - SQLExpressionBetween - -/// 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) -/// -/// :nodoc: -struct SQLExpressionBetween: SQLExpression { - let expression: SQLExpression - let lowerBound: SQLExpression - let upperBound: SQLExpression - let isNegated: Bool - - init(_ expression: SQLExpression, _ lowerBound: SQLExpression, _ upperBound: SQLExpression, negated: Bool = false) { - self.expression = expression - self.lowerBound = lowerBound - self.upperBound = upperBound - self.isNegated = negated - } - - // MARK: SQLExpression - - func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - var resultSQL = try """ - \(expression._expressionSQL(context, wrappedInParenthesis: true)) \ - \(isNegated ? "NOT BETWEEN" : "BETWEEN") \ - \(lowerBound._expressionSQL(context, wrappedInParenthesis: true)) \ - AND \ - \(upperBound._expressionSQL(context, wrappedInParenthesis: true)) - """ - - if wrappedInParenthesis { - resultSQL = "(\(resultSQL))" - } - - return resultSQL - } - - func _is(_ test: _SQLBooleanTest) -> SQLExpression { - switch test { - case .true: - return SQLExpressionEqual(.equal, self, true.sqlExpression) - - case .false: - return SQLExpressionEqual(.equal, self, false.sqlExpression) - - case .falsey: - return SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated) - } - } - - var _isConstantInRequest: Bool { - expression._isConstantInRequest - && lowerBound._isConstantInRequest - && upperBound._isConstantInRequest - } - - func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLExpressionBetween( - expression._qualifiedExpression(with: alias), - lowerBound._qualifiedExpression(with: alias), - upperBound._qualifiedExpression(with: alias), - negated: isNegated) - } - - // MARK: SQLSelectable - - var _isAggregate: Bool { - expression._isAggregate - } -} - -// MARK: - SQLExpressionFunction - -/// :nodoc: -struct SQLExpressionFunction: SQLExpression { - let function: String - let arguments: [SQLExpression] - - init(_ function: String, arguments: [SQLExpression]) { - self.function = function - self.arguments = arguments - } - - init(_ function: String, arguments: SQLExpressible...) { - self.init(function, arguments: arguments.map(\.sqlExpression)) - } - - // MARK: SQLExpression - - func _column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool) throws -> String? { - guard acceptsBijection else { - return nil - } - let function = self.function.uppercased() - if ["HEX", "QUOTE"].contains(function) && arguments.count == 1 { - return try arguments[0]._column(db, for: alias, acceptsBijection: acceptsBijection) - } else if function == "IFNULL" && arguments.count == 2 && arguments[1]._isConstantInRequest { - return try arguments[0]._column(db, for: alias, acceptsBijection: acceptsBijection) - } else { - return nil - } - } - - func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - try function - + "(" - + arguments - .map { try $0._expressionSQL(context, wrappedInParenthesis: false) } - .joined(separator: ", ") - + ")" - } - - private static let knownPureFunctions = [ - "ABS", "CHAR", "COALESCE", "GLOB", "HEX", "IFNULL", - "IIF", "INSTR", "LENGTH", "LIKE", "LIKELIHOOD", - "LIKELY", "LOAD_EXTENSION", "LOWER", "LTRIM", - "NULLIF", "PRINTF", "QUOTE", "REPLACE", "ROUND", - "RTRIM", "SOUNDEX", "SQLITE_COMPILEOPTION_GET", - "SQLITE_COMPILEOPTION_USED", "SQLITE_SOURCE_ID", - "SQLITE_VERSION", "SUBSTR", "TRIM", "TRIM", - "TYPEOF", "UNICODE", "UNLIKELY", "UPPER", "ZEROBLOB", - ] - - var _isConstantInRequest: Bool { - let function = self.function.uppercased() - guard ((function == "MAX" || function == "MIN") && arguments.count > 1) - || Self.knownPureFunctions.contains(function) - else { - return false // Don't know - assume not constant - } - - return arguments.allSatisfy(\._isConstantInRequest) - } - - func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLExpressionFunction(function, arguments: arguments.map { $0._qualifiedExpression(with: alias) }) - } - - // MARK: SQLSelectable - - var _isAggregate: Bool { - let function = self.function.uppercased() - if ["MIN", "MAX"].contains(function) && arguments.count == 1 { - return true - } else if ["AVG", "COUNT", "SUM", "TOTAL"].contains(function) && arguments.count == 1 { - return true - } else if function == "GROUP_CONCAT" && (arguments.count == 1 || arguments.count == 2) { - return true - } else { - return false - } - } -} - -// MARK: - SQLExpressionCount - -/// SQLExpressionCount is a call to the SQL `COUNT` function. -/// -/// // COUNT(name) -/// SQLExpressionCount(Column("name")) -/// -/// :nodoc: -struct SQLExpressionCount: SQLExpression { - /// The counted value - let counted: SQLSelectable - - init(_ counted: SQLSelectable) { - self.counted = counted - } - - // MARK: SQLExpression - - func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - try "COUNT(\(counted._countedSQL(context)))" - } - - func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLExpressionCount(counted._qualifiedSelectable(with: alias)) - } - - // MARK: SQLSelectable - - var _isAggregate: Bool { true } -} - -// MARK: - SQLExpressionCountDistinct - -/// SQLExpressionCountDistinct is a call to the SQL `COUNT(DISTINCT ...)` function. -/// -/// // COUNT(DISTINCT name) -/// SQLExpressionCountDistinct(Column("name")) -/// -/// :nodoc: -struct SQLExpressionCountDistinct: SQLExpression { - let counted: SQLExpression - - init(_ counted: SQLExpression) { - self.counted = counted - } - - // MARK: SQLExpression - - func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - try "COUNT(DISTINCT \(counted._countedSQL(context)))" - } - - func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLExpressionCountDistinct(counted._qualifiedExpression(with: alias)) - } - - // MARK: SQLSelectable - - var _isAggregate: Bool { true } -} - -// MARK: - SQLExpressionIsEmpty - -/// This one helps generating `COUNT(...) = 0` or `COUNT(...) > 0` while letting -/// the user using the not `!` logical operator, or comparisons with booleans -/// such as `== true` or `== false`. -/// -/// :nodoc: -struct SQLExpressionIsEmpty: SQLExpression { - var countExpression: SQLExpression - var isEmpty: Bool - - // countExpression should be a counting expression - init(_ countExpression: SQLExpression, isEmpty: Bool = true) { - self.countExpression = countExpression - self.isEmpty = isEmpty - } - - // MARK: SQLExpression - - func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - var resultSQL = try """ - \(countExpression._expressionSQL(context, wrappedInParenthesis: true)) \ - \(isEmpty ? "= 0" : "> 0") - """ - - if wrappedInParenthesis { - resultSQL = "(\(resultSQL))" - } - - return resultSQL - } - - func _is(_ test: _SQLBooleanTest) -> SQLExpression { - switch test { - case .true: - return self - case .false, .falsey: - return SQLExpressionIsEmpty(countExpression, isEmpty: !isEmpty) - } - } - - var _isConstantInRequest: Bool { countExpression._isConstantInRequest } - - func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLExpressionIsEmpty(countExpression._qualifiedExpression(with: alias), isEmpty: isEmpty) - } - - // MARK: SQLSelectable - - var _isAggregate: Bool { countExpression._isAggregate } -} - -// MARK: - SQLExpressionTableMatch - -/// :nodoc: -struct SQLExpressionTableMatch: SQLExpression { - var alias: TableAlias - var pattern: SQLExpression - - func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - var resultSQL = try """ - \(context.resolvedName(for: alias).quotedDatabaseIdentifier) \ - MATCH \ - \(pattern._expressionSQL(context, wrappedInParenthesis: true)) - """ - - if wrappedInParenthesis { - resultSQL = "(\(resultSQL))" - } - - return resultSQL - } - - func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLExpressionTableMatch( - alias: self.alias, - pattern: pattern._qualifiedExpression(with: alias)) - } -} - -// MARK: - SQLExpressionCollate - -/// SQLExpressionCollate is an expression tainted by an SQLite collation. -/// -/// // email = 'arthur@example.com' COLLATE NOCASE -/// SQLExpressionCollate(Column("email") == "arthur@example.com", "NOCASE") -/// -/// :nodoc: -struct SQLExpressionCollate: SQLExpression { - let expression: SQLExpression - let collationName: Database.CollationName - - init(_ expression: SQLExpression, collationName: Database.CollationName) { - self.expression = expression - self.collationName = collationName - } - - // MARK: SQLExpression - - func _column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool) throws -> String? { - try expression._column(db, for: alias, acceptsBijection: acceptsBijection) - } - - func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - var resultSQL = try """ - \(expression._expressionSQL(context, wrappedInParenthesis: false)) \ - COLLATE \ - \(collationName.rawValue) - """ - - if wrappedInParenthesis { - resultSQL = "(\(resultSQL))" - } - - return resultSQL - } - - func _identifyingColums(_ db: Database, for alias: TableAlias) throws -> Set { - try expression._identifyingColums(db, for: alias) - } - - func _identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set? { - try expression._identifyingRowIDs(db, for: alias) - } - - func _is(_ test: _SQLBooleanTest) -> SQLExpression { - SQLExpressionCollate(expression._is(test), collationName: collationName) - } - - var _isConstantInRequest: Bool { expression._isConstantInRequest } - - var _isTrue: Bool { expression._isTrue } - - func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLExpressionCollate(expression._qualifiedExpression(with: alias), collationName: collationName) - } - - // MARK: SQLSelectable - - var _isAggregate: Bool { expression._isAggregate } - -} - -// MARK: - SQLExpressionFastPrimaryKey - -/// SQLExpressionFastPrimaryKey is an expression that picks the fastest available -/// primary key. -/// -/// It crashes for WITHOUT ROWID table with a multi-columns primary key. -/// Future versions of GRDB may use [row values](https://www.sqlite.org/rowvalue.html). -/// -/// :nodoc: -struct SQLExpressionFastPrimaryKey: SQLExpression { - func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - // Likely a GRDB bug: how comes this expression is used before it - // has been qualified? - fatalError("SQLExpressionFastPrimaryKey is not qualified.") - } - - func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLExpressionQualifiedFastPrimaryKey(alias: alias) - } -} - -/// :nodoc: -struct SQLExpressionQualifiedFastPrimaryKey: SQLExpression { - let alias: TableAlias - - /// 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 rowid - return rowIDColumn - } else if primaryKey.tableHasRowID { - // Prefer the rowid - 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") - } - } - - func _column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool) throws -> String? { - if alias == self.alias { - return try columnName(db) - } - return nil - } - - func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - try SQLQualifiedColumn(columnName(context.db), alias: alias) - ._expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis) - } - - func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - // Never requalify - self - } -} diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 7ff6f2fb7..89eeacbd2 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -1,7 +1,287 @@ -/// Implementation details of `SQLExpression`. -/// -/// :nodoc: -public protocol _SQLExpression { +/// SQLExpression is the type that represents an SQL expression, as +/// described at https://www.sqlite.org/lang_expr.html +public struct SQLExpression { + private var impl: Impl + + private enum Impl { + // MARK: Basic Expressions + + /// An unqualified database column. + /// + /// "score" is a valid unqualified name. "player.score" is not. + case column(String) + + /// A qualified column in the database, as in + /// + /// SELECT player.score FROM player + case qualifiedColumn(String, TableAlias) + + /// A database value + case databaseValue(DatabaseValue) + + /// A [row value](https://www.sqlite.org/rowvalue.html). + /// + /// - precondition: expressions.count > 0 + case rowValue([SQLExpression]) + + /// A subquery expression + case subquery(SQLSubquery) + + /// A literal SQL expression + case literal(SQLLiteral) + + // MARK: Operators + + /// An expression that checks if a values is included in a range with the + /// `BETWEEN` operator. + /// + /// id BETWEEN 1 AND 3 + indirect case between( + expression: SQLExpression, + lowerBound: SQLExpression, + upperBound: SQLExpression, + isNegated: Bool) + + /// An expression made of two expressions joined with a + /// binary operator. + /// + /// length * width + /// score >= 1000 + indirect case binary(SQLBinaryOperator, SQLExpression, SQLExpression) + + /// An expression made of several expressions joined with an associative + /// binary operator. + /// + /// a AND b AND c + /// score + bonus + /// + /// - precondition: expressions.count > 1 + case associativeBinary(SQLAssociativeBinaryOperator, [SQLExpression]) + + /// An expression that checks the inclusion of a value in a collection + /// with the `IN` operator. + /// + /// id IN (1,2,3) + /// score IN (SELECT ...) + indirect case `in`(SQLExpression, SQLCollection, isNegated: Bool) + + /// An expression made of an unary operator and an operand expression. + /// + /// -score + indirect case unary(SQLUnaryOperator, SQLExpression) + + /// An equality comparison + /// + /// a = b + /// a <> b + /// a IS b + /// a IS NOT b + indirect case compare(SQLCompareOperator, SQLExpression, SQLExpression) + + /// A full-text table match + /// + /// SELECT * FROM document WHERE document MATCH 'query' + indirect case tableMatch(TableAlias, SQLExpression) + + /// The logical not + /// + /// NOT selected + indirect case not(SQLExpression) + + // MARK: Collations + + /// An expression tainted by an SQLite collation. + /// + /// SELECT * FROM player WHERE email = 'arthur@example.com' COLLATE NOCASE + indirect case collated(SQLExpression, Database.CollationName) + + // MARK: Functions + + /// A call to the SQL `COUNT(...)` function. + /// + /// SELECT COUNT(name) FROM player + /// SELECT COUNT(*) FROM player + indirect case count(SQLSelection) + + /// A call to the SQL `COUNT(DISTINCT ...)` function. + /// + /// SELECT COUNT(DISTINCT name) FROM player + indirect case countDistinct(SQLExpression) + + /// A function call + /// + /// LENGTH(name) + case function(String, [SQLExpression]) + + /// This expression helps generating `COUNT(...) = 0` or + /// `COUNT(...) > 0`. + /// + /// It has a specific behavior when negated with the `!` logical + /// operator, or compared with booleans. + /// + /// WHERE COUNT(DISTINCT player.id) == 0 + /// WHERE COUNT(DISTINCT player.id) > 0 + indirect case isEmpty(SQLExpression, isNegated: Bool) + + // MARK: Deferred + + /// 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). + case fastPrimaryKey + + /// Qualified version of `.fastPrimaryKey` + case qualifiedFastPrimaryKey(TableAlias) + } + + /// SQLite row values were shipped in SQLite 3.15: + /// https://www.sqlite.org/releaselog/3_15_0.html + static let rowValuesAreAvailable = (sqlite3_libversion_number() >= 3015000) + + static func column(_ name: String) -> Self { + self.init(impl: .column(name)) + } + + static func qualifiedColumn(_ name: String, _ alias: TableAlias) -> Self { + self.init(impl: .qualifiedColumn(name, alias)) + } + + static func databaseValue(_ dbValue: DatabaseValue) -> Self { + self.init(impl: .databaseValue(dbValue)) + } + + static let null = SQLExpression.databaseValue(.null) + + /// Returns nil if and only if expressions is empty + static func rowValue(_ expressions: [SQLExpression]) -> Self? { + guard let expression = expressions.first else { + return nil + } + if expressions.count == 1 { + return expression + } + return self.init(impl: .rowValue(expressions)) + } + + static func subquery(_ subquery: SQLSubquery) -> Self { + self.init(impl: .subquery(subquery)) + } + + static func literal(_ sqlLiteral: SQLLiteral) -> Self { + self.init(impl: .literal(sqlLiteral)) + } + + static func between( + expression: SQLExpression, + lowerBound: SQLExpression, + upperBound: SQLExpression, + isNegated: Bool = false) -> Self + { + self.init(impl: .between( + expression: expression, + lowerBound: lowerBound, + upperBound: upperBound, + isNegated: isNegated)) + } + + static func binary(_ op: SQLBinaryOperator, _ lhs: SQLExpression, _ rhs: SQLExpression) -> Self { + self.init(impl: .binary(op, lhs, rhs)) + } + + static func associativeBinary(_ op: SQLAssociativeBinaryOperator, _ expressions: [SQLExpression]) -> Self { + // flatten when possible: a • (b • c) = a • b • c + var expressions = expressions + if op.isStrictlyAssociative { + expressions = expressions.flatMap { expression -> [SQLExpression] in + if case .associativeBinary(op, let expressions) = expression.impl { + return expressions + } else { + return [expression] + } + } + } + + guard let expression = expressions.first else { + return op.neutralValue.sqlExpression + } + if expressions.count == 1 { + return expression + } + return self.init(impl: .associativeBinary(op, expressions)) + } + + static func `in`(_ expression: SQLExpression, _ collection: SQLCollection, isNegated: Bool = false) -> Self { + self.init(impl: .in(expression, collection, isNegated: isNegated)) + } + + static func unary(_ op: SQLUnaryOperator, _ expression: SQLExpression) -> Self { + self.init(impl: .unary(op, expression)) + } + + static func compare(_ op: SQLCompareOperator, _ lhs: SQLExpression, _ rhs: SQLExpression) -> Self { + self.init(impl: .compare(op, lhs, rhs)) + } + + /// "x = y" or "x IS NULL" + static func equal(_ lhs: SQLExpression, _ rhs: SQLExpression) -> Self { + switch (lhs.impl, rhs.impl) { + case let (impl, .databaseValue(.null)), + let (.databaseValue(.null), impl): + // ... IS NULL + return .compare(.is, SQLExpression(impl: impl), .null) + default: + // lhs = rhs + return .compare(.equal, lhs, rhs) + } + } + + static func tableMatch(_ alias: TableAlias, _ expression: SQLExpression) -> Self { + self.init(impl: .tableMatch(alias, expression)) + } + + static func not(_ expression: SQLExpression) -> Self { + self.init(impl: .not(expression)) + } + + static func collated(_ expression: SQLExpression, _ collationName: Database.CollationName) -> Self { + self.init(impl: .collated(expression, collationName)) + } + + static func count(_ selection: SQLSelection) -> Self { + self.init(impl: .count(selection)) + } + + static func countDistinct(_ expression: SQLExpression) -> Self { + self.init(impl: .countDistinct(expression)) + } + + static func function(_ name: String, _ expressions: [SQLExpression]) -> Self { + self.init(impl: .function(name, expressions)) + } + + static func isEmpty(_ expression: SQLExpression, isNegated: Bool = false) -> Self { + self.init(impl: .isEmpty(expression, isNegated: isNegated)) + } + + static let fastPrimaryKey = SQLExpression(impl: .fastPrimaryKey) + + static func qualifiedFastPrimaryKey(_ alias: TableAlias) -> Self { + self.init(impl: .qualifiedFastPrimaryKey(alias)) + } +} + +extension SQLExpression { + /// The expression as a quoted SQL literal (not public in order to avoid abuses) + /// + /// try "foo'bar".databaseValue.quotedSQL(db) // "'foo''bar'"" + func quotedSQL(_ db: Database) throws -> String { + let context = SQLGenerationContext(db, argumentsSink: .forRawSQL) + return try sql(context) + } +} + +extension SQLExpression { /// If this expression is a table colum, returns the name of this column. /// /// When in doubt, returns nil. @@ -27,16 +307,260 @@ public protocol _SQLExpression { /// - parameter acceptsBijection: If true, expressions that define a /// bijection on a column return this column. For example: `-score` /// returns `score`. - func _column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool) throws -> String? - + func column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool = false) throws -> String? { + switch impl { + case let .qualifiedColumn(name, a): + if alias == a { + return name + } else { + return nil + } + + case let .binary(op, lhs, rhs): + guard acceptsBijection && op == .subtract else { + return nil + } + + if lhs.isConstantInRequest { + return try rhs.column(db, for: alias, acceptsBijection: acceptsBijection) + } else if rhs.isConstantInRequest { + return try lhs.column(db, for: alias, acceptsBijection: acceptsBijection) + } else { + return nil + } + + case let .associativeBinary(op, expressions): + assert(expressions.count > 1) + guard acceptsBijection && op.isBijective else { + return nil + } + let nonConstants = expressions.filter { $0.isConstantInRequest == false } + if nonConstants.count == 1 { + return try nonConstants[0].column(db, for: alias, acceptsBijection: acceptsBijection) + } + return nil + + case let .unary(op, expression): + if acceptsBijection && op == .minus { + return try expression.column(db, for: alias, acceptsBijection: acceptsBijection) + } + return nil + + case let .collated(expression, _): + return try expression.column(db, for: alias, acceptsBijection: acceptsBijection) + + case let .function(name, expressions): + guard acceptsBijection else { + return nil + } + let name = name.uppercased() + if ["HEX", "QUOTE"].contains(name) && expressions.count == 1 { + return try expressions[0].column(db, for: alias, acceptsBijection: acceptsBijection) + } else if name == "IFNULL" && expressions.count == 2 && expressions[1].isConstantInRequest { + return try expressions[0].column(db, for: alias, acceptsBijection: acceptsBijection) + } else { + return nil + } + + case let .qualifiedFastPrimaryKey(a): + if alias == a { + return try db.primaryKey(alias.tableName).fastPrimaryKeyColumn + } + return nil + + default: + return nil + } + } +} + +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 - + func sql(_ context: SQLGenerationContext, wrappedInParenthesis: Bool = false) throws -> String { + switch impl { + case let .column(name): + return name.quotedDatabaseIdentifier + + case let .qualifiedColumn(name, alias): + if let qualifier = context.qualifier(for: alias) { + return qualifier.quotedDatabaseIdentifier + + "." + + name.quotedDatabaseIdentifier + } + return name.quotedDatabaseIdentifier + + case let .databaseValue(dbValue): + if dbValue.isNull { + // fast path for NULL + return "NULL" + } else if context.append(arguments: [dbValue]) { + // Use statement arguments + return "?" + } else { + // Quoting needed: just use SQLite, which knows better. + return try String.fetchOne(context.db, sql: "SELECT QUOTE(?)", arguments: [dbValue])! + } + + case let .rowValue(expressions): + assert(!expressions.isEmpty) + let values = try expressions.map { try $0.sql(context) } + return "(" + + values.joined(separator: ", ") + + ")" + + case let .subquery(subquery): + return try "(" + + subquery.sql(context) + + ")" + + case let .literal(sqlLiteral): + var resultSQL = try sqlLiteral.sql(context) + if wrappedInParenthesis { + resultSQL = "(\(resultSQL))" + } + return resultSQL + + case let .between(expression: expression, lowerBound: lowerBound, upperBound: upperBound, isNegated: isNegated): + var resultSQL = try """ + \(expression.sql(context, wrappedInParenthesis: true)) \ + \(isNegated ? "NOT BETWEEN" : "BETWEEN") \ + \(lowerBound.sql(context, wrappedInParenthesis: true)) \ + AND \ + \(upperBound.sql(context, wrappedInParenthesis: true)) + """ + if wrappedInParenthesis { + resultSQL = "(\(resultSQL))" + } + return resultSQL + + case let .binary(op, lhs, rhs): + var resultSQL = try """ + \(lhs.sql(context, wrappedInParenthesis: true)) \ + \(op.sql) \ + \(rhs.sql(context, wrappedInParenthesis: true)) + """ + if wrappedInParenthesis { + resultSQL = "(\(resultSQL))" + } + return resultSQL + + case let .associativeBinary(op, expressions): + assert(expressions.count > 1) + let expressionSQLs = try expressions.map { + try $0.sql(context, wrappedInParenthesis: true) + } + let joiner = " \(op.sql) " + var resultSQL = expressionSQLs.joined(separator: joiner) + if wrappedInParenthesis { + resultSQL = "(\(resultSQL))" + } + return resultSQL + + case let .in(expression, collection, isNegated: isNegated): + var resultSQL = try """ + \(expression.sql(context, wrappedInParenthesis: true)) \ + \(isNegated ? "NOT IN" : "IN") \ + \(collection.sql(context)) + """ + if wrappedInParenthesis { + resultSQL = "(\(resultSQL))" + } + return resultSQL + + case let .unary(op, expression): + var resultSQL = try op.sql + + (op.needsRightSpace ? " " : "") + + expression.sql(context, wrappedInParenthesis: true) + if wrappedInParenthesis { + resultSQL = "(\(resultSQL))" + } + return resultSQL + + case let .compare(op, lhs, rhs): + var resultSQL = try """ + \(lhs.sql(context, wrappedInParenthesis: true)) \ + \(op.rawValue) \ + \(rhs.sql(context, wrappedInParenthesis: true)) + """ + if wrappedInParenthesis { + resultSQL = "(\(resultSQL))" + } + return resultSQL + + case let .tableMatch(alias, expression): + var resultSQL = try """ + \(context.resolvedName(for: alias).quotedDatabaseIdentifier) \ + MATCH \ + \(expression.sql(context, wrappedInParenthesis: true)) + """ + if wrappedInParenthesis { + resultSQL = "(\(resultSQL))" + } + return resultSQL + + case let .not(expression): + var resultSQL = try "NOT \(expression.sql(context, wrappedInParenthesis: true))" + if wrappedInParenthesis { + resultSQL = "(\(resultSQL))" + } + return resultSQL + + case let .collated(expression, collationName): + var resultSQL = try """ + \(expression.sql(context)) \ + COLLATE \ + \(collationName.rawValue) + """ + if wrappedInParenthesis { + resultSQL = "(\(resultSQL))" + } + return resultSQL + + case let .count(selection): + return try "COUNT(\(selection.countedSQL(context)))" + + case let .countDistinct(expression): + return try "COUNT(DISTINCT \(expression.sql(context)))" + + case let .function(name, expressions): + return try name + + "(" + + expressions.map { try $0.sql(context) }.joined(separator: ", ") + + ")" + + case let .isEmpty(expression, isNegated: isNegated): + var resultSQL = try """ + \(expression.sql(context, wrappedInParenthesis: true)) \ + \(isNegated ? "> 0" : "= 0") + """ + if wrappedInParenthesis { + resultSQL = "(\(resultSQL))" + } + return resultSQL + + case .fastPrimaryKey: + // Likely a GRDB bug: how comes this expression is used before it + // has been qualified? + fatalError("SQLExpression.fastPrimaryKey is not qualified.") + + case let .qualifiedFastPrimaryKey(alias): + let primaryKey = try context.db.primaryKey(alias.tableName) + guard let column = primaryKey.fastPrimaryKeyColumn else { + fatalError("Not implemented for WITHOUT ROWID table with a multi-columns primary key") + } + return try SQLExpression + .qualifiedColumn(column, alias) + .sql(context, wrappedInParenthesis: wrappedInParenthesis) + } + } +} + +extension SQLExpression { /// Returns the columns that identify a unique row in the request /// /// When in doubt, returns an empty set. @@ -59,8 +583,53 @@ public protocol _SQLExpression { /// /// // SELECT * FROM "player" WHERE "name" = 'Arthur' LIMIT 1 /// try Player.filter(Column("name") == "Arthur").fetchOne(db) - func _identifyingColums(_ db: Database, for alias: TableAlias) throws -> Set - + func identifyingColums(_ db: Database, for alias: TableAlias) throws -> Set { + switch impl { + case let .rowValue(expressions): + assert(!expressions.isEmpty) + return try expressions.reduce(into: []) { try $0.formUnion($1.identifyingColums(db, for: alias)) } + + case let .associativeBinary(op, expressions): + assert(expressions.count > 1) + if op == .and { + return try expressions.reduce(into: []) { try $0.formUnion($1.identifyingColums(db, for: alias)) } + } else if op == .or { + return [] + } else { + return [] + } + + case let .compare(op, lhs, rhs): + switch op { + case .equal, .is: + if let column = try lhs.column(db, for: alias, acceptsBijection: true), + rhs.isConstantInRequest + { + return [column] + } + + if let column = try rhs.column(db, for: alias, acceptsBijection: true), + lhs.isConstantInRequest + { + return [column] + } + + return [] + + case .notEqual, .isNot: + return [] + } + + case let .collated(expression, _): + return try expression.identifyingColums(db, for: alias) + + default: + return [] + } + } +} + +extension SQLExpression { /// Returns the rowIds that identify rows in the request. A nil result means /// an unbounded list. /// @@ -84,8 +653,108 @@ public protocol _SQLExpression { /// let request = Player.filter(keys: [1, 2, 3]) /// let regionObservation = DatabaseRegionObservation(tracking: request) /// let valueObservation = ValueObservation.tracking(request.fetchAll) - func _identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set? - + func identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set? { + switch impl { + case let .databaseValue(dbValue): + if dbValue.isNull || dbValue == false.databaseValue { + // Those requests select no row: + // - WHERE NULL + // - WHERE 0 + return [] + } + return nil + + case let .associativeBinary(op, expressions): + assert(expressions.count > 1) + if op == .and { + var result: Set? = nil + for expression in expressions { + if let expressionRowIDs = try expression.identifyingRowIDs(db, for: alias) { + if var rowIDs = result { + rowIDs.formIntersection(expressionRowIDs) + result = rowIDs + if rowIDs.isEmpty { + break + } + } else { + result = expressionRowIDs + } + } + } + return result + } else if op == .or { + var result: Set = [] + for expression in expressions { + if let expressionRowIDs = try expression.identifyingRowIDs(db, for: alias) { + result.formUnion(expressionRowIDs) + } else { + return nil + } + } + return result + } else { + return nil + } + + case let .in(expression, collection, isNegated: false): + if let expressions = collection.collectionExpressions, + let column = try expression.column(db, for: alias), + try db.columnIsRowID(column, of: alias.tableName) + { + return Set(expressions.compactMap { expression in + if case let .databaseValue(dbValue) = expression.impl { + return Int64.fromDatabaseValue(dbValue) + } else { + return nil + } + }) + } else { + return nil + } + + case let .compare(op, lhs, rhs): + switch op { + case .equal, .is: + if let column = try lhs.column(db, for: alias), + try db.columnIsRowID(column, of: alias.tableName), + case .databaseValue(let dbValue) = rhs.impl + { + if let rowID = Int64.fromDatabaseValue(dbValue) { + return [rowID] + } else { + // We miss `rowid = '1'` here, because SQLite would interpret the '1' string as a number + return [] + } + } + + if let column = try rhs.column(db, for: alias), + try db.columnIsRowID(column, of: alias.tableName), + case .databaseValue(let dbValue) = lhs.impl + { + if let rowID = Int64.fromDatabaseValue(dbValue) { + return [rowID] + } else { + // We miss `rowid = '1'` here, because SQLite would interpret the '1' string as a number + return [] + } + } + + return nil + + case .notEqual, .isNot: + return nil + } + + case let .collated(expression, _): + return try expression.identifyingRowIDs(db, for: alias) + + default: + return nil + } + } +} + +extension SQLExpression { /// Performs a boolean test. /// /// We generally distinguish four boolean values: @@ -122,7 +791,138 @@ public protocol _SQLExpression { /// - `!association.isEmpty` -> `COUNT(child.id) > 0` /// - `association.isEmpty == true` -> `COUNT(child.id) = 0` /// - `association.isEmpty == false` -> `COUNT(child.id) > 0` - func _is(_ test: _SQLBooleanTest) -> SQLExpression + func `is`(_ test: SQLBooleanTest) -> SQLExpression { + switch impl { + case let .databaseValue(dbValue): + switch dbValue.storage { + case .null: + return .null + + case .int64(let int64) where int64 == 0 || int64 == 1: + switch test { + case .true: + return (int64 == 1).sqlExpression + case .false, .falsey: + return (int64 == 0).sqlExpression + } + + default: + switch test { + case .true: + return .compare(.equal, self, true.sqlExpression) + case .false: + return .compare(.equal, self, false.sqlExpression) + case .falsey: + return .not(self) + } + } + + case let .between(expression: expression, lowerBound: lowerBound, upperBound: upperBound, isNegated: isNegated): + switch test { + case .true: + return .compare(.equal, self, true.sqlExpression) + + case .false: + return .compare(.equal, self, false.sqlExpression) + + case .falsey: + return .between( + expression: expression, + lowerBound: lowerBound, + upperBound: upperBound, + isNegated: !isNegated) + } + + case let .binary(op, lhs, rhs): + switch test { + case .true: + return .compare(.equal, self, true.sqlExpression) + + case .false: + return .compare(.equal, self, false.sqlExpression) + + case .falsey: + if let negatedOp = op.negated { + return .binary(negatedOp, lhs, rhs) + } else { + return .not(self) + } + } + + case let .in(expression, collection, isNegated: isNegated): + switch test { + case .true: + return .compare(.equal, self, true.sqlExpression) + + case .false: + return .compare(.equal, self, false.sqlExpression) + + case .falsey: + return .in(expression, collection, isNegated: !isNegated) + } + + case let .compare(op, lhs, rhs): + switch test { + case .true: + return .compare(.equal, self, true.sqlExpression) + + case .false: + return .compare(.equal, self, false.sqlExpression) + + case .falsey: + return .compare(op.negated, lhs, rhs) + } + + case .not: + switch test { + case .true: + return .compare(.equal, self, true.sqlExpression) + + case .false: + return .compare(.equal, self, false.sqlExpression) + + case .falsey: + // Support `NOT (NOT expression)` as a technique to build 0 or 1 + return .not(self) + } + + case let .collated(expression, collationName): + return .collated(expression.is(test), collationName) + + case let .isEmpty(expression, isNegated: isNegated): + switch test { + case .true: + return self + case .false, .falsey: + return .isEmpty(expression, isNegated: !isNegated) + } + + default: + switch test { + case .true: + return .compare(.equal, self, true.sqlExpression) + + case .false: + return .compare(.equal, self, false.sqlExpression) + + case .falsey: + return .not(self) + } + } + } +} + +extension SQLExpression { + private static let knownPureFunctions = [ + "ABS", "CHAR", "COALESCE", "GLOB", "HEX", "IFNULL", + "IIF", "INSTR", "LENGTH", "LIKE", "LIKELIHOOD", + "LIKELY", "LOAD_EXTENSION", "LOWER", "LTRIM", + "NULLIF", "PRINTF", "QUOTE", "REPLACE", "ROUND", + "RTRIM", "SOUNDEX", "SQLITE_COMPILEOPTION_GET", + "SQLITE_COMPILEOPTION_USED", "SQLITE_SOURCE_ID", + "SQLITE_VERSION", "SUBSTR", "TRIM", "TRIM", + "TYPEOF", "UNICODE", "UNLIKELY", "UPPER", "ZEROBLOB", + ] /// Returns true if the expression has a unique value when SQLite runs /// a request. @@ -133,39 +933,273 @@ public protocol _SQLExpression { /// 1 + 2 -- true /// score -- false /// - /// This property supports `_identifyingColums(_:for:)` - var _isConstantInRequest: Bool { get } - + /// This property supports `identifyingColums(_:for:)` + var isConstantInRequest: Bool { + switch impl { + case .databaseValue: + return true + + case let .rowValue(expressions), + let .associativeBinary(_, expressions): + return expressions.allSatisfy(\.isConstantInRequest) + + case let .between(expression: expression, lowerBound: lowerBound, upperBound: upperBound, isNegated: _): + return expression.isConstantInRequest + && lowerBound.isConstantInRequest + && upperBound.isConstantInRequest + + case let .binary(_, lhs, rhs), + let .compare(_, lhs, rhs): + return lhs.isConstantInRequest && rhs.isConstantInRequest + + case let .in(expression, collection, isNegated: _): + guard let expressions = collection.collectionExpressions else { + return false + } + return expression.isConstantInRequest && expressions.allSatisfy(\.isConstantInRequest) + + case let .unary(_, expression), + let .not(expression), + let .isEmpty(expression, isNegated: _), + let .collated(expression, _): + return expression.isConstantInRequest + + case let .function(name, expressions): + let name = name.uppercased() + guard ((name == "MAX" || name == "MIN") && expressions.count > 1) + || Self.knownPureFunctions.contains(name) + else { + return false // Don't know - assume not constant + } + + return expressions.allSatisfy(\.isConstantInRequest) + + default: + return false + } + } +} + +extension SQLExpression { /// Returns true iff the expression is trivially true. /// /// When in doubt, returns false. /// - /// This property helps clearing up the ON clause. - var _isTrue: Bool { get } - - /// Returns a qualified expression - func _qualifiedExpression(with alias: TableAlias) -> SQLExpression -} - -extension _SQLExpression { - /// If this expression is a table colum, returns the name of this column. - /// - /// When in doubt, returns nil. - func _column(_ db: Database, for alias: TableAlias) throws -> String? { - try _column(db, for: alias, acceptsBijection: false) + /// This property helps clearing up the JOIN clauses. + var isTrue: Bool { + switch impl { + case .databaseValue(true.databaseValue): + return true + + case let .collated(expression, _): + return expression.isTrue + + default: + return false + } } } -/// 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 { + /// Returns a qualified expression + func qualified(with alias: TableAlias) -> SQLExpression { + switch impl { + case .databaseValue, + .qualifiedColumn, + .qualifiedFastPrimaryKey, + .subquery: + return self + + case let .column(name): + return .qualifiedColumn(name, alias) + + case let .rowValue(expressions): + assert(!expressions.isEmpty) + return .rowValue(expressions.map { $0.qualified(with: alias) })! + + case let .literal(sqlLiteral): + return .literal(sqlLiteral.qualified(with: alias)) + + case let .between(expression: expression, lowerBound: lowerBound, upperBound: upperBound, isNegated: isNegated): + return .between( + expression: expression.qualified(with: alias), + lowerBound: lowerBound.qualified(with: alias), + upperBound: upperBound.qualified(with: alias), + isNegated: isNegated) + + case let .binary(op, lhs, rhs): + return .binary(op, lhs.qualified(with: alias), rhs.qualified(with: alias)) + + case let .associativeBinary(op, expressions): + return .associativeBinary(op, expressions.map { $0.qualified(with: alias) }) + + case let .in(expression, collection, isNegated: isNegated): + return .in( + expression.qualified(with: alias), + collection.qualified(with: alias), + isNegated: isNegated + ) + + case let .unary(op, expression): + return .unary(op, expression.qualified(with: alias)) + + case let .compare(op, lhs, rhs): + return .compare(op, lhs.qualified(with: alias), rhs.qualified(with: alias)) + + case let .tableMatch(a, expression): + return .tableMatch(a, expression.qualified(with: alias)) + + case let .not(expression): + return .not(expression.qualified(with: alias)) + + case let .collated(expression, collationName): + return .collated(expression.qualified(with: alias), collationName) + + case let .count(selection): + return .count(selection.qualified(with: alias)) + + case let .countDistinct(expression): + return .countDistinct(expression.qualified(with: alias)) + + case let .function(name, expressions): + return .function(name, expressions.map { $0.qualified(with: alias) }) + + case let .isEmpty(expression, isNegated: isNegated): + return .isEmpty(expression.qualified(with: alias), isNegated: isNegated) + + case .fastPrimaryKey: + return .qualifiedFastPrimaryKey(alias) + } + } +} -/// `_SQLBooleanTest` supports boolean tests. +extension SQLExpression { + /// Returns true if the expression is an aggregate. + /// + /// When in doubt, returns false. + /// + /// SELECT score -- false + /// SELECT COUNT(*) -- true + /// SELECT MAX(score) -- true + /// SELECT MAX(score) + 1 -- true + /// + /// This method makes it possible to avoid inserting `LIMIT 1` to the SQL + /// of some requests: + /// + /// // SELECT MAX("score") FROM "player" + /// try Player.select(max(Column("score")), as: Int.self).fetchOne(db) + /// + /// // SELECT "score" FROM "player" LIMIT 1 + /// try Player.select(Column("score"), as: Int.self).fetchOne(db) + var isAggregate: Bool { + switch impl { + case let .rowValue(expressions), + let .associativeBinary(_, expressions): + return expressions.contains(where: \.isAggregate) + + case let .between(expression: expression, lowerBound: _, upperBound: _, isNegated: _), + let .unary(_, expression), + let .not(expression), + let .collated(expression, _), + let .isEmpty(expression, isNegated: _): + return expression.isAggregate + + case let .binary(_, lhs, rhs), + let .compare(_, lhs, rhs): + return lhs.isAggregate || rhs.isAggregate + + case let .in(expression, collection, isNegated: _): + if expression.isAggregate { + // SELECT aggregate IN (...) + return true + } + + if let expressions = collection.collectionExpressions, + expressions.contains(where: \.isAggregate) + { + // SELECT expr IN (aggregate, ...) + return true + } + + return false + + case .count, + .countDistinct: + return true + + case let .function(name, expressions): + let name = name.uppercased() + if ["MIN", "MAX"].contains(name) && expressions.count == 1 { + return true + } else if ["AVG", "COUNT", "SUM", "TOTAL"].contains(name) && expressions.count == 1 { + return true + } else if name == "GROUP_CONCAT" && (expressions.count == 1 || expressions.count == 2) { + return true + } else { + // TODO: return true if all arguments are aggregates? + return false + } + + default: + return false + } + } +} + +extension Sequence where Element: SQLExpressible { + /// Returns an expression by joining all elements with an associative SQL + /// binary operator. + /// + /// For example: + /// + /// // SELECT * FROM player + /// // WHERE (registered + /// // AND (score >= 1000) + /// // AND (name IS NOT NULL)) + /// let conditions = [ + /// Column("registered"), + /// Column("score") >= 1000, + /// Column("name") != nil] + /// Player.filter(conditions.joined(operator: .and)) + /// + /// 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`, and true for `.and`. + public func joined(operator: SQLAssociativeBinaryOperator) -> SQLExpression { + .associativeBinary(`operator`, map(\.sqlExpression)) + } +} + +extension Sequence where Element == SQLExpressible { + /// Returns an expression by joining all elements with an associative SQL + /// binary operator. + /// + /// For example: + /// + /// // SELECT * FROM player + /// // WHERE (registered + /// // AND (score >= 1000) + /// // AND (name IS NOT NULL)) + /// let conditions = [ + /// Column("registered"), + /// Column("score") >= 1000, + /// Column("name") != nil] + /// Player.filter(conditions.joined(operator: .and)) + /// + /// 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`, and true for `.and`. + public func joined(operator: SQLAssociativeBinaryOperator) -> SQLExpression { + .associativeBinary(`operator`, map(\.sqlExpression)) + } +} + +// MARK: - SQLBooleanTest + +/// `SQLBooleanTest` supports boolean tests. /// -/// See `SQLExpression._is(_:)` -/// -/// :nodoc: -public enum _SQLBooleanTest { +/// See `SQLExpression.is(_:)` +enum SQLBooleanTest { /// Fuels `expression == true` case `true` @@ -176,94 +1210,381 @@ public enum _SQLBooleanTest { case falsey } -extension SQLExpression { - /// Returns self - public var sqlExpression: SQLExpression { self } +// MARK: - SQLAssociativeBinaryOperator + +/// SQLAssociativeBinaryOperator is an SQLite associative binary operator, such +/// as `+`, `*`, `AND`, etc. +/// +/// 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 { + /// The SQL operator + let sql: String - // MARK: _SQLExpression + /// The neutral value + let neutralValue: DatabaseValue - /// :nodoc: - public func _column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool) throws -> String? { - nil + /// If true, (a • b) • c is strictly equal to a • (b • c). + /// + /// `AND`, `OR`, `||` (concat) are stricly associative. + /// + /// `+` and `*` are not stricly associative when applied to floating + /// point values. + let isStrictlyAssociative: Bool + + /// If true, (a • b) is a bijective function of a, and a bijective + /// function of b. + /// + /// `+` and `||` (concat) are bijective. + /// + /// `AND`, `OR` and `*` are not. + let isBijective: Bool + + /// Creates a binary operator + init(sql: String, neutralValue: DatabaseValue, strictlyAssociative: Bool, bijective: Bool) { + self.sql = sql + self.neutralValue = neutralValue + self.isStrictlyAssociative = strictlyAssociative + self.isBijective = bijective } - /// :nodoc: - public func _identifyingColums(_ db: Database, for alias: TableAlias) throws -> Set { - [] + /// 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, + bijective: true) + + /// 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, + bijective: 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, + bijective: false) + + /// 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, + bijective: false) + + /// 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, + bijective: true) +} + +// MARK: - SQLBinaryOperator + +/// SQLBinaryOperator is an SQLite binary operator, such as >, =, etc. +struct SQLBinaryOperator: Hashable { + /// The SQL operator + let sql: String + + /// The SQL for the negated operator, if any + let negatedSQL: String? + + /// Creates a binary operator + /// + /// SQLBinaryOperator("-") + /// SQLBinaryOperator("LIKE", negated: "NOT LIKE") + init(_ sql: String, negated: String? = nil) { + self.sql = sql + self.negatedSQL = negated } - /// :nodoc: - public func _identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set? { - nil - } - - /// :nodoc: - public func _is(_ test: _SQLBooleanTest) -> SQLExpression { - switch test { - case .true: - return SQLExpressionEqual(.equal, self, true.sqlExpression) - - case .false: - return SQLExpressionEqual(.equal, self, false.sqlExpression) - - case .falsey: - return SQLExpressionNot(self) + /// Returns the negated binary operator, if any + /// + /// let operator = SQLBinaryOperator("IS", negated: "IS NOT") + /// operator.negated!.sql // IS NOT + var negated: SQLBinaryOperator? { + guard let negatedSQL = negatedSQL else { + return nil } + return SQLBinaryOperator(negatedSQL, negated: sql) } - /// :nodoc: - public var _isConstantInRequest: Bool { false } + /// The `<` binary operator + static let lessThan = SQLBinaryOperator("<") - /// :nodoc: - public var _isTrue: Bool { false } + /// The `<=` binary operator + static let lessThanOrEqual = SQLBinaryOperator("<=") - // MARK: SQLOrderingTerm + /// The `>` binary operator + static let greaterThan = SQLBinaryOperator(">") - /// :nodoc: - public func _orderingTermSQL(_ context: SQLGenerationContext) throws -> String { - try _expressionSQL(context, wrappedInParenthesis: false) - } + /// The `>=` binary operator + static let greaterThanOrEqual = SQLBinaryOperator(">=") - /// :nodoc: - public func _qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { - _qualifiedExpression(with: alias) - } + /// The `-` binary operator + static let subtract = SQLBinaryOperator("-") - /// :nodoc: - public var _reversed: SQLOrderingTerm { desc } + /// The `/` binary operator + static let divide = SQLBinaryOperator("/") - // MARK: SQLSelectable + /// The `LIKE` binary operator + static let like = SQLBinaryOperator("LIKE", negated: "NOT LIKE") - /// :nodoc: - public func _columnCount(_ db: Database) throws -> Int { 1 } + /// The `MATCH` binary operator + static let match = SQLBinaryOperator("MATCH") +} + +// MARK: - SQLCompareOperator + +enum SQLCompareOperator: String { + case equal = "=" + case notEqual = "<>" + case `is` = "IS" + case isNot = "IS NOT" - /// :nodoc: - public func _count(distinct: Bool) -> _SQLCount? { - if distinct { - // SELECT DISTINCT expr FROM tableName ... - // -> - // SELECT COUNT(DISTINCT expr) FROM tableName ... - return .distinct(self) - } else { - // SELECT expr FROM tableName ... - // -> - // SELECT COUNT(*) FROM tableName ... - return .all + var negated: SQLCompareOperator { + switch self { + case .equal: return .notEqual + case .notEqual: return .equal + case .is: return .isNot + case .isNot: return .is } } - - /// :nodoc: - public func _countedSQL(_ context: SQLGenerationContext) throws -> String { - try _expressionSQL(context, wrappedInParenthesis: false) - } - - /// :nodoc: - public func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { - _qualifiedExpression(with: alias) - } - - /// :nodoc: - public func _resultColumnSQL(_ context: SQLGenerationContext) throws -> String { - try _expressionSQL(context, wrappedInParenthesis: false) - } +} + +// MARK: - SQLUnaryOperator + +/// SQLUnaryOperator is a SQLite unary operator. +struct SQLUnaryOperator: Hashable { + /// The SQL operator + let sql: String + + /// If true GRDB puts a white space between the operator and the operand. + let needsRightSpace: Bool + + /// Creates an unary operator + /// + /// SQLUnaryOperator("~", needsRightSpace: false) + init(_ sql: String, needsRightSpace: Bool) { + self.sql = sql + self.needsRightSpace = needsRightSpace + } + + /// The `-` unary operator + static let minus = SQLUnaryOperator("-", needsRightSpace: false) +} + +// MARK: - SQLExpressible + +/// `SQLExpressible` is the protocol for all types that can be used as an +/// SQL expression. +/// +/// It is adopted by protocols like `DatabaseValueConvertible`, and types +/// like `Column`. +/// +/// See https://github.com/groue/GRDB.swift/#the-query-interface +public protocol SQLExpressible: SQLSelectable, SQLOrderingTerm { + /// Returns an SQL expression. + var sqlExpression: SQLExpression { get } +} + +extension SQLExpressible { + public var sqlSelection: SQLSelection { + .expression(sqlExpression) + } + + public var sqlOrdering: SQLOrdering { + .expression(sqlExpression) + } +} + +/// `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. +/// +/// For example, `Column` is a type that only exists to help you build requests, +/// and it adopts `SQLSpecificExpressible`. +/// +/// On the other side, `Int` adopts `SQLExpressible`. +public protocol SQLSpecificExpressible: SQLExpressible { + // SQLExpressible can be adopted by Swift standard types, and user + // types, through the DatabaseValueConvertible protocol which inherits + // from SQLExpressible. + // + // For example, Int adopts SQLExpressible through + // DatabaseValueConvertible. + // + // SQLSpecificExpressible, on the other side, is not adopted by any + // Swift standard type or any user type. It is only adopted by GRDB types, + // such as Column and SQLExpression. + // + // This separation lets us define functions and operators that do not + // spill out. The three declarations below have no chance overloading a + // Swift-defined operator, or a user-defined operator: + // + // - ==(SQLExpressible, SQLSpecificExpressible) + // - ==(SQLSpecificExpressible, SQLExpressible) + // - ==(SQLSpecificExpressible, SQLSpecificExpressible) +} + +extension SQLExpression: SQLSpecificExpressible { + // Not a real deprecation, just a usage warning + @available(*, deprecated, message: "Already SQLExpression") + public var sqlExpression: SQLExpression { self } +} + +// MARK: - SQL Ordering Support + +/// :nodoc: +extension SQLSpecificExpressible { + + /// 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 asc: 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: SQLOrdering { + .desc(sqlExpression) + } + + #if GRDBCUSTOMSQLITE + /// 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 ascNullsLast: 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: SQLOrdering { + .descNullsFirst(sqlExpression) + } + #elseif !GRDBCIPHER + /// Returns a value that can be used as an argument to QueryInterfaceRequest.order() + /// + /// See https://github.com/groue/GRDB.swift/#the-query-interface + @available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) + public var ascNullsLast: 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 + @available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) + public var descNullsFirst: SQLOrdering { + .descNullsFirst(sqlExpression) + } + #endif +} + + +// MARK: - SQL Selection Support + +/// :nodoc: +extension SQLSpecificExpressible { + /// Give the expression the given SQL name. + /// + /// For example: + /// + /// // SELECT (width * height) AS area FROM shape + /// let area = (Column("width") * Column("height")).forKey("area") + /// let request = Shape.select(area) + /// if let row = try Row.fetchOne(db, request) { + /// let area: Int = row["area"] + /// } + public func forKey(_ key: String) -> SQLSelection { + .aliasedExpression(sqlExpression, key) + } + + /// Give the expression the same SQL name as the coding key. + /// + /// For example: + /// + /// struct Shape: Decodable, FetchableRecord, TableRecord { + /// let width: Int + /// let height: Int + /// let area: Int + /// + /// static let databaseSelection: [SQLSelectable] = [ + /// Column(CodingKeys.width), + /// Column(CodingKeys.height), + /// (Column(CodingKeys.width) * Column(CodingKeys.height)).forKey(CodingKeys.area), + /// ] + /// } + /// + /// // SELECT width, height, (width * height) AS area FROM shape + /// let shapes: [Shape] = try Shape.fetchAll(db) + public func forKey(_ key: CodingKey) -> SQLSelection { + forKey(key.stringValue) + } +} + + +// MARK: - SQL Collations Support + +/// :nodoc: +extension SQLSpecificExpressible { + + /// Returns a collated expression. + /// + /// For example: + /// + /// Player.filter(Column("email").collating(.nocase) == "contact@example.com") + public func collating(_ collation: Database.CollationName) -> SQLCollatedExpression { + SQLCollatedExpression(sqlExpression, collationName: collation) + } + + /// Returns a collated expression. + /// + /// For example: + /// + /// Player.filter(Column("name").collating(.localizedStandardCompare) == "Hervé") + public func collating(_ collation: DatabaseCollation) -> SQLCollatedExpression { + SQLCollatedExpression(sqlExpression, collationName: Database.CollationName(rawValue: collation.name)) + } } diff --git a/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift b/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift index 7940b0484..75d4af2cd 100644 --- a/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift +++ b/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift @@ -6,7 +6,7 @@ /// /// When the schema does not define any foreign key, we can still infer complete /// mapping from partial information and primary keys. -struct SQLForeignKeyRequest: Equatable { +struct SQLForeignKeyRequest { let originTable: String let destinationTable: String let originColumns: [String]? diff --git a/GRDB/QueryInterface/SQL/SQLFunctions.swift b/GRDB/QueryInterface/SQL/SQLFunctions.swift index 5f4e4a261..f350abeef 100644 --- a/GRDB/QueryInterface/SQL/SQLFunctions.swift +++ b/GRDB/QueryInterface/SQL/SQLFunctions.swift @@ -5,7 +5,7 @@ extension DatabaseFunction { /// /// See https://github.com/groue/GRDB.swift/#sql-functions public func callAsFunction(_ arguments: SQLExpressible...) -> SQLExpression { - SQLExpressionFunction(name, arguments: arguments.map(\.sqlExpression)) + .function(name, arguments.map(\.sqlExpression)) } } @@ -17,7 +17,7 @@ extension DatabaseFunction { /// // ABS(amount) /// abs(Column("amount")) public func abs(_ value: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionFunction("ABS", arguments: value) + .function("ABS", [value.sqlExpression]) } @@ -28,7 +28,7 @@ public func abs(_ value: SQLSpecificExpressible) -> SQLExpression { /// // AVG(length) /// average(Column("length")) public func average(_ value: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionFunction("AVG", arguments: value) + .function("AVG", [value.sqlExpression]) } @@ -39,7 +39,7 @@ public func average(_ value: SQLSpecificExpressible) -> SQLExpression { /// // COUNT(email) /// count(Column("email")) public func count(_ counted: SQLSelectable) -> SQLExpression { - SQLExpressionCount(counted) + .count(counted.sqlSelection) } @@ -50,7 +50,7 @@ public func count(_ counted: SQLSelectable) -> SQLExpression { /// // COUNT(DISTINCT email) /// count(distinct: Column("email")) public func count(distinct value: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionCountDistinct(value.sqlExpression) + .countDistinct(value.sqlExpression) } @@ -61,7 +61,7 @@ public func count(distinct value: SQLSpecificExpressible) -> SQLExpression { /// // IFNULL(name, 'Anonymous') /// Column("name") ?? "Anonymous" public func ?? (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - SQLExpressionFunction("IFNULL", arguments: lhs, rhs) + .function("IFNULL", [lhs.sqlExpression, rhs.sqlExpression]) } @@ -72,7 +72,7 @@ public func ?? (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// // LENGTH(name) /// length(Column("name")) public func length(_ value: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionFunction("LENGTH", arguments: value) + .function("LENGTH", [value.sqlExpression]) } @@ -83,7 +83,7 @@ public func length(_ value: SQLSpecificExpressible) -> SQLExpression { /// // MAX(score) /// max(Column("score")) public func max(_ value: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionFunction("MAX", arguments: value) + .function("MAX", [value.sqlExpression]) } @@ -94,7 +94,7 @@ public func max(_ value: SQLSpecificExpressible) -> SQLExpression { /// // MIN(score) /// min(Column("score")) public func min(_ value: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionFunction("MIN", arguments: value) + .function("MIN", [value.sqlExpression]) } @@ -105,7 +105,7 @@ public func min(_ value: SQLSpecificExpressible) -> SQLExpression { /// // SUM(amount) /// sum(Column("amount")) public func sum(_ value: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionFunction("SUM", arguments: value) + .function("SUM", [value.sqlExpression]) } @@ -227,7 +227,7 @@ public enum SQLDateModifier: SQLSpecificExpressible { case utc public var sqlExpression: SQLExpression { - rawValue.databaseValue + rawValue.sqlExpression } var rawValue: String { @@ -274,7 +274,7 @@ public enum SQLDateModifier: SQLSpecificExpressible { /// /// 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.map(\.sqlExpression)) + .function("JULIANDAY", [value.sqlExpression] + modifiers.map(\.sqlExpression)) } // MARK: DATETIME(...) @@ -289,5 +289,5 @@ public func julianDay(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModif /// /// For more information, see https://www.sqlite.org/lang_datefunc.html public func dateTime(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression { - SQLExpressionFunction("DATETIME", arguments: [value.sqlExpression] + modifiers.map(\.sqlExpression)) + .function("DATETIME", [value.sqlExpression] + modifiers.map(\.sqlExpression)) } diff --git a/GRDB/QueryInterface/SQL/SQLOperators.swift b/GRDB/QueryInterface/SQL/SQLOperators.swift index 84759d2b4..25f088f79 100644 --- a/GRDB/QueryInterface/SQL/SQLOperators.swift +++ b/GRDB/QueryInterface/SQL/SQLOperators.swift @@ -1,27 +1,5 @@ // MARK: - Egality and Identity Operators (=, <>, IS, IS NOT) -// Outputs "x = y" or "x IS NULL" -private func isEqual(_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression { - switch (lhs, rhs) { - case let (lhs, rhs as DatabaseValue): - switch rhs.storage { - case .null: - return SQLExpressionEqual(.is, lhs, rhs) - default: - return SQLExpressionEqual(.equal, lhs, rhs) - } - case let (lhs as DatabaseValue, rhs): - switch lhs.storage { - case .null: - return SQLExpressionEqual(.is, rhs, lhs) - default: - return SQLExpressionEqual(.equal, lhs, rhs) - } - default: - return SQLExpressionEqual(.equal, lhs, rhs) - } -} - /// An SQL expression that compares two expressions with the `=` SQL operator. /// /// // name = 'Arthur' @@ -32,7 +10,7 @@ private func isEqual(_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpressio /// // name IS NULL /// Column("name") == nil public func == (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { - isEqual(lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null) + .equal(lhs.sqlExpression, rhs?.sqlExpression ?? .null) } /// An SQL expression that compares two expressions with the `=` SQL operator. @@ -45,7 +23,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) + .collated(lhs.expression == rhs, lhs.collationName) } /// An SQL expression that checks the boolean value of an expression. @@ -59,9 +37,9 @@ public func == (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpressi /// Column("validated") == false public func == (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression { if rhs { - return lhs.sqlExpression._is(.true) + return lhs.sqlExpression.is(.true) } else { - return lhs.sqlExpression._is(.false) + return lhs.sqlExpression.is(.false) } } @@ -75,7 +53,7 @@ public func == (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression { /// // name IS NULL /// nil == Column("name") public func == (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { - isEqual(lhs?.sqlExpression ?? DatabaseValue.null, rhs.sqlExpression) + .equal(lhs?.sqlExpression ?? .null, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `=` SQL operator. @@ -88,7 +66,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) + .collated(lhs == rhs.expression, rhs.collationName) } /// An SQL expression that checks the boolean value of an expression. @@ -102,9 +80,9 @@ public func == (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpressi /// false == Column("validated") public func == (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression { if lhs { - return rhs.sqlExpression._is(.true) + return rhs.sqlExpression.is(.true) } else { - return rhs.sqlExpression._is(.false) + return rhs.sqlExpression.is(.false) } } @@ -113,7 +91,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) + .equal(lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `<>` SQL operator. @@ -207,7 +185,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) + .compare(.is, lhs.sqlExpression, rhs?.sqlExpression ?? .null) } /// An SQL expression that compares two expressions with the `IS` SQL operator. @@ -215,7 +193,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) + .collated(lhs.expression === rhs, lhs.collationName) } /// An SQL expression that compares two expressions with the `IS` SQL operator. @@ -224,9 +202,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 .compare(.is, lhs.sqlExpression, rhs.sqlExpression) } else { - return SQLExpressionEqual(.is, rhs.sqlExpression, DatabaseValue.null) + return .compare(.is, rhs.sqlExpression, .null) } } @@ -235,7 +213,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) + .collated(lhs === rhs.expression, rhs.collationName) } /// An SQL expression that compares two expressions with the `IS` SQL operator. @@ -243,7 +221,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) + .compare(.is, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `IS NOT` SQL operator. @@ -293,7 +271,7 @@ public func !== (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQ /// // score < 18 /// Column("score") < 18 public func < (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - SQLExpressionBinary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) + .binary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `<` SQL operator. @@ -301,7 +279,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) + .collated(lhs.expression < rhs, lhs.collationName) } /// An SQL expression that compares two expressions with the `<` SQL operator. @@ -309,7 +287,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) + .binary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `<` SQL operator. @@ -317,7 +295,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) + .collated(lhs < rhs.expression, rhs.collationName) } /// An SQL expression that compares two expressions with the `<` SQL operator. @@ -325,7 +303,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) + .binary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `<=` SQL operator. @@ -333,7 +311,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) + .binary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `<=` SQL operator. @@ -341,7 +319,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) + .collated(lhs.expression <= rhs, lhs.collationName) } /// An SQL expression that compares two expressions with the `<=` SQL operator. @@ -349,7 +327,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) + .binary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `<=` SQL operator. @@ -357,7 +335,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) + .collated(lhs <= rhs.expression, rhs.collationName) } /// An SQL expression that compares two expressions with the `<=` SQL operator. @@ -365,7 +343,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) + .binary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `>` SQL operator. @@ -373,7 +351,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) + .binary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `>` SQL operator. @@ -381,7 +359,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) + .collated(lhs.expression > rhs, lhs.collationName) } /// An SQL expression that compares two expressions with the `>` SQL operator. @@ -389,7 +367,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) + .binary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `>` SQL operator. @@ -397,7 +375,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) + .collated(lhs > rhs.expression, rhs.collationName) } /// An SQL expression that compares two expressions with the `>` SQL operator. @@ -405,7 +383,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) + .binary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `>=` SQL operator. @@ -413,7 +391,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) + .binary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `>=` SQL operator. @@ -421,7 +399,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) + .collated(lhs.expression >= rhs, lhs.collationName) } /// An SQL expression that compares two expressions with the `>=` SQL operator. @@ -429,7 +407,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) + .binary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `>=` SQL operator. @@ -437,7 +415,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) + .collated(lhs >= rhs.expression, rhs.collationName) } /// An SQL expression that compares two expressions with the `>=` SQL operator. @@ -445,7 +423,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) + .binary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } // MARK: - Inclusion Operators (BETWEEN, IN) @@ -474,7 +452,10 @@ 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) + .between( + expression: element.sqlExpression, + lowerBound: lowerBound.sqlExpression, + upperBound: upperBound.sqlExpression) } /// An SQL expression that checks the inclusion of an expression in a range. @@ -482,7 +463,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) + .collated(contains(element.expression), element.collationName) } } @@ -502,7 +483,10 @@ 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) + .between( + expression: element.sqlExpression, + lowerBound: lowerBound.sqlExpression, + upperBound: upperBound.sqlExpression) } } @@ -513,7 +497,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) + SQLCollection.array(map(\.sqlExpression)).contains(element.sqlExpression) } /// An SQL expression that checks the inclusion of an expression in @@ -522,7 +506,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) + .collated(contains(element.expression), element.collationName) } } @@ -533,7 +517,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) + SQLCollection.array(map(\.sqlExpression)).contains(element.sqlExpression) } /// An SQL expression that checks the inclusion of an expression in @@ -542,7 +526,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) + .collated(contains(element.expression), element.collationName) } } @@ -554,7 +538,7 @@ extension Sequence where Self.Iterator.Element == SQLExpressible { /// // width * 2 /// Column("width") * 2 public func * (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - SQLExpressionAssociativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) + .associativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic multiplication. @@ -562,7 +546,7 @@ public func * (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// // 2 * width /// 2 * Column("width") public func * (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionAssociativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) + .associativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic multiplication. @@ -570,7 +554,7 @@ public func * (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// // width * height /// Column("width") * Column("height") public func * (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionAssociativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) + .associativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic division. @@ -578,7 +562,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) + .binary(.divide, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL arithmetic division. @@ -586,7 +570,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) + .binary(.divide, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL arithmetic division. @@ -594,7 +578,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) + .binary(.divide, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL arithmetic addition. @@ -602,7 +586,7 @@ public func / (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// // width + 2 /// Column("width") + 2 public func + (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - SQLExpressionAssociativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) + .associativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic addition. @@ -610,7 +594,7 @@ public func + (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// // 2 + width /// 2 + Column("width") public func + (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionAssociativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) + .associativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) } /// An SQL arithmetic addition. @@ -618,7 +602,7 @@ public func + (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// // width + height /// Column("width") + Column("height") public func + (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionAssociativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) + .associativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) } /// A negated SQL arithmetic expression. @@ -626,7 +610,7 @@ public func + (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// // -width /// -Column("width") public prefix func - (value: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionUnary(.minus, value.sqlExpression) + .unary(.minus, value.sqlExpression) } /// An SQL arithmetic substraction. @@ -634,7 +618,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) + .binary(.subtract, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL arithmetic substraction. @@ -642,7 +626,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) + .binary(.subtract, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL arithmetic substraction. @@ -650,7 +634,7 @@ public func - (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// // width - height /// Column("width") - Column("height") public func - (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionBinary(.subtract, lhs.sqlExpression, rhs.sqlExpression) + .binary(.subtract, lhs.sqlExpression, rhs.sqlExpression) } @@ -661,7 +645,7 @@ public func - (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// // favorite AND 0 /// Column("favorite") && false public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - SQLExpressionAssociativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) + .associativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `AND` SQL operator. @@ -669,7 +653,7 @@ public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// // 0 AND favorite /// false && Column("favorite") public func && (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionAssociativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) + .associativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `AND` SQL operator. @@ -677,7 +661,7 @@ public func && (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// // email IS NOT NULL AND favorite /// Column("email") != nil && Column("favorite") public func && (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionAssociativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) + .associativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -685,7 +669,7 @@ public func && (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// // favorite OR 1 /// Column("favorite") || true public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - SQLExpressionAssociativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) + .associativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -693,7 +677,7 @@ public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// // 0 OR favorite /// true || Column("favorite") public func || (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionAssociativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) + .associativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -701,7 +685,7 @@ public func || (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// // email IS NULL OR hidden /// Column("email") == nil || Column("hidden") public func || (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - SQLExpressionAssociativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) + .associativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) } /// A negated logical SQL expression with the `NOT` SQL operator. @@ -714,7 +698,7 @@ public func || (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// // id NOT BETWEEN 1 AND 10 /// !((1...10).contains(Column("id"))) public prefix func ! (value: SQLSpecificExpressible) -> SQLExpression { - value.sqlExpression._is(.falsey) + value.sqlExpression.is(.falsey) } // MARK: - Like Operator @@ -727,6 +711,6 @@ extension SQLSpecificExpressible { /// // email LIKE '%@example.com" /// Column("email").like("%@example.com") public func like(_ pattern: SQLExpressible) -> SQLExpression { - SQLExpressionBinary(.like, self, pattern) + .binary(.like, sqlExpression, pattern.sqlExpression) } } diff --git a/GRDB/QueryInterface/SQL/SQLOrdering.swift b/GRDB/QueryInterface/SQL/SQLOrdering.swift index 1ae4dc6d8..51a71cc40 100644 --- a/GRDB/QueryInterface/SQL/SQLOrdering.swift +++ b/GRDB/QueryInterface/SQL/SQLOrdering.swift @@ -1,88 +1,130 @@ -/// Implementation details of `SQLOrderingTerm`. -/// -/// :nodoc: -public protocol _SQLOrderingTerm { - /// The ordering term, reversed - var _reversed: SQLOrderingTerm { get } +/// The type that can be used as an SQL ordering term, as described at +/// https://www.sqlite.org/syntax/ordering-term.html +public struct SQLOrdering { + private var impl: Impl - /// Returns a qualified ordering - func _qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm + private enum Impl { + /// An expression + /// + /// ORDER BY score + case expression(SQLExpression) + + /// An ascending expression + /// + /// ORDER BY score ASC + case asc(SQLExpression) + + /// An descending expression + /// + /// ORDER BY score DESC + case desc(SQLExpression) + + /// Only available from SQLite 3.30.0 + case ascNullsLast(SQLExpression) + + /// Only available from SQLite 3.30.0 + case descNullsFirst(SQLExpression) + + /// A literal SQL ordering + case literal(SQLLiteral) + } - /// 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 + static func expression(_ expression: SQLExpression) -> SQLOrdering { + self.init(impl: .expression(expression)) + } + + static func asc(_ expression: SQLExpression) -> SQLOrdering { + self.init(impl: .asc(expression)) + } + + static func desc(_ expression: SQLExpression) -> SQLOrdering { + self.init(impl: .desc(expression)) + } + + static func ascNullsLast(_ expression: SQLExpression) -> SQLOrdering { + self.init(impl: .ascNullsLast(expression)) + } + + static func descNullsFirst(_ expression: SQLExpression) -> SQLOrdering { + self.init(impl: .descNullsFirst(expression)) + } + + static func literal(_ sqlLiteral: SQLLiteral) -> SQLOrdering { + self.init(impl: .literal(sqlLiteral)) + } } +extension SQLOrdering { + func sql(_ context: SQLGenerationContext) throws -> String { + switch impl { + case .expression(let expression): + return try expression.sql(context) + case .asc(let expression): + return try expression.sql(context) + " ASC" + case .desc(let expression): + return try expression.sql(context) + " DESC" + case .ascNullsLast(let expression): + return try expression.sql(context) + " ASC NULLS LAST" + case .descNullsFirst(let expression): + return try expression.sql(context) + " DESC NULLS FIRST" + case .literal(let literal): + return try literal.sql(context) + } + } +} + +extension SQLOrdering { + func qualified(with alias: TableAlias) -> SQLOrdering { + switch impl { + case .expression(let expression): + return .expression(expression.qualified(with: alias)) + case .asc(let expression): + return .asc(expression.qualified(with: alias)) + case .desc(let expression): + return .desc(expression.qualified(with: alias)) + case .ascNullsLast(let expression): + return .ascNullsLast(expression.qualified(with: alias)) + case .descNullsFirst(let expression): + return .descNullsFirst(expression.qualified(with: alias)) + case .literal(let literal): + return .literal(literal.qualified(with: alias)) + } + } +} + +extension SQLOrdering { + var reversed: SQLOrdering { + switch impl { + case .expression(let expression): + return .desc(expression) + case .asc(let expression): + return .desc(expression) + case .desc(let expression): + return .asc(expression) + case .ascNullsLast(let expression): + return .descNullsFirst(expression) + case .descNullsFirst(let expression): + return .ascNullsLast(expression) + case .literal: + fatalError(""" + Ordering literals can't be reversed. \ + To resolve this error, order by expression literals instead. + """) + } + } +} + +// MARK: - SQLOrderingTerm + /// 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 { } - -/// :nodoc: -enum SQLOrdering: SQLOrderingTerm, Refinable { - case asc(SQLExpression) - case desc(SQLExpression) - - // Only available from SQLite 3.30.0. This enum is not public, so those - // cases don't harm as long as we don't expose them through public APIs. - case ascNullsLast(SQLExpression) - case descNullsFirst(SQLExpression) - - var expression: SQLExpression { - get { - switch self { - case .asc(let expression): - return expression - case .desc(let expression): - return expression - case .ascNullsLast(let expression): - return expression - case .descNullsFirst(let expression): - return expression - } - } - set { - switch self { - case .asc: - self = .asc(newValue) - case .desc: - self = .desc(newValue) - case .ascNullsLast: - self = .ascNullsLast(newValue) - case .descNullsFirst: - self = .descNullsFirst(newValue) - } - } - } - - func _orderingTermSQL(_ context: SQLGenerationContext) throws -> String { - switch self { - case .asc(let expression): - return try expression._expressionSQL(context, wrappedInParenthesis: false) + " ASC" - case .desc(let expression): - return try expression._expressionSQL(context, wrappedInParenthesis: false) + " DESC" - case .ascNullsLast(let expression): - return try expression._expressionSQL(context, wrappedInParenthesis: false) + " ASC NULLS LAST" - case .descNullsFirst(let expression): - return try expression._expressionSQL(context, wrappedInParenthesis: false) + " DESC NULLS FIRST" - } - } - - func _qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { - map(\.expression) { $0._qualifiedExpression(with: alias) } - } - - var _reversed: SQLOrderingTerm { - switch self { - case .asc(let expression): - return SQLOrdering.desc(expression) - case .desc(let expression): - return SQLOrdering.asc(expression) - case .ascNullsLast(let expression): - return SQLOrdering.descNullsFirst(expression) - case .descNullsFirst(let expression): - return SQLOrdering.ascNullsLast(expression) - } - } +public protocol SQLOrderingTerm { + /// Returns an SQL ordering. + var sqlOrdering: SQLOrdering { get } +} + +extension SQLOrdering: SQLOrderingTerm { + // Not a real deprecation, just a usage warning + @available(*, deprecated, message: "Already QLOrdering:") + public var sqlOrdering: SQLOrdering { self } } diff --git a/GRDB/QueryInterface/SQL/SQLQuery.swift b/GRDB/QueryInterface/SQL/SQLQuery.swift index 43c9e4751..ba461f740 100644 --- a/GRDB/QueryInterface/SQL/SQLQuery.swift +++ b/GRDB/QueryInterface/SQL/SQLQuery.swift @@ -31,23 +31,23 @@ extension SQLQuery: Refinable { extension SQLQuery: SelectionRequest { func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self { - map(\.relation) { $0.select(selection) } + map(\.relation) { $0.select { try selection($0).map(\.sqlSelection) } } } func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self { - map(\.relation) { $0.annotated(with: selection) } + map(\.relation) { $0.annotated { try selection($0).map(\.sqlSelection) } } } } extension SQLQuery: FilteredRequest { func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { - map(\.relation) { $0.filter(predicate) } + map(\.relation) { $0.filter { try predicate($0).sqlExpression } } } } extension SQLQuery: OrderedRequest { func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self { - map(\.relation) { $0.order(orderings) } + map(\.relation) { $0.order { try orderings($0).map(\.sqlOrdering) } } } func reversed() -> Self { @@ -95,6 +95,12 @@ extension SQLQuery: _JoinableRequest { } } +extension SQLQuery: SQLSubqueryable { + var sqlSubquery: SQLSubquery { + .query(self) + } +} + extension SQLQuery { func fetchCount(_ db: Database) throws -> Int { guard groupPromise == nil && limit == nil && ctes.isEmpty else { @@ -112,16 +118,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 try fetchTrivialCount(db) } var countQuery = self.unordered() countQuery.isDistinct = false switch count { case .all: - countQuery = countQuery.select(SQLExpressionCount(AllColumns())) + countQuery = countQuery.select(SQLExpression.count(.allColumns)) case .distinct(let expression): - countQuery = countQuery.select(SQLExpressionCountDistinct(expression)) + countQuery = countQuery.select(SQLExpression.countDistinct(expression)) } return try QueryInterfaceRequest(query: countQuery).fetchOne(db)! } else { @@ -134,15 +140,14 @@ extension SQLQuery { // SELECT expr1, expr2, ... FROM tableName ... // -> // SELECT COUNT(*) FROM tableName ... - let countQuery = unordered().select(SQLExpressionCount(AllColumns())) + let countQuery = unordered().select(SQLExpression.count(.allColumns)) return try QueryInterfaceRequest(query: countQuery).fetchOne(db)! } } // SELECT COUNT(*) FROM (self) func fetchTrivialCount(_ db: Database) throws -> Int { - let request = QueryInterfaceRequest(query: unordered()) - let countRequest: SQLRequest = "SELECT COUNT(*) FROM (\(request))" + let countRequest: SQLRequest = "SELECT COUNT(*) FROM (\(unordered()))" return try countRequest.fetchOne(db)! } } diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index fb0578d1e..50459e48a 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -158,7 +158,7 @@ struct SQLRelation { } var source: SQLSource - var selectionPromise: DatabasePromise<[SQLSelectable]> = DatabasePromise(value: []) + var selectionPromise: DatabasePromise<[SQLSelection]> = DatabasePromise(value: []) // Filter is an array of expressions that we'll join with the AND operator. // This gives nicer output in generated SQL: `(a AND b AND c)` instead of // `((a AND b) AND c)`. @@ -190,7 +190,7 @@ extension SQLRelation { /// Convenience factory methods which selects all rows from a table. static func all( fromTable tableName: String, - selection: @escaping (Database) -> [SQLSelectable] = { _ in [AllColumns()] }) + selection: @escaping (Database) -> [SQLSelection] = { _ in [.allColumns] }) -> Self { SQLRelation( @@ -200,21 +200,21 @@ extension SQLRelation { } extension SQLRelation: Refinable { - func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self { + func select(_ selection: @escaping (Database) throws -> [SQLSelection]) -> Self { with(\.selectionPromise, DatabasePromise(selection)) } // Convenience - func select(_ selection: [SQLSelectable]) -> Self { + func select(_ selection: [SQLSelection]) -> Self { select { _ in selection } } /// Removes all selections from chidren - func selectOnly(_ selection: [SQLSelectable]) -> Self { + func selectOnly(_ selection: [SQLSelection]) -> Self { select(selection).map(\.children, { $0.mapValues { $0.map(\.relation, { $0.selectOnly([]) }) } }) } - func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self { + func annotated(with selection: @escaping (Database) throws -> [SQLSelection]) -> Self { map(\.selectionPromise) { selectionPromise in DatabasePromise { db in try selectionPromise.resolve(db) + selection(db) @@ -223,11 +223,11 @@ extension SQLRelation: Refinable { } // Convenience - func annotated(with selection: [SQLSelectable]) -> Self { + func annotated(with selection: [SQLSelection]) -> Self { annotated(with: { _ in selection }) } - func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self { + func order(_ orderings: @escaping (Database) throws -> [SQLOrdering]) -> Self { with(\.ordering, SQLRelation.Ordering(orderings: orderings)) } @@ -434,13 +434,13 @@ extension SQLRelation { /// SQLRelation.Ordering provides the order clause to SQLRelation. struct Ordering { private enum Element { - case terms(DatabasePromise<[SQLOrderingTerm]>) + case terms(DatabasePromise<[SQLOrdering]>) case ordering(SQLRelation.Ordering) 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) } @@ -449,13 +449,13 @@ 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.qualified(with: alias) } }) case .ordering(let ordering): return .ordering(ordering.qualified(with: alias)) } } - func resolve(_ db: Database) throws -> [SQLOrderingTerm] { + func resolve(_ db: Database) throws -> [SQLOrdering] { switch self { case .terms(let terms): return try terms.resolve(db) @@ -481,7 +481,7 @@ extension SQLRelation { isReversed: false) } - init(orderings: @escaping (Database) throws -> [SQLOrderingTerm]) { + init(orderings: @escaping (Database) throws -> [SQLOrdering]) { self.init( elements: [.terms(DatabasePromise(orderings))], isReversed: false) @@ -505,7 +505,7 @@ extension SQLRelation { isReversed: isReversed) } - func resolve(_ db: Database) throws -> [SQLOrderingTerm] { + func resolve(_ db: Database) throws -> [SQLOrdering] { if isReversed { return try elements.flatMap { try $0.reversed.resolve(db) } } else { @@ -555,11 +555,11 @@ enum SQLAssociationCondition { /// player[Column("id")] == bonus[Column("playerID")] /// }) /// Player.with(bonus).joining(required: association) - case expression((_ left: TableAlias, _ right: TableAlias) -> SQLExpressible) + case expression((_ left: TableAlias, _ right: TableAlias) -> SQLExpression) /// The condition that does not constrain the two associated tables /// in any way. - static let none = expression({ _, _ in true }) + static let none = expression({ _, _ in true.sqlExpression }) func reversed(to destinationTable: String) -> SQLAssociationCondition { switch self { @@ -578,7 +578,7 @@ enum SQLAssociationCondition { { switch self { case let .expression(condition): - return [condition(leftAlias, rightAlias).sqlExpression] + return [condition(leftAlias, rightAlias)] case let .foreignKey(foreignKey): return try foreignKey .joinMapping(db, from: leftAlias.tableName) @@ -707,7 +707,10 @@ extension JoinMapping { .map({ mapping -> SQLExpression in let leftValue = leftRow.databaseValue(at: mapping.leftIndex) // Force `=` operator, because SQLite doesn't match foreign keys on NULL - return SQLExpressionEqual(.equal, mapping.rightColumn, leftValue) + return SQLExpression.compare( + .equal, + mapping.rightColumn.sqlExpression, + leftValue.sqlExpression) }) .joined(operator: .and) }) @@ -728,11 +731,7 @@ extension JoinMapping { /// - Returns: An array of SQL expression that should be joined with /// the AND operator and qualified with the right table. func joinExpressions(leftAlias: TableAlias, rightAlias: TableAlias) -> [SQLExpression] { - map { - let right = SQLQualifiedColumn($0.right, alias: rightAlias) - let left = SQLQualifiedColumn($0.left, alias: leftAlias) - return right == left - } + map { rightAlias[$0.right] == leftAlias[$0.left] } } } @@ -813,7 +812,7 @@ extension SQLRelation { } // replace selection unless empty - let mergedSelectionPromise = DatabasePromise { db -> [SQLSelectable] in + let mergedSelectionPromise = DatabasePromise { db -> [SQLSelection] in let otherSelection = try other.selectionPromise.resolve(db) if otherSelection.isEmpty { return try self.selectionPromise.resolve(db) diff --git a/GRDB/QueryInterface/SQL/SQLRowValue.swift b/GRDB/QueryInterface/SQL/SQLRowValue.swift deleted file mode 100644 index c35b47f43..000000000 --- a/GRDB/QueryInterface/SQL/SQLRowValue.swift +++ /dev/null @@ -1,70 +0,0 @@ -/// A [row value](https://www.sqlite.org/rowvalue.html). -/// -/// :nodoc: -struct SQLRowValue: SQLExpression { - let expressions: [SQLExpression] - - /// SQLite row values were shipped in SQLite 3.15: - /// https://www.sqlite.org/releaselog/3_15_0.html - static let isAvailable = (sqlite3_libversion_number() >= 3015000) - - /// - precondition: `expressions` is not empty - init(_ expressions: [SQLExpression]) { - assert(!expressions.isEmpty) - self.expressions = expressions - } - - // MARK: - SQLExpression - - func _column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool) throws -> String? { - if let expression = expressions.first, expressions.count == 1 { - return try expression._column(db, for: alias, acceptsBijection: acceptsBijection) - } - - return nil - } - - func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - if let expression = expressions.first, expressions.count == 1 { - return try expression._expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis) - } - - let values = try expressions.map { - try $0._expressionSQL(context, wrappedInParenthesis: false) - } - - return "(" - + values.joined(separator: ", ") - + ")" - } - - func _identifyingColums(_ db: Database, for alias: TableAlias) throws -> Set { - if let expression = expressions.first, expressions.count == 1 { - return try expression._identifyingColums(db, for: alias) - } - - return try expressions.reduce(into: []) { try $0.formUnion($1._identifyingColums(db, for: alias)) } - } - - var _isConstantInRequest: Bool { - expressions.allSatisfy(\._isConstantInRequest) - } - - var _isTrue: Bool { - if let expression = expressions.first, expressions.count == 1 { - return expression._isTrue - } - - return false - } - - func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { - SQLRowValue(expressions.map { $0._qualifiedExpression(with: alias) }) - } - - // MARK: - SQLSelectable - - var _isAggregate: Bool { - expressions.contains(where: \._isAggregate) - } -} diff --git a/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift deleted file mode 100644 index 7f445252a..000000000 --- a/GRDB/QueryInterface/SQL/SQLSelectable+QueryInterface.swift +++ /dev/null @@ -1,168 +0,0 @@ -// MARK: - AllColumns - -/// AllColumns is the `*` in `SELECT *`. -/// -/// You use AllColumns in your custom implementation of -/// TableRecord.databaseSelection. -/// -/// For example: -/// -/// struct Player : TableRecord { -/// static var databaseTableName = "player" -/// static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] -/// } -/// -/// // SELECT *, rowid FROM player -/// let request = Player.all() -public struct AllColumns: SQLSelectable { - // As long as the CTE is embedded here, the following request will fail - // at runtime, in `_columnCount(_:)`, because we can't access the number of - // columns in the CTE: - // - // let association = Player.association(to: cte) - // Player.including(required: association.select(AllColumns(), ...)) - // - // The need for this should not be frequent. And the user has - // two workarounds: - // - // - provide explicit columns in the CTE definition. - // - prefer `annotated(with:)` when she wants to extend the selection. - // - // TODO: Make `cteRequestOrAssociation.select(AllColumns())` possible. - - /// When nil, select all columns from a regular database table. - /// When not nil, select all columns from a common table expression. - var cte: SQLCTE? - - /// The `*` selection. - /// - /// For example: - /// - /// // SELECT * FROM player - /// Player.select(AllColumns()) - public init() { } - - /// The `*` selection for a common table expression. - /// - /// WITH t AS (...) SELECT * FROM t - init(cte: SQLCTE) { - self.cte = cte - } - - /// :nodoc: - public func _columnCount(_ db: Database) throws -> Int { - if let cte = cte { - return try cte.columnsCount(db) - } - - fatalError("Can't compute number of columns without an alias") - } - - /// :nodoc: - public func _count(distinct: Bool) -> _SQLCount? { - // SELECT DISTINCT * FROM tableName ... - if distinct { - // Can't count - return nil - } - - // SELECT * FROM tableName ... - // -> - // SELECT COUNT(*) FROM tableName ... - return .all - } - - /// :nodoc: - public func _countedSQL(_ context: SQLGenerationContext) throws -> String { "*" } - - /// :nodoc: - public func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { - SQLQualifiedAllColumns(alias: alias, cte: cte) - } - - /// :nodoc: - public func _resultColumnSQL(_ context: SQLGenerationContext) throws -> String { "*" } -} - -// MARK: - SQLQualifiedAllColumns - -/// _SQLQualifiedAllColumns is the `t.*` in `SELECT t.*`. -/// -/// :nodoc: -struct SQLQualifiedAllColumns: SQLSelectable { - /// When nil, select all columns from a regular database table. - /// When not nil, select all columns from a common table expression. - var cte: SQLCTE? - let alias: TableAlias - - init(alias: TableAlias, cte: SQLCTE?) { - self.alias = alias - self.cte = cte - } - - func _columnCount(_ db: Database) throws -> Int { - if let cte = cte { - return try cte.columnsCount(db) - } else { - return try db.columns(in: alias.tableName).count - } - } - - func _count(distinct: Bool) -> _SQLCount? { nil } - - func _countedSQL(_ context: SQLGenerationContext) throws -> String { - if context.qualifier(for: alias) != nil { - // SELECT COUNT(t.*) is invalid SQL - fatalError("Not implemented, or invalid query") - } - - return "*" - } - - func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { - // Never requalify - return self - } - - func _resultColumnSQL(_ context: SQLGenerationContext) throws -> String { - if let qualifier = context.qualifier(for: alias) { - return qualifier.quotedDatabaseIdentifier + ".*" - } - return "*" - } -} - -// MARK: - SQLAliasedExpression - -/// :nodoc: -struct SQLAliasedExpression: SQLSelectable { - let expression: SQLExpression - let name: String - - init(_ expression: SQLExpression, name: String) { - self.expression = expression - self.name = name - } - - func _columnCount(_ db: Database) throws -> Int { 1 } - - func _count(distinct: Bool) -> _SQLCount? { - expression._count(distinct: distinct) - } - - func _countedSQL(_ context: SQLGenerationContext) throws -> String { - try expression._countedSQL(context) - } - - var _isAggregate: Bool { expression._isAggregate } - - func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { - SQLAliasedExpression(expression._qualifiedExpression(with: alias), name: name) - } - - func _resultColumnSQL(_ context: SQLGenerationContext) throws -> String { - try expression._resultColumnSQL(context) - + " AS " - + name.quotedDatabaseIdentifier - } -} diff --git a/GRDB/QueryInterface/SQL/SQLSelectable.swift b/GRDB/QueryInterface/SQL/SQLSelectable.swift deleted file mode 100644 index ab486a373..000000000 --- a/GRDB/QueryInterface/SQL/SQLSelectable.swift +++ /dev/null @@ -1,80 +0,0 @@ -/// Implementation details of `SQLSelectable`. -/// -/// :nodoc: -public protocol _SQLSelectable { - /// Returns the number of columns in the selectable. - func _columnCount(_ db: Database) throws -> Int - - /// If the selectable can be counted, return how to count it. - func _count(distinct: Bool) -> _SQLCount? - - /// Returns the SQL that feeds the argument of the `COUNT` function. - /// - /// For example: - /// - /// COUNT(*) - /// COUNT(id) - /// ^---- countedSQL - /// - /// - parameter context: An SQL generation context which accepts - /// statement arguments. - func _countedSQL(_ context: SQLGenerationContext) throws -> String - - /// Returns true if the selectable is an aggregate. - /// - /// When in doubt, returns false. - /// - /// SELECT * -- false - /// SELECT score -- false - /// SELECT COUNT(*) -- true - /// SELECT MAX(score) -- true - /// SELECT MAX(score) + 1 -- true - /// - /// This method makes it possible to avoid inserting `LIMIT 1` to the SQL - /// of some requests: - /// - /// // SELECT MAX("score") FROM "player" - /// try Player.select(max(Column("score")), as: Int.self).fetchOne(db) - /// - /// // SELECT "score" FROM "player" LIMIT 1 - /// try Player.select(Column("score"), as: Int.self).fetchOne(db) - var _isAggregate: Bool { get } - - /// Returns a qualified selectable - func _qualifiedSelectable(with alias: TableAlias) -> 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 -} - -/// 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: _SQLSelectable { } - -/// :nodoc: -public enum _SQLCount { - /// Represents `COUNT(*)` - case all - - /// Represents `COUNT(DISTINCT expression)` - case distinct(SQLExpression) -} - -extension SQLSelectable { - /// :nodoc: - public var _isAggregate: Bool { false } -} diff --git a/GRDB/QueryInterface/SQL/SQLSelection.swift b/GRDB/QueryInterface/SQL/SQLSelection.swift new file mode 100644 index 000000000..f919460d9 --- /dev/null +++ b/GRDB/QueryInterface/SQL/SQLSelection.swift @@ -0,0 +1,334 @@ +/// The type that can be selected, as described at +/// https://www.sqlite.org/syntax/result-column.html +public struct SQLSelection { + private var impl: Impl + + private enum Impl { + /// All columns + /// + /// SELECT * + case allColumns + + /// All columns from a table + /// + /// SELECT player.* + case qualifiedAllColumns(TableAlias) + + // As long as the CTE is embedded here, the following request will fail + // at runtime, in `columnCount(_:)`, because we can't access the number of + // columns in the CTE: + // + // let association = Player.association(to: cte) + // Player.including(required: association.select(AllColumns(), ...)) + // + // The need for this should not be frequent. And the user has + // two workarounds: + // + // - provide explicit columns in the CTE definition. + // - prefer `annotated(with:)` when she wants to extend the selection. + // + // TODO: Make `cteRequestOrAssociation.select(AllColumns())` possible. + /// All columns from a common table expression + case allCTEColumns(SQLCTE) + + case qualifiedAllCTEColumns(SQLCTE, TableAlias) + + /// An expression + /// + /// SELECT id + /// SELECT LENGTH(name) + case expression(SQLExpression) + + /// An aliased expression + /// + /// SELECT score + bonud AS totalScore + case aliasedExpression(SQLExpression, String) + + /// A literal SQL selection + case literal(SQLLiteral) + } + + static let allColumns = SQLSelection(impl: .allColumns) + + static func qualifiedAllColumns(_ alias: TableAlias) -> Self { + self.init(impl: .qualifiedAllColumns(alias)) + } + + static func allCTEColumns(_ cte: SQLCTE) -> Self { + self.init(impl: .allCTEColumns(cte)) + } + + static func qualifiedAllCTEColumns(_ cte: SQLCTE, _ alias: TableAlias) -> Self { + self.init(impl: .qualifiedAllCTEColumns(cte, alias)) + } + + static func expression(_ expression: SQLExpression) -> Self { + self.init(impl: .expression(expression)) + } + + static func aliasedExpression(_ expression: SQLExpression, _ name: String) -> Self { + self.init(impl: .aliasedExpression(expression, name)) + } + + static func literal(_ sqlLiteral: SQLLiteral) -> Self { + self.init(impl: .literal(sqlLiteral)) + } +} + +extension SQLSelection { + /// Returns the number of columns in the selection. + func columnCount(_ db: Database) throws -> Int { + switch impl { + case .allColumns: + // Likely a GRDB bug + fatalError("Can't compute number of columns without an alias") + + case let .qualifiedAllColumns(alias): + return try db.columns(in: alias.tableName).count + + case let .allCTEColumns(cte): + return try cte.columnsCount(db) + + case let .qualifiedAllCTEColumns(cte, _): + return try cte.columnsCount(db) + + case .expression, + .aliasedExpression: + return 1 + + case .literal: + fatalError(""" + Selection literals don't known how many columns they contain. \ + To resolve this error, select one or several literal expressions instead. \ + See SQLLiteral.sqlExpression. + """) + } + } +} + +extension SQLSelection { + /// If the selection can be counted, return how to count it. + func count(distinct: Bool) -> SQLCount? { + switch impl { + case .allColumns, + .allCTEColumns: + // SELECT DISTINCT * FROM tableName ... + if distinct { + // Can't count + return nil + } + + // SELECT * FROM tableName ... + // -> + // SELECT COUNT(*) FROM tableName ... + return .all + + case .qualifiedAllColumns, + .qualifiedAllCTEColumns: + return nil + + case let .expression(expression), + let .aliasedExpression(expression, _): + if distinct { + // SELECT DISTINCT expr FROM tableName ... + // -> + // SELECT COUNT(DISTINCT expr) FROM tableName ... + return .distinct(expression) + } else { + // SELECT expr FROM tableName ... + // -> + // SELECT COUNT(*) FROM tableName ... + return .all + } + + case .literal: + return nil + } + } + + /// 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 { + switch impl { + case .allColumns, + .allCTEColumns: + return "*" + + case let .qualifiedAllColumns(alias), + let .qualifiedAllCTEColumns(_, alias): + if context.qualifier(for: alias) != nil { + // SELECT COUNT(t.*) is invalid SQL + fatalError("Not implemented, or invalid query") + } + return "*" + + case let .expression(expression), + let .aliasedExpression(expression, _): + return try expression.sql(context) + + case .literal: + fatalError(""" + Selection literals can't be counted. \ + To resolve this error, select one or several literal expressions instead. \ + See SQLLiteral.sqlExpression. + """) + } + } +} + +extension SQLSelection { + /// 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 sql(_ context: SQLGenerationContext) throws -> String { + switch impl { + case .allColumns, + .allCTEColumns: + return "*" + + case let .qualifiedAllColumns(alias), + let .qualifiedAllCTEColumns(_, alias): + if let qualifier = context.qualifier(for: alias) { + return qualifier.quotedDatabaseIdentifier + ".*" + } + return "*" + + case let .expression(expression): + return try expression.sql(context) + + case let .aliasedExpression(expression, name): + return try expression.sql(context) + " AS " + name.quotedDatabaseIdentifier + + case let .literal(sqlLiteral): + return try sqlLiteral.sql(context) + } + } +} + +extension SQLSelection { + /// Returns true if the selection 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 + /// + /// This method makes it possible to avoid inserting `LIMIT 1` to the SQL + /// of some requests: + /// + /// // SELECT MAX("score") FROM "player" + /// try Player.select(max(Column("score")), as: Int.self).fetchOne(db) + /// + /// // SELECT "score" FROM "player" LIMIT 1 + /// try Player.select(Column("score"), as: Int.self).fetchOne(db) + var isAggregate: Bool { + switch impl { + case let .expression(expression), + let .aliasedExpression(expression, _): + return expression.isAggregate + + default: + return false + } + } +} + +extension SQLSelection { + /// Returns a qualified selection + func qualified(with alias: TableAlias) -> SQLSelection { + switch impl { + case .qualifiedAllColumns, + .qualifiedAllCTEColumns: + return self + + case .allColumns: + return .qualifiedAllColumns(alias) + + case let .allCTEColumns(cte): + return .qualifiedAllCTEColumns(cte, alias) + + case let .expression(expression): + return .expression(expression.qualified(with: alias)) + + case let .aliasedExpression(expression, name): + return .aliasedExpression(expression.qualified(with: alias), name) + + case let .literal(sqlLiteral): + return .literal(sqlLiteral.qualified(with: alias)) + } + } +} + +enum SQLCount { + /// Represents `COUNT(*)` + case all + + /// Represents `COUNT(DISTINCT expression)` + case distinct(SQLExpression) +} + +// MARK: - SQLSelectable + +/// SQLSelectable is the protocol for types that can be selected, as +/// described at https://www.sqlite.org/syntax/result-column.html +public protocol SQLSelectable { + /// Returns an SQL selection. + var sqlSelection: SQLSelection { get } +} + +extension SQLSelection: SQLSelectable { + // Not a real deprecation, just a usage warning + @available(*, deprecated, message: "Already SQLSelection") + public var sqlSelection: SQLSelection { self } +} + +// MARK: - AllColumns + +/// AllColumns is the `*` in `SELECT *`. +/// +/// You use AllColumns in your custom implementation of +/// TableRecord.databaseSelection. +/// +/// For example: +/// +/// struct Player : TableRecord { +/// static var databaseTableName = "player" +/// static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] +/// } +/// +/// // SELECT *, rowid FROM player +/// let request = Player.all() +public struct AllColumns: SQLSelectable { + /// The `*` selection. + /// + /// For example: + /// + /// // SELECT * FROM player + /// Player.select(AllColumns()) + public init() { } + + public var sqlSelection: SQLSelection { + .allColumns + } +} diff --git a/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift b/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift deleted file mode 100644 index d7ecbcf5c..000000000 --- a/GRDB/QueryInterface/SQL/SQLSpecificExpressible+QueryInterface.swift +++ /dev/null @@ -1,118 +0,0 @@ -// MARK: - SQL Ordering Support - -/// :nodoc: -extension SQLSpecificExpressible { - - /// 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 asc: SQLOrderingTerm { - 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) - } - - #if GRDBCUSTOMSQLITE - /// 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 ascNullsLast: SQLOrderingTerm { - 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) - } - #elseif !GRDBCIPHER - /// Returns a value that can be used as an argument to QueryInterfaceRequest.order() - /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface - @available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) - public var ascNullsLast: SQLOrderingTerm { - SQLOrdering.ascNullsLast(sqlExpression) - } - - /// Returns a value that can be used as an argument to QueryInterfaceRequest.order() - /// - /// See https://github.com/groue/GRDB.swift/#the-query-interface - @available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) - public var descNullsFirst: SQLOrderingTerm { - SQLOrdering.descNullsFirst(sqlExpression) - } - #endif -} - - -// MARK: - SQL Selection Support - -/// :nodoc: -extension SQLSpecificExpressible { - /// Give the expression the given SQL name. - /// - /// For example: - /// - /// // SELECT (width * height) AS area FROM shape - /// let area = (Column("width") * Column("height")).forKey("area") - /// let request = Shape.select(area) - /// if let row = try Row.fetchOne(db, request) { - /// let area: Int = row["area"] - /// } - public func forKey(_ key: String) -> SQLSelectable { - SQLAliasedExpression(sqlExpression, name: key) - } - - /// Give the expression the same SQL name as the coding key. - /// - /// For example: - /// - /// struct Shape: Decodable, FetchableRecord, TableRecord { - /// let width: Int - /// let height: Int - /// let area: Int - /// - /// static let databaseSelection: [SQLSelectable] = [ - /// Column(CodingKeys.width), - /// Column(CodingKeys.height), - /// (Column(CodingKeys.width) * Column(CodingKeys.height)).forKey(CodingKeys.area), - /// ] - /// } - /// - /// // SELECT width, height, (width * height) AS area FROM shape - /// let shapes: [Shape] = try Shape.fetchAll(db) - public func forKey(_ key: CodingKey) -> SQLSelectable { - forKey(key.stringValue) - } -} - - -// MARK: - SQL Collations Support - -/// :nodoc: -extension SQLSpecificExpressible { - - /// Returns a collated expression. - /// - /// For example: - /// - /// Player.filter(Column("email").collating(.nocase) == "contact@example.com") - public func collating(_ collation: Database.CollationName) -> SQLCollatedExpression { - SQLCollatedExpression(sqlExpression, collationName: collation) - } - - /// Returns a collated expression. - /// - /// For example: - /// - /// Player.filter(Column("name").collating(.localizedStandardCompare) == "Hervé") - public func collating(_ collation: DatabaseCollation) -> SQLCollatedExpression { - SQLCollatedExpression(sqlExpression, collationName: Database.CollationName(rawValue: collation.name)) - } -} diff --git a/GRDB/QueryInterface/SQL/SQLSubquery.swift b/GRDB/QueryInterface/SQL/SQLSubquery.swift new file mode 100644 index 000000000..63f8666a9 --- /dev/null +++ b/GRDB/QueryInterface/SQL/SQLSubquery.swift @@ -0,0 +1,116 @@ +/// The type that can be embedded as a subquery. +public struct SQLSubquery { + private var impl: Impl + + private enum Impl { + /// A literal SQL query + case literal(SQLLiteral) + + /// A query interface query + case query(SQLQuery) + } + + static func literal(_ sqlLiteral: SQLLiteral) -> Self { + self.init(impl: .literal(sqlLiteral)) + } + + static func query(_ query: SQLQuery) -> Self { + self.init(impl: .query(query)) + } +} + +extension SQLSubquery { + /// The number of columns selected by the subquery. + /// + /// This method makes it possible to find the columns of a CTE in a request + /// that includes a CTE association: + /// + /// // WITH cte AS (SELECT 1 AS a, 2 AS b) + /// // SELECT player.*, cte.* + /// // FROM player + /// // JOIN cte + /// let cte = CommonTableExpression(named: "cte", sql: "SELECT 1 AS a, 2 AS b") + /// let request = Player + /// .with(cte) + /// .including(required: Player.association(to: cte)) + /// let row = try Row.fetchOne(db, request)! + /// + /// // We know that "SELECT 1 AS a, 2 AS b" selects two columns, + /// // so we can find cte columns in the row: + /// row.scopes["cte"] // [a:1, b:2] + func columnsCount(_ db: Database) throws -> Int { + switch impl { + case let .literal(sqlLiteral): + // Compile request. We can freely use the statement cache because we + // do not execute the statement or modify its arguments. + let context = SQLGenerationContext(db) + let sql = try sqlLiteral.sql(context) + let statement = try db.cachedSelectStatement(sql: sql) + return statement.columnCount + + case let .query(query): + return try SQLQueryGenerator(query: query).columnsCount(db) + } + } +} + +extension SQLSubquery { + /// Returns the subquery SQL. + /// + /// For example: + /// + /// // SELECT * + /// // FROM "player" + /// // WHERE "score" = (SELECT MAX("score") FROM "player") + /// let maxScore = Player.select(max(Column("score"))) + /// let players = try Player + /// .filter(Column("score") == maxScore) + /// .fetchAll(db) + /// + /// - parameter context: An SQL generation context. + /// - parameter singleResult: A hint that a single result row will be + /// consumed. Implementations can optionally use it to optimize the + /// generated SQL, for example by adding a `LIMIT 1` SQL clause. + /// - returns: An SQL string. + func sql(_ context: SQLGenerationContext) throws -> String { + switch impl { + case let .literal(sqlLiteral): + return try sqlLiteral.sql(context) + + case let .query(query): + return try SQLQueryGenerator(query: query, forSingleResult: false).requestSQL(context) + } + } +} + +// MARK: - SQLSubqueryable + +/// The protocol for types that can be embedded as a subquery. +public protocol SQLSubqueryable: SQLSpecificExpressible { + var sqlSubquery: SQLSubquery { get } +} + +extension SQLSubquery: SQLSubqueryable { + // Not a real deprecation, just a usage warning + @available(*, deprecated, message: "Already SQLSubquery") + public var sqlSubquery: SQLSubquery { self } +} + +extension SQLSubqueryable { + /// Returns a subquery expression. + public var sqlExpression: SQLExpression { + .subquery(sqlSubquery) + } +} + +extension SQLSubqueryable { + /// Returns an expression that checks the inclusion of the expression in + /// the subquery. + /// + /// // 1000 IN (SELECT score FROM player) + /// let request = Player.select(Column("score"), as: Int.self) + /// let condition = request.contains(1000) + public func contains(_ value: SQLExpressible) -> SQLExpression { + SQLCollection.subquery(sqlSubquery).contains(value.sqlExpression) + } +} diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index b16b396ae..4d1c65d38 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -9,9 +9,7 @@ /// and columns. /// /// - It gathers SQL arguments in order to prevent SQL injection. -/// -/// :nodoc: -public final class SQLGenerationContext { +final class SQLGenerationContext { private enum Parent { case none(db: Database, argumentsSink: StatementArgumentsSink) case context(SQLGenerationContext) @@ -63,15 +61,20 @@ public final class SQLGenerationContext { /// /// - parameter parent: A parent context. /// - parameter aliases: An array of table aliases to disambiguate. - init( + private init( parent: SQLGenerationContext, - aliases: [TableAlias] = []) + aliases: [TableAlias]) { self.parent = .context(parent) self.resolvedNames = aliases.resolvedNames self.ownAliases = Set(aliases) } + /// Returns a generation context suitable for subqueries. + func subqueryContext(aliases: [TableAlias] = []) -> SQLGenerationContext { + SQLGenerationContext(parent: self, aliases: aliases) + } + /// Returns whether arguments could be appended. /// /// A false result means that the generation context does not support @@ -374,26 +377,26 @@ 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) + public subscript(_ selectable: SQLSelectable) -> SQLSelection { + selectable.sqlSelection.qualified(with: self) } /// Returns a qualified expression that is able to resolve ambiguities in /// joined queries. - public subscript(_ expression: SQLExpression) -> SQLExpression { - expression._qualifiedExpression(with: self) + public subscript(_ expression: SQLSpecificExpressible & SQLSelectable & SQLOrderingTerm) -> SQLExpression { + expression.sqlExpression.qualified(with: self) } /// Returns a qualified ordering that is able to resolve ambiguities in /// joined queries. - public subscript(_ ordering: SQLOrderingTerm) -> SQLOrderingTerm { - ordering._qualifiedOrdering(with: self) + public subscript(_ ordering: SQLOrderingTerm) -> SQLOrdering { + ordering.sqlOrdering.qualified(with: self) } /// Returns a qualified columnn that is able to resolve ambiguities in /// joined queries. public subscript(_ column: String) -> SQLExpression { - Column(column)._qualifiedExpression(with: self) + .qualifiedColumn(column, self) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) @@ -413,7 +416,7 @@ public class TableAlias: Hashable { /// } public var exists: SQLExpression { // TODO: this fails with SQL views. Can we do something? - SQLExpressionQualifiedFastPrimaryKey(alias: self) != nil + SQLExpression.qualifiedFastPrimaryKey(self) != nil } /// :nodoc: diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 18c6a2767..5df7d302a 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -47,10 +47,10 @@ struct SQLQueryGenerator: Refinable { // `HAVING MAX(year) < 2000` INTO `HAVING MAX(book.year) < 2000`. let sourceAlias = relation.source.alias groupPromise = query.groupPromise?.map { - $0.map { $0._qualifiedExpression(with: sourceAlias) } + $0.map { $0.qualified(with: sourceAlias) } } havingExpressionsPromise = query.havingExpressionsPromise.map { - $0.map { $0._qualifiedExpression(with: sourceAlias) } + $0.map { $0.qualified(with: sourceAlias) } } limit = query.limit @@ -61,10 +61,7 @@ struct SQLQueryGenerator: Refinable { } func requestSQL(_ context: SQLGenerationContext) throws -> String { - // Build an SQL generation context with all aliases found in the query, - // so that we can disambiguate tables that are used several times with - // SQL aliases. - let context = SQLGenerationContext(parent: context, aliases: relation.allAliases) + let context = context.subqueryContext(aliases: relation.allAliases) var sql = try commonTableExpressionsPrefix(context) sql += "SELECT" @@ -75,7 +72,10 @@ struct SQLQueryGenerator: Refinable { let selection = try relation.selectionPromise.resolve(context.db) GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with an empty selection") - sql += try " " + selection.map { try $0._resultColumnSQL(context) }.joined(separator: ", ") + sql += " " + sql += try selection + .map { try $0.sql(context) } + .joined(separator: ", ") sql += " FROM " sql += try relation.source.sql(context) @@ -91,28 +91,32 @@ struct SQLQueryGenerator: Refinable { let filters = try relation.filtersPromise.resolve(context.db) if filters.isEmpty == false { sql += " WHERE " - sql += try filters.joined(operator: .and)._expressionSQL(context, wrappedInParenthesis: false) + sql += try filters + .joined(operator: .and) + .sql(context) } let groupExpressions = try groupPromise?.resolve(context.db) ?? [] if !groupExpressions.isEmpty { sql += " GROUP BY " sql += try groupExpressions - .map { try $0._expressionSQL(context, wrappedInParenthesis: false) } + .map { try $0.sql(context) } .joined(separator: ", ") } let havingExpressions = try havingExpressionsPromise.resolve(context.db) if havingExpressions.isEmpty == false { sql += " HAVING " - sql += try havingExpressions.joined(operator: .and)._expressionSQL(context, wrappedInParenthesis: false) + sql += try havingExpressions + .joined(operator: .and) + .sql(context) } let orderings = try relation.ordering.resolve(context.db) if !orderings.isEmpty { sql += " ORDER BY " sql += try orderings - .map { try $0._orderingTermSQL(context) } + .map { try $0.sql(context) } .joined(separator: ", ") } @@ -146,7 +150,7 @@ struct SQLQueryGenerator: Refinable { .selectionPromise .resolve(db) .reduce(0) { - try $0 + $1._columnCount(db) + try $0 + $1.columnCount(db) } } @@ -201,7 +205,7 @@ struct SQLQueryGenerator: Refinable { // The filter knows better let filter = try relation.filtersPromise.resolve(db).joined(operator: .and) - guard let rowIDs = try filter._identifyingRowIDs(db, for: relation.source.alias) else { + guard let rowIDs = try filter.identifyingRowIDs(db, for: relation.source.alias) else { return selectedRegion } @@ -214,7 +218,7 @@ struct SQLQueryGenerator: Refinable { /// If false, we don't know how many rows this query returns. private func expectsSingleResult( _ db: Database, - selection: [SQLSelectable], + selection: [SQLSelection], filters: [SQLExpression], groupExpressions: [SQLExpression]) throws -> Bool @@ -229,7 +233,7 @@ struct SQLQueryGenerator: Refinable { if try db.tableExists(tableName) { // skip views let identifyingColums = try filters .joined(operator: .and) - ._identifyingColums(db, for: relation.source.alias) + .identifyingColums(db, for: relation.source.alias) if try db.table(tableName, hasUniqueKey: identifyingColums) { // Filter by unique key: guaranteed single row! return true @@ -237,7 +241,7 @@ struct SQLQueryGenerator: Refinable { } // Do we aggregate without grouping? - if groupExpressions.isEmpty && selection.contains(where: \._isAggregate) { + if groupExpressions.isEmpty && selection.contains(where: \.isAggregate) { // Selection contains an aggregate function: guaranteed single row!Ë return true } @@ -262,13 +266,16 @@ struct SQLQueryGenerator: Refinable { sql += " WHERE " sql += try filters .joined(operator: .and) - ._expressionSQL(context, wrappedInParenthesis: false) + .sql(context) } if let limit = limit { let orderings = try relation.ordering.resolve(db) if !orderings.isEmpty { - sql += try " ORDER BY " + orderings.map { try $0._orderingTermSQL(context) }.joined(separator: ", ") + sql += " ORDER BY " + sql += try orderings + .map { try $0.sql(context) } + .joined(separator: ", ") } sql += " LIMIT " + limit.sql } @@ -291,13 +298,13 @@ struct SQLQueryGenerator: Refinable { let tableName = relation.source.tableName let alias = TableAlias(tableName: tableName) let context = SQLGenerationContext(db, aliases: [alias]) - let subqueryContext = SQLGenerationContext(parent: context, aliases: relation.allAliases) - let primaryKey = SQLExpressionFastPrimaryKey() + let subqueryContext = context.subqueryContext(aliases: relation.allAliases) + let primaryKey = SQLExpression.fastPrimaryKey var sql = "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE " - sql += try alias[primaryKey]._expressionSQL(context, wrappedInParenthesis: false) + sql += try alias[primaryKey].sql(context) sql += " IN (" - sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).requestSQL(subqueryContext) + sql += try map(\.relation, { $0.selectOnly([.expression(primaryKey)]) }).requestSQL(subqueryContext) sql += ")" let statement = try db.makeUpdateStatement(sql: sql) @@ -338,23 +345,26 @@ struct SQLQueryGenerator: Refinable { sql += try relation.source.sql(context) - let assignmentsSQL = try assignments + sql += " SET " + sql += try assignments .map { try $0.sql(context) } .joined(separator: ", ") - sql += " SET " + assignmentsSQL let filters = try relation.filtersPromise.resolve(db) if filters.isEmpty == false { sql += " WHERE " sql += try filters .joined(operator: .and) - ._expressionSQL(context, wrappedInParenthesis: false) + .sql(context) } if let limit = limit { let orderings = try relation.ordering.resolve(db) if !orderings.isEmpty { - sql += try " ORDER BY " + orderings.map { try $0._orderingTermSQL(context) }.joined(separator: ", ") + sql += " ORDER BY " + sql += try orderings + .map { try $0.sql(context) } + .joined(separator: ", ") } sql += " LIMIT " + limit.sql } @@ -389,8 +399,8 @@ struct SQLQueryGenerator: Refinable { let tableName = relation.source.tableName let alias = TableAlias(tableName: tableName) let context = SQLGenerationContext(db, aliases: [alias]) - let subqueryContext = SQLGenerationContext(parent: context, aliases: relation.allAliases) - let primaryKey = SQLExpressionFastPrimaryKey() + let subqueryContext = context.subqueryContext(aliases: relation.allAliases) + let primaryKey = SQLExpression.fastPrimaryKey // UPDATE table... var sql = "UPDATE " @@ -400,16 +410,16 @@ struct SQLQueryGenerator: Refinable { sql += tableName.quotedDatabaseIdentifier // SET column = value... - let assignmentsSQL = try assignments + sql += " SET " + sql += try assignments .map { try $0.sql(context) } .joined(separator: ", ") - sql += " SET " + assignmentsSQL // WHERE id IN (SELECT id FROM ...) sql += " WHERE " - sql += try alias[primaryKey]._expressionSQL(context, wrappedInParenthesis: false) + sql += try alias[primaryKey].sql(context) sql += " IN (" - sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).requestSQL(subqueryContext) + sql += try map(\.relation, { $0.selectOnly([.expression(primaryKey)]) }).requestSQL(subqueryContext) sql += ")" let statement = try db.makeUpdateStatement(sql: sql) @@ -431,14 +441,14 @@ struct SQLQueryGenerator: Refinable { var columnsSQL = "" if let columns = cte.columns, !columns.isEmpty { columnsSQL = "(" - + columns.map(\.quotedDatabaseIdentifier).joined(separator: ", ") - + ")" + columnsSQL += columns + .map(\.quotedDatabaseIdentifier) + .joined(separator: ", ") + columnsSQL += ")" } - let cteContext = SQLGenerationContext(parent: context) - let requestSQL = try cte.requestPromise - .resolve(context.db) - ._requestSQL(cteContext, forSingleResult: false) - return "\(tableName.quotedDatabaseIdentifier)\(columnsSQL) AS (\(requestSQL))" + let cteContext = context.subqueryContext() + let subquerySQL = try cte.sqlSubquery.sql(cteContext) + return "\(tableName.quotedDatabaseIdentifier)\(columnsSQL) AS (\(subquerySQL))" } .joined(separator: ", ") sql += " " @@ -471,7 +481,7 @@ struct SQLQueryGenerator: Refinable { var groupingColumns: Set = [] for expression in groupExpressions { - guard let column = try expression._column(db, for: relation.source.alias, acceptsBijection: true) else { + guard let column = try expression.column(db, for: relation.source.alias, acceptsBijection: true) else { // Grouping by something which is not a column: assume non // unique grouping. return .nonUnique @@ -545,14 +555,14 @@ private struct SQLQualifiedRelation { let source: SQLQualifiedSource /// The selection from source, not including selection of joined relations - private var sourceSelectionPromise: DatabasePromise<[SQLSelectable]> + private var sourceSelectionPromise: DatabasePromise<[SQLSelection]> /// The full selection, including selection of joined relations /// /// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ... /// | /// • selectionPromise - var selectionPromise: DatabasePromise<[SQLSelectable]> { + var selectionPromise: DatabasePromise<[SQLSelection]> { DatabasePromise { db in let selection = try self.sourceSelectionPromise.resolve(db) return try self.joins.values.reduce(into: selection) { selection, join in @@ -603,10 +613,10 @@ private struct SQLQualifiedRelation { joins = relation.children.compactMapValues { SQLQualifiedJoin($0) } let sourceAlias = source.alias sourceSelectionPromise = relation.selectionPromise.map { - $0.map { $0._qualifiedSelectable(with: sourceAlias) } + $0.map { $0.qualified(with: sourceAlias) } } filtersPromise = relation.filtersPromise.map { - $0.map { $0._qualifiedExpression(with: sourceAlias) } + $0.map { $0.qualified(with: sourceAlias) } } sourceOrdering = relation.ordering.qualified(with: sourceAlias) } @@ -630,7 +640,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. @@ -672,9 +682,9 @@ private struct SQLQualifiedRelation { } /// Removes all selections from joins - func selectOnly(_ selection: [SQLSelectable]) -> Self { + func selectOnly(_ selection: [SQLSelection]) -> Self { let sourceSelectionPromise = DatabasePromise(value: selection.map { - $0._qualifiedSelectable(with: source.alias) + $0.qualified(with: source.alias) }) return self .with(\.sourceSelectionPromise, sourceSelectionPromise) @@ -741,7 +751,7 @@ private struct SQLQualifiedJoin: Refinable { } /// Removes all selections from joins - func selectOnly(_ selection: [SQLSelectable]) -> SQLQualifiedJoin { + func selectOnly(_ selection: [SQLSelection]) -> SQLQualifiedJoin { map(\.relation) { $0.selectOnly(selection) } } @@ -779,16 +789,16 @@ private struct SQLQualifiedJoin: Refinable { // ... AND conditions += try relation.filtersPromise .resolve(context.db) - .map { $0._qualifiedExpression(with: rightAlias) } + .map { $0.qualified(with: rightAlias) } // Avoid generating on ON clause for trivially true conditions - conditions = conditions.filter { !$0._isTrue } + conditions = conditions.filter { !$0.isTrue } if conditions.isEmpty == false { - let joiningSQL = try conditions + sql += " ON " + sql += try conditions .joined(operator: .and) - ._expressionSQL(context, wrappedInParenthesis: false) - sql += " ON \(joiningSQL)" + .sql(context) } for (_, join) in relation.joins { diff --git a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift index 0fd649863..c4ad4a08d 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(.selection($0.sqlSelection.qualified(with: alias))) } .joined(separator: CollectionOfOne(.sql(", ")))) } @@ -72,7 +72,7 @@ extension SQLInterpolation { public mutating func appendInterpolation(_ selection: T) where T: SQLSelectable { - elements.append(.selectable(selection)) + elements.append(.selection(selection.sqlSelection)) } /// Appends the selectable SQL, or NULL if it is nil. @@ -84,7 +84,7 @@ extension SQLInterpolation { @_disfavoredOverload public mutating func appendInterpolation(_ selection: SQLSelectable?) { if let selection = selection { - elements.append(.selectable(selection)) + elements.append(.selection(selection.sqlSelection)) } else { appendLiteral("NULL") } @@ -101,7 +101,7 @@ extension SQLInterpolation { public mutating func appendInterpolation(_ orderingTerm: T) where T: SQLOrderingTerm { - elements.append(.orderingTerm(orderingTerm)) + elements.append(.ordering(orderingTerm.sqlOrdering)) } /// Appends the ordering SQL. @@ -112,23 +112,11 @@ extension SQLInterpolation { /// """ @_disfavoredOverload public mutating func appendInterpolation(_ orderingTerm: SQLOrderingTerm) { - elements.append(.orderingTerm(orderingTerm)) + elements.append(.ordering(orderingTerm.sqlOrdering)) } // MARK: - SQLExpressible - /// Appends the expression SQL. - /// - /// // SELECT name FROM player - /// let request: SQLRequest = """ - /// SELECT \(Column("name")) FROM player - /// """ - public mutating func appendInterpolation(_ expressible: T) - where T: SQLExpressible - { - elements.append(.expression(expressible.sqlExpression)) - } - /// Appends the expression SQL. /// /// // SELECT name FROM player @@ -193,7 +181,7 @@ extension SQLInterpolation { appendInterpolation(Column(key.stringValue)) } - // MARK: - SQLRequestProtocol + // MARK: - FetchRequest /// Appends the request SQL (not wrapped inside parentheses). /// @@ -205,10 +193,10 @@ extension SQLInterpolation { /// let request: SQLRequest = """ /// SELECT * FROM player WHERE score = (\(subquery)) /// """ - public mutating func appendInterpolation(_ request: T) - where T: FetchRequest & SQLExpression + public mutating func appendInterpolation(_ subquery: T) + where T: SQLSubqueryable & SQLExpressible & SQLSelectable & SQLOrderingTerm { - elements.append(.subquery(DatabasePromise(value: request))) + elements.append(.subquery(subquery.sqlSubquery)) } // MARK: - Sequence @@ -231,7 +219,14 @@ extension SQLInterpolation { public mutating func appendInterpolation(_ sequence: T) where T: Sequence, T.Element: SQLExpressible { - appendInterpolation(sequence.lazy.map(\.sqlExpression)) + let e: [SQLLiteral.Element] = sequence.map { .expression($0.sqlExpression) } + if e.isEmpty { + appendLiteral("(SELECT NULL WHERE NULL)") + } else { + appendLiteral("(") + elements.append(contentsOf: e.map(CollectionOfOne.init(_:)).joined(separator: CollectionOfOne(.sql(",")))) + appendLiteral(")") + } } /// Appends a sequence of expressions, wrapped in parentheses. @@ -250,16 +245,9 @@ extension SQLInterpolation { /// SELECT * FROM player WHERE a IN \(expressions) /// """ public mutating func appendInterpolation(_ sequence: T) - where T: Sequence, T.Element == SQLExpression + where T: Sequence, T.Element == SQLExpressible { - let e: [SQLLiteral.Element] = sequence.map { .expression($0.sqlExpression) } - if e.isEmpty { - appendLiteral("(SELECT NULL WHERE NULL)") - } else { - appendLiteral("(") - elements.append(contentsOf: e.map(CollectionOfOne.init(_:)).joined(separator: CollectionOfOne(.sql(",")))) - appendLiteral(")") - } + appendInterpolation(sequence.lazy.map(\.sqlExpression)) } // When a value is both an expression and a sequence of expressions, @@ -302,7 +290,7 @@ extension SQLInterpolation { } elements.append(.sql(" AS (")) - elements.append(.subquery(cte.cte.requestPromise)) + elements.append(.subquery(cte.cte.sqlSubquery)) elements.append(.sql(")")) } diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index 50ad022b7..43aa01e01 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -254,7 +254,9 @@ extension TableRecord { on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> SQLExpressible) -> JoinAssociation { - JoinAssociation(to: cte.relationForAll, condition: .expression(condition)) + JoinAssociation( + to: cte.relationForAll, + condition: .expression { condition($0, $1).sqlExpression }) } /// Creates an association to a common table expression that you can join diff --git a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift index 0fc790ebc..e0f1f2ac7 100644 --- a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift @@ -3,7 +3,7 @@ extension TableRecord { // MARK: Request Derivation static var relationForAll: SQLRelation { - .all(fromTable: databaseTableName, selection: { _ in databaseSelection }) + .all(fromTable: databaseTableName, selection: { _ in databaseSelection.map(\.sqlSelection) }) } /// Creates a request which fetches all records. diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index 8d577e9f2..bef83be36 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -133,7 +133,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.sqlSelection.qualified(with: alias).columnCount(db) } .reduce(0, +) } } diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index eccc078bb..390cbefb1 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -248,22 +248,12 @@ 5656A8862295BD56001FF3FF /* SQLOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8452295BD56001FF3FF /* SQLOrdering.swift */; }; 5656A8872295BD56001FF3FF /* SQLOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8462295BD56001FF3FF /* SQLOperators.swift */; }; 5656A8882295BD56001FF3FF /* SQLOperators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8462295BD56001FF3FF /* SQLOperators.swift */; }; - 5656A8892295BD56001FF3FF /* SQLExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8472295BD56001FF3FF /* SQLExpressible.swift */; }; - 5656A88A2295BD56001FF3FF /* SQLExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8472295BD56001FF3FF /* SQLExpressible.swift */; }; - 5656A88B2295BD56001FF3FF /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8482295BD56001FF3FF /* SQLExpression+QueryInterface.swift */; }; - 5656A88C2295BD56001FF3FF /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8482295BD56001FF3FF /* SQLExpression+QueryInterface.swift */; }; - 5656A88D2295BD56001FF3FF /* SQLSelectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8492295BD56001FF3FF /* SQLSelectable.swift */; }; - 5656A88E2295BD56001FF3FF /* SQLSelectable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8492295BD56001FF3FF /* SQLSelectable.swift */; }; 5656A88F2295BD56001FF3FF /* Column.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84A2295BD56001FF3FF /* Column.swift */; }; 5656A8902295BD56001FF3FF /* Column.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84A2295BD56001FF3FF /* Column.swift */; }; - 5656A8912295BD56001FF3FF /* SQLSpecificExpressible+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84B2295BD56001FF3FF /* SQLSpecificExpressible+QueryInterface.swift */; }; - 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 */; }; 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 */; }; - 5656A89A2295BD56001FF3FF /* SQLSelectable+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84F2295BD56001FF3FF /* SQLSelectable+QueryInterface.swift */; }; 5656A89B2295BD56001FF3FF /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8502295BD56001FF3FF /* SQLQuery.swift */; }; 5656A89C2295BD56001FF3FF /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8502295BD56001FF3FF /* SQLQuery.swift */; }; 5656A8A72295BF44001FF3FF /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8A52295BF44001FF3FF /* DatabasePromise.swift */; }; @@ -364,6 +354,10 @@ 567F45AF1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; 568068341EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; 568068381EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; + 568ECB0D25D904CA00B71526 /* SQLSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB0C25D904CA00B71526 /* SQLSelection.swift */; }; + 568ECB0E25D904CA00B71526 /* SQLSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB0C25D904CA00B71526 /* SQLSelection.swift */; }; + 568ECB3525D91CEF00B71526 /* SQLSubquery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB3425D91CEE00B71526 /* SQLSubquery.swift */; }; + 568ECB3625D91CEF00B71526 /* SQLSubquery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB3425D91CEE00B71526 /* SQLSubquery.swift */; }; 5690C3291D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */; }; 5690C32D1D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */; }; 5690C33A1D23E7D200E59934 /* FoundationDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3361D23E7D200E59934 /* FoundationDateTests.swift */; }; @@ -487,8 +481,6 @@ 56D507651F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; 56D51D021EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; 56D51D051EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; - 56D8B40D257D0FBE008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B40B257D0FBE008AA1F7 /* SQLRowValue.swift */; }; - 56D8B40E257D0FBE008AA1F7 /* SQLRowValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D8B40B257D0FBE008AA1F7 /* SQLRowValue.swift */; }; 56DAA2D51DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D91DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2DD1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; }; @@ -909,14 +901,9 @@ 5656A8442295BD56001FF3FF /* SQLExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpression.swift; sourceTree = ""; }; 5656A8452295BD56001FF3FF /* SQLOrdering.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOrdering.swift; sourceTree = ""; }; 5656A8462295BD56001FF3FF /* SQLOperators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperators.swift; sourceTree = ""; }; - 5656A8472295BD56001FF3FF /* SQLExpressible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpressible.swift; sourceTree = ""; }; - 5656A8482295BD56001FF3FF /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = ""; }; - 5656A8492295BD56001FF3FF /* SQLSelectable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectable.swift; sourceTree = ""; }; 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 = ""; }; 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 = ""; }; 5656A8A52295BF44001FF3FF /* DatabasePromise.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePromise.swift; sourceTree = ""; }; 5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = ""; }; @@ -977,6 +964,8 @@ 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = ""; }; 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = ""; }; 5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; + 568ECB0C25D904CA00B71526 /* SQLSelection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelection.swift; sourceTree = ""; }; + 568ECB3425D91CEE00B71526 /* SQLSubquery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSubquery.swift; sourceTree = ""; }; 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateComponentsTests.swift; sourceTree = ""; }; 5690C3361D23E7D200E59934 /* FoundationDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateTests.swift; sourceTree = ""; }; 5690C33F1D23E82A00E59934 /* Data.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Data.swift; sourceTree = ""; }; @@ -1083,7 +1072,6 @@ 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS4.swift; sourceTree = ""; }; 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = ""; }; - 56D8B40B257D0FBE008AA1F7 /* SQLRowValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRowValue.swift; sourceTree = ""; }; 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCursorTests.swift; sourceTree = ""; }; 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Cursor.swift; sourceTree = ""; }; 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = ""; }; @@ -1552,19 +1540,15 @@ 5656A8412295BD56001FF3FF /* SQLAssociation.swift */, 56F34FF024B0F0D8007513FC /* SQLCollatedExpression.swift */, 5656A8432295BD56001FF3FF /* SQLCollection.swift */, - 5656A8472295BD56001FF3FF /* SQLExpressible.swift */, 5656A8442295BD56001FF3FF /* SQLExpression.swift */, - 5656A8482295BD56001FF3FF /* SQLExpression+QueryInterface.swift */, 5656A8422295BD56001FF3FF /* SQLForeignKeyRequest.swift */, 5656A84C2295BD56001FF3FF /* SQLFunctions.swift */, 5656A8462295BD56001FF3FF /* SQLOperators.swift */, 5656A8452295BD56001FF3FF /* SQLOrdering.swift */, 5656A8502295BD56001FF3FF /* SQLQuery.swift */, 5656A84E2295BD56001FF3FF /* SQLRelation.swift */, - 56D8B40B257D0FBE008AA1F7 /* SQLRowValue.swift */, - 5656A8492295BD56001FF3FF /* SQLSelectable.swift */, - 5656A84F2295BD56001FF3FF /* SQLSelectable+QueryInterface.swift */, - 5656A84B2295BD56001FF3FF /* SQLSpecificExpressible+QueryInterface.swift */, + 568ECB0C25D904CA00B71526 /* SQLSelection.swift */, + 568ECB3425D91CEE00B71526 /* SQLSubquery.swift */, ); path = SQL; sourceTree = ""; @@ -2283,7 +2267,6 @@ F3BA801A1CFB2876003DC1BA /* StatementColumnConvertible.swift in Sources */, 566B91381FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56CEB4FF1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, - 5656A8922295BD56001FF3FF /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 5698AD3A1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, 5656A8742295BD56001FF3FF /* QueryInterfaceRequest.swift in Sources */, 566B91181FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, @@ -2305,11 +2288,11 @@ 5659F49D1EA8D989004A4992 /* Pool.swift in Sources */, 563A4B72242E7CE60075D8CF /* ValueObservationScheduler.swift in Sources */, 5674A6F61F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, - 5656A88A2295BD56001FF3FF /* SQLExpressible.swift in Sources */, 5698AC3C1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 5698AD171DAAD16F0056AF8C /* FTS5Tokenizer.swift in Sources */, 569BBA4C229170B300478429 /* Inflections+English.swift in Sources */, 5656A8762295BD56001FF3FF /* RequestProtocols.swift in Sources */, + 568ECB3625D91CEF00B71526 /* SQLSubquery.swift in Sources */, 561729552235340E0006E219 /* EncodableRecord.swift in Sources */, 5656A87E2295BD56001FF3FF /* SQLAssociation.swift in Sources */, F3BA80131CFB2876003DC1BA /* DatabaseValue.swift in Sources */, @@ -2329,12 +2312,12 @@ 56256EDF25D1BC07008C2BDD /* ForeignKey.swift in Sources */, F3BA800A1CFB286A003DC1BA /* Configuration.swift in Sources */, 5656A86C2295BD56001FF3FF /* HasManyAssociation.swift in Sources */, - 5656A88E2295BD56001FF3FF /* SQLSelectable.swift in Sources */, 5671FC251DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 5656A8862295BD56001FF3FF /* SQLOrdering.swift in Sources */, F3BA80311CFB289F003DC1BA /* Migration.swift in Sources */, F3BA801D1CFB288C003DC1BA /* DatabaseDateComponents.swift in Sources */, 5674A6ED1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, + 568ECB0E25D904CA00B71526 /* SQLSelection.swift in Sources */, 5657AB141D10899D006283EF /* URL.swift in Sources */, 56F34FF224B0F0D8007513FC /* SQLCollatedExpression.swift in Sources */, 5644DE7920F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */, @@ -2360,7 +2343,6 @@ F3BA80331CFB28A4003DC1BA /* PersistableRecord.swift in Sources */, 5656A8802295BD56001FF3FF /* SQLForeignKeyRequest.swift in Sources */, 56B964BE1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, - 56D8B40E257D0FBE008AA1F7 /* SQLRowValue.swift in Sources */, 561408A1221596A100DAD589 /* GRDB-5.0.swift in Sources */, F3BA80211CFB288C003DC1BA /* NSNull.swift in Sources */, 56FBFED72210731100945324 /* SQLRequest.swift in Sources */, @@ -2370,7 +2352,6 @@ 5656A8702295BD56001FF3FF /* Association.swift in Sources */, 563B8F9C249E74E5007A48C9 /* Trace.swift in Sources */, 5656A89C2295BD56001FF3FF /* SQLQuery.swift in Sources */, - 5656A88C2295BD56001FF3FF /* SQLExpression+QueryInterface.swift in Sources */, 5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 5656A85C2295BD56001FF3FF /* TableDefinition.swift in Sources */, 5656A8562295BD56001FF3FF /* FTS5+QueryInterface.swift in Sources */, @@ -2382,7 +2363,6 @@ 5613ED6221A95E6100DC7A68 /* ValueObservation.swift in Sources */, F3BA80361CFB28A4003DC1BA /* TableRecord.swift in Sources */, 567071F5208A00BE006AD95A /* SQLiteDateParser.swift in Sources */, - 5656A89A2295BD56001FF3FF /* SQLSelectable+QueryInterface.swift in Sources */, F3BA80271CFB2891003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 5657AABE1D107001006283EF /* NSData.swift in Sources */, 5674A6E61F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, @@ -2644,7 +2624,6 @@ F3BA80761CFB2E55003DC1BA /* StatementColumnConvertible.swift in Sources */, 566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56CEB4FC1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, - 5656A8912295BD56001FF3FF /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 5698AD371DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, 5656A8732295BD56001FF3FF /* QueryInterfaceRequest.swift in Sources */, 566B91151FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, @@ -2666,11 +2645,11 @@ 5659F49A1EA8D989004A4992 /* Pool.swift in Sources */, 563A4B71242E7CE60075D8CF /* ValueObservationScheduler.swift in Sources */, 5674A6F51F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, - 5656A8892295BD56001FF3FF /* SQLExpressible.swift in Sources */, 5698AC391D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 5698AD161DAAD16F0056AF8C /* FTS5Tokenizer.swift in Sources */, 569BBA4D229170B300478429 /* Inflections+English.swift in Sources */, 5656A8752295BD56001FF3FF /* RequestProtocols.swift in Sources */, + 568ECB3525D91CEF00B71526 /* SQLSubquery.swift in Sources */, 561729562235340E0006E219 /* EncodableRecord.swift in Sources */, 5656A87D2295BD56001FF3FF /* SQLAssociation.swift in Sources */, F3BA806F1CFB2E55003DC1BA /* DatabaseValue.swift in Sources */, @@ -2690,12 +2669,12 @@ 56256EDE25D1BC07008C2BDD /* ForeignKey.swift in Sources */, F3BA80661CFB2E55003DC1BA /* Configuration.swift in Sources */, 5656A86B2295BD56001FF3FF /* HasManyAssociation.swift in Sources */, - 5656A88D2295BD56001FF3FF /* SQLSelectable.swift in Sources */, 5671FC221DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 5656A8852295BD56001FF3FF /* SQLOrdering.swift in Sources */, F3BA808D1CFB2E75003DC1BA /* Migration.swift in Sources */, F3BA80791CFB2E61003DC1BA /* DatabaseDateComponents.swift in Sources */, 5674A6EC1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, + 568ECB0D25D904CA00B71526 /* SQLSelection.swift in Sources */, 5657AB111D10899D006283EF /* URL.swift in Sources */, 56F34FF124B0F0D8007513FC /* SQLCollatedExpression.swift in Sources */, 5644DE7820F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */, @@ -2721,7 +2700,6 @@ F3BA808F1CFB2E7A003DC1BA /* PersistableRecord.swift in Sources */, 5656A87F2295BD56001FF3FF /* SQLForeignKeyRequest.swift in Sources */, 56B964BB1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, - 56D8B40D257D0FBE008AA1F7 /* SQLRowValue.swift in Sources */, 561408A0221596A100DAD589 /* GRDB-5.0.swift in Sources */, F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */, 56FBFED62210731100945324 /* SQLRequest.swift in Sources */, @@ -2731,7 +2709,6 @@ 5656A86F2295BD56001FF3FF /* Association.swift in Sources */, 563B8F9B249E74E5007A48C9 /* Trace.swift in Sources */, 5656A89B2295BD56001FF3FF /* SQLQuery.swift in Sources */, - 5656A88B2295BD56001FF3FF /* SQLExpression+QueryInterface.swift in Sources */, 5698AD231DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 5656A85B2295BD56001FF3FF /* TableDefinition.swift in Sources */, 5656A8552295BD56001FF3FF /* FTS5+QueryInterface.swift in Sources */, @@ -2743,7 +2720,6 @@ 5613ED6121A95E6100DC7A68 /* ValueObservation.swift in Sources */, F3BA80921CFB2E7A003DC1BA /* TableRecord.swift in Sources */, 567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */, - 5656A8992295BD56001FF3FF /* SQLSelectable+QueryInterface.swift in Sources */, F3BA80831CFB2E67003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 5657AABB1D107001006283EF /* NSData.swift in Sources */, 5674A6E51F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, diff --git a/Tests/GRDBTests/DatabaseValueConvertibleEscapingTests.swift b/Tests/GRDBTests/DatabaseValueConvertibleEscapingTests.swift index 02521958a..e63902536 100644 --- a/Tests/GRDBTests/DatabaseValueConvertibleEscapingTests.swift +++ b/Tests/GRDBTests/DatabaseValueConvertibleEscapingTests.swift @@ -6,40 +6,40 @@ class DatabaseValueConvertibleEscapingTests: GRDBTestCase { func testNull() throws { try makeDatabaseQueue().inDatabase { db in - try XCTAssertEqual(DatabaseValue.null.quotedSQL(db), "NULL") + try XCTAssertEqual(DatabaseValue.null.sqlExpression.quotedSQL(db), "NULL") } } func testText() throws { try makeDatabaseQueue().inDatabase { db in - try XCTAssertEqual("".databaseValue.quotedSQL(db), "''") - try XCTAssertEqual("foo".databaseValue.quotedSQL(db), "'foo'") - try XCTAssertEqual("\"foo\"".databaseValue.quotedSQL(db), #"'"foo"'"#) - try XCTAssertEqual("'foo'".databaseValue.quotedSQL(db), "'''foo'''") + try XCTAssertEqual("".sqlExpression.quotedSQL(db), "''") + try XCTAssertEqual("foo".sqlExpression.quotedSQL(db), "'foo'") + try XCTAssertEqual("\"foo\"".sqlExpression.quotedSQL(db), #"'"foo"'"#) + try XCTAssertEqual("'foo'".sqlExpression.quotedSQL(db), "'''foo'''") } } func testInteger() throws { try makeDatabaseQueue().inDatabase { db in - try XCTAssertEqual(0.databaseValue.quotedSQL(db), "0") - try XCTAssertEqual(Int64.min.databaseValue.quotedSQL(db), "-9223372036854775808") - try XCTAssertEqual(Int64.max.databaseValue.quotedSQL(db), "9223372036854775807") + try XCTAssertEqual(0.sqlExpression.quotedSQL(db), "0") + try XCTAssertEqual(Int64.min.sqlExpression.quotedSQL(db), "-9223372036854775808") + try XCTAssertEqual(Int64.max.sqlExpression.quotedSQL(db), "9223372036854775807") } } func testDouble() throws { try makeDatabaseQueue().inDatabase { db in - try XCTAssertEqual(0.0.databaseValue.quotedSQL(db), "0.0") - try XCTAssertEqual(1.0.databaseValue.quotedSQL(db), "1.0") - try XCTAssertEqual((-1.0).databaseValue.quotedSQL(db), "-1.0") - try XCTAssertEqual(1.5.databaseValue.quotedSQL(db), "1.5") + try XCTAssertEqual(0.0.sqlExpression.quotedSQL(db), "0.0") + try XCTAssertEqual(1.0.sqlExpression.quotedSQL(db), "1.0") + try XCTAssertEqual((-1.0).sqlExpression.quotedSQL(db), "-1.0") + try XCTAssertEqual(1.5.sqlExpression.quotedSQL(db), "1.5") } } func testBlob() throws { try makeDatabaseQueue().inDatabase { db in - try XCTAssertEqual(Data().databaseValue.quotedSQL(db), "X''") - try XCTAssertEqual("foo".data(using: .utf8)!.databaseValue.quotedSQL(db), "X'666F6F'") + try XCTAssertEqual(Data().sqlExpression.quotedSQL(db), "X''") + try XCTAssertEqual("foo".data(using: .utf8)!.sqlExpression.quotedSQL(db), "X'666F6F'") } } diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index 380b05e78..0a5ffe28c 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -1361,19 +1361,19 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { CREATE TABLE compoundPrimaryKeyRecord (a INTEGER, b INTEGER, PRIMARY KEY (a, b)); """) - try assertEqualSQL(db, IntegerPrimaryKeyRecord.select(SQLExpressionFastPrimaryKey()), """ + try assertEqualSQL(db, IntegerPrimaryKeyRecord.select(SQLExpression.fastPrimaryKey), """ SELECT "id" FROM "integerPrimaryKeyRecord" """) - try assertEqualSQL(db, UUIDRecord.select(SQLExpressionFastPrimaryKey()), """ + try assertEqualSQL(db, UUIDRecord.select(SQLExpression.fastPrimaryKey), """ SELECT "rowid" FROM "uuidRecord" """) - try assertEqualSQL(db, UUIDRecordWithoutRowID.select(SQLExpressionFastPrimaryKey()), """ + try assertEqualSQL(db, UUIDRecordWithoutRowID.select(SQLExpression.fastPrimaryKey), """ SELECT "uuid" FROM "uuidRecordWithoutRowID" """) - try assertEqualSQL(db, RowIDRecord.select(SQLExpressionFastPrimaryKey()), """ + try assertEqualSQL(db, RowIDRecord.select(SQLExpression.fastPrimaryKey), """ SELECT "rowid" FROM "rowIDRecord" """) - try assertEqualSQL(db, CompoundPrimaryKeyRecord.select(SQLExpressionFastPrimaryKey()), """ + try assertEqualSQL(db, CompoundPrimaryKeyRecord.select(SQLExpression.fastPrimaryKey), """ SELECT "rowid" FROM "compoundPrimaryKeyRecord" """) } diff --git a/Tests/GRDBTests/RawRepresentable+DatabaseValueConvertibleTests.swift b/Tests/GRDBTests/RawRepresentable+DatabaseValueConvertibleTests.swift index 4a1637cba..b557bb97d 100644 --- a/Tests/GRDBTests/RawRepresentable+DatabaseValueConvertibleTests.swift +++ b/Tests/GRDBTests/RawRepresentable+DatabaseValueConvertibleTests.swift @@ -33,6 +33,8 @@ extension Color32 : SQLExpressible { } extension Color64 : SQLExpressible { } extension Color : SQLExpressible { } extension Grape : SQLExpressible { } +extension Wrapper: SQLOrderingTerm where RawValue: SQLOrderingTerm { } +extension Wrapper: SQLSelectable where RawValue: SQLSelectable { } extension Wrapper: SQLExpressible where RawValue: SQLExpressible { } extension Color32 : DatabaseValueConvertible { } diff --git a/Tests/GRDBTests/SQLExpressionIsConstantTests.swift b/Tests/GRDBTests/SQLExpressionIsConstantTests.swift index e807cde4b..8398f2161 100644 --- a/Tests/GRDBTests/SQLExpressionIsConstantTests.swift +++ b/Tests/GRDBTests/SQLExpressionIsConstantTests.swift @@ -1,26 +1,6 @@ import XCTest @testable import GRDB -// Column -// DatabaseValue -// SQLExpressionAssociativeBinary -// SQLExpressionBetween -// SQLExpressionBinary -// SQLExpressionCollate -// SQLExpressionContains -// SQLExpressionCount -// SQLExpressionCountDistinct -// SQLExpressionEqual -// SQLExpressionFastPrimaryKey -// SQLExpressionFunction -// SQLExpressionIsEmpty -// SQLExpressionLiteral -// SQLExpressionNot -// SQLExpressionQualifiedFastPrimaryKey -// SQLExpressionTableMatch -// SQLExpressionUnary -// SQLQualifiedColumn -// SQLRowValue class SQLExpressionIsConstantTests: GRDBTestCase { func testColumn() throws { try makeDatabaseQueue().write { db in @@ -28,124 +8,124 @@ class SQLExpressionIsConstantTests: GRDBTestCase { let alias = TableAlias(tableName: "t") // Column - try XCTAssertEqual(Column("a")._column(db, for: alias, acceptsBijection: true), nil) - try XCTAssertEqual(Column("a")._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(Column("a").sqlExpression.column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual(Column("a").sqlExpression.column(db, for: alias, acceptsBijection: false), nil) // DatabaseValue - try XCTAssertEqual("foo".databaseValue._column(db, for: alias, acceptsBijection: true), nil) - try XCTAssertEqual("foo".databaseValue._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual("foo".sqlExpression.column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual("foo".sqlExpression.column(db, for: alias, acceptsBijection: false), nil) // SQLExpressionAssociativeBinary - try XCTAssertEqual([].joined(operator: .multiply)._column(db, for: alias, acceptsBijection: true), nil) - try XCTAssertEqual([].joined(operator: .multiply)._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual([Column("a")].joined(operator: .multiply)._column(db, for: alias, acceptsBijection: true), nil) - try XCTAssertEqual([Column("a")].joined(operator: .multiply)._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual([alias[Column("a")]].joined(operator: .multiply)._column(db, for: alias, acceptsBijection: true), "a") - try XCTAssertEqual([alias[Column("a")]].joined(operator: .multiply)._column(db, for: alias, acceptsBijection: false), "a") - try XCTAssertEqual([-alias[Column("a")]].joined(operator: .multiply)._column(db, for: alias, acceptsBijection: true), "a") - try XCTAssertEqual([-alias[Column("a")]].joined(operator: .multiply)._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual((alias[Column("a")] * "foo".databaseValue)._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual((alias[Column("a")] * "foo".databaseValue)._column(db, for: alias, acceptsBijection: true), nil) - try XCTAssertEqual((alias[Column("a")] + "foo".databaseValue)._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual((alias[Column("a")] + "foo".databaseValue)._column(db, for: alias, acceptsBijection: true), "a") - try XCTAssertEqual((alias[Column("a")] + alias[Column("b")])._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual((alias[Column("a")] + alias[Column("b")])._column(db, for: alias, acceptsBijection: true), nil) - try XCTAssertEqual([alias[Column("a")], "foo".databaseValue].joined(operator: .concat)._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual([alias[Column("a")], "foo".databaseValue].joined(operator: .concat)._column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual([].joined(operator: .multiply).column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual([].joined(operator: .multiply).column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual([Column("a")].joined(operator: .multiply).column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual([Column("a")].joined(operator: .multiply).column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual([alias[Column("a")]].joined(operator: .multiply).column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual([alias[Column("a")]].joined(operator: .multiply).column(db, for: alias, acceptsBijection: false), "a") + try XCTAssertEqual([-alias[Column("a")]].joined(operator: .multiply).column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual([-alias[Column("a")]].joined(operator: .multiply).column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((alias[Column("a")] * "foo".databaseValue).column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((alias[Column("a")] * "foo".databaseValue).column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual((alias[Column("a")] + "foo".databaseValue).column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((alias[Column("a")] + "foo".databaseValue).column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual((alias[Column("a")] + alias[Column("b")]).column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((alias[Column("a")] + alias[Column("b")]).column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual([alias[Column("a")], "foo".databaseValue].joined(operator: .concat).column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual([alias[Column("a")], "foo".databaseValue].joined(operator: .concat).column(db, for: alias, acceptsBijection: true), "a") // SQLExpressionBetween - try XCTAssertEqual((1...3).contains(alias[Column("a")])._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual((1...3).contains(alias[Column("a")])._column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((1...3).contains(alias[Column("a")]).column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((1...3).contains(alias[Column("a")]).column(db, for: alias, acceptsBijection: false), nil) // SQLExpressionBinary - try XCTAssertEqual((alias[Column("a")] - "foo".databaseValue)._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual((alias[Column("a")] - "foo".databaseValue)._column(db, for: alias, acceptsBijection: true), "a") - try XCTAssertEqual((alias[Column("a")] - alias[Column("b")])._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual((alias[Column("a")] - alias[Column("b")])._column(db, for: alias, acceptsBijection: true), nil) - try XCTAssertEqual((alias[Column("a")] < "foo".databaseValue)._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual((alias[Column("a")] < "foo".databaseValue)._column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual((alias[Column("a")] - "foo".databaseValue).column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((alias[Column("a")] - "foo".databaseValue).column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual((alias[Column("a")] - alias[Column("b")]).column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((alias[Column("a")] - alias[Column("b")]).column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual((alias[Column("a")] < "foo".databaseValue).column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((alias[Column("a")] < "foo".databaseValue).column(db, for: alias, acceptsBijection: true), nil) // SQLExpressionCollate - try XCTAssertEqual(Column("a").collating(.binary).sqlExpression._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual(Column("a").collating(.binary).sqlExpression._column(db, for: alias, acceptsBijection: true), nil) - try XCTAssertEqual(alias[Column("a")].collating(.binary).sqlExpression._column(db, for: alias, acceptsBijection: false), "a") - try XCTAssertEqual(alias[Column("a")].collating(.binary).sqlExpression._column(db, for: alias, acceptsBijection: true), "a") - try XCTAssertEqual((alias[Column("a")] + "foo".databaseValue).collating(.binary).sqlExpression._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual((alias[Column("a")] + "foo".databaseValue).collating(.binary).sqlExpression._column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual(Column("a").collating(.binary).sqlExpression.column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(Column("a").collating(.binary).sqlExpression.column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual(alias[Column("a")].collating(.binary).sqlExpression.column(db, for: alias, acceptsBijection: false), "a") + try XCTAssertEqual(alias[Column("a")].collating(.binary).sqlExpression.column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual((alias[Column("a")] + "foo".databaseValue).collating(.binary).sqlExpression.column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((alias[Column("a")] + "foo".databaseValue).collating(.binary).sqlExpression.column(db, for: alias, acceptsBijection: true), "a") // SQLExpressionContains - try XCTAssertEqual([1, 2, 3].contains(alias[Column("a")])._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual([1, 2, 3].contains(alias[Column("a")])._column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual([1, 2, 3].contains(alias[Column("a")]).column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual([1, 2, 3].contains(alias[Column("a")]).column(db, for: alias, acceptsBijection: true), nil) // SQLExpressionCount - try XCTAssertEqual(count(alias[Column("a")])._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual(count(alias[Column("a")])._column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual(count(alias[Column("a")]).column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(count(alias[Column("a")]).column(db, for: alias, acceptsBijection: true), nil) // SQLExpressionCountDistinct - try XCTAssertEqual(count(distinct: alias[Column("a")])._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual(count(distinct: alias[Column("a")])._column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual(count(distinct: alias[Column("a")]).column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(count(distinct: alias[Column("a")]).column(db, for: alias, acceptsBijection: true), nil) // SQLExpressionEqual - try XCTAssertEqual((alias[Column("a")] == "foo")._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual((alias[Column("a")] == "foo")._column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual((alias[Column("a")] == "foo").column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((alias[Column("a")] == "foo").column(db, for: alias, acceptsBijection: true), nil) // SQLExpressionFastPrimaryKey - try XCTAssertEqual(SQLExpressionFastPrimaryKey()._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual(SQLExpressionFastPrimaryKey()._column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual(SQLExpression.fastPrimaryKey.column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(SQLExpression.fastPrimaryKey.column(db, for: alias, acceptsBijection: true), nil) // SQLExpressionFunction - try XCTAssertEqual(length(alias[Column("a")])._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual(length(alias[Column("a")])._column(db, for: alias, acceptsBijection: true), nil) - try XCTAssertEqual((alias[Column("a")] ?? "foo")._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual((alias[Column("a")] ?? "foo")._column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual(length(alias[Column("a")]).column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(length(alias[Column("a")]).column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual((alias[Column("a")] ?? "foo").column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((alias[Column("a")] ?? "foo").column(db, for: alias, acceptsBijection: true), "a") - // SQLExpressionIsEmpty - try XCTAssertEqual(SQLExpressionIsEmpty(alias[Column("a")])._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual(SQLExpressionIsEmpty(alias[Column("a")])._column(db, for: alias, acceptsBijection: true), nil) + // SQLExpression.isEmpty + try XCTAssertEqual(SQLExpression.isEmpty(alias[Column("a")]).column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(SQLExpression.isEmpty(alias[Column("a")]).column(db, for: alias, acceptsBijection: true), nil) // SQLExpressionLiteral - try XCTAssertEqual(SQLLiteral("\(alias[Column("a")]) * 2").sqlExpression._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual(SQLLiteral("\(alias[Column("a")]) * 2").sqlExpression._column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual(SQLLiteral("\(alias[Column("a")]) * 2").sqlExpression.column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(SQLLiteral("\(alias[Column("a")]) * 2").sqlExpression.column(db, for: alias, acceptsBijection: true), nil) // SQLExpressionNot - try XCTAssertEqual((!alias[Column("a")])._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual((!alias[Column("a")])._column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual((!alias[Column("a")]).column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((!alias[Column("a")]).column(db, for: alias, acceptsBijection: true), nil) // SQLExpressionQualifiedFastPrimaryKey - try XCTAssertEqual(alias[SQLExpressionFastPrimaryKey()]._column(db, for: alias, acceptsBijection: false), "id") - try XCTAssertEqual(alias[SQLExpressionFastPrimaryKey()]._column(db, for: alias, acceptsBijection: true), "id") + try XCTAssertEqual(alias[SQLExpression.fastPrimaryKey].column(db, for: alias, acceptsBijection: false), "id") + try XCTAssertEqual(alias[SQLExpression.fastPrimaryKey].column(db, for: alias, acceptsBijection: true), "id") - // SQLExpressionTableMatch - try XCTAssertEqual(SQLExpressionTableMatch(alias: alias, pattern: alias[Column("a")])._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual(SQLExpressionTableMatch(alias: alias, pattern: alias[Column("a")])._column(db, for: alias, acceptsBijection: true), nil) + // SQLExpression.tableMatch + try XCTAssertEqual(SQLExpression.tableMatch(alias, alias[Column("a")]).column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(SQLExpression.tableMatch(alias, alias[Column("a")]).column(db, for: alias, acceptsBijection: true), nil) // SQLExpressionUnary - try XCTAssertEqual((-Column("a"))._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual((-Column("a"))._column(db, for: alias, acceptsBijection: true), nil) - try XCTAssertEqual((-alias[Column("a")])._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual((-alias[Column("a")])._column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual((-Column("a")).column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((-Column("a")).column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual((-alias[Column("a")]).column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual((-alias[Column("a")]).column(db, for: alias, acceptsBijection: true), "a") // SQLQualifiedColumn - try XCTAssertEqual(alias[Column("a")]._column(db, for: alias, acceptsBijection: false), "a") - try XCTAssertEqual(alias[Column("a")]._column(db, for: alias, acceptsBijection: true), "a") - try XCTAssertEqual(TableAlias()[Column("a")]._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual(TableAlias()[Column("a")]._column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual(alias[Column("a")].column(db, for: alias, acceptsBijection: false), "a") + try XCTAssertEqual(alias[Column("a")].column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual(TableAlias()[Column("a")].column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(TableAlias()[Column("a")].column(db, for: alias, acceptsBijection: true), nil) - // SQLRowValue - try XCTAssertEqual(SQLRowValue([1.databaseValue])._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual(SQLRowValue([1.databaseValue])._column(db, for: alias, acceptsBijection: true), nil) - try XCTAssertEqual(SQLRowValue([alias[Column("a")]])._column(db, for: alias, acceptsBijection: false), "a") - try XCTAssertEqual(SQLRowValue([alias[Column("a")]])._column(db, for: alias, acceptsBijection: true), "a") - try XCTAssertEqual(SQLRowValue([-alias[Column("a")]])._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual(SQLRowValue([-alias[Column("a")]])._column(db, for: alias, acceptsBijection: true), "a") - try XCTAssertEqual(SQLRowValue([1.databaseValue, 2.databaseValue])._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual(SQLRowValue([1.databaseValue, 2.databaseValue])._column(db, for: alias, acceptsBijection: true), nil) - try XCTAssertEqual(SQLRowValue([alias[Column("a")], 2.databaseValue])._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual(SQLRowValue([alias[Column("a")], 2.databaseValue])._column(db, for: alias, acceptsBijection: true), nil) - try XCTAssertEqual(SQLRowValue([1.databaseValue, alias[Column("a")]])._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual(SQLRowValue([1.databaseValue, alias[Column("a")]])._column(db, for: alias, acceptsBijection: true), nil) - try XCTAssertEqual(SQLRowValue([alias[Column("a")], alias[Column("a")]])._column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual(SQLRowValue([alias[Column("a")], alias[Column("a")]])._column(db, for: alias, acceptsBijection: true), nil) + // SQLExpression.rowValue + try XCTAssertEqual(SQLExpression.rowValue([1.sqlExpression])!.column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(SQLExpression.rowValue([1.sqlExpression])!.column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual(SQLExpression.rowValue([alias[Column("a")]])!.column(db, for: alias, acceptsBijection: false), "a") + try XCTAssertEqual(SQLExpression.rowValue([alias[Column("a")]])!.column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual(SQLExpression.rowValue([-alias[Column("a")]])!.column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(SQLExpression.rowValue([-alias[Column("a")]])!.column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual(SQLExpression.rowValue([1.sqlExpression, 2.sqlExpression])!.column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(SQLExpression.rowValue([1.sqlExpression, 2.sqlExpression])!.column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual(SQLExpression.rowValue([alias[Column("a")], 2.sqlExpression])!.column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(SQLExpression.rowValue([alias[Column("a")], 2.sqlExpression])!.column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual(SQLExpression.rowValue([1.sqlExpression, alias[Column("a")]])!.column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(SQLExpression.rowValue([1.sqlExpression, alias[Column("a")]])!.column(db, for: alias, acceptsBijection: true), nil) + try XCTAssertEqual(SQLExpression.rowValue([alias[Column("a")], alias[Column("a")]])!.column(db, for: alias, acceptsBijection: false), nil) + try XCTAssertEqual(SQLExpression.rowValue([alias[Column("a")], alias[Column("a")]])!.column(db, for: alias, acceptsBijection: true), nil) } } @@ -155,74 +135,74 @@ class SQLExpressionIsConstantTests: GRDBTestCase { let alias = TableAlias(tableName: "t") // Column - try XCTAssertEqual(Column("a")._identifyingColums(db, for: alias), []) + try XCTAssertEqual(Column("a").sqlExpression.identifyingColums(db, for: alias), []) // DatabaseValue - try XCTAssertEqual("foo".databaseValue._identifyingColums(db, for: alias), []) + try XCTAssertEqual("foo".sqlExpression.identifyingColums(db, for: alias), []) // SQLExpressionAssociativeBinary - try XCTAssertEqual((alias[Column("a")] == 1 || alias[Column("b")] == 2)._identifyingColums(db, for: alias), []) - try XCTAssertEqual((alias[Column("a")] == 1 && alias[Column("b")] == 2)._identifyingColums(db, for: alias), ["a", "b"]) - try XCTAssertEqual((alias[Column("a")] == 1 && TableAlias()[Column("b")] == 2)._identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual((alias[Column("a")] == 1 || alias[Column("b")] == 2).identifyingColums(db, for: alias), []) + try XCTAssertEqual((alias[Column("a")] == 1 && alias[Column("b")] == 2).identifyingColums(db, for: alias), ["a", "b"]) + try XCTAssertEqual((alias[Column("a")] == 1 && TableAlias()[Column("b")] == 2).identifyingColums(db, for: alias), ["a"]) // SQLExpressionBetween - try XCTAssertEqual((1...3).contains(alias[Column("a")])._identifyingColums(db, for: alias), []) + try XCTAssertEqual((1...3).contains(alias[Column("a")]).identifyingColums(db, for: alias), []) // SQLExpressionBinary - try XCTAssertEqual((alias[Column("a")] - 1)._identifyingColums(db, for: alias), []) + try XCTAssertEqual((alias[Column("a")] - 1).identifyingColums(db, for: alias), []) // SQLExpressionCollate - try XCTAssertEqual((alias[Column("a")] == 1).collating(.binary).sqlExpression._identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual((alias[Column("a")] == 1).collating(.binary).sqlExpression.identifyingColums(db, for: alias), ["a"]) // SQLExpressionContains - try XCTAssertEqual([1, 2, 3].contains(alias[Column("a")])._identifyingColums(db, for: alias), []) + try XCTAssertEqual([1, 2, 3].contains(alias[Column("a")]).identifyingColums(db, for: alias), []) // SQLExpressionCount - try XCTAssertEqual(count(alias[Column("a")])._identifyingColums(db, for: alias), []) + try XCTAssertEqual(count(alias[Column("a")]).identifyingColums(db, for: alias), []) // SQLExpressionCountDistinct - try XCTAssertEqual(count(distinct: alias[Column("a")])._identifyingColums(db, for: alias), []) + try XCTAssertEqual(count(distinct: alias[Column("a")]).identifyingColums(db, for: alias), []) // SQLExpressionEqual - try XCTAssertEqual((alias[Column("a")] == nil)._identifyingColums(db, for: alias), ["a"]) - try XCTAssertEqual((alias[Column("a")] == 1)._identifyingColums(db, for: alias), ["a"]) - try XCTAssertEqual((1 == alias[Column("a")])._identifyingColums(db, for: alias), ["a"]) - try XCTAssertEqual((-alias[Column("a")] == 1)._identifyingColums(db, for: alias), ["a"]) - try XCTAssertEqual(((alias[Column("a")] * 2) == 1)._identifyingColums(db, for: alias), []) - try XCTAssertEqual(((alias[Column("a")] + 2) == 1)._identifyingColums(db, for: alias), ["a"]) - try XCTAssertEqual(((alias[Column("a")] - 2) == 1)._identifyingColums(db, for: alias), ["a"]) - try XCTAssertEqual((alias[SQLExpressionFastPrimaryKey()] == 1)._identifyingColums(db, for: alias), ["id"]) - try XCTAssertEqual((alias[Column("a")] == alias[Column("b")])._identifyingColums(db, for: alias), []) - try XCTAssertEqual((TableAlias()[Column("a")] == nil)._identifyingColums(db, for: alias), []) - try XCTAssertEqual((TableAlias()[Column("a")] == 1)._identifyingColums(db, for: alias), []) - try XCTAssertEqual((SQLRowValue([alias[SQLExpressionFastPrimaryKey()]]) == 1)._identifyingColums(db, for: alias), ["id"]) + try XCTAssertEqual((alias[Column("a")] == nil).identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual((alias[Column("a")] == 1).identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual((1 == alias[Column("a")]).identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual((-alias[Column("a")] == 1).identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual(((alias[Column("a")] * 2) == 1).identifyingColums(db, for: alias), []) + try XCTAssertEqual(((alias[Column("a")] + 2) == 1).identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual(((alias[Column("a")] - 2) == 1).identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual((alias[SQLExpression.fastPrimaryKey] == 1).identifyingColums(db, for: alias), ["id"]) + try XCTAssertEqual((alias[Column("a")] == alias[Column("b")]).identifyingColums(db, for: alias), []) + try XCTAssertEqual((TableAlias()[Column("a")] == nil).identifyingColums(db, for: alias), []) + try XCTAssertEqual((TableAlias()[Column("a")] == 1).identifyingColums(db, for: alias), []) + try XCTAssertEqual((SQLExpression.rowValue([alias[SQLExpression.fastPrimaryKey]])! == 1).identifyingColums(db, for: alias), ["id"]) // SQLExpressionFastPrimaryKey - try XCTAssertEqual(SQLExpressionFastPrimaryKey()._identifyingColums(db, for: alias), []) + try XCTAssertEqual(SQLExpression.fastPrimaryKey.identifyingColums(db, for: alias), []) // SQLExpressionFunction - try XCTAssertEqual(length(alias[Column("a")])._identifyingColums(db, for: alias), []) + try XCTAssertEqual(length(alias[Column("a")]).identifyingColums(db, for: alias), []) - // SQLExpressionIsEmpty - try XCTAssertEqual(SQLExpressionIsEmpty(alias[Column("a")])._identifyingColums(db, for: alias), []) + // SQLExpression.isEmpty + try XCTAssertEqual(SQLExpression.isEmpty(alias[Column("a")]).identifyingColums(db, for: alias), []) // SQLExpressionLiteral // SQLExpressionNot - try XCTAssertEqual((!alias[Column("a")])._identifyingColums(db, for: alias), []) + try XCTAssertEqual((!alias[Column("a")]).identifyingColums(db, for: alias), []) // SQLExpressionQualifiedFastPrimaryKey - try XCTAssertEqual(alias[SQLExpressionFastPrimaryKey()]._identifyingColums(db, for: alias), []) + try XCTAssertEqual(alias[SQLExpression.fastPrimaryKey].identifyingColums(db, for: alias), []) - // SQLExpressionTableMatch + // SQLExpression.tableMatch // SQLExpressionUnary - try XCTAssertEqual((-alias[Column("a")])._identifyingColums(db, for: alias), []) + try XCTAssertEqual((-alias[Column("a")]).identifyingColums(db, for: alias), []) // SQLQualifiedColumn - try XCTAssertEqual(alias[Column("a")]._identifyingColums(db, for: alias), []) + try XCTAssertEqual(alias[Column("a")].identifyingColums(db, for: alias), []) - // SQLRowValue - try XCTAssertEqual(SQLRowValue([alias[SQLExpressionFastPrimaryKey()]])._identifyingColums(db, for: alias), []) - try XCTAssertEqual(SQLRowValue([alias[SQLExpressionFastPrimaryKey()] == 1])._identifyingColums(db, for: alias), ["id"]) + // SQLExpression.rowValue + try XCTAssertEqual(SQLExpression.rowValue([alias[SQLExpression.fastPrimaryKey]])!.identifyingColums(db, for: alias), []) + try XCTAssertEqual(SQLExpression.rowValue([alias[SQLExpression.fastPrimaryKey] == 1])!.identifyingColums(db, for: alias), ["id"]) } } @@ -234,120 +214,120 @@ class SQLExpressionIsConstantTests: GRDBTestCase { // Column // DatabaseValue // SQLExpressionAssociativeBinary - try XCTAssertEqual((alias[Column("id")] == 1 || alias[Column("id")] == 3)._identifyingRowIDs(db, for: alias), [1, 3]) - try XCTAssertEqual((alias[Column("id")] == 1 && alias[Column("id")] == 3)._identifyingRowIDs(db, for: alias), []) - try XCTAssertEqual((alias[Column("id")] == 1 && alias[Column("id")] == 1)._identifyingRowIDs(db, for: alias), [1]) + try XCTAssertEqual((alias[Column("id")] == 1 || alias[Column("id")] == 3).identifyingRowIDs(db, for: alias), [1, 3]) + try XCTAssertEqual((alias[Column("id")] == 1 && alias[Column("id")] == 3).identifyingRowIDs(db, for: alias), []) + try XCTAssertEqual((alias[Column("id")] == 1 && alias[Column("id")] == 1).identifyingRowIDs(db, for: alias), [1]) // SQLExpressionBetween - try XCTAssertEqual((0...Int.max).contains(TableAlias()[Column("id")])._identifyingRowIDs(db, for: alias), nil) + try XCTAssertEqual((0...Int.max).contains(TableAlias()[Column("id")]).identifyingRowIDs(db, for: alias), nil) // SQLExpressionBinary // SQLExpressionCollate // SQLExpressionContains - try XCTAssertEqual([1, 2, 3].contains(TableAlias()[Column("id")])._identifyingRowIDs(db, for: alias), nil) - try XCTAssertEqual([1, 2, 3].contains(alias[Column("id")])._identifyingRowIDs(db, for: alias), [1, 2, 3]) - try XCTAssertEqual([].contains(alias[Column("id")])._identifyingRowIDs(db, for: alias), []) - try XCTAssertEqual([1, 2, 3].contains(alias[Column("id")] + 1)._identifyingRowIDs(db, for: alias), nil) + try XCTAssertEqual([1, 2, 3].contains(TableAlias()[Column("id")]).identifyingRowIDs(db, for: alias), nil) + try XCTAssertEqual([1, 2, 3].contains(alias[Column("id")]).identifyingRowIDs(db, for: alias), [1, 2, 3]) + try XCTAssertEqual([].contains(alias[Column("id")]).identifyingRowIDs(db, for: alias), []) + try XCTAssertEqual([1, 2, 3].contains(alias[Column("id")] + 1).identifyingRowIDs(db, for: alias), nil) // SQLExpressionCount // SQLExpressionCountDistinct // SQLExpressionEqual - try XCTAssertEqual((TableAlias()[Column("id")] == 1)._identifyingRowIDs(db, for: alias), nil) - try XCTAssertEqual((alias[Column("id")] == 1)._identifyingRowIDs(db, for: alias), [1]) - try XCTAssertEqual((alias[Column("id")] == nil)._identifyingRowIDs(db, for: alias), []) - try XCTAssertEqual(((alias[Column("id")] + 1) == 2)._identifyingRowIDs(db, for: alias), nil) + try XCTAssertEqual((TableAlias()[Column("id")] == 1).identifyingRowIDs(db, for: alias), nil) + try XCTAssertEqual((alias[Column("id")] == 1).identifyingRowIDs(db, for: alias), [1]) + try XCTAssertEqual((alias[Column("id")] == nil).identifyingRowIDs(db, for: alias), []) + try XCTAssertEqual(((alias[Column("id")] + 1) == 2).identifyingRowIDs(db, for: alias), nil) // SQLExpressionFastPrimaryKey // SQLExpressionFunction - // SQLExpressionIsEmpty + // SQLExpression.isEmpty // SQLExpressionLiteral // SQLExpressionNot // SQLExpressionQualifiedFastPrimaryKey - // SQLExpressionTableMatch + // SQLExpression.tableMatch // SQLExpressionUnary // SQLQualifiedColumn - // SQLRowValue + // SQLExpression.rowValue } } func testIsConstantInRequest() { // Column - XCTAssertFalse(Column("a")._isConstantInRequest) + XCTAssertFalse(Column("a").sqlExpression.isConstantInRequest) // DatabaseValue - XCTAssertTrue(1.databaseValue._isConstantInRequest) + XCTAssertTrue(1.sqlExpression.isConstantInRequest) // SQLExpressionAssociativeBinary - XCTAssertTrue([].joined(operator: .multiply)._isConstantInRequest) - XCTAssertTrue([1.databaseValue].joined(operator: .multiply)._isConstantInRequest) - XCTAssertFalse([Column("a")].joined(operator: .multiply)._isConstantInRequest) - XCTAssertTrue([1.databaseValue, 2.databaseValue].joined(operator: .multiply)._isConstantInRequest) - XCTAssertFalse([Column("a"), 2.databaseValue].joined(operator: .multiply)._isConstantInRequest) - XCTAssertFalse([1.databaseValue, Column("a")].joined(operator: .multiply)._isConstantInRequest) + XCTAssertTrue([].joined(operator: .multiply).isConstantInRequest) + XCTAssertTrue([1.databaseValue].joined(operator: .multiply).isConstantInRequest) + XCTAssertFalse([Column("a")].joined(operator: .multiply).isConstantInRequest) + XCTAssertTrue([1.databaseValue, 2.databaseValue].joined(operator: .multiply).isConstantInRequest) + XCTAssertFalse([Column("a"), 2.databaseValue].joined(operator: .multiply).isConstantInRequest) + XCTAssertFalse([1.databaseValue, Column("a")].joined(operator: .multiply).isConstantInRequest) // SQLExpressionBetween - XCTAssertTrue((1...3).contains(1.databaseValue)._isConstantInRequest) - XCTAssertFalse((1...3).contains(Column("a"))._isConstantInRequest) + XCTAssertTrue((1...3).contains(1.databaseValue).isConstantInRequest) + XCTAssertFalse((1...3).contains(Column("a")).isConstantInRequest) // SQLExpressionBinary - XCTAssertTrue((1.databaseValue - 2.databaseValue)._isConstantInRequest) - XCTAssertFalse((Column("a") - 2.databaseValue)._isConstantInRequest) - XCTAssertFalse((1.databaseValue - Column("a"))._isConstantInRequest) + XCTAssertTrue((1.databaseValue - 2.databaseValue).isConstantInRequest) + XCTAssertFalse((Column("a") - 2.databaseValue).isConstantInRequest) + XCTAssertFalse((1.databaseValue - Column("a")).isConstantInRequest) // SQLExpressionCollate - XCTAssertTrue("foo".databaseValue.collating(.binary).sqlExpression._isConstantInRequest) - XCTAssertFalse(Column("a").collating(.binary).sqlExpression._isConstantInRequest) + XCTAssertTrue("foo".databaseValue.collating(.binary).sqlExpression.isConstantInRequest) + XCTAssertFalse(Column("a").collating(.binary).sqlExpression.isConstantInRequest) // SQLExpressionContains - XCTAssertFalse([1, 2, 3].contains(Column("a"))._isConstantInRequest) + XCTAssertFalse([1, 2, 3].contains(Column("a")).isConstantInRequest) // SQLExpressionCount - XCTAssertFalse(count(Column("a"))._isConstantInRequest) + XCTAssertFalse(count(Column("a")).isConstantInRequest) // SQLExpressionCountDistinct - XCTAssertFalse(count(distinct: Column("a"))._isConstantInRequest) + XCTAssertFalse(count(distinct: Column("a")).isConstantInRequest) // SQLExpressionEqual - XCTAssertTrue((1.databaseValue == 2.databaseValue)._isConstantInRequest) - XCTAssertFalse((Column("a") == 2.databaseValue)._isConstantInRequest) - XCTAssertFalse((1.databaseValue == Column("a"))._isConstantInRequest) + XCTAssertTrue((1.databaseValue == 2.databaseValue).isConstantInRequest) + XCTAssertFalse((Column("a") == 2.databaseValue).isConstantInRequest) + XCTAssertFalse((1.databaseValue == Column("a")).isConstantInRequest) // SQLExpressionFastPrimaryKey - XCTAssertFalse(SQLExpressionFastPrimaryKey()._isConstantInRequest) + XCTAssertFalse(SQLExpression.fastPrimaryKey.isConstantInRequest) // SQLExpressionFunction - XCTAssertTrue(length("foo".databaseValue)._isConstantInRequest) - XCTAssertFalse(length(Column("a"))._isConstantInRequest) + XCTAssertTrue(length("foo".databaseValue).isConstantInRequest) + XCTAssertFalse(length(Column("a")).isConstantInRequest) - // SQLExpressionIsEmpty - XCTAssertTrue(SQLExpressionIsEmpty("foo".databaseValue)._isConstantInRequest) - XCTAssertFalse(SQLExpressionIsEmpty(Column("a"))._isConstantInRequest) + // SQLExpression.isEmpty + XCTAssertTrue(SQLExpression.isEmpty("foo".sqlExpression).isConstantInRequest) + XCTAssertFalse(SQLExpression.isEmpty(Column("a").sqlExpression).isConstantInRequest) // SQLExpressionLiteral - XCTAssertFalse(SQLLiteral("1").sqlExpression._isConstantInRequest) + XCTAssertFalse(SQLLiteral("1").sqlExpression.isConstantInRequest) // SQLExpressionNot - XCTAssertTrue((!(true.databaseValue))._isConstantInRequest) - XCTAssertFalse((!Column("a"))._isConstantInRequest) + XCTAssertTrue((!(true.databaseValue)).isConstantInRequest) + XCTAssertFalse((!Column("a")).isConstantInRequest) // SQLExpressionQualifiedFastPrimaryKey - XCTAssertFalse(SQLExpressionFastPrimaryKey()._qualifiedExpression(with: TableAlias())._isConstantInRequest) + XCTAssertFalse(SQLExpression.fastPrimaryKey.qualified(with: TableAlias()).isConstantInRequest) - // SQLExpressionTableMatch - XCTAssertFalse(SQLExpressionTableMatch(alias: TableAlias(), pattern: "foo".databaseValue)._isConstantInRequest) + // SQLExpression.tableMatch + XCTAssertFalse(SQLExpression.tableMatch(TableAlias(), "foo".sqlExpression).isConstantInRequest) // SQLExpressionUnary - XCTAssertTrue((-(1.databaseValue))._isConstantInRequest) - XCTAssertFalse((-Column("a"))._isConstantInRequest) + XCTAssertTrue((-(1.databaseValue)).isConstantInRequest) + XCTAssertFalse((-Column("a")).isConstantInRequest) // SQLQualifiedColumn - XCTAssertFalse(Column("a")._qualifiedExpression(with: TableAlias())._isConstantInRequest) + XCTAssertFalse(Column("a").sqlExpression.qualified(with: TableAlias()).isConstantInRequest) - // SQLRowValue - XCTAssertTrue(SQLRowValue([1.databaseValue])._isConstantInRequest) - XCTAssertFalse(SQLRowValue([Column("a")])._isConstantInRequest) - XCTAssertTrue(SQLRowValue([1.databaseValue, 2.databaseValue])._isConstantInRequest) - XCTAssertFalse(SQLRowValue([Column("a"), 2.databaseValue])._isConstantInRequest) - XCTAssertFalse(SQLRowValue([1.databaseValue, Column("a")])._isConstantInRequest) + // SQLExpression.rowValue + XCTAssertTrue(SQLExpression.rowValue([1.sqlExpression])!.isConstantInRequest) + XCTAssertFalse(SQLExpression.rowValue([Column("a").sqlExpression])!.isConstantInRequest) + XCTAssertTrue(SQLExpression.rowValue([1.sqlExpression, 2.sqlExpression])!.isConstantInRequest) + XCTAssertFalse(SQLExpression.rowValue([Column("a").sqlExpression, 2.sqlExpression])!.isConstantInRequest) + XCTAssertFalse(SQLExpression.rowValue([1.sqlExpression, Column("a").sqlExpression])!.isConstantInRequest) } } diff --git a/Tests/GRDBTests/SQLExpressionLiteralTests.swift b/Tests/GRDBTests/SQLExpressionLiteralTests.swift index 84e5035e8..5d80056b0 100644 --- a/Tests/GRDBTests/SQLExpressionLiteralTests.swift +++ b/Tests/GRDBTests/SQLExpressionLiteralTests.swift @@ -8,7 +8,7 @@ class SQLExpressionLiteralTests: GRDBTestCase { try DatabaseQueue().inDatabase { db in let expression = Column("foo").collating(.nocase) == "'fooéı👨👨🏿🇫🇷🇨🇮'" && Column("baz") >= 1 let context = SQLGenerationContext(db) - let sql = try expression._expressionSQL(context, wrappedInParenthesis: true) + let sql = try expression.sql(context, wrappedInParenthesis: true) XCTAssertEqual(sql, "((\"foo\" = ? COLLATE NOCASE) AND (\"baz\" >= ?))") let values = context.arguments.values XCTAssertEqual(values.count, 2) @@ -21,7 +21,7 @@ class SQLExpressionLiteralTests: GRDBTestCase { try DatabaseQueue().inDatabase { db in let expression = Column("foo").collating(.nocase) == "'fooéı👨👨🏿🇫🇷🇨🇮'" && Column("baz") >= 1 let context = SQLGenerationContext(db, argumentsSink: .forRawSQL) - let sql = try expression._expressionSQL(context, wrappedInParenthesis: true) + let sql = try expression.sql(context, wrappedInParenthesis: true) XCTAssert(context.arguments.isEmpty) XCTAssertEqual(sql, "((\"foo\" = '''fooéı👨👨🏿🇫🇷🇨🇮''' COLLATE NOCASE) AND (\"baz\" >= 1))") } diff --git a/Tests/GRDBTests/SQLIdentifyingColumnsTests.swift b/Tests/GRDBTests/SQLIdentifyingColumnsTests.swift index 8d9a31651..c10401302 100644 --- a/Tests/GRDBTests/SQLIdentifyingColumnsTests.swift +++ b/Tests/GRDBTests/SQLIdentifyingColumnsTests.swift @@ -10,21 +10,21 @@ class SQLIdentifyingColumnsTests: GRDBTestCase { let alias = TableAlias(tableName: "t") let otherAlias = TableAlias() - try XCTAssertEqual((alias[Column("a")] == 1)._identifyingColums(db, for: alias), ["a"]) - try XCTAssertEqual((alias[Column("a")] === 1)._identifyingColums(db, for: alias), ["a"]) - try XCTAssertEqual((alias[Column("a")] == nil)._identifyingColums(db, for: alias), ["a"]) - try XCTAssertEqual((1 == alias[Column("a")])._identifyingColums(db, for: alias), ["a"]) - try XCTAssertEqual((alias[SQLExpressionFastPrimaryKey()] == 1)._identifyingColums(db, for: alias), ["id"]) - try XCTAssertEqual((alias[Column("a")] == 1 && alias[Column("a")] == 2)._identifyingColums(db, for: alias), ["a"]) - try XCTAssertEqual((alias[Column("a")] == 1 && alias[Column("b")] == 1)._identifyingColums(db, for: alias), ["a", "b"]) - try XCTAssertEqual((alias[Column("a")] == 1 && alias[Column("b")] > 1)._identifyingColums(db, for: alias), ["a"]) - try XCTAssertEqual((otherAlias[Column("a")] == 1 && alias[Column("b")] == 1)._identifyingColums(db, for: alias), ["b"]) + try XCTAssertEqual((alias[Column("a")] == 1).identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual((alias[Column("a")] === 1).identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual((alias[Column("a")] == nil).identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual((1 == alias[Column("a")]).identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual((alias[SQLExpression.fastPrimaryKey] == 1).identifyingColums(db, for: alias), ["id"]) + try XCTAssertEqual((alias[Column("a")] == 1 && alias[Column("a")] == 2).identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual((alias[Column("a")] == 1 && alias[Column("b")] == 1).identifyingColums(db, for: alias), ["a", "b"]) + try XCTAssertEqual((alias[Column("a")] == 1 && alias[Column("b")] > 1).identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual((otherAlias[Column("a")] == 1 && alias[Column("b")] == 1).identifyingColums(db, for: alias), ["b"]) - try XCTAssertEqual((otherAlias[Column("a")])._identifyingColums(db, for: alias), []) - try XCTAssertEqual((alias[Column("a")] == 1 || alias[Column("a")] == 2)._identifyingColums(db, for: alias), []) - try XCTAssertEqual((alias[Column("a")] == alias[Column("b")])._identifyingColums(db, for: alias), []) - try XCTAssertEqual((alias[Column("a")] > 1)._identifyingColums(db, for: alias), []) - try XCTAssertEqual((alias[Column("a")] != 1)._identifyingColums(db, for: alias), []) + try XCTAssertEqual((otherAlias[Column("a")]).identifyingColums(db, for: alias), []) + try XCTAssertEqual((alias[Column("a")] == 1 || alias[Column("a")] == 2).identifyingColums(db, for: alias), []) + try XCTAssertEqual((alias[Column("a")] == alias[Column("b")]).identifyingColums(db, for: alias), []) + try XCTAssertEqual((alias[Column("a")] > 1).identifyingColums(db, for: alias), []) + try XCTAssertEqual((alias[Column("a")] != 1).identifyingColums(db, for: alias), []) } } } diff --git a/Tests/GRDBTests/SQLLiteralTests.swift b/Tests/GRDBTests/SQLLiteralTests.swift index 8b104640b..b3126ce32 100644 --- a/Tests/GRDBTests/SQLLiteralTests.swift +++ b/Tests/GRDBTests/SQLLiteralTests.swift @@ -484,7 +484,7 @@ extension SQLLiteralTests { try makeDatabaseQueue().inDatabase { db in let set: Set = [1] let array = ["foo", "bar", "baz"] - let expressions = [Column("a"), Column("b") + 2] + let expressions: [SQLExpressible] = [Column("a"), Column("b") + 2] let query: SQLLiteral = """ SELECT * FROM player WHERE teamId IN \(set)