diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 0240ba7cc..e06acb792 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -27,8 +27,6 @@ 5605F1881C69111300235C62 /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */; }; 5605F18D1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; 5605F18E1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; - 5605F1931C6B1A8700235C62 /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; - 5605F1941C6B1A8700235C62 /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; 56071A411DB54ED000CA6E47 /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; }; 5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; }; 560A37A41C8F625000949E71 /* DatabasePool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A31C8F625000949E71 /* DatabasePool.swift */; }; @@ -271,12 +269,6 @@ 5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */; }; 5653EB0D20944C7C00F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */; }; 5653EB0E20944C7C00F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */; }; - 5653EB0F20944C7C00F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */; }; - 5653EB1020944C7C00F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */; }; - 5653EB1120944C7C00F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */; }; - 5653EB1520944C7C00F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */; }; - 5653EB1620944C7C00F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */; }; - 5653EB1720944C7C00F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */; }; 5653EB1820944C7C00F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFF20944C7C00F46237 /* ForeignKey.swift */; }; 5653EB1920944C7C00F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFF20944C7C00F46237 /* ForeignKey.swift */; }; 5653EB1A20944C7C00F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFF20944C7C00F46237 /* ForeignKey.swift */; }; @@ -324,7 +316,6 @@ 565490D91D5AE252005622CB /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; 565490DA1D5AE252005622CB /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; 565490DB1D5AE252005622CB /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; - 565490DE1D5AE252005622CB /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; 565490DF1D5AE252005622CB /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 565490E01D5AE252005622CB /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; 565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; @@ -332,9 +323,6 @@ 565490E41D5AE252005622CB /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 56553C101C3E906C00522B5C /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; }; 56553C131C3E906C00522B5C /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DC3773F319C8CBB3004FCF85 /* GRDB.framework */; }; - 5656BF4F20C723E300F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF4E20C723E300F98521 /* QueryOrdering.swift */; }; - 5656BF5020C723E300F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF4E20C723E300F98521 /* QueryOrdering.swift */; }; - 5656BF5120C723E300F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF4E20C723E300F98521 /* QueryOrdering.swift */; }; 5657AAB91D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AABC1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AB0F1D10899D006283EF /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; }; @@ -458,6 +446,9 @@ 56873BEC1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; }; 56873BEF1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; }; 56873BF21F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; }; + 568D131F2207213E00674B58 /* SQLSelectQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLSelectQueryGenerator.swift */; }; + 568D13202207213E00674B58 /* SQLSelectQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLSelectQueryGenerator.swift */; }; + 568D13212207213F00674B58 /* SQLSelectQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLSelectQueryGenerator.swift */; }; 5690AFD82120589A001530EA /* InsertRecordCodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFD72120589A001530EA /* InsertRecordCodableTests.swift */; }; 5690AFD92120589A001530EA /* InsertRecordCodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFD72120589A001530EA /* InsertRecordCodableTests.swift */; }; 5690AFDB212058CB001530EA /* FetchRecordCodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFDA212058CB001530EA /* FetchRecordCodableTests.swift */; }; @@ -731,6 +722,15 @@ 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 */; }; + 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 */; }; + 56D91AA92205F2F100770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA82205F2F000770D8D /* DatabasePromise.swift */; }; + 56D91AAA2205F2F100770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA82205F2F000770D8D /* DatabasePromise.swift */; }; + 56D91AAB2205F2F100770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA82205F2F000770D8D /* DatabasePromise.swift */; }; + 56D91AB02205F8AC00770D8D /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLSelectQuery.swift */; }; + 56D91AB12205F8AC00770D8D /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLSelectQuery.swift */; }; + 56D91AB22205F8AC00770D8D /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLSelectQuery.swift */; }; 56DAA2D21DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D61DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; }; @@ -912,7 +912,6 @@ 5605F1581C672E4000235C62 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = ""; }; 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionTests.swift; sourceTree = ""; }; 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollatedExpression.swift; sourceTree = ""; }; - 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceQuery.swift; sourceTree = ""; }; 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = ""; }; 560A37A31C8F625000949E71 /* DatabasePool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePool.swift; sourceTree = ""; }; 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SerializedDatabase.swift; sourceTree = ""; }; @@ -1011,15 +1010,12 @@ 5653EAF920944C7B00F46237 /* ForeignKeyRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyRequest.swift; sourceTree = ""; }; 5653EAFA20944C7B00F46237 /* Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Association.swift; sourceTree = ""; }; 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasManyAssociation.swift; sourceTree = ""; }; - 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRequest.swift; sourceTree = ""; }; - 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationQuery.swift; sourceTree = ""; }; 5653EAFF20944C7C00F46237 /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = ""; }; 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasOneAssociation.swift; sourceTree = ""; }; 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "QueryInterfaceRequest+Association.swift"; sourceTree = ""; }; 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLGenerationContext.swift; sourceTree = ""; }; 565490A01D5A4798005622CB /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 56553C181C3E906C00522B5C /* GRDBOSXCrashTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXCrashTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 5656BF4E20C723E300F98521 /* QueryOrdering.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QueryOrdering.swift; sourceTree = ""; }; 5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = ""; }; 5657AB0E1D10899D006283EF /* URL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URL.swift; sourceTree = ""; }; 5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDataTests.swift; sourceTree = ""; }; @@ -1081,6 +1077,7 @@ 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 = ""; }; 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Fixits-1.2.swift"; sourceTree = ""; }; + 568D13182207213E00674B58 /* SQLSelectQueryGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectQueryGenerator.swift; sourceTree = ""; }; 5690AFD72120589A001530EA /* InsertRecordCodableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InsertRecordCodableTests.swift; sourceTree = ""; }; 5690AFDA212058CB001530EA /* FetchRecordCodableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRecordCodableTests.swift; sourceTree = ""; }; 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateComponentsTests.swift; sourceTree = ""; }; @@ -1216,6 +1213,9 @@ 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; 56D507821F6D7A4500AE1C5B /* InsertRecordStructTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InsertRecordStructTests.swift; sourceTree = ""; }; 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.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 /* SQLSelectQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectQuery.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 = ""; }; @@ -1524,12 +1524,11 @@ children = ( 5653EAF720944BC900F46237 /* Association */, 56CEB5401EAA359A00BFAF62 /* Column.swift */, + 56D91AA82205F2F000770D8D /* DatabasePromise.swift */, 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */, 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, - 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */, - 5656BF4E20C723E300F98521 /* QueryOrdering.swift */, 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, @@ -1538,8 +1537,11 @@ 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */, 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */, 56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */, + 56D91AA12205E03700770D8D /* SQLRelation.swift */, 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */, 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */, + 56D91AAF2205F8AC00770D8D /* SQLSelectQuery.swift */, + 568D13182207213E00674B58 /* SQLSelectQueryGenerator.swift */, 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */, 566475C91D981D5E00FF74B8 /* Support */, 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */, @@ -1607,8 +1609,6 @@ children = ( 5653EAFA20944C7B00F46237 /* Association.swift */, 563EF42C2161180D007DAACD /* AssociationAggregate.swift */, - 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */, - 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */, 5653EAF820944C7B00F46237 /* BelongsToAssociation.swift */, 5653EAFF20944C7C00F46237 /* ForeignKey.swift */, 5653EAF920944C7B00F46237 /* ForeignKeyRequest.swift */, @@ -2490,12 +2490,13 @@ 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 */, - 5656BF5120C723E300F98521 /* QueryOrdering.swift in Sources */, 565490C11D5AE236005622CB /* FetchRequest.swift in Sources */, 5613ED4621A95B2C00DC7A68 /* ValueReducer.swift in Sources */, 5698AD1C1DAAD17F0056AF8C /* FTS5Tokenizer.swift in Sources */, 56CEB5171EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, + 56D91AB22205F8AC00770D8D /* SQLSelectQuery.swift in Sources */, 56B964B71DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, 5613ED5221A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */, 5653EB0B20944C7C00F46237 /* Association.swift in Sources */, @@ -2521,7 +2522,6 @@ 56CEB5001EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD271DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 5613ED4121A95A8B00DC7A68 /* ValueObservation+Combine.swift in Sources */, - 5653EB1120944C7C00F46237 /* AssociationRequest.swift in Sources */, C96C0F2D2084A45A006B2981 /* SQLiteDateParser.swift in Sources */, 566A841C2041146100E50BFD /* DatabaseSnapshot.swift in Sources */, 5613ED4A21A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */, @@ -2541,6 +2541,7 @@ 5674A6FF1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, 56E06F181E85906E008AE2A4 /* Fixits-0.102.0.swift in Sources */, 56B964A31DA51B4C0002DA19 /* FTS5.swift in Sources */, + 56D91AAB2205F2F100770D8D /* DatabasePromise.swift in Sources */, 566475A01D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 565490BB1D5AE236005622CB /* DatabaseReader.swift in Sources */, 5659F4A61EA8D997004A4992 /* Result.swift in Sources */, @@ -2568,6 +2569,7 @@ 5671FC261DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 5653EC142098738B00F46237 /* SQLGenerationContext.swift in Sources */, 56CEB5521EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, + 568D13212207213F00674B58 /* SQLSelectQueryGenerator.swift in Sources */, 565490DB1D5AE252005622CB /* SQLCollatedExpression.swift in Sources */, 5674A7071F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, 565490C61D5AE236005622CB /* Statement.swift in Sources */, @@ -2587,12 +2589,10 @@ 565490D31D5AE252005622CB /* (null) in Sources */, 566475D91D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 566B910F1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, - 565490DE1D5AE252005622CB /* QueryInterfaceQuery.swift in Sources */, 56F5ABDD1D814330001F60CB /* UUID.swift in Sources */, 565490CB1D5AE252005622CB /* (null) in Sources */, 563EF417215F87EB007DAACD /* OrderedDictionary.swift in Sources */, 565490D61D5AE252005622CB /* StandardLibrary.swift in Sources */, - 5653EB1720944C7C00F46237 /* AssociationQuery.swift in Sources */, 565490B81D5AE236005622CB /* DatabaseError.swift in Sources */, 564CE4D821B2DEB600652B19 /* ValueObservation+CompactMap.swift in Sources */, 56BF6D3C1DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, @@ -2657,6 +2657,7 @@ 56CEB51C1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, 5698AC3A1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 5664759D1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, + 568D13202207213E00674B58 /* SQLSelectQueryGenerator.swift in Sources */, 5674048A1CEF84C8003ED5CC /* RowAdapter.swift in Sources */, 563EF416215F87EB007DAACD /* OrderedDictionary.swift in Sources */, 563363C51C942C37000BE133 /* DatabaseWriter.swift in Sources */, @@ -2673,12 +2674,10 @@ 56A8C2331D1914540096E9D4 /* UUID.swift in Sources */, 56BF6D321DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 560D92411C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */, - 5653EB1020944C7C00F46237 /* AssociationRequest.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 */, - 5653EB1620944C7C00F46237 /* AssociationQuery.swift in Sources */, 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */, 564CE52121B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */, 5653EC132098738B00F46237 /* SQLGenerationContext.swift in Sources */, @@ -2691,7 +2690,7 @@ 5674A7081F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, 56A2388C1B9C75030082EB20 /* Statement.swift in Sources */, 5659F4931EA8D964004A4992 /* ReadWriteBox.swift in Sources */, - 5605F1941C6B1A8700235C62 /* QueryInterfaceQuery.swift in Sources */, + 56D91AB12205F8AC00770D8D /* SQLSelectQuery.swift in Sources */, 56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */, 5690C3431D23E82A00E59934 /* Data.swift in Sources */, 5674A7001F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, @@ -2714,6 +2713,7 @@ 569EF0E3200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */, 56A238841B9C75030082EB20 /* DatabaseQueue.swift in Sources */, 563B06AC217EF0CC00B38F35 /* ValueObservation.swift in Sources */, + 56D91AAA2205F2F100770D8D /* DatabasePromise.swift in Sources */, 5698AC7B1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */, 56D1215D1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, @@ -2726,7 +2726,6 @@ 5613ED5521A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */, 564CE5AD21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */, 56CEB5041EAA2F4D00BFAF62 /* FTS4.swift in Sources */, - 5656BF5020C723E300F98521 /* QueryOrdering.swift in Sources */, 5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */, 560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */, 5613ED4521A95B2C00DC7A68 /* ValueReducer.swift in Sources */, @@ -2744,6 +2743,7 @@ 566B912E1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 56CEB5641EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56873BEF1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, + 56D91AA32205E03700770D8D /* SQLRelation.swift in Sources */, 564F9C311F07611600877A00 /* DatabaseFunction.swift in Sources */, 564CE59E21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */, 56B964A01DA51B4C0002DA19 /* FTS5.swift in Sources */, @@ -3117,6 +3117,7 @@ files = ( 56873BEC1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */, + 56D91AB02205F8AC00770D8D /* SQLSelectQuery.swift in Sources */, 5613ED4C21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, 56BF6D3D1DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, 5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */, @@ -3133,6 +3134,7 @@ 566A841A2041146100E50BFD /* DatabaseSnapshot.swift in Sources */, 569EF0E2200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */, 56CEB4F11EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, + 56D91AA22205E03700770D8D /* SQLRelation.swift in Sources */, 56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */, 5605F18D1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */, 5613ED5421A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */, @@ -3181,7 +3183,6 @@ 566475BA1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 5653EB0920944C7C00F46237 /* Association.swift in Sources */, 56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */, - 5656BF4F20C723E300F98521 /* QueryOrdering.swift in Sources */, 5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56A238A41B9C753B0082EB20 /* Record.swift in Sources */, 56CEB5451EAA359A00BFAF62 /* Column.swift in Sources */, @@ -3191,9 +3192,9 @@ 5613ED4821A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */, 56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */, 5674A6EB1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, + 56D91AA92205F2F100770D8D /* DatabasePromise.swift in Sources */, 560A37A41C8F625000949E71 /* DatabasePool.swift in Sources */, 56B7F43A1BEB42D500E39BBF /* Migration.swift in Sources */, - 5605F1931C6B1A8700235C62 /* QueryInterfaceQuery.swift in Sources */, 5613ED3521A95A5C00DC7A68 /* ValueObservation+Map.swift in Sources */, 566B912B1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 56A2388B1B9C75030082EB20 /* Statement.swift in Sources */, @@ -3202,12 +3203,11 @@ 56FC98781D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, 56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */, 5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */, + 568D131F2207213E00674B58 /* SQLSelectQueryGenerator.swift in Sources */, 5605F15D1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */, 56BF6D361DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, - 5653EB0F20944C7C00F46237 /* AssociationRequest.swift in Sources */, 56193E8E1CD8A3E200F95862 /* FetchedRecordsController.swift in Sources */, 56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, - 5653EB1520944C7C00F46237 /* AssociationQuery.swift in Sources */, 563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */, 564CE43121AA901800652B19 /* ValueObserver.swift in Sources */, 5605F1651C672E4000235C62 /* NSNull.swift in Sources */, diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 57e49d7a8..d38f4cdcb 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -3,9 +3,58 @@ /// The base protocol for all associations that define a connection between two /// record types. public protocol Association: DerivableRequest { + // OriginRowDecoder and RowDecoder provide type safety: + // + // Book.including(required: Book.author) // compiles + // Fruit.including(required: Book.author) // does not compile + + /// The record type at the origin of the association. + /// + /// In the `belongsTo` association below, it is Book: + /// + /// struct Book: TableRecord { + /// // BelongsToAssociation + /// static let author = belongsTo(Author.self) + /// } associatedtype OriginRowDecoder + + /// The associated record type. + /// + /// In the `belongsTo` association below, it is Author: + /// + /// struct Book: TableRecord { + /// // BelongsToAssociation + /// static let author = belongsTo(Author.self) + /// } associatedtype RowDecoder + // Association is a protocol, not a struct. + // This is because we want associations to be richly typed. + // Yet, we don't want to pollute user code with implementation details of + // associations. So let's hide all this stuff behind the _impl property: + + /// :nodoc: + associatedtype Impl: AssociationImpl + + /// :nodoc: + var _impl: Impl { get } + + /// :nodoc: + init(_impl: Impl) +} + +extension Association { + private func mapImpl(_ transform: (Impl) throws -> Impl) rethrows -> Self { + return try Self.init(_impl: transform(_impl)) + } + + private func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self { + return mapImpl { $0.mapRelation(transform) } + } +} + +extension Association { + /// The association key defines how rows fetched from this association /// should be consumed. /// @@ -30,35 +79,10 @@ public protocol Association: DerivableRequest { /// for row in Row.fetchAll(db, request) { /// let team: Team = row["custom"] /// } - var key: String { get } + var key: String { + return _impl.key + } - /// Creates an association with the given key. - /// - /// This new key impacts how rows fetched from the resulting association - /// should be consumed: - /// - /// struct Player: TableRecord { - /// static let team = belongsTo(Team.self) - /// } - /// - /// // Consume rows: - /// let request = Player.including(required: Player.team.forKey("custom")) - /// for row in Row.fetchAll(db, request) { - /// let team: Team = row["custom"] - /// } - func forKey(_ key: String) -> Self - - /// :nodoc: - var request: AssociationRequest { get } - - /// :nodoc: - var joinCondition: JoinCondition { get } - - /// :nodoc: - func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> Self -} - -extension Association { /// Creates an association which selects *selection*. /// /// struct Player: TableRecord { @@ -81,7 +105,7 @@ extension Association { /// .select([Column("color")]) /// var request = Player.including(required: association) public func select(_ selection: [SQLSelectable]) -> Self { - return mapRequest { $0.select(selection) } + return mapRelation { $0.select(selection) } } /// Creates an association with the provided *predicate promise* added to @@ -97,7 +121,7 @@ extension Association { /// let association = Player.team.filter { db in true } /// var request = Player.including(required: association) public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { - return mapRequest { $0.filter(predicate) } + return mapRelation { $0.filter(predicate) } } /// Creates an association with the provided *orderings promise*. @@ -125,7 +149,7 @@ extension Association { /// .order{ _ in [Column("name")] } /// var request = Player.including(required: association) public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self { - return mapRequest { $0.order(orderings) } + return mapRelation { $0.order(orderings) } } /// Creates an association that reverses applied orderings. @@ -149,7 +173,25 @@ extension Association { /// let association = Player.team.reversed() /// var request = Player.including(required: association) public func reversed() -> Self { - return mapRequest { $0.reversed() } + return mapRelation { $0.reversed() } + } + + /// Creates an association with the given key. + /// + /// This new key impacts how rows fetched from the resulting association + /// should be consumed: + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // Consume rows: + /// let request = Player.including(required: Player.team.forKey("custom")) + /// for row in Row.fetchAll(db, request) { + /// let team: Team = row["custom"] + /// } + public func forKey(_ key: String) -> Self { + return mapImpl { $0.forKey(key) } } /// Creates an association with the given key. @@ -207,45 +249,7 @@ extension Association { /// .including(required: Player.team.aliased(teamAlias)) /// .filter(sql: "custom.color = ?", arguments: ["red"]) public func aliased(_ alias: TableAlias) -> Self { - return mapRequest { $0.aliased(alias) } - } -} - -/// The condition that links two joined tables. -/// -/// We only support one kind of join condition, today: foreign keys. -/// -/// SELECT ... -/// FROM book -/// JOIN author ON author.id = book.authorId -/// <--the join condition---> -/// -/// When we eventually add support for new ways to join tables, JoinCondition -/// is the type we'll need to update. -/// -/// The Equatable conformance is used when we merge associations. Two -/// associations can be merged if and only if their join conditions -/// are equal: -/// -/// let request = Book -/// .include(required: Book.author) -/// .include(required: Book.author) -public struct JoinCondition: Equatable { - var foreignKeyRequest: ForeignKeyRequest - var originIsLeft: Bool - - func sqlExpression(_ db: Database, leftAlias: TableAlias, rightAlias: TableAlias) throws -> SQLExpression? { - let foreignKeyMapping = try foreignKeyRequest.fetch(db).mapping - let columnMapping: [(left: Column, right: Column)] - if originIsLeft { - columnMapping = foreignKeyMapping.map { (left: Column($0.origin), right: Column($0.destination)) } - } else { - columnMapping = foreignKeyMapping.map { (left: Column($0.destination), right: Column($0.origin)) } - } - - return columnMapping - .map { $0.right.qualifiedExpression(with: rightAlias) == $0.left.qualifiedExpression(with: leftAlias) } - .joined(operator: .and) + return mapRelation { $0.qualified(with: alias) } } } @@ -254,28 +258,28 @@ extension Association { /// associated record are selected. The returned association does not /// require that the associated database table contains a matching row. public func including(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return mapRequest { $0.joining(.optional, association) } + return mapRelation { association._impl.joinedRelation($0, joinOperator: .optional) } } /// Creates an association that includes another one. The columns of the /// associated record are selected. The returned association requires /// that the associated database table contains a matching row. public func including(required association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return mapRequest { $0.joining(.required, association) } + return mapRelation { association._impl.joinedRelation($0, joinOperator: .required) } } /// Creates an association that joins another one. The columns of the /// associated record are not selected. The returned association does not /// require that the associated database table contains a matching row. public func joining(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return mapRequest { $0.joining(.optional, association.select([])) } + return mapRelation { association.select([])._impl.joinedRelation($0, joinOperator: .optional) } } /// Creates an association that joins another one. The columns of the /// associated record are not selected. The returned association requires /// that the associated database table contains a matching row. public func joining(required association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return mapRequest { $0.joining(.required, association.select([])) } + return mapRelation { association.select([])._impl.joinedRelation($0, joinOperator: .required) } } } @@ -301,17 +305,15 @@ extension Association where OriginRowDecoder: MutablePersistableRecord { let associationAlias = TableAlias() let recordAlias = TableAlias() - // Turn the association request into a query interface request: + // Turn the association query into a query interface request: // JOIN association -> SELECT FROM association - return QueryInterfaceRequest(request) + return QueryInterfaceRequest(query: SQLSelectQuery(relation: _impl.relation)) // Turn the JOIN condition into a regular WHERE condition .filter { db in // Build a join condition: `association.recordId = record.id` // We still need to replace `record.id` with the actual record id. - guard let joinExpression = try self.joinCondition.sqlExpression(db, leftAlias: recordAlias, rightAlias: associationAlias) else { - fatalError("Can't request from record without join condition") - } + let joinExpression = try self._impl.joinCondition.sqlExpression(db, leftAlias: recordAlias, rightAlias: associationAlias) // Serialize record: ["id": 123, ...] // We do it as late as possible, when request is about to be @@ -329,3 +331,78 @@ extension Association where OriginRowDecoder: MutablePersistableRecord { .aliased(associationAlias) } } + +// MARK: - AssociationImpl + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// The protocol for implementation details of associations. +/// +/// :nodoc: +public /* TODO: internal */ protocol AssociationImpl { + /// The association key + var key: String { get } + + /// Creates an association with the given key. + func forKey(_ key: String) -> Self + + /// Returns an association whose relation is transformed by the + /// given closure. + /// + /// This method provides fundamental support for association derivation: + /// + /// // Invokes Book.author.mapRelation { $0.filter(...) } + /// Book.author.filter(...) + func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self + + /// Returns a relation joined with self. + /// + /// This method provides fundamental support for joining methods. + func joinedRelation(_ relation: SQLRelation, joinOperator: JoinOperator) -> SQLRelation + + // TODO: remove relation & joinCondition properties. + // + // They assume that an association is implemented as a direct join to an + // associated table. This is limiting: has-one-through and has-many-through + // associations can't be implemented in such context. + // + // Their impact is limited yet. Those propertise are currently only used by + // Association.request(from:). When this method gets a new implementation + // that does not need a direct join to an associated table, we'll be able to + // remove those properties. + var relation: SQLRelation { get } + var joinCondition: JoinCondition { get } +} + +// MARK: - + +/// The AssociationImpl shared by BelongsTo, HasOne, and HasMany, which is +/// implemented as a simple join. +/// +/// :nodoc: +public /* TODO: internal */ struct JoinAssociationImpl: AssociationImpl { + public var key: String + public /* TODO: internal */ let joinCondition: JoinCondition + public /* TODO: internal */ var relation: SQLRelation + + public func forKey(_ key: String) -> JoinAssociationImpl { + var assoc = self + assoc.key = key + return assoc + } + + public func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> JoinAssociationImpl { + var assoc = self + assoc.relation = transform(relation) + return assoc + } + + public func joinedRelation(_ relation: SQLRelation, joinOperator: JoinOperator) -> SQLRelation { + let join = SQLJoin( + joinOperator: joinOperator, + joinCondition: joinCondition, + relation: self.relation) + return relation.appendingJoin(join, forKey: key) + } +} + diff --git a/GRDB/QueryInterface/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Association/AssociationAggregate.swift index faeb31476..7206b0ce2 100644 --- a/GRDB/QueryInterface/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Association/AssociationAggregate.swift @@ -16,8 +16,49 @@ import Foundation /// /// let request = Author.annotated(with: bookCount) /// let request = Author.having(bookCount >= 10) +/// +/// The RowDecoder generic type helps the compiler prevent incorrect use +/// of aggregates: +/// +/// // Won't compile because Fruit is not Author. +/// let request = Fruit.annotated(with: bookCount) public struct AssociationAggregate { + /// Given a request, returns a tuple made of a request extended with the + /// associated records used to compute the aggregate, and an expression + /// whose value is the aggregated value. + /// + /// For example: + /// + /// struct Author: TableRecord { + /// static let books = hasMany(Book.self) + /// } + /// + /// // SELECT * FROM author + /// let request = Author.all() + /// + /// let aggregate = Author.books.count + /// let tuple = aggregate.prepare(request) + /// + /// // The request extended with associated records: + /// // + /// // SELECT author.* FROM author + /// // LEFT JOIN book ON book.authorId = author.id + /// // GROUP BY author.id + /// tuple.request + /// + /// // The aggregated value: + /// // + /// // COUNT(DISTINCT book.rowid) + /// tuple.expression + /// + /// The aggregated value is not right away embedded in the extended request: + /// + /// - We don't know yet if the aggregated value will be used in the + /// SQL selection, or in the HAVING clause. + /// - It helps implementing aggregate operators such as `&&`, `+`, etc. let prepare: (QueryInterfaceRequest) -> (request: QueryInterfaceRequest, expression: SQLExpression) + + /// The SQL alias for the value of this aggregate. See aliased(_:). var alias: String? init(_ prepare: @escaping (QueryInterfaceRequest) -> (request: QueryInterfaceRequest, expression: SQLExpression)) { @@ -63,7 +104,11 @@ extension AssociationAggregate { // MARK: - Logical Operators (AND, OR, NOT) -/// :nodoc: +/// Returns a logically negated aggregate. +/// +/// For example: +/// +/// let request = Author.having(!Author.books.isEmpty) public prefix func ! (aggregate: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = aggregate.prepare(request) @@ -71,7 +116,11 @@ public prefix func ! (aggregate: AssociationAggregate) - } } -/// :nodoc: +/// Groups two aggregates with the `AND` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.isEmpty && Author.paintings.isEmpty) public func && (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -80,6 +129,7 @@ public func && (lhs: AssociationAggregate, rhs: Associat } } +// TODO: test & document /// :nodoc: public func && (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in @@ -88,6 +138,7 @@ public func && (lhs: AssociationAggregate, rhs: SQLExpre } } +// TODO: test & document /// :nodoc: public func && (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in @@ -96,7 +147,12 @@ public func && (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -105,6 +161,7 @@ public func || (lhs: AssociationAggregate, rhs: Associat } } +// TODO: test & document /// :nodoc: public func || (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in @@ -113,6 +170,7 @@ public func || (lhs: AssociationAggregate, rhs: SQLExpre } } +// TODO: test & document /// :nodoc: public func || (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in @@ -123,7 +181,11 @@ public func || (lhs: SQLExpressible, rhs: AssociationAggregate, IS, IS NOT) -/// :nodoc: +/// Returns an aggregate that compares two aggregates with the `=` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count == Author.paintings.count) public func == (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -132,7 +194,11 @@ public func == (lhs: AssociationAggregate, rhs: Associat } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `=` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count == 3) public func == (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -140,7 +206,11 @@ public func == (lhs: AssociationAggregate, rhs: SQLExpre } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `=` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(3 == Author.books.count) public func == (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -148,7 +218,11 @@ public func == (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: Bool) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -156,7 +230,11 @@ public func == (lhs: AssociationAggregate, rhs: Bool) -> } } -/// :nodoc: +/// Returns an aggregate that checks the boolean value of an aggregate. +/// +/// For example: +/// +/// let request = Author.having(false == Author.books.isEmpty) public func == (lhs: Bool, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -164,7 +242,11 @@ public func == (lhs: Bool, rhs: AssociationAggregate) -> } } -/// :nodoc: +/// Returns an aggregate that compares two aggregates with the `<>` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count != Author.paintings.count) public func != (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -173,7 +255,11 @@ public func != (lhs: AssociationAggregate, rhs: Associat } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `<>` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count != 3) public func != (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -181,7 +267,11 @@ public func != (lhs: AssociationAggregate, rhs: SQLExpre } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `<>` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(3 != Author.books.count) public func != (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -189,7 +279,11 @@ public func != (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: Bool) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -197,7 +291,11 @@ public func != (lhs: AssociationAggregate, rhs: Bool) -> } } -/// :nodoc: +/// Returns an aggregate that checks the boolean value of an aggregate. +/// +/// For example: +/// +/// let request = Author.having(true != Author.books.isEmpty) public func != (lhs: Bool, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -205,7 +303,11 @@ public func != (lhs: Bool, rhs: AssociationAggregate) -> } } -/// :nodoc: +/// Returns an aggregate that compares two aggregates with the `IS` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count === Author.paintings.count) public func === (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -214,7 +316,11 @@ public func === (lhs: AssociationAggregate, rhs: Associa } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `IS` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count === 3) public func === (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -222,7 +328,11 @@ public func === (lhs: AssociationAggregate, rhs: SQLExpr } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `IS` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(3 === Author.books.count) public func === (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -230,7 +340,11 @@ public func === (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -239,7 +353,11 @@ public func !== (lhs: AssociationAggregate, rhs: Associa } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `IS NOT` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count !== 3) public func !== (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -247,7 +365,11 @@ public func !== (lhs: AssociationAggregate, rhs: SQLExpr } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `IS NOT` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(3 !== Author.books.count) public func !== (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -257,7 +379,11 @@ public func !== (lhs: SQLExpressible, rhs: AssociationAggregate, <=, >=) -/// :nodoc: +/// Returns an aggregate that compares two aggregates with the `<=` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count <= Author.paintings.count) public func <= (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -266,7 +392,11 @@ public func <= (lhs: AssociationAggregate, rhs: Associat } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `<=` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count <= 3) public func <= (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -274,7 +404,11 @@ public func <= (lhs: AssociationAggregate, rhs: SQLExpre } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `<=` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(3 <= Author.books.count) public func <= (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -282,7 +416,11 @@ public func <= (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -291,7 +429,11 @@ public func < (lhs: AssociationAggregate, rhs: Associati } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `<` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count < 3) public func < (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -299,7 +441,11 @@ public func < (lhs: AssociationAggregate, rhs: SQLExpres } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `<` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(3 < Author.books.count) public func < (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -307,7 +453,11 @@ public func < (lhs: SQLExpressible, rhs: AssociationAggregate` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count > Author.paintings.count) public func > (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -316,7 +466,11 @@ public func > (lhs: AssociationAggregate, rhs: Associati } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `>` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count > 3) public func > (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -324,7 +478,11 @@ public func > (lhs: AssociationAggregate, rhs: SQLExpres } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `>` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(3 > Author.books.count) public func > (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -332,7 +490,11 @@ public func > (lhs: SQLExpressible, rhs: AssociationAggregate=` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count >= Author.paintings.count) public func >= (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -341,7 +503,11 @@ public func >= (lhs: AssociationAggregate, rhs: Associat } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `>=` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(Author.books.count >= 3) public func >= (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -349,7 +515,11 @@ public func >= (lhs: AssociationAggregate, rhs: SQLExpre } } -/// :nodoc: +/// Returns an aggregate that compares an aggregate with the `>=` SQL operator. +/// +/// For example: +/// +/// let request = Author.having(3 >= Author.books.count) public func >= (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -359,7 +529,11 @@ public func >= (lhs: SQLExpressible, rhs: AssociationAggregate(aggregate: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = aggregate.prepare(request) @@ -367,7 +541,11 @@ public prefix func - (aggregate: AssociationAggregate) - } } -/// :nodoc: +/// Returns an aggregate that sums two aggregates with the `+` SQL operator. +/// +/// For example: +/// +/// let request = Author.annotated(with: Author.books.count + Author.paintings.count) public func + (lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -376,7 +554,11 @@ public func + (lhs: AssociationAggregate, rhs: Associati } } -/// :nodoc: +/// Returns an aggregate that sums an aggregate with the `+` SQL operator. +/// +/// For example: +/// +/// let request = Author.annotated(with: Author.books.count + 1) public func + (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -384,7 +566,11 @@ public func + (lhs: AssociationAggregate, rhs: SQLExpres } } -/// :nodoc: +/// Returns an aggregate that sums an aggregate with the `+` SQL operator. +/// +/// For example: +/// +/// let request = Author.annotated(with: 1 + Author.books.count) public func + (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -392,7 +578,11 @@ public func + (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -401,7 +591,11 @@ public func - (lhs: AssociationAggregate, rhs: Associati } } -/// :nodoc: +/// Returns an aggregate that substracts an aggregate with the `-` SQL operator. +/// +/// For example: +/// +/// let request = Author.annotated(with: Author.books.count - 1) public func - (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -409,7 +603,11 @@ public func - (lhs: AssociationAggregate, rhs: SQLExpres } } -/// :nodoc: +/// Returns an aggregate that substracts an aggregate with the `-` SQL operator. +/// +/// For example: +/// +/// let request = Author.annotated(with: 1 - Author.books.count) public func - (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -417,7 +615,11 @@ public func - (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -426,7 +628,11 @@ public func * (lhs: AssociationAggregate, rhs: Associati } } -/// :nodoc: +/// Returns an aggregate that substracts an aggregate with the `*` SQL operator. +/// +/// For example: +/// +/// let request = Author.annotated(with: Author.books.count * 2) public func * (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -434,7 +640,11 @@ public func * (lhs: AssociationAggregate, rhs: SQLExpres } } -/// :nodoc: +/// Returns an aggregate that substracts an aggregate with the `*` SQL operator. +/// +/// For example: +/// +/// let request = Author.annotated(with: 2 * Author.books.count) public func * (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -442,7 +652,11 @@ public func * (lhs: SQLExpressible, rhs: AssociationAggregate(lhs: AssociationAggregate, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (lRequest, lExpression) = lhs.prepare(request) @@ -451,7 +665,11 @@ public func / (lhs: AssociationAggregate, rhs: Associati } } -/// :nodoc: +/// Returns an aggregate that substracts an aggregate with the `/` SQL operator. +/// +/// For example: +/// +/// let request = Author.annotated(with: Author.books.count / 2) public func / (lhs: AssociationAggregate, rhs: SQLExpressible) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = lhs.prepare(request) @@ -459,7 +677,11 @@ public func / (lhs: AssociationAggregate, rhs: SQLExpres } } -/// :nodoc: +/// Returns an aggregate that substracts an aggregate with the `/` SQL operator. +/// +/// For example: +/// +/// let request = Author.annotated(with: 2 / Author.books.count) public func / (lhs: SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { return AssociationAggregate { request in let (request, expression) = rhs.prepare(request) @@ -467,3 +689,7 @@ public func / (lhs: SQLExpressible, rhs: AssociationAggregate - var ordering: QueryOrdering - var joins: OrderedDictionary - - var alias: TableAlias? { - return source.alias - } -} - -extension AssociationQuery { - init(_ query: QueryInterfaceQuery) { - GRDBPrecondition(!query.isDistinct, "Not implemented: join distinct queries") - GRDBPrecondition(query.groupPromise == nil, "Can't join aggregated queries") - GRDBPrecondition(query.havingExpression == nil, "Can't join aggregated queries") - GRDBPrecondition(query.limit == nil, "Can't join limited queries") - - self.init( - source: query.source, - selection: query.selection, - filterPromise: query.filterPromise, - ordering: query.ordering, - joins: query.joins) - } -} - -extension AssociationQuery { - func select(_ selection: [SQLSelectable]) -> AssociationQuery { - var query = self - query.selection = selection - return query - } - - func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> AssociationQuery { - var query = self - query.filterPromise = query.filterPromise.map { (db, filter) in - if let filter = filter { - return try filter && predicate(db) - } else { - return try predicate(db).sqlExpression - } - } - return query - } - - func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> AssociationQuery { - return order(QueryOrdering(orderings: orderings)) - } - - func reversed() -> AssociationQuery { - return order(ordering.reversed) - } - - private func order(_ ordering: QueryOrdering) -> AssociationQuery { - var query = self - query.ordering = ordering - return query - } - - func appendingJoin(_ join: AssociationJoin, forKey key: String) -> AssociationQuery { - var query = self - if let existingJoin = query.joins.removeValue(forKey: key) { - guard let mergedJoin = existingJoin.merged(with: join) else { - // can't merge - fatalError("The association key \"\(key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") - } - query.joins.append(value: mergedJoin, forKey: key) - } else { - query.joins.append(value: join, forKey: key) - } - return query - } - - func qualified(with alias: TableAlias) -> AssociationQuery { - var query = self - query.source = source.qualified(with: alias) - return query - } -} - -extension AssociationQuery { - /// A finalized query is ready for SQL generation - var finalizedQuery: AssociationQuery { - var query = self - - let alias = TableAlias() - query.source = source.qualified(with: alias) - query.selection = selection.map { $0.qualifiedSelectable(with: alias) } - query.filterPromise = filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) } - query.ordering = ordering.qualified(with: alias) - query.joins = joins.mapValues { $0.finalizedJoin } - - return query - } - - /// precondition: self is the result of finalizedQuery - var finalizedAliases: [TableAlias] { - var aliases: [TableAlias] = [] - if let alias = alias { - aliases.append(alias) - } - return joins.reduce(into: aliases) { - $0.append(contentsOf: $1.value.finalizedAliases) - } - } - - /// precondition: self is the result of finalizedQuery - var finalizedSelection: [SQLSelectable] { - return joins.reduce(into: selection) { - $0.append(contentsOf: $1.value.finalizedSelection) - } - } - - /// precondition: self is the result of finalizedQuery - var finalizedOrdering: QueryOrdering { - return joins.reduce(ordering) { - $0.appending($1.value.finalizedOrdering) - } - } - - /// precondition: self is the result of finalizedQuery - func finalizedRowAdapter(_ db: Database, fromIndex startIndex: Int, forKeyPath keyPath: [String]) throws -> (adapter: RowAdapter, endIndex: Int)? { - let selectionWidth = try selection - .map { try $0.columnCount(db) } - .reduce(0, +) - - var endIndex = startIndex + selectionWidth - var scopes: [String: RowAdapter] = [:] - for (key, join) in joins { - if let (joinAdapter, joinEndIndex) = try join.finalizedRowAdapter(db, fromIndex: endIndex, forKeyPath: keyPath + [key]) { - scopes[key] = joinAdapter - endIndex = joinEndIndex - } - } - - if selectionWidth == 0 && scopes.isEmpty { - return nil - } - - let adapter = RangeRowAdapter(startIndex ..< (startIndex + selectionWidth)) - return (adapter: adapter.addingScopes(scopes), endIndex: endIndex) - } -} - -extension AssociationQuery { - /// Returns nil if queries can't be merged (conflict in source, joins...) - func merged(with other: AssociationQuery) -> AssociationQuery? { - guard let mergedSource = source.merged(with: other.source) else { - // can't merge - return nil - } - - let mergedFilterPromise = filterPromise.map { (db, expression) in - let otherExpression = try other.filterPromise.resolve(db) - let expressions = [expression, otherExpression].compactMap { $0 } - if expressions.isEmpty { - return nil - } - return expressions.joined(operator: .and) - } - - var mergedJoins: OrderedDictionary = [:] - for (key, join) in joins { - if let otherJoin = other.joins[key] { - guard let mergedJoin = join.merged(with: otherJoin) else { - // can't merge - return nil - } - mergedJoins.append(value: mergedJoin, forKey: key) - } else { - mergedJoins.append(value: join, forKey: key) - } - } - for (key, join) in other.joins where mergedJoins[key] == nil { - mergedJoins.append(value: join, forKey: key) - } - - // replace selection unless empty - let mergedSelection = other.selection.isEmpty ? selection : other.selection - - // replace ordering unless empty - let mergedOrdering = other.ordering.isEmpty ? ordering : other.ordering - - return AssociationQuery( - source: mergedSource, - selection: mergedSelection, - filterPromise: mergedFilterPromise, - ordering: mergedOrdering, - joins: mergedJoins) - } -} diff --git a/GRDB/QueryInterface/Association/AssociationRequest.swift b/GRDB/QueryInterface/Association/AssociationRequest.swift deleted file mode 100644 index 5eede5d33..000000000 --- a/GRDB/QueryInterface/Association/AssociationRequest.swift +++ /dev/null @@ -1,49 +0,0 @@ -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// -/// In `SELECT a.*, b.* FROM a JOIN b ON b.aid = a.id AND b.name = 'foo'`, -/// the AssociationRequest is (`b.*` + `b.name = 'foo'`). -/// :nodoc: -public struct AssociationRequest { - let query: AssociationQuery - - init(query: AssociationQuery) { - self.query = query - } - - init(_ request: QueryInterfaceRequest) { - self.init(query: AssociationQuery(request.query)) - } -} - -extension AssociationRequest { - func select(_ selection: [SQLSelectable]) -> AssociationRequest { - return AssociationRequest(query: query.select(selection)) - } - - func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> AssociationRequest { - return AssociationRequest(query: query.filter(predicate)) - } - - func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> AssociationRequest { - return AssociationRequest(query: query.order(orderings)) - } - - func reversed() -> AssociationRequest { - return AssociationRequest(query: query.reversed()) - } - - func aliased(_ alias: TableAlias) -> AssociationRequest { - return AssociationRequest(query: query.qualified(with: alias)) - } - - func joining(_ joinOperator: AssociationJoinOperator, _ association: A) - -> AssociationRequest - where A.OriginRowDecoder == T - { - let join = AssociationJoin( - joinOperator: joinOperator, - joinCondition: association.joinCondition, - query: association.request.query) - return AssociationRequest(query: query.appendingJoin(join, forKey: association.key)) - } -} diff --git a/GRDB/QueryInterface/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Association/BelongsToAssociation.swift index 97b2bbaa8..32c9f390a 100644 --- a/GRDB/QueryInterface/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -64,26 +64,13 @@ public struct BelongsToAssociation: Association { /// :nodoc: public typealias RowDecoder = Destination - - public var key: String /// :nodoc: - public let joinCondition: JoinCondition + public var _impl: JoinAssociationImpl /// :nodoc: - public var request: AssociationRequest - - public func forKey(_ key: String) -> BelongsToAssociation { - var association = self - association.key = key - return association - } - - /// :nodoc: - public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> BelongsToAssociation { - var association = self - association.request = transform(request) - return association + public init(_impl: JoinAssociationImpl) { + self._impl = _impl } } @@ -165,10 +152,10 @@ extension TableRecord { let joinCondition = JoinCondition( foreignKeyRequest: foreignKeyRequest, originIsLeft: true) - - return BelongsToAssociation( + + return BelongsToAssociation(_impl: JoinAssociationImpl( key: key ?? Destination.databaseTableName, joinCondition: joinCondition, - request: AssociationRequest(Destination.all())) + relation: Destination.all().relation)) } } diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift index d61c8e48d..5f0994e07 100644 --- a/GRDB/QueryInterface/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -64,26 +64,13 @@ public struct HasManyAssociation: Association { /// :nodoc: public typealias RowDecoder = Destination - - public var key: String /// :nodoc: - public let joinCondition: JoinCondition + public var _impl: JoinAssociationImpl /// :nodoc: - public var request: AssociationRequest - - public func forKey(_ key: String) -> HasManyAssociation { - var association = self - association.key = key - return association - } - - /// :nodoc: - public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasManyAssociation { - var association = self - association.request = transform(request) - return association + public init(_impl: JoinAssociationImpl) { + self._impl = _impl } } @@ -166,7 +153,7 @@ extension HasManyAssociation where Origin: TableRecord, Destination: TableRecord return aggregate } } - + /// The sum of the given expression in associated records. /// /// For example: @@ -255,9 +242,9 @@ extension TableRecord { foreignKeyRequest: foreignKeyRequest, originIsLeft: false) - return HasManyAssociation( + return HasManyAssociation(_impl: JoinAssociationImpl( key: key ?? Destination.databaseTableName, joinCondition: joinCondition, - request: AssociationRequest(Destination.all())) + relation: Destination.all().relation)) } } diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift index e795ae494..61779de5f 100644 --- a/GRDB/QueryInterface/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -60,32 +60,19 @@ /// } /// /// See ForeignKey for more information. -public struct HasOneAssociation : Association { +public struct HasOneAssociation: Association { /// :nodoc: public typealias OriginRowDecoder = Origin /// :nodoc: public typealias RowDecoder = Destination - public var key: String + /// :nodoc: + public var _impl: JoinAssociationImpl /// :nodoc: - public let joinCondition: JoinCondition - - /// :nodoc: - public var request: AssociationRequest - - public func forKey(_ key: String) -> HasOneAssociation { - var association = self - association.key = key - return association - } - - /// :nodoc: - public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasOneAssociation { - var association = self - association.request = transform(request) - return association + public init(_impl: JoinAssociationImpl) { + self._impl = _impl } } @@ -168,9 +155,9 @@ extension TableRecord { foreignKeyRequest: foreignKeyRequest, originIsLeft: false) - return HasOneAssociation( + return HasOneAssociation(_impl: JoinAssociationImpl( key: key ?? Destination.databaseTableName, joinCondition: joinCondition, - request: AssociationRequest(Destination.all())) + relation: Destination.all().relation)) } } diff --git a/GRDB/QueryInterface/DatabasePromise.swift b/GRDB/QueryInterface/DatabasePromise.swift new file mode 100644 index 000000000..3d25acecf --- /dev/null +++ b/GRDB/QueryInterface/DatabasePromise.swift @@ -0,0 +1,44 @@ +/// DatabasePromise represents a value that can only be resolved when a +/// database connection is available. +/// +/// This type is important for the query interface, which lets the user define +/// requests without any database context. +/// +/// For example, consider those two requests: +/// +/// let playerRequest = Player.filter(key: 1) +/// let countryRequest = Country.filter(key: "FR") +/// +/// Both need a database connection in order to introspect the database schema, +/// find the primary key of both table, and generate the correct SQL: +/// +/// try dbQueue.read { db in +/// // SELECT * FROM player WHERE id = 1 +/// let player = try playerRequest.fetchOne(db) +/// // SELECT * FROM country WHERE code = 'FR' +/// let country = try countryRequest.fetchOne(db) +/// } +/// +/// Such late computations are backed by DatabasePromise. In our example, +/// see SQLRelation.filterPromise. +struct DatabasePromise { + /// Returns the resolved value. + let resolve: (Database) throws -> T + + /// Creates a promise that resolves to a value. + init(value: T) { + self.resolve = { _ in value } + } + + /// Creates a promise from a closure. + init(_ resolve: @escaping (Database) throws -> T) { + self.resolve = resolve + } + + /// Returns a promise whose value is transformed by the given closure. + func map(_ transform: @escaping (Database, T) throws -> U) -> DatabasePromise { + return DatabasePromise { db in + try transform(db, self.resolve(db)) + } + } +} diff --git a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift index 0c1d56aaa..7bdfaade4 100644 --- a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift @@ -16,9 +16,8 @@ extension QueryInterfaceRequest { return none() } let alias = TableAlias() - let qualifiedQuery = query.qualified(with: alias) let matchExpression = TableMatchExpression(alias: alias, pattern: pattern.databaseValue) - return QueryInterfaceRequest(query: qualifiedQuery).filter(matchExpression) + return self.aliased(alias).filter(matchExpression) } } diff --git a/GRDB/QueryInterface/FTS5+QueryInterface.swift b/GRDB/QueryInterface/FTS5+QueryInterface.swift index 2affcfe44..ab3bb55e0 100644 --- a/GRDB/QueryInterface/FTS5+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS5+QueryInterface.swift @@ -21,9 +21,8 @@ return none() } let alias = TableAlias() - let qualifiedQuery = query.qualified(with: alias) let matchExpression = TableMatchExpression(alias: alias, pattern: pattern.databaseValue) - return QueryInterfaceRequest(query: qualifiedQuery).filter(matchExpression) + return self.aliased(alias).filter(matchExpression) } } diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift deleted file mode 100644 index 0dc8eec85..000000000 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ /dev/null @@ -1,652 +0,0 @@ -struct DatabasePromise { - let resolve: (Database) throws -> T - - init(value: T) { - self.resolve = { _ in value } - } - - init(_ resolve: @escaping (Database) throws -> T) { - self.resolve = resolve - } - - func map(_ transform: @escaping (Database, T) throws -> T) -> DatabasePromise { - return DatabasePromise { db in - try transform(db, self.resolve(db)) - } - } -} - -struct QueryInterfaceQuery { - var source: SQLSource - var selection: [SQLSelectable] - var isDistinct: Bool - var filterPromise: DatabasePromise - var groupPromise: DatabasePromise<[SQLExpression]>? - var ordering: QueryOrdering - var havingExpression: SQLExpression? - var limit: SQLLimit? - var joins: OrderedDictionary - - init( - source: SQLSource, - selection: [SQLSelectable] = [], - isDistinct: Bool = false, - filterPromise: DatabasePromise = DatabasePromise(value: nil), - groupPromise: DatabasePromise<[SQLExpression]>? = nil, - ordering: QueryOrdering = QueryOrdering(), - havingExpression: SQLExpression? = nil, - limit: SQLLimit? = nil, - joins: OrderedDictionary = [:]) - { - self.source = source - self.selection = selection - self.isDistinct = isDistinct - self.filterPromise = filterPromise - self.groupPromise = groupPromise - self.ordering = ordering - self.havingExpression = havingExpression - self.limit = limit - self.joins = joins - } - - init(_ query: AssociationQuery) { - self.init( - source: query.source, - selection: query.selection, - filterPromise: query.filterPromise, - ordering: query.ordering, - joins: query.joins) - } - - var alias: TableAlias? { - return source.alias - } -} - -extension QueryInterfaceQuery { - func select(_ selection: [SQLSelectable]) -> QueryInterfaceQuery { - var query = self - query.selection = selection - return query - } - - func annotated(with selection: [SQLSelectable]) -> QueryInterfaceQuery { - var query = self - query.selection.append(contentsOf: selection) - return query - } - - func distinct() -> QueryInterfaceQuery { - var query = self - query.isDistinct = true - return query - } - - func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceQuery { - var query = self - query.filterPromise = query.filterPromise.map { (db, filter) in - if let filter = filter { - return try filter && predicate(db) - } else { - return try predicate(db).sqlExpression - } - } - return query - } - - func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> QueryInterfaceQuery { - var query = self - query.groupPromise = DatabasePromise { db in try expressions(db).map { $0.sqlExpression } } - return query - } - - func having(_ predicate: SQLExpressible) -> QueryInterfaceQuery { - var query = self - if let havingExpression = query.havingExpression { - query.havingExpression = (havingExpression && predicate).sqlExpression - } else { - query.havingExpression = predicate.sqlExpression - } - return query - } - - func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceQuery { - return order(QueryOrdering(orderings: orderings)) - } - - func reversed() -> QueryInterfaceQuery { - return order(ordering.reversed) - } - - private func order(_ ordering: QueryOrdering) -> QueryInterfaceQuery { - var query = self - query.ordering = ordering - return query - } - - func unordered() -> QueryInterfaceQuery { - var query = self - query.ordering = QueryOrdering() - return query - } - - func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceQuery { - var query = self - query.limit = SQLLimit(limit: limit, offset: offset) - return query - } - - func appendingJoin(_ join: AssociationJoin, forKey key: String) -> QueryInterfaceQuery { - var query = self - if let existingJoin = query.joins.removeValue(forKey: key) { - guard let mergedJoin = existingJoin.merged(with: join) else { - // can't merge - fatalError("The association key \"\(key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") - } - query.joins.append(value: mergedJoin, forKey: key) - } else { - query.joins.append(value: join, forKey: key) - } - return query - } - - func qualified(with alias: TableAlias) -> QueryInterfaceQuery { - var query = self - query.source = source.qualified(with: alias) - return query - } -} - -extension QueryInterfaceQuery { - /// A finalized query is ready for SQL generation - var finalizedQuery: QueryInterfaceQuery { - var query = self - - let alias = TableAlias() - query.source = source.qualified(with: alias) - query.selection = query.selection.map { $0.qualifiedSelectable(with: alias) } - query.filterPromise = query.filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) } - query.groupPromise = query.groupPromise?.map { [alias] (_, exprs) in exprs.map { $0.qualifiedExpression(with: alias) } } - query.ordering = query.ordering.qualified(with: alias) - query.havingExpression = query.havingExpression?.qualifiedExpression(with: alias) - - query.joins = query.joins.mapValues { $0.finalizedJoin } - - return query - } - - /// precondition: self is the result of finalizedQuery - var finalizedAliases: [TableAlias] { - var aliases: [TableAlias] = [] - if let alias = alias { - aliases.append(alias) - } - return joins.reduce(into: aliases) { - $0.append(contentsOf: $1.value.finalizedAliases) - } - } - - /// precondition: self is the result of finalizedQuery - var finalizedSelection: [SQLSelectable] { - return joins.reduce(into: selection) { - $0.append(contentsOf: $1.value.finalizedSelection) - } - } - - /// precondition: self is the result of finalizedQuery - var finalizedOrdering: QueryOrdering { - return joins.reduce(ordering) { - $0.appending($1.value.finalizedOrdering) - } - } - - /// precondition: self is the result of finalizedQuery - private func finalizedRowAdapter(_ db: Database) throws -> RowAdapter? { - if joins.isEmpty { - return nil - } - - let selectionWidth = try selection - .map { try $0.columnCount(db) } - .reduce(0, +) - - var endIndex = selectionWidth - var scopes: [String: RowAdapter] = [:] - for (key, join) in joins { - if let (joinAdapter, joinEndIndex) = try join.finalizedRowAdapter(db, fromIndex: endIndex, forKeyPath: [key]) { - scopes[key] = joinAdapter - endIndex = joinEndIndex - } - } - - if selectionWidth == 0 && scopes.isEmpty { - return nil - } - - let adapter = RangeRowAdapter(0 ..< (0 + selectionWidth)) - return adapter.addingScopes(scopes) - } -} - -extension QueryInterfaceQuery { - /// precondition: self is the result of finalizedQuery - func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { - var sql = "SELECT" - - if isDistinct { - sql += " DISTINCT" - } - - let selection = finalizedSelection - GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") - sql += " " + selection.map { $0.resultColumnSQL(&context) }.joined(separator: ", ") - - sql += try " FROM " + source.sourceSQL(db, &context) - - for (_, join) in joins { - sql += try " " + join.joinSQL(db, &context, leftAlias: alias!, isRequiredAllowed: true) - } - - if let filter = try filterPromise.resolve(db) { - sql += " WHERE " + filter.expressionSQL(&context) - } - - if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty { - sql += " GROUP BY " - sql += groupExpressions.map { $0.expressionSQL(&context) } - .joined(separator: ", ") - } - - if let havingExpression = havingExpression { - sql += " HAVING " + havingExpression.expressionSQL(&context) - } - - let orderings = try finalizedOrdering.resolve(db) - if !orderings.isEmpty { - sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") - } - - if let limit = limit { - sql += " LIMIT " + limit.sql - } - - return sql - } - - /// precondition: self is the result of finalizedQuery - private func makeSelectStatement(_ db: Database) throws -> SelectStatement { - var context = SQLGenerationContext.queryGenerationContext(aliases: finalizedAliases) - let sql = try self.sql(db, &context) - let statement = try db.makeSelectStatement(sql) - statement.arguments = context.arguments! - return statement - } - - /// precondition: self is the result of finalizedQuery - func makeDeleteStatement(_ db: Database) throws -> UpdateStatement { - if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty { - // Programmer error - fatalError("Can't delete query with GROUP BY clause") - } - - guard havingExpression == nil else { - // Programmer error - fatalError("Can't delete query with HAVING clause") - } - - guard joins.isEmpty else { - // Programmer error - fatalError("Can't delete query with JOIN clause") - } - - guard case .table = source else { - // Programmer error - fatalError("Can't delete without any database table") - } - - var context = SQLGenerationContext.queryGenerationContext(aliases: finalizedAliases) - - var sql = try "DELETE FROM " + source.sourceSQL(db, &context) - - if let filter = try filterPromise.resolve(db) { - sql += " WHERE " + filter.expressionSQL(&context) - } - - if let limit = limit { - let orderings = try finalizedOrdering.resolve(db) - if !orderings.isEmpty { - sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") - } - - if Database.sqliteCompileOptions.contains("ENABLE_UPDATE_DELETE_LIMIT") { - sql += " LIMIT " + limit.sql - } else { - fatalError("Can't delete query with limit") - } - } - - let statement = try db.makeUpdateStatement(sql) - statement.arguments = context.arguments! - return statement - } - - /// precondition: self is the result of finalizedQuery - func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try (makeSelectStatement(db), finalizedRowAdapter(db)) - } - - func fetchCount(_ db: Database) throws -> Int { - let (statement, adapter) = try countQuery.prepare(db) - return try Int.fetchOne(statement, adapter: adapter)! - } - - /// The database region that the request looks into. - /// precondition: self is the result of finalizedQuery - func databaseRegion(_ db: Database) throws -> DatabaseRegion { - let statement = try makeSelectStatement(db) - let databaseRegion = statement.databaseRegion - - // Can we intersect the region with rowIds? - // - // Give up unless request feeds from a single database table - guard case .table(tableName: let tableName, alias: _) = source else { - // TODO: try harder - return databaseRegion - } - - // Give up unless primary key is rowId - let primaryKeyInfo = try db.primaryKey(tableName) - guard primaryKeyInfo.isRowID else { - return databaseRegion - } - - // Give up unless there is a where clause - guard let filter = try filterPromise.resolve(db) else { - return databaseRegion - } - - // The filter knows better - guard let rowIds = filter.matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else { - return databaseRegion - } - - // Database regions are case-insensitive: use the canonical table name - let canonicalTableName = try db.canonicalTableName(tableName) - return databaseRegion.tableIntersection(canonicalTableName, rowIds: rowIds) - } - - private var countQuery: QueryInterfaceQuery { - guard groupPromise == nil && limit == nil else { - // SELECT ... GROUP BY ... - // SELECT ... LIMIT ... - return trivialCountQuery - } - - guard joins.isEmpty, case .table = source else { - // SELECT ... FROM (something which is not a plain table) - return trivialCountQuery - } - - GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") - if selection.count == 1 { - guard let count = self.selection[0].count(distinct: isDistinct) else { - return trivialCountQuery - } - var countQuery = self.unordered() - countQuery.isDistinct = false - countQuery.selection = [count.sqlSelectable] - return countQuery - } else { - // SELECT [DISTINCT] expr1, expr2, ... FROM tableName ... - - guard !isDistinct else { - return trivialCountQuery - } - - // SELECT expr1, expr2, ... FROM tableName ... - // -> - // SELECT COUNT(*) FROM tableName ... - var countQuery = self.unordered() - countQuery.selection = [SQLExpressionCount(AllColumns())] - return countQuery - } - } - - // SELECT COUNT(*) FROM (self) - private var trivialCountQuery: QueryInterfaceQuery { - return QueryInterfaceQuery( - source: .query(unordered()), - selection: [SQLExpressionCount(AllColumns())]) - } -} - -// MARK: - AssociationJoin - -/// Not to be mismatched with SQL join operators (inner join, left join). -/// -/// AssociationJoinOperator is designed to be hierarchically nested, unlike -/// SQL join operators. -/// -/// Consider the following request for (A, B, C) tuples: -/// -/// let r = A.including(optional: A.b.including(required: B.c)) -/// -/// It chains three associations, the first optional, the second required. -/// -/// It looks like it means: "Give me all As, along with their Bs, granted those -/// Bs have their Cs. For As whose B has no C, give me a nil B". -/// -/// It can not be expressed as one left join, and a regular join, as below, -/// Because this would not honor the first optional: -/// -/// -- dubious -/// SELECT a.*, b.*, c.* -/// FROM a -/// LEFT JOIN b ON ... -/// JOIN c ON ... -/// -/// Instead, it should: -/// - allow (A + missing (B + C)) -/// - prevent (A + (B + missing C)). -/// -/// This can be expressed in SQL with two left joins, and an extra condition: -/// -/// -- likely correct -/// SELECT a.*, b.*, c.* -/// FROM a -/// LEFT JOIN b ON ... -/// LEFT JOIN c ON ... -/// WHERE NOT((b.id IS NOT NULL) AND (c.id IS NULL)) -- no B without C -/// -/// This is currently not implemented, and requires a little more thought. -/// I don't even know if inventing a whole new way to perform joins should even -/// be on the table. But we have a hierarchical way to express joined queries, -/// and they have a meaning: -/// -/// // what is my meaning? -/// A.including(optional: A.b.including(required: B.c)) -enum AssociationJoinOperator { - case required, optional -} - -struct AssociationJoin { - var joinOperator: AssociationJoinOperator - var joinCondition: JoinCondition - var query: AssociationQuery - - var finalizedJoin: AssociationJoin { - var join = self - join.query = query.finalizedQuery - return join - } - - var finalizedAliases: [TableAlias] { - return query.finalizedAliases - } - - var finalizedSelection: [SQLSelectable] { - return query.finalizedSelection - } - - var finalizedOrdering: QueryOrdering { - return query.finalizedOrdering - } - - func finalizedRowAdapter(_ db: Database, fromIndex startIndex: Int, forKeyPath keyPath: [String]) throws -> (adapter: RowAdapter, endIndex: Int)? { - return try query.finalizedRowAdapter(db, fromIndex: startIndex, forKeyPath: keyPath) - } - - /// precondition: query is the result of finalizedQuery - func joinSQL(_ db: Database,_ context: inout SQLGenerationContext, leftAlias: TableAlias, isRequiredAllowed: Bool) throws -> String { - var isRequiredAllowed = isRequiredAllowed - var sql = "" - switch joinOperator { - case .optional: - isRequiredAllowed = false - sql += "LEFT JOIN" - case .required: - guard isRequiredAllowed else { - // TODO: chainOptionalRequired - fatalError("Not implemented: chaining a required association behind an optional association") - } - sql += "JOIN" - } - - sql += try " " + query.source.sourceSQL(db, &context) - - let rightAlias = query.alias! - let filters = try [ - joinCondition.sqlExpression(db, leftAlias: leftAlias, rightAlias: rightAlias), - query.filterPromise.resolve(db) - ].compactMap { $0 } - if !filters.isEmpty { - sql += " ON " + filters.joined(operator: .and).expressionSQL(&context) - } - - for (_, join) in query.joins { - sql += try " " + join.joinSQL(db, &context, leftAlias: rightAlias, isRequiredAllowed: isRequiredAllowed) - } - - return sql - } - - /// Returns nil if joins can't be merged (conflict in condition, query...) - func merged(with other: AssociationJoin) -> AssociationJoin? { - guard joinCondition == other.joinCondition else { - // can't merge - return nil - } - - guard let mergedQuery = query.merged(with: other.query) else { - // can't merge - return nil - } - - let mergedJoinOperator: AssociationJoinOperator - switch (joinOperator, other.joinOperator) { - case (.required, _), (_, .required): - mergedJoinOperator = .required - default: - mergedJoinOperator = .optional - } - - return AssociationJoin( - joinOperator: mergedJoinOperator, - joinCondition: joinCondition, - query: mergedQuery) - } -} - -// MARK: - SQLSource - -enum SQLSource { - case table(tableName: String, alias: TableAlias?) - indirect case query(QueryInterfaceQuery) - - var alias: TableAlias? { - switch self { - case .table(_, let alias): - return alias - case .query(let query): - return query.alias - } - } - - func sourceSQL(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { - switch self { - case .table(let tableName, let alias): - if let alias = alias, let aliasName = context.aliasName(for: alias) { - return "\(tableName.quotedDatabaseIdentifier) \(aliasName.quotedDatabaseIdentifier)" - } else { - return "\(tableName.quotedDatabaseIdentifier)" - } - case .query(let query): - return try "(\(query.sql(db, &context)))" - } - } - - func qualified(with alias: TableAlias) -> SQLSource { - switch self { - case .table(let tableName, let sourceAlias): - if let sourceAlias = sourceAlias { - alias.becomeProxy(of: sourceAlias) - return self - } else { - alias.setTableName(tableName) - return .table(tableName: tableName, alias: alias) - } - case .query(let query): - return .query(query.qualified(with: alias)) - } - } - - /// Returns nil if sources can't be merged (conflict in tables, aliases...) - func merged(with other: SQLSource) -> SQLSource? { - switch (self, other) { - case let (.table(tableName: tableName, alias: alias), .table(tableName: otherTableName, alias: otherAlias)): - guard tableName == otherTableName else { - // can't merge - return nil - } - switch (alias, otherAlias) { - case (nil, nil): - return .table(tableName: tableName, alias: nil) - case let (alias?, nil), let (nil, alias?): - return .table(tableName: tableName, alias: alias) - case let (alias?, otherAlias?): - guard let mergedAlias = alias.merge(with: otherAlias) else { - // can't merge - return nil - } - return .table(tableName: tableName, alias: mergedAlias) - } - default: - // can't merge - return nil - } - } -} - -struct SQLLimit { - let limit: Int - let offset: Int? - - var sql: String { - if let offset = offset { - return "\(limit) OFFSET \(offset)" - } else { - return "\(limit)" - } - } -} - -extension SQLCount { - var sqlSelectable: SQLSelectable { - switch self { - case .all: - return SQLExpressionCount(AllColumns()) - case .distinct(let expression): - return SQLExpressionCountDistinct(expression) - } - } -} diff --git a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift index 42031bae9..d381f4af1 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift @@ -1,48 +1,37 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { - func joining(_ joinOperator: AssociationJoinOperator, _ association: A) - -> QueryInterfaceRequest - where A.OriginRowDecoder == RowDecoder - { - let join = AssociationJoin( - joinOperator: joinOperator, - joinCondition: association.joinCondition, - query: association.request.query) - return QueryInterfaceRequest(query: query.appendingJoin(join, forKey: association.key)) - } - // MARK: - Associations /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned association does not /// require that the associated database table contains a matching row. - public func including(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { - return joining(.optional, association) + public func including(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { + return mapQuery { $0.mapRelation { association._impl.joinedRelation($0, joinOperator: .optional) } } } /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned association requires /// that the associated database table contains a matching row. - public func including(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { - return joining(.required, association) + public func including(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { + return mapQuery { $0.mapRelation { association._impl.joinedRelation($0, joinOperator: .required) } } } /// Creates a request that includes an association. The columns of the /// associated record are not selected. The returned association does not /// require that the associated database table contains a matching row. - public func joining(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { - return joining(.optional, association.select([])) + public func joining(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { + return mapQuery { $0.mapRelation { association.select([])._impl.joinedRelation($0, joinOperator: .optional) } } } /// Creates a request that includes an association. The columns of the /// associated record are not selected. The returned association requires /// that the associated database table contains a matching row. - public func joining(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { - return joining(.required, association.select([])) + public func joining(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { + return mapQuery { $0.mapRelation { association.select([])._impl.joinedRelation($0, joinOperator: .required) } } } // MARK: - Association Aggregates - private func annotated(with aggregate: AssociationAggregate) -> QueryInterfaceRequest { + private func annotated(with aggregate: AssociationAggregate) -> QueryInterfaceRequest { let (request, expression) = aggregate.prepare(self) if let alias = aggregate.alias { return request.annotated(with: [expression.aliased(alias)]) @@ -57,7 +46,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { /// // FROM player LEFT JOIN book ... /// var request = Player.all() /// request = request.annotated(with: Player.books.count) - public func annotated(with aggregates: AssociationAggregate...) -> QueryInterfaceRequest { + public func annotated(with aggregates: AssociationAggregate...) -> QueryInterfaceRequest { return annotated(with: aggregates) } @@ -67,7 +56,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { /// // FROM player LEFT JOIN book ... /// var request = Player.all() /// request = request.annotated(with: [Player.books.count]) - public func annotated(with aggregates: [AssociationAggregate]) -> QueryInterfaceRequest { + public func annotated(with aggregates: [AssociationAggregate]) -> QueryInterfaceRequest { return aggregates.reduce(self) { request, aggregate in request.annotated(with: aggregate) } @@ -81,7 +70,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { /// // HAVING COUNT(DISTINCT book.rowid) = 0 /// var request = Player.all() /// request = request.having(Player.books.isEmpty) - public func having(_ predicate: AssociationAggregate) -> QueryInterfaceRequest { + public func having(_ predicate: AssociationAggregate) -> QueryInterfaceRequest { let (request, expression) = predicate.prepare(self) return request.having(expression) } diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index bd9eb60d5..5d155f840 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -1,16 +1,27 @@ +/// QueryInterfaceRequest is the type of requests generated by TableRecord: +/// +/// struct Player: TableRecord { ... } +/// let playerRequest = Player.all() // QueryInterfaceRequest +/// +/// It wraps an SQLSelectQuery, and has an attached type. +/// +/// The attached type helps decoding raw database values: +/// +/// try dbQueue.read { db in +/// try playerRequest.fetchAll(db) // [Player] +/// try playerRequest.asRequest(of: Row.self).fetchAll(db) // [Row] +/// } +/// +/// The attached type also helps the compiler validate associated requests: +/// +/// playerRequest.including(required: Player.team) // OK +/// fruitRequest.including(required: Player.team) // Does not compile + /// A QueryInterfaceRequest describes an SQL query. /// /// See https://github.com/groue/GRDB.swift#the-query-interface public struct QueryInterfaceRequest { - let query: QueryInterfaceQuery - - init(query: QueryInterfaceQuery) { - self.query = query - } - - init(_ request: AssociationRequest) { - self.query = QueryInterfaceQuery(request.query) - } + var query: SQLSelectQuery } extension QueryInterfaceRequest : FetchRequest { @@ -23,7 +34,7 @@ extension QueryInterfaceRequest : FetchRequest { /// - returns: A prepared statement and an eventual row adapter. /// :nodoc: public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try query.finalizedQuery.prepare(db) + return try SQLSelectQueryGenerator(query).prepare(db) } /// Returns the number of rows fetched by the request. @@ -39,7 +50,7 @@ extension QueryInterfaceRequest : FetchRequest { /// - parameter db: A database connection. /// :nodoc: public func databaseRegion(_ db: Database) throws -> DatabaseRegion { - return try query.finalizedQuery.databaseRegion(db) + return try SQLSelectQueryGenerator(query).databaseRegion(db) } } @@ -59,8 +70,8 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { /// request /// .select([Column("id")]) /// .select([Column("email")]) - public func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.select(selection)) + public func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest { + return mapQuery { $0.select(selection) } } /// Creates a request which selects *selection*, and fetches values of @@ -72,7 +83,7 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { /// let maxScore: Int? = try request.fetchOne(db) /// } public func select(_ selection: [SQLSelectable], as type: RowDecoder.Type) -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.select(selection)) + return mapQuery { $0.select(selection) }.asRequest(of: RowDecoder.self) } /// Creates a request which selects *selection*, and fetches values of @@ -106,8 +117,8 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { /// request = request /// .select([Column("id"), Column("email")]) /// .annotated(with: [Column("name")]) - public func annotated(with selection: [SQLSelectable]) -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.annotated(with: selection)) + public func annotated(with selection: [SQLSelectable]) -> QueryInterfaceRequest { + return mapQuery { $0.annotated(with: selection) } } /// Creates a request which returns distinct rows. @@ -119,8 +130,8 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { /// // SELECT DISTINCT name FROM player /// var request = Player.select(Column("name")) /// request = request.distinct() - public func distinct() -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.distinct()) + public func distinct() -> QueryInterfaceRequest { + return mapQuery { $0.distinct() } } /// Creates a request with the provided *predicate promise* added to the @@ -129,19 +140,19 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { /// // SELECT * FROM player WHERE 1 /// var request = Player.all() /// request = request.filter { db in true } - public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.filter(predicate)) + public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { + return mapQuery { $0.filter(predicate) } } /// Creates a request grouped according to *expressions promise*. - public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.group(expressions)) + public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> QueryInterfaceRequest { + return mapQuery { $0.group(expressions) } } /// Creates a request with the provided *predicate* added to the /// eventual set of already applied predicates. - public func having(_ predicate: SQLExpressible) -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.having(predicate)) + public func having(_ predicate: SQLExpressible) -> QueryInterfaceRequest { + return mapQuery { $0.having(predicate) } } /// Creates a request with the provided *orderings promise*. @@ -157,8 +168,8 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { /// .order{ _ in [Column("email")] } /// .reversed() /// .order{ _ in [Column("name")] } - public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.order(orderings)) + public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceRequest { + return mapQuery { $0.order(orderings) } } /// Creates a request that reverses applied orderings. @@ -172,8 +183,8 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { /// // SELECT * FROM player /// var request = Player.all() /// request = request.reversed() - public func reversed() -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.reversed()) + public func reversed() -> QueryInterfaceRequest { + return mapQuery { $0.reversed() } } /// Creates a request which fetches *limit* rows, starting at *offset*. @@ -183,8 +194,8 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { /// request = request.limit(1) /// /// Any previous limit is replaced. - public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.limit(limit, offset: offset)) + public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { + return mapQuery { $0.limit(limit, offset: offset) } } /// Creates a request that allows you to define expressions that target @@ -205,7 +216,7 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { /// .aliased(playerAlias) /// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")]) public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.qualified(with: alias)) + return mapQuery { $0.qualified(with: alias) } } /// Creates a request bound to type Target. @@ -221,8 +232,37 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { /// /// - parameter type: The fetched type Target /// - returns: A typed request bound to type Target. - public func asRequest(of type: Target.Type) -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query) + public func asRequest(of type: RowDecoder.Type) -> QueryInterfaceRequest { + return QueryInterfaceRequest(query: query) + } + + /// Returns a request whose query is transformed by the given closure. + func mapQuery(_ transform: (SQLSelectQuery) -> SQLSelectQuery) -> QueryInterfaceRequest { + var request = self + request.query = transform(query) + return request + } +} + +extension QueryInterfaceRequest { + /// Turns a request into a SQLRelation. + /// + /// This method helps initializing associations: + /// + /// struct Book: TableRecord { + /// // invokes Author.all().relation + /// static let author = belongsTo(Author.self) + /// } + var relation: SQLRelation { + let query = self.query + + // Prevent information loss + GRDBPrecondition(!query.isDistinct, "Not implemented: join distinct queries") + GRDBPrecondition(query.groupPromise == nil, "Can't join aggregated queries") + GRDBPrecondition(query.havingExpression == nil, "Can't join aggregated queries") + GRDBPrecondition(query.limit == nil, "Can't join limited queries") + + return query.relation } } @@ -250,7 +290,7 @@ extension QueryInterfaceRequest where T: MutablePersistableRecord { /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. @discardableResult public func deleteAll(_ db: Database) throws -> Int { - try query.makeDeleteStatement(db).execute() + try SQLSelectQueryGenerator(query).makeDeleteStatement(db).execute() return db.changesCount } } @@ -268,9 +308,10 @@ extension TableRecord { /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. public static func all() -> QueryInterfaceRequest { - let query = QueryInterfaceQuery( + let relation = SQLRelation( source: .table(tableName: databaseTableName, alias: nil), selection: databaseSelection) + let query = SQLSelectQuery(relation: relation) return QueryInterfaceRequest(query: query) } diff --git a/GRDB/QueryInterface/QueryOrdering.swift b/GRDB/QueryInterface/QueryOrdering.swift deleted file mode 100644 index d9f199aac..000000000 --- a/GRDB/QueryInterface/QueryOrdering.swift +++ /dev/null @@ -1,85 +0,0 @@ -/// QueryOrdering provides the order clause to QueryInterfaceQuery -/// and AssociationQuery. -struct QueryOrdering { - private enum Element { - case orderingTerms((Database) throws -> [SQLOrderingTerm]) - case queryOrdering(QueryOrdering) - - var reversed: Element { - switch self { - case .orderingTerms(let orderings): - return .orderingTerms { db in try orderings(db).map { $0.reversed } } - case .queryOrdering(let queryOrdering): - return .queryOrdering(queryOrdering.reversed) - } - } - - func qualified(with alias: TableAlias) -> Element { - switch self { - case .orderingTerms(let orderings): - return .orderingTerms { db in try orderings(db).map { $0.qualifiedOrdering(with: alias) } } - case .queryOrdering(let queryOrdering): - return .queryOrdering(queryOrdering.qualified(with: alias)) - } - } - - func resolve(_ db: Database) throws -> [SQLOrderingTerm] { - switch self { - case .orderingTerms(let orderings): - return try orderings(db) - case .queryOrdering(let queryOrdering): - return try queryOrdering.resolve(db) - } - } - } - - private var elements: [Element] = [] - var isReversed: Bool - - var isEmpty: Bool { - return elements.isEmpty - } - - private init(elements: [Element], isReversed: Bool) { - self.elements = elements - self.isReversed = isReversed - } - - init() { - self.init( - elements: [], - isReversed: false) - } - - init(orderings: @escaping (Database) throws -> [SQLOrderingTerm]) { - self.init( - elements: [.orderingTerms(orderings)], - isReversed: false) - } - - var reversed: QueryOrdering { - return QueryOrdering( - elements: elements, - isReversed: !isReversed) - } - - func qualified(with alias: TableAlias) -> QueryOrdering { - return QueryOrdering( - elements: elements.map { $0.qualified(with: alias) }, - isReversed: isReversed) - } - - func appending(_ ordering: QueryOrdering) -> QueryOrdering { - return QueryOrdering( - elements: elements + [.queryOrdering(ordering)], - isReversed: isReversed) - } - - func resolve(_ db: Database) throws -> [SQLOrderingTerm] { - if isReversed { - return try elements.flatMap { try $0.reversed.resolve(db) } - } else { - return try elements.flatMap { try $0.resolve(db) } - } - } -} diff --git a/GRDB/QueryInterface/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGenerationContext.swift index ffa06b1a5..7a98561dd 100644 --- a/GRDB/QueryInterface/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGenerationContext.swift @@ -17,7 +17,7 @@ public struct SQLGenerationContext { qualifierNeeded: false) } - /// Used for QueryInterfaceQuery.makeSelectStatement() and QueryInterfaceQuery.makeDeleteStatement() + /// Used for SQLSelectQuery.makeSelectStatement() and SQLSelectQuery.makeDeleteStatement() static func queryGenerationContext(aliases: [TableAlias]) -> SQLGenerationContext { return SQLGenerationContext( arguments: [], @@ -201,7 +201,7 @@ public class TableAlias: Hashable { } /// Returns nil if aliases can't be merged (conflict in tables, aliases...) - func merge(with other: TableAlias) -> TableAlias? { + func merged(with other: TableAlias) -> TableAlias? { let root = self.root let otherRoot = other.root switch (root.impl, otherRoot.impl) { diff --git a/GRDB/QueryInterface/SQLRelation.swift b/GRDB/QueryInterface/SQLRelation.swift new file mode 100644 index 000000000..269310d13 --- /dev/null +++ b/GRDB/QueryInterface/SQLRelation.swift @@ -0,0 +1,468 @@ +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// A "relation" as defined by the [relational terminology](https://en.wikipedia.org/wiki/Relational_database#Terminology): +/// +/// > A set of tuples sharing the same attributes; a set of columns and rows. +/// +/// :nodoc: +public /* TODO: internal */ struct SQLRelation { + var source: SQLSource + var selection: [SQLSelectable] + var filterPromise: DatabasePromise + var ordering: SQLRelation.Ordering + var joins: OrderedDictionary + + var alias: TableAlias? { + return source.alias + } + + init( + source: SQLSource, + selection: [SQLSelectable] = [], + filterPromise: DatabasePromise = DatabasePromise(value: nil), + ordering: SQLRelation.Ordering = SQLRelation.Ordering(), + joins: OrderedDictionary = [:]) + { + self.source = source + self.selection = selection + self.filterPromise = filterPromise + self.ordering = ordering + self.joins = joins + } +} + +extension SQLRelation { + func select(_ selection: [SQLSelectable]) -> SQLRelation { + var relation = self + relation.selection = selection + return relation + } + + func annotated(with selection: [SQLSelectable]) -> SQLRelation { + var relation = self + relation.selection.append(contentsOf: selection) + return relation + } + + func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> SQLRelation { + var relation = self + relation.filterPromise = relation.filterPromise.map { (db, filter) in + if let filter = filter { + return try filter && predicate(db) + } else { + return try predicate(db).sqlExpression + } + } + return relation + } + + func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> SQLRelation { + return order(SQLRelation.Ordering(orderings: orderings)) + } + + func reversed() -> SQLRelation { + return order(ordering.reversed) + } + + private func order(_ ordering: SQLRelation.Ordering) -> SQLRelation { + var relation = self + relation.ordering = ordering + return relation + } + + func unordered() -> SQLRelation { + return order(SQLRelation.Ordering()) + } + + func appendingJoin(_ join: SQLJoin, forKey key: String) -> SQLRelation { + var relation = self + if let existingJoin = relation.joins.removeValue(forKey: key) { + guard let mergedJoin = existingJoin.merged(with: join) else { + // can't merge + fatalError("The association key \"\(key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") + } + relation.joins.append(value: mergedJoin, forKey: key) + } else { + relation.joins.append(value: join, forKey: key) + } + return relation + } + + func qualified(with alias: TableAlias) -> SQLRelation { + var relation = self + relation.source = source.qualified(with: alias) + return relation + } +} + +// MARK: - SQLSource + +enum SQLSource { + case table(tableName: String, alias: TableAlias?) + indirect case query(SQLSelectQuery) + + var alias: TableAlias? { + switch self { + case .table(_, let alias): + return alias + case .query(let query): + return query.alias + } + } + + func qualified(with alias: TableAlias) -> SQLSource { + switch self { + case .table(let tableName, let sourceAlias): + if let sourceAlias = sourceAlias { + alias.becomeProxy(of: sourceAlias) + return self + } else { + alias.setTableName(tableName) + return .table(tableName: tableName, alias: alias) + } + case .query(let query): + return .query(query.qualified(with: alias)) + } + } +} + +// MARK: - SQLRelation.Ordering + +extension SQLRelation { + /// SQLRelation.Ordering provides the order clause to SQLRelation. + struct Ordering { + private enum Element { + case terms(DatabasePromise<[SQLOrderingTerm]>) + case ordering(SQLRelation.Ordering) + + var reversed: Element { + switch self { + case .terms(let terms): + return .terms(terms.map { (db, terms) in terms.map { $0.reversed } }) + case .ordering(let ordering): + return .ordering(ordering.reversed) + } + } + + func qualified(with alias: TableAlias) -> Element { + switch self { + case .terms(let terms): + return .terms(terms.map { (db, terms) in terms.map { $0.qualifiedOrdering(with: alias) } }) + case .ordering(let ordering): + return .ordering(ordering.qualified(with: alias)) + } + } + + func resolve(_ db: Database) throws -> [SQLOrderingTerm] { + switch self { + case .terms(let terms): + return try terms.resolve(db) + case .ordering(let ordering): + return try ordering.resolve(db) + } + } + } + + private var elements: [Element] = [] + var isReversed: Bool + + var isEmpty: Bool { + return elements.isEmpty + } + + private init(elements: [Element], isReversed: Bool) { + self.elements = elements + self.isReversed = isReversed + } + + init() { + self.init( + elements: [], + isReversed: false) + } + + init(orderings: @escaping (Database) throws -> [SQLOrderingTerm]) { + self.init( + elements: [.terms(DatabasePromise(orderings))], + isReversed: false) + } + + var reversed: Ordering { + return Ordering( + elements: elements, + isReversed: !isReversed) + } + + func qualified(with alias: TableAlias) -> Ordering { + return Ordering( + elements: elements.map { $0.qualified(with: alias) }, + isReversed: isReversed) + } + + func appending(_ ordering: Ordering) -> Ordering { + return Ordering( + elements: elements + [.ordering(ordering)], + isReversed: isReversed) + } + + func resolve(_ db: Database) throws -> [SQLOrderingTerm] { + if isReversed { + return try elements.flatMap { try $0.reversed.resolve(db) } + } else { + return try elements.flatMap { try $0.resolve(db) } + } + } + } +} + +// MARK: - SQLJoin + +/// Not to be mismatched with SQL join operators (inner join, left join). +/// +/// JoinOperator is designed to be hierarchically nested, unlike +/// SQL join operators. +/// +/// Consider the following request for (A, B, C) tuples: +/// +/// let r = A.including(optional: A.b.including(required: B.c)) +/// +/// It chains three associations, the first optional, the second required. +/// +/// It looks like it means: "Give me all As, along with their Bs, granted those +/// Bs have their Cs. For As whose B has no C, give me a nil B". +/// +/// It can not be expressed as one left join, and a regular join, as below, +/// Because this would not honor the first optional: +/// +/// -- dubious +/// SELECT a.*, b.*, c.* +/// FROM a +/// LEFT JOIN b ON ... +/// JOIN c ON ... +/// +/// Instead, it should: +/// - allow (A + missing (B + C)) +/// - prevent (A + (B + missing C)). +/// +/// This can be expressed in SQL with two left joins, and an extra condition: +/// +/// -- likely correct +/// SELECT a.*, b.*, c.* +/// FROM a +/// LEFT JOIN b ON ... +/// LEFT JOIN c ON ... +/// WHERE NOT((b.id IS NOT NULL) AND (c.id IS NULL)) -- no B without C +/// +/// This is currently not implemented, and requires a little more thought. +/// I don't even know if inventing a whole new way to perform joins should even +/// be on the table. But we have a hierarchical way to express joined queries, +/// and they have a meaning: +/// +/// // what is my meaning? +/// A.including(optional: A.b.including(required: B.c)) +/// +/// :nodoc: +public /* TODO: internal */ enum JoinOperator { + case required, optional +} + +/// The condition that links two joined tables. +/// +/// Currently, we only support one kind of join condition: foreign keys. +/// +/// SELECT ... FROM book JOIN author ON author.id = book.authorId +/// <- the join condition --> +/// +/// When we eventually add support for new ways to join tables, JoinCondition +/// is the type we'll need to update. +/// +/// JoinCondition equality allows merging of associations: +/// +/// // request1 and request2 are equivalent +/// let request1 = Book +/// .including(required: Book.author) +/// let request2 = Book +/// .including(required: Book.author) +/// .including(required: Book.author) +/// +/// // request3 and request4 are equivalent +/// let request3 = Book +/// .including(required: Book.author.filter(condition1 && condition2)) +/// let request4 = Book +/// .joining(required: Book.author.filter(condition1)) +/// .including(optional: Book.author.filter(condition2)) +/// +/// :nodoc: +public /* TODO: internal */ struct JoinCondition: Equatable { + /// Definition of a foreign key + var foreignKeyRequest: ForeignKeyRequest + + /// True if the table at the origin of the foreign key is on the left of + /// the sql JOIN operator. + /// + /// Let's consider the `book.authorId -> author.id` foreign key. + /// Its origin table is `book`. + /// + /// The origin table `book` is on the left of the JOIN operator for + /// the BelongsTo association: + /// + /// -- Book.including(required: Book.author) + /// SELECT ... FROM book JOIN author ON author.id = book.authorId + /// + /// The origin table `book`is on the right of the JOIN operator for + /// the HasMany and HasOne associations: + /// + /// -- Author.including(required: Author.books) + /// SELECT ... FROM author JOIN book ON author.id = book.authorId + var originIsLeft: Bool + + /// Returns an SQL expression for the join condition. + /// + /// SELECT ... FROM book JOIN author ON author.id = book.authorId + /// <- the SQL expression --> + /// + /// - parameter db: A database connection. + /// - parameter leftAlias: A TableAlias for the table on the left of the + /// JOIN operator. + /// - parameter rightAlias: A TableAlias for the table on the right of the + /// JOIN operator. + /// - Returns: An SQL expression. + func sqlExpression(_ db: Database, leftAlias: TableAlias, rightAlias: TableAlias) throws -> SQLExpression { + let foreignKeyMapping = try foreignKeyRequest.fetch(db).mapping + let columnMapping: [(left: Column, right: Column)] + if originIsLeft { + columnMapping = foreignKeyMapping.map { (left: Column($0.origin), right: Column($0.destination)) } + } else { + columnMapping = foreignKeyMapping.map { (left: Column($0.destination), right: Column($0.origin)) } + } + + return columnMapping + .map { $0.right.qualifiedExpression(with: rightAlias) == $0.left.qualifiedExpression(with: leftAlias) } + .joined(operator: .and) + } +} + +struct SQLJoin { + var joinOperator: JoinOperator + var joinCondition: JoinCondition + var relation: SQLRelation +} + +// MARK: - Merging +// +// "Merging" is an operation that takes two relations and, if they are +// compatible, gathers them into a merged relation. +// +// It is an important feature that allows the user to define associated requests +// in several steps. For example, in the sample code below, both requests are +// equivalent and generate the same SQL query, thanks to merging: +// +// let request1 = Book.including(required: Book.author) +// +// let request2 = Book +// .including(required: Book.author) +// .including(required: Book.author) + +extension SQLRelation { + /// Returns nil if relations can't be merged (conflict in source, joins...) + func merged(with other: SQLRelation) -> SQLRelation? { + guard let mergedSource = source.merged(with: other.source) else { + // can't merge + return nil + } + + let mergedFilterPromise = filterPromise.map { (db, expression) -> SQLExpression? in + let otherExpression = try other.filterPromise.resolve(db) + let expressions = [expression, otherExpression].compactMap { $0 } + if expressions.isEmpty { + return nil + } + return expressions.joined(operator: .and) + } + + var mergedJoins: OrderedDictionary = [:] + for (key, join) in joins { + if let otherJoin = other.joins[key] { + guard let mergedJoin = join.merged(with: otherJoin) else { + // can't merge + return nil + } + mergedJoins.append(value: mergedJoin, forKey: key) + } else { + mergedJoins.append(value: join, forKey: key) + } + } + for (key, join) in other.joins where mergedJoins[key] == nil { + mergedJoins.append(value: join, forKey: key) + } + + // replace selection unless empty + let mergedSelection = other.selection.isEmpty ? selection : other.selection + + // replace ordering unless empty + let mergedOrdering = other.ordering.isEmpty ? ordering : other.ordering + + return SQLRelation( + source: mergedSource, + selection: mergedSelection, + filterPromise: mergedFilterPromise, + ordering: mergedOrdering, + joins: mergedJoins) + } +} + +extension SQLSource { + /// Returns nil if sources can't be merged (conflict in tables, aliases...) + func merged(with other: SQLSource) -> SQLSource? { + switch (self, other) { + case let (.table(tableName: tableName, alias: alias), .table(tableName: otherTableName, alias: otherAlias)): + guard tableName == otherTableName else { + // can't merge + return nil + } + switch (alias, otherAlias) { + case (nil, nil): + return .table(tableName: tableName, alias: nil) + case let (alias?, nil), let (nil, alias?): + return .table(tableName: tableName, alias: alias) + case let (alias?, otherAlias?): + guard let mergedAlias = alias.merged(with: otherAlias) else { + // can't merge + return nil + } + return .table(tableName: tableName, alias: mergedAlias) + } + default: + // can't merge + return nil + } + } +} + +extension SQLJoin { + /// Returns nil if joins can't be merged (conflict in condition, relation...) + func merged(with other: SQLJoin) -> SQLJoin? { + guard joinCondition == other.joinCondition else { + // can't merge + return nil + } + + guard let mergedRelation = relation.merged(with: other.relation) else { + // can't merge + return nil + } + + let mergedJoinOperator: JoinOperator + switch (joinOperator, other.joinOperator) { + case (.required, _), (_, .required): + mergedJoinOperator = .required + default: + mergedJoinOperator = .optional + } + + return SQLJoin( + joinOperator: mergedJoinOperator, + joinCondition: joinCondition, + relation: mergedRelation) + } +} diff --git a/GRDB/QueryInterface/SQLSelectQuery.swift b/GRDB/QueryInterface/SQLSelectQuery.swift new file mode 100644 index 000000000..15e62f6b0 --- /dev/null +++ b/GRDB/QueryInterface/SQLSelectQuery.swift @@ -0,0 +1,161 @@ +/// SQLSelectQuery is a representation of an SQL SELECT query. +/// +/// See SQLSelectQueryGenerator for actual SQL generation. +struct SQLSelectQuery { + var relation: SQLRelation + var isDistinct: Bool + var groupPromise: DatabasePromise<[SQLExpression]>? + var havingExpression: SQLExpression? + var limit: SQLLimit? + + init( + relation: SQLRelation, + isDistinct: Bool = false, + groupPromise: DatabasePromise<[SQLExpression]>? = nil, + havingExpression: SQLExpression? = nil, + limit: SQLLimit? = nil) + { + self.relation = relation + self.isDistinct = isDistinct + self.groupPromise = groupPromise + self.havingExpression = havingExpression + self.limit = limit + } + + var alias: TableAlias? { + return relation.alias + } +} + +extension SQLSelectQuery: SelectionRequest, FilteredRequest, OrderedRequest { + func select(_ selection: [SQLSelectable]) -> SQLSelectQuery { + return mapRelation { $0.select(selection) } + } + + func annotated(with selection: [SQLSelectable]) -> SQLSelectQuery { + return mapRelation { $0.annotated(with: selection) } + } + + func distinct() -> SQLSelectQuery { + var query = self + query.isDistinct = true + return query + } + + func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> SQLSelectQuery { + return mapRelation { $0.filter(predicate) } + } + + func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> SQLSelectQuery { + var query = self + query.groupPromise = DatabasePromise { db in try expressions(db).map { $0.sqlExpression } } + return query + } + + func having(_ predicate: SQLExpressible) -> SQLSelectQuery { + var query = self + if let havingExpression = query.havingExpression { + query.havingExpression = (havingExpression && predicate).sqlExpression + } else { + query.havingExpression = predicate.sqlExpression + } + return query + } + + func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> SQLSelectQuery { + return mapRelation { $0.order(orderings) } + } + + func reversed() -> SQLSelectQuery { + return mapRelation { $0.reversed() } + } + + func unordered() -> SQLSelectQuery { + return mapRelation { $0.unordered() } + } + + func limit(_ limit: Int, offset: Int? = nil) -> SQLSelectQuery { + var query = self + query.limit = SQLLimit(limit: limit, offset: offset) + return query + } + + func qualified(with alias: TableAlias) -> SQLSelectQuery { + return mapRelation { $0.qualified(with: alias) } + } + + /// Returns a query whose relation is transformed by the given closure. + func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> SQLSelectQuery { + var query = self + query.relation = transform(relation) + return query + } +} + +extension SQLSelectQuery { + func fetchCount(_ db: Database) throws -> Int { + let (statement, adapter) = try SQLSelectQueryGenerator(countQuery).prepare(db) + return try Int.fetchOne(statement, adapter: adapter)! + } + + private var countQuery: SQLSelectQuery { + guard groupPromise == nil && limit == nil else { + // SELECT ... GROUP BY ... + // SELECT ... LIMIT ... + return trivialCountQuery + } + + guard relation.joins.isEmpty, case .table = relation.source else { + // SELECT ... FROM (something which is not a plain table) + return trivialCountQuery + } + + GRDBPrecondition(!relation.selection.isEmpty, "Can't generate SQL with empty selection") + if relation.selection.count == 1 { + guard let count = relation.selection[0].count(distinct: isDistinct) else { + return trivialCountQuery + } + var countQuery = self.unordered() + countQuery.isDistinct = false + switch count { + case .all: + countQuery = countQuery.select(SQLExpressionCount(AllColumns())) + case .distinct(let expression): + countQuery = countQuery.select(SQLExpressionCountDistinct(expression)) + } + return countQuery + } else { + // SELECT [DISTINCT] expr1, expr2, ... FROM tableName ... + + guard !isDistinct else { + return trivialCountQuery + } + + // SELECT expr1, expr2, ... FROM tableName ... + // -> + // SELECT COUNT(*) FROM tableName ... + return self.unordered().select(SQLExpressionCount(AllColumns())) + } + } + + // SELECT COUNT(*) FROM (self) + private var trivialCountQuery: SQLSelectQuery { + let relation = SQLRelation( + source: .query(unordered()), + selection: [SQLExpressionCount(AllColumns())]) + return SQLSelectQuery(relation: relation) + } +} + +struct SQLLimit { + let limit: Int + let offset: Int? + + var sql: String { + if let offset = offset { + return "\(limit) OFFSET \(offset)" + } else { + return "\(limit)" + } + } +} diff --git a/GRDB/QueryInterface/SQLSelectQueryGenerator.swift b/GRDB/QueryInterface/SQLSelectQueryGenerator.swift new file mode 100644 index 000000000..fe4f1c5c3 --- /dev/null +++ b/GRDB/QueryInterface/SQLSelectQueryGenerator.swift @@ -0,0 +1,431 @@ +/// SQLSelectQueryGenerator is able to generate an SQL SELECT query. +struct SQLSelectQueryGenerator { + private let relation: SQLQualifiedRelation + private let isDistinct: Bool + private let groupPromise: DatabasePromise<[SQLExpression]>? + private let havingExpression: SQLExpression? + private let limit: SQLLimit? + + init(_ query: SQLSelectQuery) { + // To generate SQL, we need a "qualified" relation, where all tables, + // expressions, etc, are identified with table aliases. + // + // All those aliases let us disambiguate tables at the SQL level, and + // prefix columns names. For example, the following request... + // + // Book.filter(Column("kind") == Book.Kind.novel) + // .including(optional: Book.author) + // .including(optional: Book.translator) + // .annotated(with: Book.awards.count) + // + // ... generates the following SQL, where all identifiers are correctly + // disambiguated and qualified: + // + // SELECT book.*, person1.*, person2.*, COUNT(DISTINCT award.id) + // FROM book + // LEFT JOIN person person1 ON person1.id = book.authorId + // LEFT JOIN person person2 ON person2.id = book.translatorId + // LEFT JOIN award ON award.bookId = book.id + // GROUP BY book.id + // WHERE book.kind = 'novel' + relation = SQLQualifiedRelation(query.relation) + + // Qualify group expressions and having clause with the relation alias. + // + // This turns `GROUP BY id` INTO `GROUP BY book.id`, and + // `HAVING MAX(year) < 2000` INTO `HAVING MAX(book.year) < 2000`. + let alias = relation.alias + groupPromise = query.groupPromise?.map { [alias] (_, exprs) in exprs.map { $0.qualifiedExpression(with: alias) } } + havingExpression = query.havingExpression?.qualifiedExpression(with: alias) + + // Preserve other flags + isDistinct = query.isDistinct + limit = query.limit + } + + func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { + var sql = "SELECT" + + if isDistinct { + sql += " DISTINCT" + } + + let selection = relation.selection + GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") + sql += " " + selection.map { $0.resultColumnSQL(&context) }.joined(separator: ", ") + + sql += try " FROM " + relation.source.sql(db, &context) + + for (_, join) in relation.joins { + sql += try " " + join.sql(db, &context, leftAlias: relation.alias, isRequiredAllowed: true) + } + + if let filter = try relation.filterPromise.resolve(db) { + sql += " WHERE " + filter.expressionSQL(&context) + } + + if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty { + sql += " GROUP BY " + sql += groupExpressions.map { $0.expressionSQL(&context) } + .joined(separator: ", ") + } + + if let havingExpression = havingExpression { + sql += " HAVING " + havingExpression.expressionSQL(&context) + } + + let orderings = try relation.ordering.resolve(db) + if !orderings.isEmpty { + sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") + } + + if let limit = limit { + sql += " LIMIT " + limit.sql + } + + return sql + } + + func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { + return try (makeSelectStatement(db), rowAdapter(db)) + } + + func databaseRegion(_ db: Database) throws -> DatabaseRegion { + let statement = try makeSelectStatement(db) + let databaseRegion = statement.databaseRegion + + // Can we intersect the region with rowIds? + // + // Give up unless request feeds from a single database table + guard case .table(tableName: let tableName, alias: _) = relation.source else { + // TODO: try harder + return databaseRegion + } + + // Give up unless primary key is rowId + let primaryKeyInfo = try db.primaryKey(tableName) + guard primaryKeyInfo.isRowID else { + return databaseRegion + } + + // Give up unless there is a where clause + guard let filter = try relation.filterPromise.resolve(db) else { + return databaseRegion + } + + // The filter knows better + guard let rowIds = filter.matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else { + return databaseRegion + } + + // Database regions are case-insensitive: use the canonical table name + let canonicalTableName = try db.canonicalTableName(tableName) + return databaseRegion.tableIntersection(canonicalTableName, rowIds: rowIds) + } + + func makeDeleteStatement(_ db: Database) throws -> UpdateStatement { + if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty { + // Programmer error + fatalError("Can't delete query with GROUP BY clause") + } + + guard havingExpression == nil else { + // Programmer error + fatalError("Can't delete query with HAVING clause") + } + + guard relation.joins.isEmpty else { + // Programmer error + fatalError("Can't delete query with JOIN clause") + } + + guard case .table = relation.source else { + // Programmer error + fatalError("Can't delete without any database table") + } + + var context = SQLGenerationContext.queryGenerationContext(aliases: relation.allAliases) + + var sql = try "DELETE FROM " + relation.source.sql(db, &context) + + if let filter = try relation.filterPromise.resolve(db) { + sql += " WHERE " + filter.expressionSQL(&context) + } + + if let limit = limit { + let orderings = try relation.ordering.resolve(db) + if !orderings.isEmpty { + sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") + } + + if Database.sqliteCompileOptions.contains("ENABLE_UPDATE_DELETE_LIMIT") { + sql += " LIMIT " + limit.sql + } else { + fatalError("Can't delete query with limit") + } + } + + let statement = try db.makeUpdateStatement(sql) + statement.arguments = context.arguments! + return statement + } + + /// Returns a select statement + private func makeSelectStatement(_ db: Database) throws -> SelectStatement { + // Build an SQK generation context with all aliases found in the query, + // so that we can disambiguate tables that are used several times with + // SQL aliases. + var context = SQLGenerationContext.queryGenerationContext(aliases: relation.allAliases) + + // Generate SQL + let sql = try self.sql(db, &context) + + // Compile & set arguments + let statement = try db.makeSelectStatement(sql) + statement.arguments = context.arguments! // not nil for this kind of context + return statement + } + + /// Returns the row adapter which presents the fetched rows according to the + /// tree of joined relations. + /// + /// The adapter is nil for queries without any included relation, + /// because the fetched rows don't need any processing: + /// + /// // SELECT * FROM book + /// let request = Book.all() + /// for row in try Row.fetchAll(db, request) { + /// row // [id:1, title:"Moby-Dick"] + /// let book = Book(row: row) + /// } + /// + /// But as soon as the selection includes columns of a included relation, + /// we need an adapter: + /// + /// // SELECT book.*, author.* FROM book JOIN author ON author.id = book.authorId + /// let request = Book.including(required: Book.author) + /// for row in try Row.fetchAll(db, request) { + /// row // [id:1, title:"Moby-Dick"] + /// let book = Book(row: row) + /// + /// row.scopes["author"] // [id:12, name:"Herman Melville"] + /// let author: Author = row["author"] + /// } + private func rowAdapter(_ db: Database) throws -> RowAdapter? { + return try relation.rowAdapter(db, fromIndex: 0)?.adapter + } +} + +/// A "qualified" relation, where all tables are identified with a table alias. +private struct SQLQualifiedRelation { + /// The alias for the relation + /// + /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... + /// ^ alias + let alias: TableAlias + + /// All aliases, including aliases of joined relations + var allAliases: [TableAlias] { + return joins.reduce(into: [alias]) { + $0.append(contentsOf: $1.value.relation.allAliases) + } + } + + /// The source + /// + /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... + /// ^ source + let source: SQLQualifiedSource + + /// The selection, not including selection of joined relations + private let ownSelection: [SQLSelectable] + + /// The full selection, including selection of joined relations + /// + /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... + /// ^ fullSelection + var selection: [SQLSelectable] { + return joins.reduce(into: ownSelection) { + $0.append(contentsOf: $1.value.relation.selection) + } + } + + /// The filtering clause + /// + /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... + /// ^ filterPromise + let filterPromise: DatabasePromise + + /// The ordering, not including ordering of joined relations + private let ownOrdering: SQLRelation.Ordering + + /// The full ordering, including orderings of joined relations + /// + /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... + /// ^ ordering + var ordering: SQLRelation.Ordering { + return joins.reduce(ownOrdering) { + $0.appending($1.value.relation.ordering) + } + } + + /// The joins + /// + /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... + /// ^ joins + let joins: OrderedDictionary + + init(_ relation: SQLRelation) { + // The alias that qualifies this relation + let alias = TableAlias() + self.alias = alias + + // Qualify the source, so that it be disambiguated with an SQL alias + // if needed (when a select query uses the same table several times). + // This disambiguation job will be actually performed by + // SQLGenerationContext, when the SQLSelectQueryGenerator which owns + // this SQLQualifiedRelation generates SQL. + source = SQLQualifiedSource(relation.source.qualified(with: alias)) + + // Qualify all joins, selection, filter, and ordering, so that all + // identifiers can be correctly disambiguated and qualified. + joins = relation.joins.mapValues(SQLQualifiedJoin.init) + ownSelection = relation.selection.map { $0.qualifiedSelectable(with: alias) } + filterPromise = relation.filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) } + ownOrdering = relation.ordering.qualified(with: alias) + } + + /// See SQLSelectQueryGenerator.rowAdapter(_:) + /// + /// - parameter db: A database connection. + /// - parameter startIndex: The index of the leftmost selected column of + /// this relation in a full SQL query. `startIndex` is 0 for the relation + /// at the root of a SQLSelectQueryGenerator (as opposed to the + /// joined relations). + /// - returns: An optional tuple made of a RowAdapter and the index past the + /// rightmost selected column of this relation. Nil is returned if this + /// relations does not need any row adapter. + func rowAdapter(_ db: Database, fromIndex startIndex: Int) throws -> (adapter: RowAdapter, endIndex: Int)? { + // Root relation && no join => no need for any adapter + if startIndex == 0 && joins.isEmpty { + return nil + } + + // The number of columns in own selection. Columns selected by joined + // relations are appended after. + let selectionWidth = try ownSelection + .map { try $0.columnCount(db) } + .reduce(0, +) + + // Recursively build adapters for each joined relation with a selection. + // Name them according to the join keys. + var endIndex = startIndex + selectionWidth + var scopes: [String: RowAdapter] = [:] + for (key, join) in joins { + if let (joinAdapter, joinEndIndex) = try join.relation.rowAdapter(db, fromIndex: endIndex) { + scopes[key] = joinAdapter + endIndex = joinEndIndex + } + } + + // (Root relation || empty selection) && no included relation => no need for any adapter + if (startIndex == 0 || selectionWidth == 0) && scopes.isEmpty { + return nil + } + + // Build a RangeRowAdapter extended with the adapters of joined relations. + // + // // SELECT book.*, author.* FROM book JOIN author ON author.id = book.authorId + // let request = Book.including(required: Book.author) + // for row in try Row.fetchAll(db, request) { + // + // The RangeRowAdapter hides the columns appended by joined relations: + // + // row // [id:1, title:"Moby-Dick"] + // let book = Book(row: row) + // + // Scopes give access to those joined relations: + // + // row.scopes["author"] // [id:12, name:"Herman Melville"] + // let author: Author = row["author"] + // } + let rangeAdapter = RangeRowAdapter(startIndex ..< (startIndex + selectionWidth)) + let adapter = rangeAdapter.addingScopes(scopes) + + return (adapter: adapter, endIndex: endIndex) + } +} + +/// A "qualified" source, where all tables are identified with a table alias. +private enum SQLQualifiedSource { + case table(tableName: String, alias: TableAlias) + indirect case query(SQLSelectQueryGenerator) + + init(_ source: SQLSource) { + switch source { + case .table(let tableName, let sourceAlias): + self = .table(tableName: tableName, alias: sourceAlias ?? TableAlias()) + case .query(let query): + self = .query(SQLSelectQueryGenerator(query)) + } + } + + func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { + switch self { + case .table(let tableName, let alias): + if let aliasName = context.aliasName(for: alias) { + return "\(tableName.quotedDatabaseIdentifier) \(aliasName.quotedDatabaseIdentifier)" + } else { + return "\(tableName.quotedDatabaseIdentifier)" + } + case .query(let query): + return try "(\(query.sql(db, &context)))" + } + } +} + +/// A "qualified" join, where all tables are identified with a table alias. +private struct SQLQualifiedJoin { + private let joinOperator: JoinOperator + private let joinCondition: JoinCondition + let relation: SQLQualifiedRelation + + init(_ join: SQLJoin) { + self.joinOperator = join.joinOperator + self.joinCondition = join.joinCondition + self.relation = SQLQualifiedRelation(join.relation) + } + + func sql(_ db: Database,_ context: inout SQLGenerationContext, leftAlias: TableAlias, isRequiredAllowed: Bool) throws -> String { + var isRequiredAllowed = isRequiredAllowed + var sql = "" + switch joinOperator { + case .optional: + isRequiredAllowed = false + sql += "LEFT JOIN" + case .required: + guard isRequiredAllowed else { + // TODO: chainOptionalRequired + fatalError("Not implemented: chaining a required association behind an optional association") + } + sql += "JOIN" + } + + sql += try " " + relation.source.sql(db, &context) + + let rightAlias = relation.alias + let filters = try [ + joinCondition.sqlExpression(db, leftAlias: leftAlias, rightAlias: rightAlias), + relation.filterPromise.resolve(db) + ].compactMap { $0 } + if !filters.isEmpty { + sql += " ON " + filters.joined(operator: .and).expressionSQL(&context) + } + + for (_, join) in relation.joins { + sql += try " " + join.sql(db, &context, leftAlias: rightAlias, isRequiredAllowed: isRequiredAllowed) + } + + return sql + } +} diff --git a/GRDB/Utils/OrderedDictionary.swift b/GRDB/Utils/OrderedDictionary.swift index 6fc1cfc4b..c4fb38609 100644 --- a/GRDB/Utils/OrderedDictionary.swift +++ b/GRDB/Utils/OrderedDictionary.swift @@ -1,16 +1,31 @@ +/// A dictionary with guaranteed keys ordering. +/// +/// var dict = OrderedDictionary() +/// dict.append(1, forKey: "foo") +/// dict.append(2, forKey: "bar") +/// +/// dict["foo"] // 1 +/// dict["bar"] // 2 +/// dict["qux"] // nil +/// dict.map { $0.key } // ["foo", "bar"], in this order. struct OrderedDictionary { private var keys: [Key] private var values: [Key: Value] + /// Creates an empty ordered dictionary. init() { self.keys = [] self.values = [:] } + /// Returns the value associated with key, or nil. subscript(_ key: Key) -> Value? { return values[key] } + /// Appends the given value for the given key. + /// + /// - precondition: There is no value associated with key yet. mutating func append(value: Value, forKey key: Key) { guard values.updateValue(value, forKey: key) == nil else { fatalError("key is already defined") @@ -18,6 +33,7 @@ struct OrderedDictionary { keys.append(key) } + /// Removes the value associated with key. @discardableResult mutating func removeValue(forKey key: Key) -> Value? { guard let value = values.removeValue(forKey: key) else { @@ -28,13 +44,12 @@ struct OrderedDictionary { return value } + /// Returns a new ordered dictionary containing the keys of this dictionary + /// with the values transformed by the given closure. func mapValues(_ transform: (Value) throws -> T) rethrows -> OrderedDictionary { - var result = OrderedDictionary() - for key in keys { - let value = values[key]! - try result.append(value: transform(value), forKey: key) + return try reduce(into: OrderedDictionary()) { dict, pair in + dict.append(value: try transform(pair.value), forKey: pair.key) } - return result } } diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 3f14b05e5..71a9ec433 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -25,7 +25,6 @@ 560FC5311CB003810014AA8E /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 560FC5321CB003810014AA8E /* DatabasePool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A31C8F625000949E71 /* DatabasePool.swift */; }; 560FC5331CB003810014AA8E /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; - 560FC5341CB003810014AA8E /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; 560FC5351CB003810014AA8E /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238781B9C75030082EB20 /* Statement.swift */; }; 560FC5361CB003810014AA8E /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; 560FC5371CB003810014AA8E /* DatabaseSchemaCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */; }; @@ -296,16 +295,12 @@ 5653EB9020961FC000F46237 /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8520961FBF00F46237 /* BelongsToAssociation.swift */; }; 5653EB9120961FC000F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8620961FBF00F46237 /* HasOneAssociation.swift */; }; 5653EB9220961FC000F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8620961FBF00F46237 /* HasOneAssociation.swift */; }; - 5653EB9320961FC000F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8720961FBF00F46237 /* AssociationQuery.swift */; }; - 5653EB9420961FC000F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8720961FBF00F46237 /* AssociationQuery.swift */; }; 5653EB9520961FC000F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8820961FBF00F46237 /* HasManyAssociation.swift */; }; 5653EB9620961FC000F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8820961FBF00F46237 /* HasManyAssociation.swift */; }; 5653EB9720961FC000F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8920961FBF00F46237 /* ForeignKey.swift */; }; 5653EB9820961FC000F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8920961FBF00F46237 /* ForeignKey.swift */; }; 5653EB9920961FC000F46237 /* ForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8A20961FBF00F46237 /* ForeignKeyRequest.swift */; }; 5653EB9A20961FC000F46237 /* ForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8A20961FBF00F46237 /* ForeignKeyRequest.swift */; }; - 5653EB9B20961FC000F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8B20961FBF00F46237 /* AssociationRequest.swift */; }; - 5653EB9C20961FC000F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8B20961FBF00F46237 /* AssociationRequest.swift */; }; 5653EB9D20961FC000F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8C20961FBF00F46237 /* Association.swift */; }; 5653EB9E20961FC000F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8C20961FBF00F46237 /* Association.swift */; }; 5653EBA220961FCA00F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA120961FCA00F46237 /* QueryInterfaceRequest+Association.swift */; }; @@ -370,8 +365,6 @@ 5653EC18209873A400F46237 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC15209873A400F46237 /* SQLExpression+QueryInterface.swift */; }; 5653EC1A209873E600F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC19209873E600F46237 /* SQLGenerationContext.swift */; }; 5653EC1B209873E600F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC19209873E600F46237 /* SQLGenerationContext.swift */; }; - 5656BF5E20C7248700F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF5C20C7248700F98521 /* QueryOrdering.swift */; }; - 5656BF5F20C7248700F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF5C20C7248700F98521 /* QueryOrdering.swift */; }; 5657AABA1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AABD1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AB101D10899D006283EF /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; }; @@ -597,6 +590,8 @@ 56873BED1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; }; 56873BF01F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; }; 568BE5231CB0371D00270F93 /* GRDBCipher.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 560FC54D1CB003810014AA8E /* GRDBCipher.framework */; }; + 568D13242207214D00674B58 /* SQLSelectQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13222207214D00674B58 /* SQLSelectQueryGenerator.swift */; }; + 568D13252207214D00674B58 /* SQLSelectQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13222207214D00674B58 /* SQLSelectQueryGenerator.swift */; }; 568E1CB21CB037BA008D97A6 /* sqlite3.h in Headers */ = {isa = PBXBuildFile; fileRef = 568BE5191CB035A900270F93 /* sqlite3.h */; settings = {ATTRIBUTES = (Public, ); }; }; 568E1CB91CB03847008D97A6 /* GRDBCipher-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = 568E1CB71CB03847008D97A6 /* GRDBCipher-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; }; 568E1CBA1CB03847008D97A6 /* GRDBCipher.h in Headers */ = {isa = PBXBuildFile; fileRef = 568E1CB81CB03847008D97A6 /* GRDBCipher.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -711,7 +706,6 @@ 56AFCA061CB1A8BB00F48B96 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238701B9C75030082EB20 /* Configuration.swift */; }; 56AFCA071CB1A8BB00F48B96 /* DatabasePool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A31C8F625000949E71 /* DatabasePool.swift */; }; 56AFCA081CB1A8BB00F48B96 /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238781B9C75030082EB20 /* Statement.swift */; }; - 56AFCA091CB1A8BB00F48B96 /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; 56AFCA0A1CB1A8BB00F48B96 /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; 56AFCA0B1CB1A8BB00F48B96 /* Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238761B9C75030082EB20 /* Row.swift */; }; 56AFCA0C1CB1A8BB00F48B96 /* DatabaseSchemaCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */; }; @@ -924,6 +918,12 @@ 56D507641F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; 56D51D011EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; 56D51D041EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; + 56D91A9C2205DD5200770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91A9B2205DD5200770D8D /* SQLRelation.swift */; }; + 56D91A9D2205DD5200770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91A9B2205DD5200770D8D /* SQLRelation.swift */; }; + 56D91AAD2205F30200770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAC2205F30200770D8D /* DatabasePromise.swift */; }; + 56D91AAE2205F30200770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAC2205F30200770D8D /* DatabasePromise.swift */; }; + 56D91AB42205F8C000770D8D /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AB32205F8C000770D8D /* SQLSelectQuery.swift */; }; + 56D91AB52205F8C000770D8D /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AB32205F8C000770D8D /* SQLSelectQuery.swift */; }; 56DAA2D31DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D41DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D71DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; @@ -1025,7 +1025,6 @@ 5605F1581C672E4000235C62 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = ""; }; 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionTests.swift; sourceTree = ""; }; 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollatedExpression.swift; sourceTree = ""; }; - 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceQuery.swift; sourceTree = ""; }; 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = ""; }; 560A37A31C8F625000949E71 /* DatabasePool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePool.swift; sourceTree = ""; }; 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SerializedDatabase.swift; sourceTree = ""; }; @@ -1106,11 +1105,9 @@ 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; 5653EB8520961FBF00F46237 /* BelongsToAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BelongsToAssociation.swift; sourceTree = ""; }; 5653EB8620961FBF00F46237 /* HasOneAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasOneAssociation.swift; sourceTree = ""; }; - 5653EB8720961FBF00F46237 /* AssociationQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationQuery.swift; sourceTree = ""; }; 5653EB8820961FBF00F46237 /* HasManyAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasManyAssociation.swift; sourceTree = ""; }; 5653EB8920961FBF00F46237 /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = ""; }; 5653EB8A20961FBF00F46237 /* ForeignKeyRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyRequest.swift; sourceTree = ""; }; - 5653EB8B20961FBF00F46237 /* AssociationRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRequest.swift; sourceTree = ""; }; 5653EB8C20961FBF00F46237 /* Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Association.swift; sourceTree = ""; }; 5653EBA120961FCA00F46237 /* QueryInterfaceRequest+Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "QueryInterfaceRequest+Association.swift"; sourceTree = ""; }; 5653EBA620961FE600F46237 /* AssociationParallelSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelSQLTests.swift; sourceTree = ""; }; @@ -1129,7 +1126,6 @@ 5653EBB320961FE800F46237 /* AssociationBelongsToRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToRowScopeTests.swift; sourceTree = ""; }; 5653EC15209873A400F46237 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = ""; }; 5653EC19209873E600F46237 /* SQLGenerationContext.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLGenerationContext.swift; sourceTree = ""; }; - 5656BF5C20C7248700F98521 /* QueryOrdering.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryOrdering.swift; sourceTree = ""; }; 5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = ""; }; 5657AB0E1D10899D006283EF /* URL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URL.swift; sourceTree = ""; }; 5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDataTests.swift; sourceTree = ""; }; @@ -1195,6 +1191,7 @@ 568BE5191CB035A900270F93 /* sqlite3.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = sqlite3.h; path = SQLCipher/src/sqlite3.h; sourceTree = ""; }; 568BE51F1CB0360500270F93 /* GRDBCipher.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = GRDBCipher.xcconfig; path = SQLCipher/GRDBCipher.xcconfig; sourceTree = ""; }; 568BE5201CB0360500270F93 /* module.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; name = module.modulemap; path = SQLCipher/module.modulemap; sourceTree = ""; }; + 568D13222207214D00674B58 /* SQLSelectQueryGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectQueryGenerator.swift; sourceTree = ""; }; 568E1CB71CB03847008D97A6 /* GRDBCipher-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "GRDBCipher-Bridging.h"; path = "SQLCipher/GRDBCipher-Bridging.h"; sourceTree = ""; }; 568E1CB81CB03847008D97A6 /* GRDBCipher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = GRDBCipher.h; path = SQLCipher/GRDBCipher.h; sourceTree = ""; }; 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateComponentsTests.swift; sourceTree = ""; }; @@ -1307,6 +1304,9 @@ 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-0.109.0.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 = ""; }; + 56D91A9B2205DD5200770D8D /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = ""; }; + 56D91AAC2205F30200770D8D /* DatabasePromise.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePromise.swift; sourceTree = ""; }; + 56D91AB32205F8C000770D8D /* SQLSelectQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectQuery.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 = ""; }; @@ -1606,12 +1606,11 @@ children = ( 5653EB8420961FBF00F46237 /* Association */, 56CEB5401EAA359A00BFAF62 /* Column.swift */, + 56D91AAC2205F30200770D8D /* DatabasePromise.swift */, 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */, 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, - 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, 5653EBA120961FCA00F46237 /* QueryInterfaceRequest+Association.swift */, - 5656BF5C20C7248700F98521 /* QueryOrdering.swift */, 5616AAF8207CD5A900AC3664 /* RequestProtocols.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, @@ -1620,8 +1619,11 @@ 5653EC15209873A400F46237 /* SQLExpression+QueryInterface.swift */, 5653EC19209873E600F46237 /* SQLGenerationContext.swift */, 56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */, + 56D91A9B2205DD5200770D8D /* SQLRelation.swift */, 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */, 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */, + 56D91AB32205F8C000770D8D /* SQLSelectQuery.swift */, + 568D13222207214D00674B58 /* SQLSelectQueryGenerator.swift */, 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */, 566475C91D981D5E00FF74B8 /* Support */, 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */, @@ -1667,8 +1669,6 @@ children = ( 5653EB8C20961FBF00F46237 /* Association.swift */, 563EF43A2161183E007DAACD /* AssociationAggregate.swift */, - 5653EB8720961FBF00F46237 /* AssociationQuery.swift */, - 5653EB8B20961FBF00F46237 /* AssociationRequest.swift */, 5653EB8520961FBF00F46237 /* BelongsToAssociation.swift */, 5653EB8920961FBF00F46237 /* ForeignKey.swift */, 5653EB8A20961FBF00F46237 /* ForeignKeyRequest.swift */, @@ -2321,6 +2321,7 @@ files = ( 56873BED1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 563EF43C2161183E007DAACD /* AssociationAggregate.swift in Sources */, + 56D91AB42205F8C000770D8D /* SQLSelectQuery.swift in Sources */, 56BF6D3E1DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, 5616AAF9207CD5A900AC3664 /* RequestProtocols.swift in Sources */, 5636E9BD1D22574100B9B05F /* FetchRequest.swift in Sources */, @@ -2328,7 +2329,6 @@ 563EF4502161F1A8007DAACD /* Inflections.swift in Sources */, 566B910A1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91241FA4CF810012D5B0 /* Database+Schema.swift in Sources */, - 5653EB9B20961FC000F46237 /* AssociationRequest.swift in Sources */, 56CEB5121EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4911EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842920413D6F00E50BFD /* DatabaseSnapshot.swift in Sources */, @@ -2338,6 +2338,7 @@ 5653EB9920961FC000F46237 /* ForeignKeyRequest.swift in Sources */, 5613ED8121A95E8400DC7A68 /* ValueObservation+Row.swift in Sources */, 566B91341FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, + 56D91A9C2205DD5200770D8D /* SQLRelation.swift in Sources */, 56D1215B1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 5613ED8921A95E8400DC7A68 /* ValueObservation+Count.swift in Sources */, 566475D41D981D5E00FF74B8 /* SQLOperators.swift in Sources */, @@ -2381,7 +2382,6 @@ 56CEB55B1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, 56BF6D301DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 560FC52A1CB003810014AA8E /* DatabaseError.swift in Sources */, - 5656BF5E20C7248700F98521 /* QueryOrdering.swift in Sources */, 56D51D011EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 566475BB1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 5613ED8721A95E8400DC7A68 /* ValueReducer.swift in Sources */, @@ -2396,11 +2396,10 @@ 5613ED8321A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, 5644DE7C20F8C903001FFDDE /* DatabaseValueConversion.swift in Sources */, 560FC5321CB003810014AA8E /* DatabasePool.swift in Sources */, + 56D91AAD2205F30200770D8D /* DatabasePromise.swift in Sources */, 560FC5331CB003810014AA8E /* Migration.swift in Sources */, - 560FC5341CB003810014AA8E /* QueryInterfaceQuery.swift in Sources */, 566B912C1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 560FC5351CB003810014AA8E /* Statement.swift in Sources */, - 5653EB9320961FC000F46237 /* AssociationQuery.swift in Sources */, 5690C3411D23E82A00E59934 /* Data.swift in Sources */, 5659F4891EA8D94E004A4992 /* Utils.swift in Sources */, 560FC5361CB003810014AA8E /* DatabaseMigrator.swift in Sources */, @@ -2408,6 +2407,7 @@ 560FC5381CB003810014AA8E /* DatabaseDateComponents.swift in Sources */, 56BF6D371DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 56193E961CD8A3E300F95862 /* FetchedRecordsController.swift in Sources */, + 568D13242207214D00674B58 /* SQLSelectQueryGenerator.swift in Sources */, 56B964BA1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, 560FC5391CB003810014AA8E /* DatabaseReader.swift in Sources */, 560FC53A1CB003810014AA8E /* NSNull.swift in Sources */, @@ -2809,6 +2809,7 @@ files = ( 56873BF01F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 563EF43D2161183E007DAACD /* AssociationAggregate.swift in Sources */, + 56D91AB52205F8C000770D8D /* SQLSelectQuery.swift in Sources */, 56BF6D411DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, 5616AAFA207CD5A900AC3664 /* RequestProtocols.swift in Sources */, 5636E9C01D22574100B9B05F /* FetchRequest.swift in Sources */, @@ -2816,7 +2817,6 @@ 563EF4512161F1A8007DAACD /* Inflections.swift in Sources */, 566B910D1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91271FA4CF810012D5B0 /* Database+Schema.swift in Sources */, - 5653EB9C20961FC000F46237 /* AssociationRequest.swift in Sources */, 56CEB5151EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4941EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842A20413D8500E50BFD /* DatabaseSnapshot.swift in Sources */, @@ -2826,6 +2826,7 @@ 5653EB9A20961FC000F46237 /* ForeignKeyRequest.swift in Sources */, 5613ED8221A95E8400DC7A68 /* ValueObservation+Row.swift in Sources */, 566B91371FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, + 56D91A9D2205DD5200770D8D /* SQLRelation.swift in Sources */, 56D1215E1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 5613ED8A21A95E8400DC7A68 /* ValueObservation+Count.swift in Sources */, 566475D71D981D5E00FF74B8 /* SQLOperators.swift in Sources */, @@ -2869,7 +2870,6 @@ 56CEB55E1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, 56BF6D331DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 56AFC9FF1CB1A8BB00F48B96 /* DatabaseValueConvertible.swift in Sources */, - 5656BF5F20C7248700F98521 /* QueryOrdering.swift in Sources */, 56D51D041EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 566475BE1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 5613ED8821A95E8400DC7A68 /* ValueReducer.swift in Sources */, @@ -2884,11 +2884,10 @@ 5613ED8421A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, 5644DE7D20F8C903001FFDDE /* DatabaseValueConversion.swift in Sources */, 56AFCA071CB1A8BB00F48B96 /* DatabasePool.swift in Sources */, + 56D91AAE2205F30200770D8D /* DatabasePromise.swift in Sources */, 56AFCA081CB1A8BB00F48B96 /* Statement.swift in Sources */, - 56AFCA091CB1A8BB00F48B96 /* QueryInterfaceQuery.swift in Sources */, 566B912F1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 56AFCA0A1CB1A8BB00F48B96 /* Migration.swift in Sources */, - 5653EB9420961FC000F46237 /* AssociationQuery.swift in Sources */, 5690C3441D23E82A00E59934 /* Data.swift in Sources */, 5659F48C1EA8D94E004A4992 /* Utils.swift in Sources */, 56AFCA0B1CB1A8BB00F48B96 /* Row.swift in Sources */, @@ -2896,6 +2895,7 @@ 56AFCA0D1CB1A8BB00F48B96 /* DatabaseDateComponents.swift in Sources */, 56BF6D3A1DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 56AFCA0E1CB1A8BB00F48B96 /* DatabaseReader.swift in Sources */, + 568D13252207214D00674B58 /* SQLSelectQueryGenerator.swift in Sources */, 56B964BD1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, 56AFCA0F1CB1A8BB00F48B96 /* NSNull.swift in Sources */, 56AFCA101CB1A8BB00F48B96 /* DatabaseQueue.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 91458697c..3fc2177d0 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -121,16 +121,12 @@ 5653EB4220961F6100F46237 /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3720961F6000F46237 /* BelongsToAssociation.swift */; }; 5653EB4320961F6100F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3820961F6000F46237 /* HasOneAssociation.swift */; }; 5653EB4420961F6100F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3820961F6000F46237 /* HasOneAssociation.swift */; }; - 5653EB4520961F6100F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3920961F6000F46237 /* AssociationQuery.swift */; }; - 5653EB4620961F6100F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3920961F6000F46237 /* AssociationQuery.swift */; }; 5653EB4720961F6100F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3A20961F6000F46237 /* HasManyAssociation.swift */; }; 5653EB4820961F6100F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3A20961F6000F46237 /* HasManyAssociation.swift */; }; 5653EB4920961F6100F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3B20961F6000F46237 /* ForeignKey.swift */; }; 5653EB4A20961F6100F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3B20961F6000F46237 /* ForeignKey.swift */; }; 5653EB4B20961F6100F46237 /* ForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3C20961F6000F46237 /* ForeignKeyRequest.swift */; }; 5653EB4C20961F6100F46237 /* ForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3C20961F6000F46237 /* ForeignKeyRequest.swift */; }; - 5653EB4D20961F6100F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3D20961F6100F46237 /* AssociationRequest.swift */; }; - 5653EB4E20961F6100F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3D20961F6100F46237 /* AssociationRequest.swift */; }; 5653EB4F20961F6100F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3E20961F6100F46237 /* Association.swift */; }; 5653EB5020961F6100F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3E20961F6100F46237 /* Association.swift */; }; 5653EB5420961F7D00F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5320961F7D00F46237 /* QueryInterfaceRequest+Association.swift */; }; @@ -165,8 +161,6 @@ 5653EB8320961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */; }; 5653EC082098737400F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC072098737400F46237 /* SQLGenerationContext.swift */; }; 5653EC092098737400F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC072098737400F46237 /* SQLGenerationContext.swift */; }; - 5656BF5A20C7247100F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF5820C7247100F98521 /* QueryOrdering.swift */; }; - 5656BF5B20C7247100F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF5820C7247100F98521 /* QueryOrdering.swift */; }; 5657AABB1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AABE1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AB111D10899D006283EF /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; }; @@ -269,6 +263,8 @@ 568068381EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; 56873BEE1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; }; 56873BF11F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; }; + 568D13152207210400674B58 /* SQLSelectQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13142207210400674B58 /* SQLSelectQueryGenerator.swift */; }; + 568D13162207210400674B58 /* SQLSelectQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13142207210400674B58 /* SQLSelectQueryGenerator.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 */; }; @@ -386,6 +382,10 @@ 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 */; }; + 56D91A9F2205E02300770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91A9E2205E02300770D8D /* SQLRelation.swift */; }; + 56D91AA02205E02300770D8D /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91A9E2205E02300770D8D /* SQLRelation.swift */; }; + 56D91AA62205F2CF00770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA52205F2CF00770D8D /* DatabasePromise.swift */; }; + 56D91AA72205F2CF00770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA52205F2CF00770D8D /* DatabasePromise.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 */; }; @@ -437,7 +437,7 @@ F3BA80281CFB2891003DC1BA /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; F3BA802B1CFB289B003DC1BA /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; F3BA802C1CFB289B003DC1BA /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; - F3BA802F1CFB289B003DC1BA /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; + F3BA802F1CFB289B003DC1BA /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */; }; F3BA80301CFB289F003DC1BA /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; F3BA80311CFB289F003DC1BA /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; F3BA80321CFB28A4003DC1BA /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; @@ -481,7 +481,7 @@ F3BA80841CFB2E67003DC1BA /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; F3BA80871CFB2E70003DC1BA /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; F3BA80881CFB2E70003DC1BA /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; - F3BA808B1CFB2E70003DC1BA /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; + F3BA808B1CFB2E70003DC1BA /* SQLSelectQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */; }; F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; F3BA808D1CFB2E75003DC1BA /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; F3BA808E1CFB2E7A003DC1BA /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; @@ -663,7 +663,7 @@ 5605F1581C672E4000235C62 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = ""; }; 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionTests.swift; sourceTree = ""; }; 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollatedExpression.swift; sourceTree = ""; }; - 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceQuery.swift; sourceTree = ""; }; + 5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectQuery.swift; sourceTree = ""; }; 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = ""; }; 560A37A31C8F625000949E71 /* DatabasePool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePool.swift; sourceTree = ""; }; 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SerializedDatabase.swift; sourceTree = ""; }; @@ -741,11 +741,9 @@ 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; 5653EB3720961F6000F46237 /* BelongsToAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BelongsToAssociation.swift; sourceTree = ""; }; 5653EB3820961F6000F46237 /* HasOneAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasOneAssociation.swift; sourceTree = ""; }; - 5653EB3920961F6000F46237 /* AssociationQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationQuery.swift; sourceTree = ""; }; 5653EB3A20961F6000F46237 /* HasManyAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasManyAssociation.swift; sourceTree = ""; }; 5653EB3B20961F6000F46237 /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = ""; }; 5653EB3C20961F6000F46237 /* ForeignKeyRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyRequest.swift; sourceTree = ""; }; - 5653EB3D20961F6100F46237 /* AssociationRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRequest.swift; sourceTree = ""; }; 5653EB3E20961F6100F46237 /* Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Association.swift; sourceTree = ""; }; 5653EB5320961F7D00F46237 /* QueryInterfaceRequest+Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "QueryInterfaceRequest+Association.swift"; sourceTree = ""; }; 5653EB5820961FB000F46237 /* AssociationParallelSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelSQLTests.swift; sourceTree = ""; }; @@ -763,7 +761,6 @@ 5653EB6420961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToDecodableRecordTests.swift; sourceTree = ""; }; 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToRowScopeTests.swift; sourceTree = ""; }; 5653EC072098737400F46237 /* SQLGenerationContext.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLGenerationContext.swift; sourceTree = ""; }; - 5656BF5820C7247100F98521 /* QueryOrdering.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryOrdering.swift; sourceTree = ""; }; 5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = ""; }; 5657AB0E1D10899D006283EF /* URL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URL.swift; sourceTree = ""; }; 5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDataTests.swift; sourceTree = ""; }; @@ -825,6 +822,7 @@ 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 = ""; }; 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Fixits-1.2.swift"; sourceTree = ""; }; + 568D13142207210400674B58 /* SQLSelectQueryGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelectQueryGenerator.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 = ""; }; @@ -932,6 +930,8 @@ 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-0.109.0.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 = ""; }; + 56D91A9E2205E02300770D8D /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = ""; }; + 56D91AA52205F2CF00770D8D /* DatabasePromise.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabasePromise.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 = ""; }; @@ -1214,12 +1214,11 @@ children = ( 5653EB3620961F6000F46237 /* Association */, 56CEB5401EAA359A00BFAF62 /* Column.swift */, + 56D91AA52205F2CF00770D8D /* DatabasePromise.swift */, 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */, 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, - 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, 5653EB5320961F7D00F46237 /* QueryInterfaceRequest+Association.swift */, - 5656BF5820C7247100F98521 /* QueryOrdering.swift */, 5616AAF4207CD59300AC3664 /* RequestProtocols.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, @@ -1228,8 +1227,11 @@ 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */, 5653EC072098737400F46237 /* SQLGenerationContext.swift */, 56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */, + 56D91A9E2205E02300770D8D /* SQLRelation.swift */, 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */, 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */, + 5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */, + 568D13142207210400674B58 /* SQLSelectQueryGenerator.swift */, 566475B91D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift */, 566475C91D981D5E00FF74B8 /* Support */, 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */, @@ -1275,8 +1277,6 @@ children = ( 5653EB3E20961F6100F46237 /* Association.swift */, 563EF4362161182C007DAACD /* AssociationAggregate.swift */, - 5653EB3920961F6000F46237 /* AssociationQuery.swift */, - 5653EB3D20961F6100F46237 /* AssociationRequest.swift */, 5653EB3720961F6000F46237 /* BelongsToAssociation.swift */, 5653EB3B20961F6000F46237 /* ForeignKey.swift */, 5653EB3C20961F6000F46237 /* ForeignKeyRequest.swift */, @@ -1965,7 +1965,6 @@ 563EF44E2161F196007DAACD /* Inflections.swift in Sources */, 566B910E1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91281FA4CF810012D5B0 /* Database+Schema.swift in Sources */, - 5653EB4E20961F6100F46237 /* AssociationRequest.swift in Sources */, 56CEB5161EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4951EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842E20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */, @@ -2012,13 +2011,12 @@ 56B964B61DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, F3BA80171CFB2876003DC1BA /* RowAdapter.swift in Sources */, 564CE4DB21B2DEEB00652B19 /* ValueObservation+CompactMap.swift in Sources */, - F3BA802F1CFB289B003DC1BA /* QueryInterfaceQuery.swift in Sources */, + F3BA802F1CFB289B003DC1BA /* SQLSelectQuery.swift in Sources */, 56CEB5061EAA2F4D00BFAF62 /* FTS4.swift in Sources */, 56CEB55F1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, F3BA80201CFB288C003DC1BA /* Date.swift in Sources */, 56A8C2351D1914540096E9D4 /* UUID.swift in Sources */, 56BF6D341DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, - 5656BF5B20C7247100F98521 /* QueryOrdering.swift in Sources */, 56D51D051EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, F3BA80151CFB2876003DC1BA /* DatabaseWriter.swift in Sources */, 5613ED6E21A95E6100DC7A68 /* ValueReducer.swift in Sources */, @@ -2031,12 +2029,13 @@ 5674A6ED1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 5657AB141D10899D006283EF /* URL.swift in Sources */, 5613ED6A21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, + 56D91AA02205E02300770D8D /* SQLRelation.swift in Sources */, 5644DE7920F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */, 56DAA2E01DE9C827006E10C8 /* Cursor.swift in Sources */, + 56D91AA72205F2CF00770D8D /* DatabasePromise.swift in Sources */, F3BA800C1CFB286F003DC1BA /* DatabaseError.swift in Sources */, 566B91301FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, F3BA80221CFB288C003DC1BA /* NSNumber.swift in Sources */, - 5653EB4620961F6100F46237 /* AssociationQuery.swift in Sources */, F3BA80321CFB28A4003DC1BA /* FetchedRecordsController.swift in Sources */, 5659F48D1EA8D94E004A4992 /* Utils.swift in Sources */, F3BA80231CFB288C003DC1BA /* NSString.swift in Sources */, @@ -2045,6 +2044,7 @@ F3BA80111CFB2876003DC1BA /* DatabaseSchemaCache.swift in Sources */, F3BA80281CFB2891003DC1BA /* StandardLibrary.swift in Sources */, F3BA80331CFB28A4003DC1BA /* PersistableRecord.swift in Sources */, + 568D13162207210400674B58 /* SQLSelectQueryGenerator.swift in Sources */, 56BF6D3B1DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 56B964BE1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, F3BA80211CFB288C003DC1BA /* NSNull.swift in Sources */, @@ -2273,7 +2273,6 @@ 563EF44D2161F196007DAACD /* Inflections.swift in Sources */, 566B910B1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91251FA4CF810012D5B0 /* Database+Schema.swift in Sources */, - 5653EB4D20961F6100F46237 /* AssociationRequest.swift in Sources */, 56CEB5131EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4921EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842D20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */, @@ -2320,13 +2319,12 @@ 56B964B31DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, F3BA80731CFB2E55003DC1BA /* RowAdapter.swift in Sources */, 564CE4DA21B2DEEB00652B19 /* ValueObservation+CompactMap.swift in Sources */, - F3BA808B1CFB2E70003DC1BA /* QueryInterfaceQuery.swift in Sources */, + F3BA808B1CFB2E70003DC1BA /* SQLSelectQuery.swift in Sources */, 56CEB5031EAA2F4D00BFAF62 /* FTS4.swift in Sources */, 56CEB55C1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, F3BA807C1CFB2E61003DC1BA /* Date.swift in Sources */, 56A8C2321D1914540096E9D4 /* UUID.swift in Sources */, 56BF6D311DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, - 5656BF5A20C7247100F98521 /* QueryOrdering.swift in Sources */, 56D51D021EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, F3BA80711CFB2E55003DC1BA /* DatabaseWriter.swift in Sources */, 5613ED6D21A95E6100DC7A68 /* ValueReducer.swift in Sources */, @@ -2339,12 +2337,13 @@ 5674A6EC1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 5657AB111D10899D006283EF /* URL.swift in Sources */, 5613ED6921A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, + 56D91A9F2205E02300770D8D /* SQLRelation.swift in Sources */, 5644DE7820F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */, 56DAA2DD1DE9C827006E10C8 /* Cursor.swift in Sources */, + 56D91AA62205F2CF00770D8D /* DatabasePromise.swift in Sources */, F3BA80681CFB2E55003DC1BA /* DatabaseError.swift in Sources */, 566B912D1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, F3BA807E1CFB2E61003DC1BA /* NSNumber.swift in Sources */, - 5653EB4520961F6100F46237 /* AssociationQuery.swift in Sources */, F3BA808E1CFB2E7A003DC1BA /* FetchedRecordsController.swift in Sources */, 5659F48A1EA8D94E004A4992 /* Utils.swift in Sources */, F3BA807F1CFB2E61003DC1BA /* NSString.swift in Sources */, @@ -2353,6 +2352,7 @@ F3BA806D1CFB2E55003DC1BA /* DatabaseSchemaCache.swift in Sources */, F3BA80841CFB2E67003DC1BA /* StandardLibrary.swift in Sources */, F3BA808F1CFB2E7A003DC1BA /* PersistableRecord.swift in Sources */, + 568D13152207210400674B58 /* SQLSelectQueryGenerator.swift in Sources */, 56BF6D381DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 56B964BB1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */, diff --git a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift index 5f23e36a6..a0ffcf846 100644 --- a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift @@ -43,6 +43,15 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase { } } + func testJoiningDoesNotUseAnyRowAdapter() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = Player.joining(required: Player.defaultTeam) + let (_, adapter) = try request.prepare(db) + XCTAssertNil(adapter) + } + } + func testDefaultScopeIncludingRequired() throws { let dbQueue = try makeDatabaseQueue() let request = Player.including(required: Player.defaultTeam) diff --git a/Tests/GRDBTests/QueryInterfaceRequestTests.swift b/Tests/GRDBTests/QueryInterfaceRequestTests.swift index 231b703ac..ee3b99bdc 100644 --- a/Tests/GRDBTests/QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/QueryInterfaceRequestTests.swift @@ -41,6 +41,15 @@ class QueryInterfaceRequestTests: GRDBTestCase { try migrator.migrate(dbWriter) } + // MARK: - Preparation + + func testSimpleRequestDoesNotUseAnyRowAdapter() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let (_, adapter) = try Reader.all().prepare(db) + XCTAssertNil(adapter) + } + } // MARK: - Fetch rows