diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 571eaeeb5..229b2acee 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -148,6 +148,64 @@ 564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; 564F9C311F07611600877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; 564F9C341F07611900877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; + 5653EAD620944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */; }; + 5653EAD720944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */; }; + 5653EAD820944B4F00F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC720944B4C00F46237 /* AssociationBelongsToRowScopeTests.swift */; }; + 5653EAD920944B4F00F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC720944B4C00F46237 /* AssociationBelongsToRowScopeTests.swift */; }; + 5653EADA20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC820944B4D00F46237 /* AssociationRowScopeSearchTests.swift */; }; + 5653EADB20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC820944B4D00F46237 /* AssociationRowScopeSearchTests.swift */; }; + 5653EADC20944B4F00F46237 /* AssociationBelongsToSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC920944B4D00F46237 /* AssociationBelongsToSQLTests.swift */; }; + 5653EADD20944B4F00F46237 /* AssociationBelongsToSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC920944B4D00F46237 /* AssociationBelongsToSQLTests.swift */; }; + 5653EADE20944B4F00F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACA20944B4D00F46237 /* AssociationHasOneSQLDerivationTests.swift */; }; + 5653EADF20944B4F00F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACA20944B4D00F46237 /* AssociationHasOneSQLDerivationTests.swift */; }; + 5653EAE020944B4F00F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACB20944B4D00F46237 /* AssociationTableAliasTestsSQLTests.swift */; }; + 5653EAE120944B4F00F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACB20944B4D00F46237 /* AssociationTableAliasTestsSQLTests.swift */; }; + 5653EAE220944B4F00F46237 /* AssociationHasOneSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACC20944B4D00F46237 /* AssociationHasOneSQLTests.swift */; }; + 5653EAE320944B4F00F46237 /* AssociationHasOneSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACC20944B4D00F46237 /* AssociationHasOneSQLTests.swift */; }; + 5653EAE420944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACD20944B4D00F46237 /* AssociationParallelRowScopesTests.swift */; }; + 5653EAE520944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACD20944B4D00F46237 /* AssociationParallelRowScopesTests.swift */; }; + 5653EAE620944B4F00F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACE20944B4D00F46237 /* AssociationBelongsToFetchableRecordTests.swift */; }; + 5653EAE720944B4F00F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACE20944B4D00F46237 /* AssociationBelongsToFetchableRecordTests.swift */; }; + 5653EAE820944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACF20944B4E00F46237 /* AssociationChainSQLTests.swift */; }; + 5653EAE920944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACF20944B4E00F46237 /* AssociationChainSQLTests.swift */; }; + 5653EAEC20944B4F00F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAD120944B4E00F46237 /* AssociationBelongsToSQLDerivationTests.swift */; }; + 5653EAED20944B4F00F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAD120944B4E00F46237 /* AssociationBelongsToSQLDerivationTests.swift */; }; + 5653EAEE20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAD220944B4E00F46237 /* AssociationParallelDecodableRecordTests.swift */; }; + 5653EAEF20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAD220944B4E00F46237 /* AssociationParallelDecodableRecordTests.swift */; }; + 5653EAF220944B4F00F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAD420944B4E00F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; + 5653EAF320944B4F00F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAD420944B4E00F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; + 5653EAF420944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAD520944B4F00F46237 /* AssociationParallelSQLTests.swift */; }; + 5653EAF520944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAD520944B4F00F46237 /* AssociationParallelSQLTests.swift */; }; + 5653EB0320944C7C00F46237 /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAF820944C7B00F46237 /* BelongsToAssociation.swift */; }; + 5653EB0420944C7C00F46237 /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAF820944C7B00F46237 /* BelongsToAssociation.swift */; }; + 5653EB0520944C7C00F46237 /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAF820944C7B00F46237 /* BelongsToAssociation.swift */; }; + 5653EB0620944C7C00F46237 /* ForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAF920944C7B00F46237 /* ForeignKeyRequest.swift */; }; + 5653EB0720944C7C00F46237 /* ForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAF920944C7B00F46237 /* ForeignKeyRequest.swift */; }; + 5653EB0820944C7C00F46237 /* ForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAF920944C7B00F46237 /* ForeignKeyRequest.swift */; }; + 5653EB0920944C7C00F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFA20944C7B00F46237 /* Association.swift */; }; + 5653EB0A20944C7C00F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFA20944C7B00F46237 /* Association.swift */; }; + 5653EB0B20944C7C00F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFA20944C7B00F46237 /* Association.swift */; }; + 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 */; }; + 5653EB1220944C7C00F46237 /* AssociationMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFD20944C7B00F46237 /* AssociationMapping.swift */; }; + 5653EB1320944C7C00F46237 /* AssociationMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFD20944C7B00F46237 /* AssociationMapping.swift */; }; + 5653EB1420944C7C00F46237 /* AssociationMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFD20944C7B00F46237 /* AssociationMapping.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 */; }; + 5653EB2120944C7C00F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */; }; + 5653EB2220944C7C00F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */; }; + 5653EB2320944C7C00F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */; }; + 5653EB252094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */; }; + 5653EB262094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */; }; + 5653EB272094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */; }; 565490B41D5A4820005622CB /* GRDB.h in Headers */ = {isa = PBXBuildFile; fileRef = DC3773F819C8CBB3004FCF85 /* GRDB.h */; settings = {ATTRIBUTES = (Public, ); }; }; 565490B51D5A4827005622CB /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; }; 565490B61D5AE236005622CB /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238701B9C75030082EB20 /* Configuration.swift */; }; @@ -809,6 +867,30 @@ 564E73DE203D50B9000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; + 5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainRowScopesTests.swift; sourceTree = ""; }; + 5653EAC720944B4C00F46237 /* AssociationBelongsToRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToRowScopeTests.swift; sourceTree = ""; }; + 5653EAC820944B4D00F46237 /* AssociationRowScopeSearchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRowScopeSearchTests.swift; sourceTree = ""; }; + 5653EAC920944B4D00F46237 /* AssociationBelongsToSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToSQLTests.swift; sourceTree = ""; }; + 5653EACA20944B4D00F46237 /* AssociationHasOneSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneSQLDerivationTests.swift; sourceTree = ""; }; + 5653EACB20944B4D00F46237 /* AssociationTableAliasTestsSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationTableAliasTestsSQLTests.swift; sourceTree = ""; }; + 5653EACC20944B4D00F46237 /* AssociationHasOneSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneSQLTests.swift; sourceTree = ""; }; + 5653EACD20944B4D00F46237 /* AssociationParallelRowScopesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelRowScopesTests.swift; sourceTree = ""; }; + 5653EACE20944B4D00F46237 /* AssociationBelongsToFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToFetchableRecordTests.swift; sourceTree = ""; }; + 5653EACF20944B4E00F46237 /* AssociationChainSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainSQLTests.swift; sourceTree = ""; }; + 5653EAD120944B4E00F46237 /* AssociationBelongsToSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToSQLDerivationTests.swift; sourceTree = ""; }; + 5653EAD220944B4E00F46237 /* AssociationParallelDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelDecodableRecordTests.swift; sourceTree = ""; }; + 5653EAD420944B4E00F46237 /* AssociationBelongsToDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToDecodableRecordTests.swift; sourceTree = ""; }; + 5653EAD520944B4F00F46237 /* AssociationParallelSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelSQLTests.swift; sourceTree = ""; }; + 5653EAF820944C7B00F46237 /* BelongsToAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BelongsToAssociation.swift; sourceTree = ""; }; + 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 = ""; }; + 5653EAFD20944C7B00F46237 /* AssociationMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationMapping.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 = ""; }; 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; }; 5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = ""; }; @@ -1268,6 +1350,7 @@ 56300B5C1C53C38F005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 5653EABF20944B1300F46237 /* Association */, 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */, 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, @@ -1284,11 +1367,13 @@ 56300B6D1C53F592005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 5653EAF720944BC900F46237 /* Association */, 56CEB5401EAA359A00BFAF62 /* Column.swift */, 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */, 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, + 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */, 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, @@ -1319,6 +1404,43 @@ name = DatabaseQueue; sourceTree = ""; }; + 5653EABF20944B1300F46237 /* Association */ = { + isa = PBXGroup; + children = ( + 5653EAD420944B4E00F46237 /* AssociationBelongsToDecodableRecordTests.swift */, + 5653EACE20944B4D00F46237 /* AssociationBelongsToFetchableRecordTests.swift */, + 5653EAC720944B4C00F46237 /* AssociationBelongsToRowScopeTests.swift */, + 5653EAD120944B4E00F46237 /* AssociationBelongsToSQLDerivationTests.swift */, + 5653EAC920944B4D00F46237 /* AssociationBelongsToSQLTests.swift */, + 5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */, + 5653EACF20944B4E00F46237 /* AssociationChainSQLTests.swift */, + 5653EACA20944B4D00F46237 /* AssociationHasOneSQLDerivationTests.swift */, + 5653EACC20944B4D00F46237 /* AssociationHasOneSQLTests.swift */, + 5653EAD220944B4E00F46237 /* AssociationParallelDecodableRecordTests.swift */, + 5653EACD20944B4D00F46237 /* AssociationParallelRowScopesTests.swift */, + 5653EAD520944B4F00F46237 /* AssociationParallelSQLTests.swift */, + 5653EAC820944B4D00F46237 /* AssociationRowScopeSearchTests.swift */, + 5653EACB20944B4D00F46237 /* AssociationTableAliasTestsSQLTests.swift */, + ); + name = Association; + sourceTree = ""; + }; + 5653EAF720944BC900F46237 /* Association */ = { + isa = PBXGroup; + children = ( + 5653EAFA20944C7B00F46237 /* Association.swift */, + 5653EAFD20944C7B00F46237 /* AssociationMapping.swift */, + 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */, + 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */, + 5653EAF820944C7B00F46237 /* BelongsToAssociation.swift */, + 5653EAFF20944C7C00F46237 /* ForeignKey.swift */, + 5653EAF920944C7B00F46237 /* ForeignKeyRequest.swift */, + 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */, + 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */, + ); + path = Association; + sourceTree = ""; + }; 5659F4861EA8D94E004A4992 /* Utils */ = { isa = PBXGroup; children = ( @@ -2191,6 +2313,7 @@ 5698AD1C1DAAD17F0056AF8C /* FTS5Tokenizer.swift in Sources */, 56CEB5171EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 56B964B71DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, + 5653EB0B20944C7C00F46237 /* Association.swift in Sources */, 56F5ABDA1D814330001F60CB /* NSData.swift in Sources */, 56D121601ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 564F9C341F07611900877A00 /* DatabaseFunction.swift in Sources */, @@ -2198,6 +2321,7 @@ 5659F4961EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 5659F48E1EA8D94E004A4992 /* Utils.swift in Sources */, 56CEB5671EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, + 5653EB272094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */, 565490B91D5AE236005622CB /* DatabasePool.swift in Sources */, 5674A6EF1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 565490D81D5AE252005622CB /* DatabaseMigrator.swift in Sources */, @@ -2207,12 +2331,14 @@ 565490D91D5AE252005622CB /* Migration.swift in Sources */, 56CEB5001EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD271DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, + 5653EB1120944C7C00F46237 /* AssociationRequest.swift in Sources */, C96C0F2D2084A45A006B2981 /* SQLiteDateParser.swift in Sources */, 566A841C2041146100E50BFD /* DatabaseSnapshot.swift in Sources */, 565490D51D5AE252005622CB /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 565490C51D5AE236005622CB /* SerializedDatabase.swift in Sources */, 56F3E7691E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */, 5698AC7E1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, + 5653EB1A20944C7C00F46237 /* ForeignKey.swift in Sources */, 5698AC3D1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 565490BF1D5AE236005622CB /* DatabaseValueConvertible.swift in Sources */, 566B91191FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, @@ -2227,6 +2353,7 @@ 565490C31D5AE236005622CB /* RowAdapter.swift in Sources */, 5698AD3B1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, 5659F49E1EA8D989004A4992 /* Pool.swift in Sources */, + 5653EB0E20944C7C00F46237 /* HasManyAssociation.swift in Sources */, 565490DA1D5AE252005622CB /* QueryInterfaceRequest.swift in Sources */, 565490CA1D5AE252005622CB /* DatabaseDateComponents.swift in Sources */, 565490D01D5AE252005622CB /* NSString.swift in Sources */, @@ -2235,6 +2362,7 @@ 5674A6E81F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, 56873BF21F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 56BF6D431DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, + 5653EB2320944C7C00F46237 /* HasOneAssociation.swift in Sources */, 565490C01D5AE236005622CB /* DatabaseWriter.swift in Sources */, 565490C41D5AE236005622CB /* SchedulingWatchdog.swift in Sources */, 566B91311FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, @@ -2242,6 +2370,7 @@ 565490CC1D5AE252005622CB /* (null) in Sources */, 56BF6D351DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 566B91291FA4CF810012D5B0 /* Database+Schema.swift in Sources */, + 5653EB1420944C7C00F46237 /* AssociationMapping.swift in Sources */, 5671FC261DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56CEB5521EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 565490DB1D5AE252005622CB /* SQLCollatedExpression.swift in Sources */, @@ -2267,13 +2396,16 @@ 56F5ABDD1D814330001F60CB /* UUID.swift in Sources */, 565490CB1D5AE252005622CB /* (null) in Sources */, 565490D61D5AE252005622CB /* StandardLibrary.swift in Sources */, + 5653EB1720944C7C00F46237 /* AssociationQuery.swift in Sources */, 565490B81D5AE236005622CB /* DatabaseError.swift in Sources */, 56BF6D3C1DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 56B1C3CF201C8D0E001938DA /* Swift4.1.swift in Sources */, 56DAA2E11DE9C827006E10C8 /* Cursor.swift in Sources */, + 5653EB0520944C7C00F46237 /* BelongsToAssociation.swift in Sources */, 565490BC1D5AE236005622CB /* DatabaseSchemaCache.swift in Sources */, 565490BA1D5AE236005622CB /* DatabaseQueue.swift in Sources */, 565490CD1D5AE252005622CB /* Date.swift in Sources */, + 5653EB0820944C7C00F46237 /* ForeignKeyRequest.swift in Sources */, 565490BE1D5AE236005622CB /* DatabaseValue.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -2307,16 +2439,19 @@ 5605F18E1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */, 566475D61D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 5698AD381DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, + 5653EB0A20944C7C00F46237 /* Association.swift in Sources */, 56A2387E1B9C75030082EB20 /* Database.swift in Sources */, 56CEB4FD1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5605F15A1C672E4000235C62 /* CGFloat.swift in Sources */, 56CEB5481EAA359A00BFAF62 /* Column.swift in Sources */, + 5653EB262094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */, 5605F1641C672E4000235C62 /* Date.swift in Sources */, 566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 5605F1721C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 56CEB5141EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 566475CF1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, 5659F49B1EA8D989004A4992 /* Pool.swift in Sources */, + 5653EB2220944C7C00F46237 /* HasOneAssociation.swift in Sources */, 569A98EE2039B6F3008D7DBF /* Fixits-3.0.swift in Sources */, 56CEB51C1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, 5698AC3A1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, @@ -2325,6 +2460,7 @@ 563363C51C942C37000BE133 /* DatabaseWriter.swift in Sources */, 5698AD1B1DAAD17D0056AF8C /* FTS5Tokenizer.swift in Sources */, 56F3E7661E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */, + 5653EB0420944C7C00F46237 /* BelongsToAssociation.swift in Sources */, 56B964B41DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, 560A37A81C8FF6E500949E71 /* SerializedDatabase.swift in Sources */, 566A841B2041146100E50BFD /* DatabaseSnapshot.swift in Sources */, @@ -2335,10 +2471,12 @@ 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 */, 5657AB121D10899D006283EF /* URL.swift in Sources */, 5616AAF2207CD45E00AC3664 /* RequestProtocols.swift in Sources */, @@ -2360,9 +2498,11 @@ 56A238881B9C75030082EB20 /* Row.swift in Sources */, 56CEB4F41EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 569531201C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */, + 5653EB1320944C7C00F46237 /* AssociationMapping.swift in Sources */, 5605F15E1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */, 56BF6D391DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 563363C11C942C04000BE133 /* DatabaseReader.swift in Sources */, + 5653EB1920944C7C00F46237 /* ForeignKey.swift in Sources */, 5659F4A31EA8D997004A4992 /* Result.swift in Sources */, 56B964BC1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, 5605F1661C672E4000235C62 /* NSNull.swift in Sources */, @@ -2371,6 +2511,7 @@ 5698AC7B1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */, 56D1215D1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, + 5653EB0D20944C7C00F46237 /* HasManyAssociation.swift in Sources */, 566AD8B51D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5698AD241DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, C96C0F2C2084A459006B2981 /* SQLiteDateParser.swift in Sources */, @@ -2380,6 +2521,7 @@ 560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */, 560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */, 566475A51D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, + 5653EB0720944C7C00F46237 /* ForeignKeyRequest.swift in Sources */, 5657AABC1D107001006283EF /* NSData.swift in Sources */, 31A778841C6A4E0600F507F6 /* FetchedRecordsController.swift in Sources */, 56A238861B9C75030082EB20 /* DatabaseValue.swift in Sources */, @@ -2434,6 +2576,7 @@ 56B14E831D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, 562393341DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, 5698AC841DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, + 5653EAE320944B4F00F46237 /* AssociationHasOneSQLTests.swift in Sources */, 566AD8CA1D531BEC002EC1A8 /* TableDefinitionTests.swift in Sources */, 56A238541B9C74A90082EB20 /* RecordPrimaryKeyMultipleTests.swift in Sources */, 56FDECE31BB32DFD009AD709 /* RowFromStatementTests.swift in Sources */, @@ -2448,12 +2591,14 @@ 5657AB421D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, 56CC922D201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */, 56D507621F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, + 5653EADD20944B4F00F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 56176C6B1EACCCC9000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 56300B621C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 56EA869F1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift in Sources */, 567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, 5657AB621D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, 5657AB6A1D108BA9006283EF /* FoundationURLTests.swift in Sources */, + 5653EADF20944B4F00F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, 56F3E74D1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, 56EB0AB31BCD787300A3DC55 /* DataMemoryTests.swift in Sources */, 56B6EF57208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */, @@ -2472,6 +2617,7 @@ 560A37AC1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift in Sources */, 5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */, 5690C33B1D23E7D200E59934 /* FoundationDateTests.swift in Sources */, + 5653EAF320944B4F00F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 565D5D721BBC694D00DC9BD4 /* Row+FoundationTests.swift in Sources */, 5623936D1DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */, 567A80571D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, @@ -2491,19 +2637,25 @@ 565B0FF01BBC7D980098DE03 /* FetchableRecordTests.swift in Sources */, 5698AC9A1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 562393521DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, + 5653EAE520944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */, 56A4CDB41D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 56CC9247201E058100CB597E /* DropFirstCursorTests.swift in Sources */, 56E8CE0E1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift in Sources */, 56A238581B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift in Sources */, 56A5EF131EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, + 5653EAE920944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */, 5698ACD21DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, 56A238621B9C74A90082EB20 /* RecordEditedTests.swift in Sources */, + 5653EAE120944B4F00F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, + 5653EAE720944B4F00F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 5695312A1C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift in Sources */, + 5653EADB20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 5698ACA21DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, 56A2385C1B9C74A90082EB20 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 56A238401B9C74A90082EB20 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 564F9C221F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, 56A8C2481D1918F00096E9D4 /* FoundationUUIDTests.swift in Sources */, + 5653EAEF20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 56A2383C1B9C74A90082EB20 /* DatabaseErrorTests.swift in Sources */, 5690C32A1D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */, 5657AB3A1D108BA9006283EF /* FoundationDataTests.swift in Sources */, @@ -2519,17 +2671,21 @@ 568068351EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 565D5D751BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */, 5623931C1DECC02000A6B01F /* RowFetchTests.swift in Sources */, + 5653EAD720944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */, 562393641DEE06D300A6B01F /* CursorTests.swift in Sources */, 5657AB5A1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, 56300B6C1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 5674A7231F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, 56F0B9921B6001C600A2F135 /* FoundationNSDateTests.swift in Sources */, 56A238381B9C74A90082EB20 /* DatabaseTests.swift in Sources */, + 5653EAED20944B4F00F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 56300B5F1C53C38F005A543B /* QueryInterfaceRequestTests.swift in Sources */, 5634B10A1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */, 560C97C81BFD0B8400BF8471 /* DatabaseFunctionTests.swift in Sources */, + 5653EAD920944B4F00F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, 56A2383A1B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift in Sources */, 56A5E40A1BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift in Sources */, + 5653EAF520944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */, 56FF455A1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, 56B7F42A1BE14A1900E39BBF /* CGFloatTests.swift in Sources */, 5605F1881C69111300235C62 /* DatabaseRegionTests.swift in Sources */, @@ -2581,6 +2737,7 @@ 56D4967C1D8130DB008276D7 /* CGFloatTests.swift in Sources */, 56D496631D81304E008276D7 /* FoundationURLTests.swift in Sources */, 56D496B71D81344B008276D7 /* RecordUniqueIndexTests.swift in Sources */, + 5653EAE220944B4F00F46237 /* AssociationHasOneSQLTests.swift in Sources */, 56D496671D813086008276D7 /* Record+QueryInterfaceRequestTests.swift in Sources */, 56DAA2D21DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */, 56D496AE1D813345008276D7 /* DatabasePoolCollationTests.swift in Sources */, @@ -2595,12 +2752,14 @@ 56D4965E1D81304E008276D7 /* FoundationNSStringTests.swift in Sources */, 5698AC891DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, 56CC922C201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */, + 5653EADC20944B4F00F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 56D5075E1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 56176C591EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 56D4968A1D81316E008276D7 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 56D496601D81304E008276D7 /* FoundationNSUUIDTests.swift in Sources */, 567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, 56D4968D1D81316E008276D7 /* DatabaseFunctionTests.swift in Sources */, + 5653EADE20944B4F00F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, 56D496661D813086008276D7 /* QueryInterfaceRequestTests.swift in Sources */, 56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, 56B6EF56208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */, @@ -2619,6 +2778,7 @@ 5698AC031D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, 56D496611D81304E008276D7 /* Row+FoundationTests.swift in Sources */, 56D496C41D813767008276D7 /* DatabaseQueueTests.swift in Sources */, + 5653EAF220944B4F00F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 56D496851D813147008276D7 /* StatementArgumentsTests.swift in Sources */, 56D496B81D813465008276D7 /* DataMemoryTests.swift in Sources */, 56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */, @@ -2638,19 +2798,25 @@ 56176C5D1EACCCC7000F3F2B /* FTS5TokenizerTests.swift in Sources */, 56D496B21D8133CE008276D7 /* DatabaseQueueInMemoryTests.swift in Sources */, 562393601DEE06D300A6B01F /* CursorTests.swift in Sources */, + 5653EAE420944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */, 56D4968F1D81316E008276D7 /* RowFromDictionaryTests.swift in Sources */, 56D4968E1D81316E008276D7 /* RowCopiedFromStatementTests.swift in Sources */, 56CC9246201E058100CB597E /* DropFirstCursorTests.swift in Sources */, 5698AC401DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 562393571DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, + 5653EAE820944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */, 56A5EF0F1EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, 56D496B61D813434008276D7 /* DatabaseRegionTests.swift in Sources */, + 5653EAE020944B4F00F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, + 5653EAE620944B4F00F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 562393181DECC02000A6B01F /* RowFetchTests.swift in Sources */, + 5653EADA20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 56D4965A1D81304E008276D7 /* FoundationNSDataTests.swift in Sources */, 56D496741D81309E008276D7 /* RecordCopyTests.swift in Sources */, 56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */, 56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, + 5653EAEE20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 56D496861D813147008276D7 /* UpdateStatementTests.swift in Sources */, 56D4965D1D81304E008276D7 /* FoundationNSNumberTests.swift in Sources */, 56B021C91D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, @@ -2666,17 +2832,21 @@ 568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */, 56D496951D81317B008276D7 /* MutablePersistableRecordTests.swift in Sources */, + 5653EAD620944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */, 5698AC801DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, 56D496821D813131008276D7 /* TransactionObserverTests.swift in Sources */, 56D496941D81317B008276D7 /* SchedulingWatchdogTests.swift in Sources */, 5674A7201F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, 56D496551D812F83008276D7 /* FoundationDataTests.swift in Sources */, 56D4966A1D813086008276D7 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, + 5653EAEC20944B4F00F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 562206071E420EA4005860AC /* DatabasePoolConcurrencyTests.swift in Sources */, 5698ACB61DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 56D4965C1D81304E008276D7 /* FoundationNSNullTests.swift in Sources */, + 5653EAD820944B4F00F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, 562205F11E420E47005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */, 56D4967F1D813131008276D7 /* StatementColumnConvertibleTests.swift in Sources */, + 5653EAF420944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */, 56D496971D81317B008276D7 /* DatabaseReaderTests.swift in Sources */, 56D496911D81316E008276D7 /* RowFromStatementTests.swift in Sources */, 56071A411DB54ED000CA6E47 /* FetchedRecordsControllerTests.swift in Sources */, @@ -2728,11 +2898,13 @@ 5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 567404881CEF84C8003ED5CC /* RowAdapter.swift in Sources */, 56E06F061E859064008AE2A4 /* Fixits-0.102.0.swift in Sources */, + 5653EB0320944C7C00F46237 /* BelongsToAssociation.swift in Sources */, 563363C41C942C37000BE133 /* DatabaseWriter.swift in Sources */, 5698AD181DAAD17A0056AF8C /* FTS5Tokenizer.swift in Sources */, 56F3E7631E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */, 56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, 560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */, + 5653EB252094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */, 5605F1691C672E4000235C62 /* NSString.swift in Sources */, 560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */, 56A8C2301D1914540096E9D4 /* UUID.swift in Sources */, @@ -2742,6 +2914,7 @@ 56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */, 56D51D001EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 566475BA1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, + 5653EB0920944C7C00F46237 /* Association.swift in Sources */, 56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */, 5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56A238A41B9C753B0082EB20 /* Record.swift in Sources */, @@ -2763,12 +2936,16 @@ 5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.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 */, 5605F1651C672E4000235C62 /* NSNull.swift in Sources */, 56CEB5191EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, + 5653EB1820944C7C00F46237 /* ForeignKey.swift in Sources */, 5674A6FB1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, + 5653EB0620944C7C00F46237 /* ForeignKeyRequest.swift in Sources */, 5698AC781DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 56A2387D1B9C75030082EB20 /* Database.swift in Sources */, 566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */, @@ -2776,12 +2953,15 @@ 56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */, 569A98ED2039B6F3008D7DBF /* Fixits-3.0.swift in Sources */, 5605F1671C672E4000235C62 /* NSNumber.swift in Sources */, + 5653EB1220944C7C00F46237 /* AssociationMapping.swift in Sources */, C96C0F2B2084A442006B2981 /* SQLiteDateParser.swift in Sources */, 56A238871B9C75030082EB20 /* Row.swift in Sources */, + 5653EB2120944C7C00F46237 /* HasOneAssociation.swift in Sources */, 5605F1731C672E4000235C62 /* StandardLibrary.swift in Sources */, 560D92471C672C4B00F4F92B /* PersistableRecord.swift in Sources */, 566475A21D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5674A6E41F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, + 5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */, 5657AAB91D107001006283EF /* NSData.swift in Sources */, 560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */, 56CEB5531EAA359A00BFAF62 /* SQLExpression.swift in Sources */, diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index 7f4603cf4..258bdefe2 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -355,6 +355,12 @@ extension DatabaseValue { public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { return self } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return self + } } // CustomStringConvertible diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift new file mode 100644 index 000000000..d0028c0ab --- /dev/null +++ b/GRDB/QueryInterface/Association/Association.swift @@ -0,0 +1,232 @@ +/// The base protocol for all associations that define a connection between two +/// Record types. +public protocol Association: SelectionRequest, FilteredRequest, OrderedRequest { + associatedtype LeftAssociated: TableRecord + associatedtype RightAssociated: TableRecord + + /// The association key defines how rows fetched from this association + /// should be consumed. + /// + /// For example: + /// + /// struct Player: TableRecord { + /// // The default key of this association is the name of the + /// // database table for teams, let's say "team": + /// static let team = belongsTo(Team.self) + /// } + /// print(Player.team.key) // Prints "team" + /// + /// // Consume rows: + /// let request = Player.including(required: Player.team) + /// for row in Row.fetchAll(db, request) { + /// let team: Team = row["team"] // the association key + /// } + /// + /// The key can be redefined with the `forKey` method: + /// + /// let request = Player.including(required: Player.team.forKey("custom")) + /// for row in Row.fetchAll(db, request) { + /// let team: Team = row["custom"] + /// } + var key: String { get } + + /// Creates an association with the given key. + /// + /// This new key impacts how rows fetched from this 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: + func associationMapping(_ db: Database) throws -> AssociationMapping + + /// :nodoc: + func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> Self +} + +func defaultAssociationKey(for type: T.Type) -> String { + return T.databaseTableName +} + +extension Association { + /// Creates an association with a new net of selected columns. + /// + /// Any previous selection is replaced. + public func select(_ selection: [SQLSelectable]) -> Self { + return mapRequest { $0.select(selection) } + } + + /// Creates an association with the provided *predicate promise* added to + /// the eventual set of already applied predicates. + public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { + return mapRequest { $0.filter(predicate) } + } + + /// Creates an association that matches nothing. + public func none() -> Self { + return mapRequest { $0.none() } + } + + /// Creates an association with the provided *orderings*. + /// + /// Any previous ordering is replaced. + public func order(_ orderings: [SQLOrderingTerm]) -> Self { + return mapRequest { $0.order(orderings) } + } + + /// Creates an association that reverses applied orderings. If no ordering + /// was applied, the returned request is identical. + public func reversed() -> Self { + return mapRequest { $0.reversed() } + } + + /// Creates an association with the given key. + /// + /// This new key helps Decodable records decode fetched rows: + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// struct PlayerInfo: FetchableRecord, Decodable { + /// let player: Player + /// let team: Team + /// + /// static func all() -> AnyFetchRequest { + /// return Player + /// .including(required: Player.team.forKey(CodingKeys.team)) + /// .asRequest(of: PlayerInfo.self) + /// } + /// } + /// + /// let playerInfos = PlayerInfo.all().fetchAll(db) + /// print(playerInfos.first?.team) + public func forKey(_ codingKey: CodingKey) -> Self { + return forKey(codingKey.stringValue) + } + + /// Creates an association that allows you to define unambiguous expressions + /// based on the associated record. + /// + /// In the example below, the "team.color = 'red'" condition in the where + /// clause could be not achieved without table aliases. + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // SELECT player.*, team.* + /// // JOIN team ON ... + /// // WHERE team.color = 'red' + /// let teamAlias = TableAlias() + /// let request = Player + /// .including(required: Player.team.aliased(teamAlias)) + /// .filter(teamAlias[Column("color"] == "red") + /// + /// When you give a name to a table alias, you can reliably inject sql + /// snippets in your requests: + /// + /// // SELECT player.*, custom.* + /// // JOIN team custom ON ... + /// // WHERE custom.color = 'red' + /// let teamAlias = TableAlias(name: "custom") + /// let request = Player + /// .including(required: Player.team.aliased(teamAlias)) + /// .filter(sql: "custom.color = ?", arguments: ["red") + public func aliased(_ alias: TableAlias) -> Self { + return mapRequest { $0.aliased(alias) } + } +} + +/// Not to be mismatched with SQL join operators (inner join, left join). +/// +/// AssociationChainOperator 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 AssociationChainOperator { + case required, optional +} + +extension Association { + /// Creates an association that includes another one. 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) -> Self where A.LeftAssociated == RightAssociated + { + return mapRequest { $0.chain(.optional, association) } + } + + /// 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.LeftAssociated == RightAssociated + { + return mapRequest { $0.chain(.required, association) } + } + + /// 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.LeftAssociated == RightAssociated + { + return mapRequest { $0.chain(.optional, association.select([])) } + } + + /// 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.LeftAssociated == RightAssociated + { + return mapRequest { $0.chain(.required, association.select([])) } + } +} diff --git a/GRDB/QueryInterface/Association/AssociationMapping.swift b/GRDB/QueryInterface/Association/AssociationMapping.swift new file mode 100644 index 000000000..a75c01494 --- /dev/null +++ b/GRDB/QueryInterface/Association/AssociationMapping.swift @@ -0,0 +1,23 @@ +public typealias AssociationMapping = (SQLTableQualifier, SQLTableQualifier) -> SQLExpression? + +enum AssociationMappingRequest { + case foreignKey(request: ForeignKeyRequest, originIsLeft: Bool) + + func fetch(_ db: Database) throws -> AssociationMapping { + switch self { + case .foreignKey(request: let foreignKeyRequest, originIsLeft: let originIsLeft): + 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 { (leftQualifier, rightQualifier) in + return columnMapping + .map { $0.right.qualifiedExpression(with: rightQualifier) == $0.left.qualifiedExpression(with: leftQualifier) } + .joined(operator: .and) + } + } + } +} diff --git a/GRDB/QueryInterface/Association/AssociationQuery.swift b/GRDB/QueryInterface/Association/AssociationQuery.swift new file mode 100644 index 000000000..c89a1b25b --- /dev/null +++ b/GRDB/QueryInterface/Association/AssociationQuery.swift @@ -0,0 +1,139 @@ +struct AssociationQuery { + var source: SQLSource + var selection: [SQLSelectable] + var filterPromise: DatabasePromise + var ordering: QueryOrdering + var joins: [AssociationJoin] + + var qualifier: SQLTableQualifier? { + return source.qualifier + } + + var allQualifiers: [SQLTableQualifier] { + var qualifiers: [SQLTableQualifier] = [] + if let qualifier = qualifier { + qualifiers.append(qualifier) + } + qualifiers.append(contentsOf: joins.flatMap { $0.rightQuery.allQualifiers }) + return qualifiers + } + + var preparedQuery: AssociationQuery { + var qualifier = SQLTableQualifier(tableName: source.tableName!) + + var query = self + query.source = query.source.qualified(with: &qualifier) + query.selection = selection.map { $0.qualifiedSelectable(with: qualifier) } + query.filterPromise = filterPromise.map { [qualifier] (_, expr) in expr?.qualifiedExpression(with: qualifier) } + query.ordering = ordering.qualified(with: qualifier) + query.joins = joins.map { + var join = $0 + join.rightQuery = join.rightQuery.preparedQuery + return join + } + return query + } + + var completeSelection: [SQLSelectable] { + return joins.reduce(into: selection) { + $0.append(contentsOf: $1.rightQuery.completeSelection) + } + } + + var completeOrdering: QueryOrdering { + return joins.reduce(ordering) { + $0.appending($1.rightQuery.completeOrdering) + } + } + + func rowAdapter(_ 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 join in joins { + if let (joinAdapter, joinEndIndex) = try join.rightQuery.rowAdapter(db, fromIndex: endIndex, forKeyPath: keyPath + [join.key]) { + GRDBPrecondition(scopes[join.key] == nil, "The association key \"\((keyPath + [join.key]).joined(separator: "."))\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") + scopes[join.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 { + init(_ query: QueryInterfaceQuery) { + GRDBPrecondition(!query.isDistinct, "Not implemented: join distinct queries") + GRDBPrecondition(query.groupByExpressions.isEmpty, "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 none() -> AssociationQuery { + var query = self + query.filterPromise = DatabasePromise(value: false.sqlExpression) + return query + } + + func order(_ orderings: [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 joining(_ join: AssociationJoin) -> AssociationQuery { + var query = self + query.joins.append(join) + return query + } + + func qualified(with qualifier: inout SQLTableQualifier) -> AssociationQuery { + var query = self + query.source = source.qualified(with: &qualifier) + return query + } +} diff --git a/GRDB/QueryInterface/Association/AssociationRequest.swift b/GRDB/QueryInterface/Association/AssociationRequest.swift new file mode 100644 index 000000000..0c8d54351 --- /dev/null +++ b/GRDB/QueryInterface/Association/AssociationRequest.swift @@ -0,0 +1,56 @@ +/// In `SELECT a.*, b.* FROM a JOIN b ON b.aid = a.id AND b.name = 'foo'`, +/// the AssociationRequest is (`b.*` + `b.name = 'foo'`). +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 none() -> AssociationRequest { + return AssociationRequest(query: query.none()) + } + + func order(_ orderings: [SQLOrderingTerm]) -> AssociationRequest { + return AssociationRequest(query: query.order(orderings)) + } + + func reversed() -> AssociationRequest { + return AssociationRequest(query: query.reversed()) + } + + func aliased(_ alias: TableAlias) -> AssociationRequest { + let userProvidedAlias = alias.userProvidedAlias + defer { + // Allow user to explicitely rename (TODO: test) + alias.userProvidedAlias = userProvidedAlias + } + return AssociationRequest(query: query.qualified(with: &alias.qualifier)) + } + + func chain(_ chainOp: AssociationChainOperator, _ association: A) + -> AssociationRequest + where A.LeftAssociated == T + { + let join = AssociationJoin( + op: chainOp, + rightQuery: association.request.query, + key: association.key, + associationMapping: association.associationMapping) + return AssociationRequest(query: query.joining(join)) + } +} diff --git a/GRDB/QueryInterface/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Association/BelongsToAssociation.swift new file mode 100644 index 000000000..fbcc82e8d --- /dev/null +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -0,0 +1,71 @@ +public struct BelongsToAssociation : Association, TableRequest where + Left: TableRecord, + Right: TableRecord +{ + public typealias LeftAssociated = Left + public typealias RightAssociated = Right + + public var key: String + + // :nodoc: + public var databaseTableName: String { return RightAssociated.databaseTableName } + + // :nodoc: + public let request: AssociationRequest + + let foreignKeyRequest: ForeignKeyRequest + + public func forKey(_ key: String) -> BelongsToAssociation { + return BelongsToAssociation( + key: key, + request: request, + foreignKeyRequest: foreignKeyRequest) + } + + // :nodoc: + public func associationMapping(_ db: Database) throws -> AssociationMapping { + return try AssociationMappingRequest + .foreignKey(request: foreignKeyRequest, originIsLeft: true) + .fetch(db) + } + + // :nodoc: + public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> BelongsToAssociation { + return BelongsToAssociation( + key: key, + request: transform(request), + foreignKeyRequest: foreignKeyRequest) + } +} + +extension TableRecord { + // TODO: Make it public if and only if we really want to build an association from any request + static func belongsTo( + _ rightRequest: QueryInterfaceRequest, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> BelongsToAssociation + where Right: TableRecord + { + let foreignKeyRequest = ForeignKeyRequest( + originTable: databaseTableName, + destinationTable: Right.databaseTableName, + foreignKey: foreignKey) + + return BelongsToAssociation( + key: key ?? defaultAssociationKey(for: Right.self), + request: AssociationRequest(rightRequest), + foreignKeyRequest: foreignKeyRequest) + } + + /// TODO + public static func belongsTo( + _ right: Right.Type, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> BelongsToAssociation + where Right: TableRecord + { + return belongsTo(Right.all(), key: key, using: foreignKey) + } +} diff --git a/GRDB/QueryInterface/Association/ForeignKey.swift b/GRDB/QueryInterface/Association/ForeignKey.swift new file mode 100644 index 000000000..c509202b7 --- /dev/null +++ b/GRDB/QueryInterface/Association/ForeignKey.swift @@ -0,0 +1,16 @@ +/// A Foreign Key that helps building associations. +public struct ForeignKey { + let originColumns: [String] + let destinationColumns: [String]? + + /// TODO + public init(_ originColumns: [String], to destinationColumns: [String]? = nil) { + self.originColumns = originColumns + self.destinationColumns = destinationColumns + } + + /// TODO + public init(_ originColumns: [Column], to destinationColumns: [Column]? = nil) { + self.init(originColumns.map { $0.name }, to: destinationColumns?.map { $0.name }) + } +} diff --git a/GRDB/QueryInterface/Association/ForeignKeyRequest.swift b/GRDB/QueryInterface/Association/ForeignKeyRequest.swift new file mode 100644 index 000000000..a7fb3a325 --- /dev/null +++ b/GRDB/QueryInterface/Association/ForeignKeyRequest.swift @@ -0,0 +1,86 @@ +/// ForeignKeyRequest looks for the foreign keys associations need to +/// join tables. +/// +/// Mappings come from foreign keys, when they exist in the database schema. +/// +/// When the schema does not define any foreign key, we can still infer complete +/// mappings from partial information and primary keys. +struct ForeignKeyRequest { + let originTable: String + let destinationTable: String + let originColumns: [String]? + let destinationColumns: [String]? + + init(originTable: String, destinationTable: String, foreignKey: ForeignKey?) { + self.originTable = originTable + self.destinationTable = destinationTable + + self.originColumns = foreignKey?.originColumns + self.destinationColumns = foreignKey?.destinationColumns + } + + func fetch(_ db: Database) throws -> ForeignKeyInfo { + if let originColumns = originColumns, let destinationColumns = destinationColumns { + // Total information: no need to query the database schema. + GRDBPrecondition(originColumns.count == destinationColumns.count, "Number of columns don't match") + let mapping = zip(originColumns, destinationColumns).map { + (origin: $0, destination: $1) + } + return ForeignKeyInfo(destinationTable: destinationTable, mapping: mapping) + } + + // Incomplete information: let's look for schema foreign keys + let foreignKeys = try db.foreignKeys(on: originTable).filter { foreignKey in + if destinationTable.lowercased() != foreignKey.destinationTable.lowercased() { + return false + } + if let originColumns = originColumns { + let originColumns = Set(originColumns.lazy.map { $0.lowercased() }) + let foreignKeyColumns = Set(foreignKey.mapping.lazy.map { $0.origin.lowercased() }) + if originColumns != foreignKeyColumns { + return false + } + } + // TODO: test + if let destinationColumns = destinationColumns { + let destinationColumns = Set(destinationColumns.lazy.map { $0.lowercased() }) + let foreignKeyColumns = Set(foreignKey.mapping.lazy.map { $0.destination.lowercased() }) + if destinationColumns != foreignKeyColumns { + return false + } + } + return true + } + + // Matching foreign key(s) found + if let foreignKey = foreignKeys.first { + if foreignKeys.count == 1 { + // Non-ambiguous + // TODO: test + return foreignKey + } else { + // Ambiguous: can't choose + fatalError("Ambiguous foreign key from \(originTable) to \(destinationTable)") + } + } + + // No matching foreign key found: use the destination primary key + if let originColumns = originColumns { + let destinationColumns = try db.primaryKey(destinationTable).columns + if (originColumns.count == destinationColumns.count) { + // TODO: test + let mapping = zip(originColumns, destinationColumns).map { + (origin: $0, destination: $1) + } + return ForeignKeyInfo(destinationTable: destinationTable, mapping: mapping) + } + } + + fatalError("Could not infer foreign key from \(originTable) to \(destinationTable)") + } +} + + +/// The (origin, destination) column pairs that join a left table to a right table. +/// :nodoc: +typealias ForeignKeyMapping = [(origin: String, destination: String)] diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift new file mode 100644 index 000000000..8653413c2 --- /dev/null +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -0,0 +1,71 @@ +public struct HasManyAssociation : Association, TableRequest where + Left: TableRecord, + Right: TableRecord +{ + public typealias LeftAssociated = Left + public typealias RightAssociated = Right + + public var key: String + + // :nodoc: + public var databaseTableName: String { return RightAssociated.databaseTableName } + + // :nodoc: + public let request: AssociationRequest + + let foreignKeyRequest: ForeignKeyRequest + + public func forKey(_ key: String) -> HasManyAssociation { + return HasManyAssociation( + key: key, + request: request, + foreignKeyRequest: foreignKeyRequest) + } + + // :nodoc: + public func associationMapping(_ db: Database) throws -> AssociationMapping { + return try AssociationMappingRequest + .foreignKey(request: foreignKeyRequest, originIsLeft: false) + .fetch(db) + } + + // :nodoc: + public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasManyAssociation { + return HasManyAssociation( + key: key, + request: transform(request), + foreignKeyRequest: foreignKeyRequest) + } +} + +extension TableRecord { + // TODO: Make it public if and only if we really want to build an association from any request + static func hasMany( + _ rightRequest: QueryInterfaceRequest, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasManyAssociation + where Right: TableRecord + { + let foreignKeyRequest = ForeignKeyRequest( + originTable: Right.databaseTableName, + destinationTable: databaseTableName, + foreignKey: foreignKey) + + return HasManyAssociation( + key: key ?? defaultAssociationKey(for: Right.self), + request: AssociationRequest(rightRequest), + foreignKeyRequest: foreignKeyRequest) + } + + /// TODO + public static func hasMany( + _ right: Right.Type, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasManyAssociation + where Right: TableRecord + { + return hasMany(Right.all(), key: key, using: foreignKey) + } +} diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift new file mode 100644 index 000000000..0a7f4b85f --- /dev/null +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -0,0 +1,71 @@ +public struct HasOneAssociation : Association, TableRequest where + Left: TableRecord, + Right: TableRecord +{ + public typealias LeftAssociated = Left + public typealias RightAssociated = Right + + public var key: String + + // :nodoc: + public var databaseTableName: String { return RightAssociated.databaseTableName } + + // :nodoc: + public let request: AssociationRequest + + let foreignKeyRequest: ForeignKeyRequest + + public func forKey(_ key: String) -> HasOneAssociation { + return HasOneAssociation( + key: key, + request: request, + foreignKeyRequest: foreignKeyRequest) + } + + // :nodoc: + public func associationMapping(_ db: Database) throws -> AssociationMapping { + return try AssociationMappingRequest + .foreignKey(request: foreignKeyRequest, originIsLeft: false) + .fetch(db) + } + + // :nodoc: + public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasOneAssociation { + return HasOneAssociation( + key: key, + request: transform(request), + foreignKeyRequest: foreignKeyRequest) + } +} + +extension TableRecord { + // TODO: Make it public if and only if we really want to build an association from any request + static func hasOne( + _ rightRequest: QueryInterfaceRequest, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasOneAssociation + where Right: TableRecord + { + let foreignKeyRequest = ForeignKeyRequest( + originTable: Right.databaseTableName, + destinationTable: databaseTableName, + foreignKey: foreignKey) + + return HasOneAssociation( + key: key ?? defaultAssociationKey(for: Right.self), + request: AssociationRequest(rightRequest), + foreignKeyRequest: foreignKeyRequest) + } + + /// TODO + public static func hasOne( + _ right: Right.Type, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasOneAssociation + where Right: TableRecord + { + return hasOne(Right.all(), key: key, using: foreignKey) + } +} diff --git a/GRDB/QueryInterface/Column.swift b/GRDB/QueryInterface/Column.swift index cd6ecb5c0..26010d442 100644 --- a/GRDB/QueryInterface/Column.swift +++ b/GRDB/QueryInterface/Column.swift @@ -37,6 +37,12 @@ extension ColumnExpression { public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { return QualifiedColumn(name, qualifier: qualifier) } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return self + } } /// A column in a database table. @@ -70,7 +76,7 @@ struct QualifiedColumn: ColumnExpression { } func expressionSQL(_ arguments: inout StatementArguments?) -> String { - if let qualifierName = qualifier.name { + if let qualifierName = qualifier.qualifiedName { return qualifierName.quotedDatabaseIdentifier + "." + name.quotedDatabaseIdentifier } return name.quotedDatabaseIdentifier @@ -80,6 +86,16 @@ struct QualifiedColumn: ColumnExpression { // Never requalify return self } + + func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + guard + let container = context[qualifier], + let value = container.value(forCaseInsensitiveColumn: name) else + { + return self + } + return value + } } /// Support for column enums: diff --git a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift index 171b12868..6e2d37356 100644 --- a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift @@ -12,13 +12,7 @@ extension QueryInterfaceRequest { /// If the search pattern is nil, the request does not match any /// database row. public func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest { - switch query.source { - case .table(let name, let alias)?: - return filter(SQLExpressionBinary(.match, Column(alias ?? name), pattern ?? DatabaseValue.null)) - default: - // Programmer error - fatalError("fts3 match requires a table") - } + return filter(Column(query.source.qualifiedName).match(pattern)) } } diff --git a/GRDB/QueryInterface/FTS5+QueryInterface.swift b/GRDB/QueryInterface/FTS5+QueryInterface.swift index 0394a5450..fcc29e883 100644 --- a/GRDB/QueryInterface/FTS5+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS5+QueryInterface.swift @@ -17,17 +17,10 @@ /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. public func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest { - switch query.source { - case .table(let name, let alias)?: - if let pattern = pattern { - return filter(SQLExpressionBinary(.match, Column(alias ?? name), pattern)) - } else { - return filter(false) - } - default: - // Programmer error - fatalError("fts5 match requires a table") + guard let pattern = pattern else { + return none() } + return filter(SQLExpressionBinary(.match, Column(query.source.qualifiedName), pattern)) } } diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index 2c3cfbec4..8999861c2 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -17,39 +17,36 @@ struct DatabasePromise { } struct QueryInterfaceQuery { + var source: SQLSource var selection: [SQLSelectable] var isDistinct: Bool - var source: SQLSource? - var wherePromise: DatabasePromise + var filterPromise: DatabasePromise var groupByExpressions: [SQLExpression] var ordering: QueryOrdering var havingExpression: SQLExpression? var limit: SQLLimit? + var joins: [AssociationJoin] init( - select selection: [SQLSelectable], + source: SQLSource, + selection: [SQLSelectable] = [], isDistinct: Bool = false, - from source: SQLSource? = nil, - filter whereExpression: SQLExpression? = nil, - groupBy groupByExpressions: [SQLExpression] = [], - orderBy ordering: QueryOrdering = QueryOrdering(), - having havingExpression: SQLExpression? = nil, - limit: SQLLimit? = nil) + filterPromise: DatabasePromise = DatabasePromise(value: nil), + groupByExpressions: [SQLExpression] = [], + ordering: QueryOrdering = QueryOrdering(), + havingExpression: SQLExpression? = nil, + limit: SQLLimit? = nil, + joins: [AssociationJoin] = []) { + self.source = source self.selection = selection self.isDistinct = isDistinct - self.source = source - self.wherePromise = DatabasePromise(value: whereExpression) + self.filterPromise = filterPromise self.groupByExpressions = groupByExpressions self.ordering = ordering self.havingExpression = havingExpression self.limit = limit - } - - func mapWhereExpression(_ transform: @escaping (Database, SQLExpression?) throws -> SQLExpression?) -> QueryInterfaceQuery { - var query = self - query.wherePromise = query.wherePromise.map(transform) - return query + self.joins = joins } func sql(_ db: Database, _ arguments: inout StatementArguments?) throws -> String { @@ -59,15 +56,18 @@ struct QueryInterfaceQuery { sql += " DISTINCT" } - assert(!selection.isEmpty) + let selection = completeSelection + GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") sql += " " + selection.map { $0.resultColumnSQL(&arguments) }.joined(separator: ", ") - if let source = source { - sql += try " FROM " + source.sourceSQL(db, &arguments) + sql += try " FROM " + source.sourceSQL(db, &arguments) + + for join in joins { + sql += try " " + join.joinSQL(db, &arguments, leftQualifier: qualifier!) } - if let whereExpression = try wherePromise.resolve(db) { - sql += " WHERE " + whereExpression.expressionSQL(&arguments) + if let filter = try filterPromise.resolve(db) { + sql += " WHERE " + filter.expressionSQL(&arguments) } if !groupByExpressions.isEmpty { @@ -78,7 +78,7 @@ struct QueryInterfaceQuery { sql += " HAVING " + havingExpression.expressionSQL(&arguments) } - let orderings = self.ordering.resolve() + let orderings = completeOrdering.resolve() if !orderings.isEmpty { sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&arguments) }.joined(separator: ", ") } @@ -93,27 +93,35 @@ struct QueryInterfaceQuery { func makeDeleteStatement(_ db: Database) throws -> UpdateStatement { guard groupByExpressions.isEmpty else { // Programmer error - fatalError("Can't delete query with GROUP BY expression") + fatalError("Can't delete query with GROUP BY clause") } guard havingExpression == nil else { // Programmer error - fatalError("Can't delete query with GROUP BY expression") + 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 sql = "DELETE" var arguments: StatementArguments? = StatementArguments() - if let source = source { - sql += try " FROM " + source.sourceSQL(db, &arguments) - } + sql += try " FROM " + source.sourceSQL(db, &arguments) - if let whereExpression = try wherePromise.resolve(db) { - sql += " WHERE " + whereExpression.expressionSQL(&arguments) + if let filter = try filterPromise.resolve(db) { + sql += " WHERE " + filter.expressionSQL(&arguments) } if let limit = limit { - let orderings = self.ordering.resolve() + let orderings = self.completeOrdering.resolve() if !orderings.isEmpty { sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&arguments) }.joined(separator: ", ") } @@ -136,15 +144,102 @@ struct QueryInterfaceQuery { query.ordering = QueryOrdering() return query } + + // MARK: Join Support + + var completeSelection: [SQLSelectable] { + return joins.reduce(into: selection) { + $0.append(contentsOf: $1.rightQuery.completeSelection) + } + } + + var completeOrdering: QueryOrdering { + return joins.reduce(ordering) { + $0.appending($1.rightQuery.completeOrdering) + } + } + + var qualifier: SQLTableQualifier? { + return source.qualifier + } + + var allQualifiers: [SQLTableQualifier] { + var qualifiers: [SQLTableQualifier] = [] + if let qualifier = source.qualifier { + qualifiers.append(qualifier) + } + qualifiers.append(contentsOf: joins.flatMap { $0.rightQuery.allQualifiers }) + return qualifiers + } } extension QueryInterfaceQuery { - func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { + private var preparedQuery: QueryInterfaceQuery { + var query = self + + if !joins.isEmpty { + var qualifier = SQLTableQualifier(tableName: query.source.tableName!) + query.source = source.qualified(with: &qualifier) + } + + if let qualifier = query.qualifier { + query.selection = query.selection.map { $0.qualifiedSelectable(with: qualifier) } + query.filterPromise = query.filterPromise.map { [qualifier] (_, expr) in expr?.qualifiedExpression(with: qualifier) } + query.groupByExpressions = query.groupByExpressions.map { $0.qualifiedExpression(with: qualifier) } + query.ordering = query.ordering.qualified(with: qualifier) + query.havingExpression = query.havingExpression?.qualifiedExpression(with: qualifier) + } + + query.joins = query.joins.map { + var join = $0 + join.rightQuery = join.rightQuery.preparedQuery + return join + } + + query.allQualifiers.resolveAmbiguities() + return query + } + + /// precondition: self is the result of preparedQuery + private func makeSelectStatement(_ db: Database) throws -> SelectStatement { var arguments: StatementArguments? = StatementArguments() - let sql = try self.sql(db, &arguments) + let sql = try preparedQuery.sql(db, &arguments) let statement = try db.makeSelectStatement(sql) try statement.setArgumentsWithValidation(arguments!) - return (statement, nil) + return statement + } + + /// precondition: self is the result of preparedQuery + private func rowAdapter(_ 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 join in joins { + if let (joinAdapter, joinEndIndex) = try join.rightQuery.rowAdapter(db, fromIndex: endIndex, forKeyPath: [join.key]) { + GRDBPrecondition(scopes[join.key] == nil, "The association key \"\(join.key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") + scopes[join.key] = joinAdapter + endIndex = joinEndIndex + } + } + + if selectionWidth == 0 && scopes.isEmpty { + return nil + } + + let adapter = RangeRowAdapter(0 ..< (0 + selectionWidth)) + return adapter.addingScopes(scopes) + } + + func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { + let query = preparedQuery + return try (query.makeSelectStatement(db), query.rowAdapter(db)) } func fetchCount(_ db: Database) throws -> Int { @@ -154,16 +249,14 @@ extension QueryInterfaceQuery { /// The database region that the request looks into. func fetchedRegion(_ db: Database) throws -> DatabaseRegion { - let (statement, _) = try prepare(db) + let statement = try preparedQuery.makeSelectStatement(db) let region = statement.fetchedRegion // Can we intersect the region with rowIds? // // Give up unless request feeds from a single database table - guard let source = source else { - return region - } - guard case .table(name: let tableName, alias: _) = source else { + guard joins.isEmpty, case .table(tableName: let tableName, qualifier: _) = source else { + // TODO: try harder return region } @@ -174,12 +267,12 @@ extension QueryInterfaceQuery { } // Give up unless there is a where clause - guard let whereExpression = try wherePromise.resolve(db) else { + guard let filter = try filterPromise.resolve(db) else { return region } - // The whereExpression knows better - guard let rowIds = whereExpression.matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else { + // The filter knows better + guard let rowIds = filter.matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else { return region } @@ -195,12 +288,12 @@ extension QueryInterfaceQuery { return trivialCountQuery } - guard let source = source, case .table = source else { - // SELECT ... FROM (something which is not a table) + guard joins.isEmpty, case .table = source else { + // SELECT ... FROM (something which is not a plain table) return trivialCountQuery } - assert(!selection.isEmpty) + 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 @@ -228,59 +321,290 @@ extension QueryInterfaceQuery { // SELECT COUNT(*) FROM (self) private var trivialCountQuery: QueryInterfaceQuery { return QueryInterfaceQuery( - select: [SQLExpressionCount(AllColumns())], - from: .query(query: unorderedQuery, alias: nil)) + source: .query(unorderedQuery), + selection: [SQLExpressionCount(AllColumns())]) } } +extension QueryInterfaceQuery { + func select(_ selection: [SQLSelectable]) -> QueryInterfaceQuery { + var query = self + query.selection = 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 none() -> QueryInterfaceQuery { + var query = self + query.filterPromise = DatabasePromise(value: false.sqlExpression) + return query + } + + func group(_ expressions: [SQLExpressible]) -> QueryInterfaceQuery { + var query = self + query.groupByExpressions = expressions.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: [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 limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceQuery { + var query = self + query.limit = SQLLimit(limit: limit, offset: offset) + return query + } + + func joining(_ join: AssociationJoin) -> QueryInterfaceQuery { + var query = self + query.joins.append(join) + return query + } + + func qualified(with qualifier: inout SQLTableQualifier) -> QueryInterfaceQuery { + var query = self + query.source = source.qualified(with: &qualifier) + return query + } +} + +extension QueryInterfaceQuery { + init(_ query: AssociationQuery) { + self.init( + source: query.source, + selection: query.selection, + filterPromise: query.filterPromise, + ordering: query.ordering, + joins: query.joins) + } +} + +// MARK: - AssociationJoin + +struct AssociationJoin { + var op: AssociationChainOperator + var rightQuery: AssociationQuery + var key: String + var associationMapping: (Database) throws -> AssociationMapping + + func joinSQL(_ db: Database,_ arguments: inout StatementArguments?, leftQualifier: SQLTableQualifier) throws -> String { + var sql = "" + switch op { + case .optional: sql += "LEFT JOIN" + case .required: sql += "JOIN" + } + + let rightQualifier = rightQuery.qualifier! + + sql += try " " + rightQuery.source.sourceSQL(db, &arguments) + + let filters = try [ + associationMapping(db)(leftQualifier, rightQualifier), + rightQuery.filterPromise.resolve(db) + ].compactMap { $0 } + if !filters.isEmpty { + sql += " ON " + filters.joined(operator: .and).expressionSQL(&arguments) + } + + for join in rightQuery.joins { + sql += try " " + join.joinSQL(db, &arguments, leftQualifier: rightQualifier) + } + + return sql + } +} + +// MARK: - QueryOrdering + struct QueryOrdering { - private var orderings: [SQLOrderingTerm] + private var elements: [Element] = [] var isReversed: Bool - init(orderings: [SQLOrderingTerm] = [], isReversed: Bool = false) { - self.orderings = orderings + private enum Element { + case orderingTerm(SQLOrderingTerm) + case queryOrdering(QueryOrdering) + + var reversed: Element { + switch self { + case .orderingTerm(let orderingTerm): + return .orderingTerm(orderingTerm.reversed) + case .queryOrdering(let queryOrdering): + return .queryOrdering(queryOrdering.reversed) + } + } + + func qualified(with qualifier: SQLTableQualifier) -> Element { + switch self { + case .orderingTerm(let orderingTerm): + return .orderingTerm(orderingTerm.qualifiedOrdering(with: qualifier)) + case .queryOrdering(let queryOrdering): + return .queryOrdering(queryOrdering.qualified(with: qualifier)) + } + } + + func resolve() -> [SQLOrderingTerm] { + switch self { + case .orderingTerm(let orderingTerm): + return [orderingTerm] + case .queryOrdering(let queryOrdering): + return queryOrdering.resolve() + } + } + } + + private init(elements: [Element], isReversed: Bool) { + self.elements = elements self.isReversed = isReversed } - func reversed() -> QueryOrdering { + init() { + self.init( + elements: [], + isReversed: false) + } + + init(orderings: [SQLOrderingTerm]) { + self.init( + elements: orderings.map { .orderingTerm($0) }, + isReversed: false) + } + + var reversed: QueryOrdering { return QueryOrdering( - orderings: orderings, + elements: elements, isReversed: !isReversed) } - func appending(ordering: SQLOrderingTerm) -> QueryOrdering { + func qualified(with qualifier: SQLTableQualifier) -> QueryOrdering { return QueryOrdering( - orderings: orderings + [ordering], + elements: elements.map { $0.qualified(with: qualifier) }, + isReversed: isReversed) + } + + func appending(_ ordering: QueryOrdering) -> QueryOrdering { + return QueryOrdering( + elements: elements + [.queryOrdering(ordering)], isReversed: isReversed) } func resolve() -> [SQLOrderingTerm] { if isReversed { - return orderings.map { $0.reversed } + return elements.flatMap { $0.reversed.resolve() } } else { - return orderings + return elements.flatMap { $0.resolve() } } } } -indirect enum SQLSource { - case table(name: String, alias: String?) - case query(query: QueryInterfaceQuery, alias: String?) +// MARK: - SQLSource + +enum SQLSource { + case table(tableName: String, qualifier: SQLTableQualifier?) + indirect case query(QueryInterfaceQuery) - func sourceSQL(_ db: Database, _ arguments: inout StatementArguments?) throws -> String { + var qualifier: SQLTableQualifier? { switch self { - case .table(let table, let alias): - if let alias = alias { - return table.quotedDatabaseIdentifier + " AS " + alias.quotedDatabaseIdentifier + case .table(_, let qualifier): + return qualifier + case .query(let query): + return query.qualifier + } + } + + /// An alias or an actual table name + var qualifiedName: String { + switch self { + case .table(let tableName, let qualifier): + return qualifier?.qualifiedName ?? tableName + case .query(let query): + return query.source.qualifiedName + } + } + + /// An actual table name, not an alias + var tableName: String? { + switch self { + case .table(let tableName, _): + return tableName + case .query(let query): + return query.source.tableName + } + } + + func sourceSQL(_ db: Database,_ arguments: inout StatementArguments?) throws -> String { + switch self { + case .table(let tableName, let qualifier): + if let alias = qualifier?.alias, alias != tableName { + return "\(tableName.quotedDatabaseIdentifier) \(alias.quotedDatabaseIdentifier)" } else { - return table.quotedDatabaseIdentifier + return "\(tableName.quotedDatabaseIdentifier)" } - case .query(let query, let alias): - if let alias = alias { - return try "(" + query.sql(db, &arguments) + ") AS " + alias.quotedDatabaseIdentifier + case .query(let query): + return try "(\(query.sql(db, &arguments)))" + } + } + + func qualified(with qualifier: inout SQLTableQualifier) -> SQLSource { + switch self { + case .table(let tableName, let oldQualifier): + if let oldQualifier = oldQualifier { + qualifier = oldQualifier + return self + } else if let qualifierTableName = qualifier.tableName { + if qualifierTableName == tableName { // TODO: should this test be case-insensitive? + return .table( + tableName: tableName, + qualifier: qualifier) + } else { + // TODO: how to enter this branch? Is it useful? + return self + } } else { - return try "(" + query.sql(db, &arguments) + ")" + qualifier.tableName = tableName + return .table( + tableName: tableName, + qualifier: qualifier) } + case .query(let query): + return .query(query.qualified(with: &qualifier)) } } } diff --git a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift new file mode 100644 index 000000000..296d0bb19 --- /dev/null +++ b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift @@ -0,0 +1,139 @@ +extension QueryInterfaceRequest where RowDecoder: TableRecord { + func chain(_ chainOp: AssociationChainOperator, _ association: A) + -> QueryInterfaceRequest + where A.LeftAssociated == RowDecoder + { + let join = AssociationJoin( + op: chainOp, + rightQuery: association.request.query, + key: association.key, + associationMapping: association.associationMapping) + return QueryInterfaceRequest(query: query.joining(join)) + } + + // 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.LeftAssociated == RowDecoder + { + return chain(.optional, association) + } + + /// 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.LeftAssociated == RowDecoder + { + return chain(.required, association) + } + + /// 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.LeftAssociated == RowDecoder + { + return chain(.optional, association.select([])) + } + + /// 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.LeftAssociated == RowDecoder + { + return chain(.required, association.select([])) + } +} + +extension Association where LeftAssociated: MutablePersistableRecord { + func request(from record: LeftAssociated) -> QueryInterfaceRequest { + var query = request.query.preparedQuery // make sure query has a qualifier + let qualifier = query.source.qualifier! + let recordQualifier = SQLTableQualifier.init(tableName: LeftAssociated.databaseTableName) + + query = query.filter { db in + let associationMapping = try self.associationMapping(db) + guard let filter = associationMapping(recordQualifier, qualifier) else { + fatalError("Can't request from record without association mapping") + } + let container = PersistenceContainer(record) + return filter.resolvedExpression(inContext: [recordQualifier: container]) + } + + return QueryInterfaceRequest(query: QueryInterfaceQuery(query)) + } +} + +extension MutablePersistableRecord { + /// Creates a request that fetches the associated record(s). + /// + /// For example: + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// let player: Player = ... + /// let request = player.request(for: Player.team) + /// let team = try request.fetchOne(db) // Team? + public func request(for association: A) + -> QueryInterfaceRequest + where A.LeftAssociated == Self + { + return association.request(from: self) + } +} + +extension TableRecord { + + // 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 static func including(optional association: A) + -> QueryInterfaceRequest + where A.LeftAssociated == Self + { + return all().including(optional: association) + } + + /// 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 static func including(required association: A) + -> QueryInterfaceRequest + where A.LeftAssociated == Self + { + return all().including(required: association) + } + + /// 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 static func joining(optional association: A) + -> QueryInterfaceRequest + where A.LeftAssociated == Self + { + return all().joining(optional: association) + } + + /// 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 static func joining(required association: A) + -> QueryInterfaceRequest + where A.LeftAssociated == Self + { + return all().joining(required: association) + } +} diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index ac29e72a4..7c3ee6d17 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -56,9 +56,7 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating /// .select([Column("id")]) /// .select([Column("email")]) public func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest { - var query = self.query - query.selection = selection - return QueryInterfaceRequest(query: query) + return QueryInterfaceRequest(query: query.select(selection)) } /// Creates a request which returns distinct rows. @@ -71,25 +69,17 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating /// var request = Player.select(Column("name")) /// request = request.distinct() public func distinct() -> QueryInterfaceRequest { - var query = self.query - query.isDistinct = true - return QueryInterfaceRequest(query: query) + return QueryInterfaceRequest(query: query.distinct()) } - /// Creates a request with the provided *predicate* added to the + /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. /// - /// // SELECT * FROM players WHERE email = 'arthur@example.com' + /// // SELECT * FROM players WHERE 1 /// var request = Player.all() - /// request = request.filter(Column("email") == "arthur@example.com") - public func filter(_ predicate: SQLExpressible) -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in - if let expression = expression { - return expression && predicate.sqlExpression - } else { - return predicate.sqlExpression - } - }) + /// request = request.filter { db in true } + public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { + return QueryInterfaceRequest(query: query.filter(predicate)) } /// Creates a request that matches nothing. @@ -98,28 +88,18 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating /// var request = Player.all() /// request = request.none() public func none() -> QueryInterfaceRequest { - var query = self.query - query.wherePromise = DatabasePromise(value: false.sqlExpression) - return QueryInterfaceRequest(query: query) + return QueryInterfaceRequest(query: query.none()) } /// Creates a request grouped according to *expressions*. public func group(_ expressions: [SQLExpressible]) -> QueryInterfaceRequest { - var query = self.query - query.groupByExpressions = expressions.map { $0.sqlExpression } - return QueryInterfaceRequest(query: query) + return QueryInterfaceRequest(query: query.group(expressions)) } /// Creates a request with the provided *predicate* added to the /// eventual set of already applied predicates. public func having(_ predicate: SQLExpressible) -> QueryInterfaceRequest { - var query = self.query - if let havingExpression = query.havingExpression { - query.havingExpression = (havingExpression && predicate).sqlExpression - } else { - query.havingExpression = predicate.sqlExpression - } - return QueryInterfaceRequest(query: query) + return QueryInterfaceRequest(query: query.having(predicate)) } /// Creates a request with the provided *orderings*. @@ -136,9 +116,7 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating /// .reversed() /// .order([Column("name")]) public func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest { - var query = self.query - query.ordering = QueryOrdering(orderings: orderings) - return QueryInterfaceRequest(query: query) + return QueryInterfaceRequest(query: query.order(orderings)) } /// Creates a request sorted in reversed order. @@ -147,9 +125,7 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating /// var request = Player.all().order(Column("name")) /// request = request.reversed() public func reversed() -> QueryInterfaceRequest { - var query = self.query - query.ordering = query.ordering.reversed() - return QueryInterfaceRequest(query: query) + return QueryInterfaceRequest(query: query.reversed()) } /// Creates a request which fetches *limit* rows, starting at *offset*. @@ -160,127 +136,40 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating /// /// Any previous limit is replaced. public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { - var query = self.query - query.limit = SQLLimit(limit: limit, offset: offset) - return QueryInterfaceRequest(query: query) + return QueryInterfaceRequest(query: query.limit(limit, offset: offset)) + } + + /// Creates a request that allows you to define unambiguous expressions + /// based on the fetched record. + /// + /// In the example below, the "team.avgScore < player.score" condition in + /// the ON clause could be not achieved without table aliases. + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // SELECT player.*, team.* + /// // JOIN team ON ... AND team.avgScore < player.score + /// let playerAlias = TableAlias() + /// let request = Player + /// .all() + /// .aliased(playerAlias) + /// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")]) + public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { + let userProvidedAlias = alias.userProvidedAlias + defer { + // Allow user to explicitely rename (TODO: test) + alias.userProvidedAlias = userProvidedAlias + } + return QueryInterfaceRequest(query: query.qualified(with: &alias.qualifier)) } } -extension QueryInterfaceRequest where T: TableRecord { - - // MARK: Request Derivation - - /// Creates a request with the provided primary key *predicate*. - /// - /// // SELECT * FROM players WHERE id = 1 - /// var request = Player.all() - /// request = request.filter(key: 1) - /// - /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableRecord.databaseSelection` property, or - /// for individual requests with the `TableRecord.select` method. - public func filter(key: PrimaryKeyType?) -> QueryInterfaceRequest { - guard let key = key else { - return T.none() - } - - return filter(keys: [key]) - } - - /// Creates a request with the provided primary key *predicate*. - /// - /// // SELECT * FROM players WHERE id IN (1, 2, 3) - /// var request = Player.all() - /// request = request.filter(keys: [1, 2, 3]) - /// - /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableRecord.databaseSelection` property, or - /// for individual requests with the `TableRecord.select` method. - public func filter(keys: Sequence) -> QueryInterfaceRequest where Sequence.Element: DatabaseValueConvertible { - let keys = Array(keys) - let makePredicate: (Column) -> SQLExpression - switch keys.count { - case 0: - return T.none() - case 1: - makePredicate = { $0 == keys[0] } - default: - makePredicate = { keys.contains($0) } - } - - return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in - let primaryKey = try db.primaryKey(T.databaseTableName) - GRDBPrecondition(primaryKey.columns.count == 1, "Requesting by key requires a single-column primary key in the table \(T.databaseTableName)") - let keysPredicate = makePredicate(Column(primaryKey.columns[0])) - if let expression = expression { - return expression && keysPredicate - } else { - return keysPredicate - } - }) - } - - /// Creates a request with the provided primary key *predicate*. - /// - /// // SELECT * FROM passports WHERE personId = 1 AND countryCode = 'FR' - /// var request = Player.all() - /// request = request.filter(key: ["personId": 1, "countryCode": "FR"]) - /// - /// When executed, this request raises a fatal error if there is no unique - /// index on the key columns. - /// - /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableRecord.databaseSelection` property, or - /// for individual requests with the `TableRecord.select` method. - public func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest { - guard let key = key else { - return T.none() - } - - return filter(keys: [key]) - } - - /// Creates a request with the provided primary key *predicate*. - /// - /// // SELECT * FROM passports WHERE (personId = 1 AND countryCode = 'FR') OR ... - /// let request = Passport.filter(keys: [["personId": 1, "countryCode": "FR"], ...]) - /// - /// When executed, this request raises a fatal error if there is no unique - /// index on the key columns. - /// - /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableRecord.databaseSelection` property, or - /// for individual requests with the `TableRecord.select` method. - public func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest { - guard !keys.isEmpty else { - return T.none() - } - - return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in - let keyPredicates: [SQLExpression] = try keys.map { key in - // Prevent filter(keys: [["foo": 1, "bar": 2]]) where - // ("foo", "bar") is not a unique key (primary key or columns of a - // unique index) - guard let orderedColumns = try db.columnsForUniqueKey(key.keys, in: T.databaseTableName) else { - fatalError("table \(T.databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))") - } - - let lowercaseOrderedColumns = orderedColumns.map { $0.lowercased() } - let columnPredicates: [SQLExpression] = key - // Sort key columns in the same order as the unique index - .sorted { (kv1, kv2) in lowercaseOrderedColumns.index(of: kv1.0.lowercased())! < lowercaseOrderedColumns.index(of: kv2.0.lowercased())! } - .map { (column, value) in Column(column) == value } - return columnPredicates.joined(operator: .and) - } - - let keysPredicate = keyPredicates.joined(operator: .or) - - if let expression = expression { - return expression && keysPredicate - } else { - return keysPredicate - } - }) +extension QueryInterfaceRequest: TableRequest where RowDecoder: TableRecord { + // :nodoc: + public var databaseTableName: String { + return T.databaseTableName } } @@ -314,14 +203,14 @@ extension TableRecord { /// for individual requests with the `TableRecord.select` method. public static func all() -> QueryInterfaceRequest { let query = QueryInterfaceQuery( - select: databaseSelection, - from: .table(name: databaseTableName, alias: nil)) + source: .table(tableName: databaseTableName, qualifier: nil), + selection: databaseSelection) return QueryInterfaceRequest(query: query) } /// Creates a request which fetches no record. public static func none() -> QueryInterfaceRequest { - return filter(false) + return all().none() // don't laugh } /// Creates a request which selects *selection*. @@ -476,4 +365,24 @@ extension TableRecord { public static func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { return all().limit(limit, offset: offset) } + + /// Creates a request that allows you to define unambiguous expressions + /// based on the fetched record. + /// + /// In the example below, the "team.avgScore < player.score" condition in + /// the ON clause could be not achieved without table aliases. + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // SELECT player.*, team.* + /// // JOIN team ON ... AND team.avgScore < player.score + /// let playerAlias = TableAlias() + /// let request = Player + /// .aliased(playerAlias) + /// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")]) + public static func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { + return all().aliased(alias) + } } diff --git a/GRDB/QueryInterface/RequestProtocols.swift b/GRDB/QueryInterface/RequestProtocols.swift index 4fa777d9b..84d1ede7c 100644 --- a/GRDB/QueryInterface/RequestProtocols.swift +++ b/GRDB/QueryInterface/RequestProtocols.swift @@ -55,13 +55,13 @@ extension SelectionRequest { /// The protocol for all requests that can be filtered. public protocol FilteredRequest { - /// Creates a request with the provided *predicate* added to the + /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. /// - /// // SELECT * FROM players WHERE email = 'arthur@example.com' + /// // SELECT * FROM players WHERE 1 /// var request = Player.all() - /// request = request.filter(Column("email") == "arthur@example.com") - func filter(_ predicate: SQLExpressible) -> Self + /// request = request.filter { db in true } + func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self /// Creates a request that matches nothing. /// @@ -72,6 +72,16 @@ public protocol FilteredRequest { } extension FilteredRequest { + /// Creates a request with the provided *predicate* added to the + /// eventual set of already applied predicates. + /// + /// // SELECT * FROM players WHERE email = 'arthur@example.com' + /// var request = Player.all() + /// request = request.filter(Column("email") == "arthur@example.com") + public func filter(_ predicate: SQLExpressible) -> Self { + return filter { _ in predicate } + } + /// Creates a request with the provided *predicate* added to the /// eventual set of already applied predicates. /// @@ -83,6 +93,93 @@ extension FilteredRequest { } } +// MARK: - TableRequest { + +/// The protocol for all requests that feed from a database table +public protocol TableRequest { + var databaseTableName: String { get } +} + +extension TableRequest where Self: FilteredRequest { + + /// Creates a request with the provided primary key *predicate*. + public func filter(key: PrimaryKeyType?) -> Self { + guard let key = key else { + return none() + } + return filter(keys: [key]) + } + + /// Creates a request with the provided primary key *predicate*. + public func filter(keys: Sequence) -> Self where Sequence.Element: DatabaseValueConvertible { + let keys = Array(keys) + let makePredicate: (Column) -> SQLExpression + switch keys.count { + case 0: + return none() + case 1: + makePredicate = { $0 == keys[0] } + default: + makePredicate = { keys.contains($0) } + } + + let databaseTableName = self.databaseTableName + return filter { db in + let primaryKey = try db.primaryKey(databaseTableName) + GRDBPrecondition( + primaryKey.columns.count == 1, + "Requesting by key requires a single-column primary key in the table \(databaseTableName)") + return makePredicate(Column(primaryKey.columns[0])) + } + } + + /// Creates a request with the provided primary key *predicate*. + /// + /// When executed, this request raises a fatal error if there is no unique + /// index on the key columns. + public func filter(key: [String: DatabaseValueConvertible?]?) -> Self { + guard let key = key else { + return none() + } + return filter(keys: [key]) + } + + /// Creates a request with the provided primary key *predicate*. + /// + /// When executed, this request raises a fatal error if there is no unique + /// index on the key columns. + public func filter(keys: [[String: DatabaseValueConvertible?]]) -> Self { + guard !keys.isEmpty else { + return none() + } + + let databaseTableName = self.databaseTableName + return filter { db in + try keys + .map { key in + // Prevent filter(keys: [["foo": 1, "bar": 2]]) where + // ("foo", "bar") is not a unique key (primary key or columns of a + // unique index) + guard let orderedColumns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else { + fatalError("table \(databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))") + } + + let lowercaseOrderedColumns = orderedColumns.map { $0.lowercased() } + return key + // Sort key columns in the same order as the unique index + .sorted { (kv1, kv2) in + let index1 = lowercaseOrderedColumns.index(of: kv1.key.lowercased())! + let index2 = lowercaseOrderedColumns.index(of: kv2.key.lowercased())! + return index1 < index2 + } + .map { (column, value) in Column(column) == value } + .joined(operator: .and) + } + .joined(operator: .or) + } + } +} + // MARK: - AggregatingRequest /// The protocol for all requests that can aggregate. diff --git a/GRDB/QueryInterface/SQLCollatedExpression.swift b/GRDB/QueryInterface/SQLCollatedExpression.swift index 3266580c0..b976014b6 100644 --- a/GRDB/QueryInterface/SQLCollatedExpression.swift +++ b/GRDB/QueryInterface/SQLCollatedExpression.swift @@ -61,4 +61,10 @@ extension SQLCollatedExpression : SQLOrderingTerm { public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String { return sqlExpression.orderingTermSQL(&arguments) } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func qualifiedOrdering(with qualifier: SQLTableQualifier) -> SQLOrderingTerm { + return SQLCollatedExpression(expression.qualifiedExpression(with: qualifier), collationName: collationName) + } } diff --git a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift index a7a7f8dcc..3248c9963 100644 --- a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift @@ -87,6 +87,12 @@ public struct SQLExpressionLiteral : SQLExpression { public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { return self } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return self + } } // MARK: - SQLExpressionUnary @@ -174,6 +180,12 @@ public struct SQLExpressionUnary : SQLExpression { public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { return SQLExpressionUnary(op, expression.qualifiedExpression(with: qualifier)) } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return SQLExpressionUnary(op, expression.resolvedExpression(inContext: context)) + } } // MARK: - SQLExpressionBinary @@ -322,6 +334,12 @@ public struct SQLExpressionBinary : SQLExpression { public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { return SQLExpressionBinary(op, lhs.qualifiedExpression(with: qualifier), rhs.qualifiedExpression(with: qualifier)) } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return SQLExpressionBinary(op, lhs.resolvedExpression(inContext: context), rhs.resolvedExpression(inContext: context)) + } } // MARK: - SQLExpressionAnd @@ -349,6 +367,10 @@ struct SQLExpressionAnd : SQLExpression { return SQLExpressionAnd(expressions.map { $0.qualifiedExpression(with: qualifier) }) } + func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return SQLExpressionAnd(expressions.map { $0.resolvedExpression(inContext: context) }) + } + func matchedRowIds(rowIdName: String?) -> Set? { let matchedRowIds = expressions.compactMap { $0.matchedRowIds(rowIdName: rowIdName) @@ -385,6 +407,10 @@ struct SQLExpressionOr : SQLExpression { return SQLExpressionOr(expressions.map { $0.qualifiedExpression(with: qualifier) }) } + func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return SQLExpressionOr(expressions.map { $0.resolvedExpression(inContext: context) }) + } + func matchedRowIds(rowIdName: String?) -> Set? { if expressions.isEmpty { return [] @@ -462,6 +488,10 @@ struct SQLExpressionContains : SQLExpression { func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { return SQLExpressionContains(expression.qualifiedExpression(with: qualifier), collection, negated: isNegated) } + + func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return SQLExpressionContains(expression.resolvedExpression(inContext: context), collection, negated: isNegated) + } } // MARK: - SQLExpressionBetween @@ -505,6 +535,14 @@ struct SQLExpressionBetween : SQLExpression { upperBound.qualifiedExpression(with: qualifier), negated: isNegated) } + + func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return SQLExpressionBetween( + expression.resolvedExpression(inContext: context), + lowerBound.resolvedExpression(inContext: context), + upperBound.resolvedExpression(inContext: context), + negated: isNegated) + } } // MARK: - SQLExpressionFunction @@ -599,6 +637,12 @@ public struct SQLExpressionFunction : SQLExpression { public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { return SQLExpressionFunction(functionName, arguments: arguments.map { $0.qualifiedExpression(with: qualifier) }) } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return SQLExpressionFunction(functionName, arguments: arguments.map { $0.resolvedExpression(inContext: context) }) + } } // MARK: - SQLExpressionCount @@ -622,6 +666,10 @@ struct SQLExpressionCount : SQLExpression { func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { return SQLExpressionCount(counted.qualifiedSelectable(with: qualifier)) } + + func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return self + } } // MARK: - SQLExpressionCountDistinct @@ -644,6 +692,10 @@ struct SQLExpressionCountDistinct : SQLExpression { func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { return SQLExpressionCountDistinct(counted.qualifiedExpression(with: qualifier)) } + + func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return self + } } // MARK: - SQLExpressionCollate @@ -673,4 +725,8 @@ struct SQLExpressionCollate : SQLExpression { func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { return SQLExpressionCollate(expression.qualifiedExpression(with: qualifier), collationName: collationName) } + + func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return SQLExpressionCollate(expression.resolvedExpression(inContext: context), collationName: collationName) + } } diff --git a/GRDB/QueryInterface/SQLExpression.swift b/GRDB/QueryInterface/SQLExpression.swift index b41be52db..8f8ddecd1 100644 --- a/GRDB/QueryInterface/SQLExpression.swift +++ b/GRDB/QueryInterface/SQLExpression.swift @@ -63,6 +63,9 @@ public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderi /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression } extension SQLExpression { @@ -96,6 +99,15 @@ extension SQLExpression { public func qualifiedSelectable(with qualifier: SQLTableQualifier) -> SQLSelectable { return qualifiedExpression(with: qualifier) } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// The default implementation returns qualifiedExpression(with:) + /// + /// :nodoc: + public func qualifiedOrdering(with qualifier: SQLTableQualifier) -> SQLOrderingTerm { + return qualifiedExpression(with: qualifier) + } } // SQLExpression: SQLExpressible @@ -150,4 +162,8 @@ struct SQLExpressionNot : SQLExpression { func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { return SQLExpressionNot(expression.qualifiedExpression(with: qualifier)) } + + func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return SQLExpressionNot(expression.resolvedExpression(inContext: context)) + } } diff --git a/GRDB/QueryInterface/SQLOrdering.swift b/GRDB/QueryInterface/SQLOrdering.swift index e3e8624ba..fec103e3f 100644 --- a/GRDB/QueryInterface/SQLOrdering.swift +++ b/GRDB/QueryInterface/SQLOrdering.swift @@ -31,6 +31,9 @@ public protocol SQLOrderingTerm { /// orderingTerm.orderingTermSQL(&arguments) // "IFNULL(name, ?)" /// arguments // ["Anonymous"] func orderingTermSQL(_ arguments: inout StatementArguments?) -> String + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + func qualifiedOrdering(with qualifier: SQLTableQualifier) -> SQLOrderingTerm } // MARK: - SQLOrdering @@ -56,4 +59,13 @@ enum SQLOrdering : SQLOrderingTerm { return expression.expressionSQL(&arguments) + " DESC" } } + + func qualifiedOrdering(with qualifier: SQLTableQualifier) -> SQLOrderingTerm { + switch self { + case .asc(let expression): + return SQLOrdering.asc(expression.qualifiedExpression(with: qualifier)) + case .desc(let expression): + return SQLOrdering.desc(expression.qualifiedExpression(with: qualifier)) + } + } } diff --git a/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift b/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift index 0e45abddd..4e5b17664 100644 --- a/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift @@ -71,7 +71,7 @@ struct QualifiedAllColumns { extension QualifiedAllColumns : SQLSelectable { func resultColumnSQL(_ arguments: inout StatementArguments?) -> String { - if let qualifierName = qualifier.name { + if let qualifierName = qualifier.qualifiedName { return qualifierName.quotedDatabaseIdentifier + ".*" } return "*" @@ -92,7 +92,8 @@ extension QualifiedAllColumns : SQLSelectable { } func columnCount(_ db: Database) throws -> Int { - return try db.columns(in: qualifier.tableName).count + assert(qualifier.tableName != nil, "Missing table name") + return try db.columns(in: qualifier.tableName!).count } } diff --git a/GRDB/QueryInterface/SQLSelectable.swift b/GRDB/QueryInterface/SQLSelectable.swift index 48dd59720..0c0e48476 100644 --- a/GRDB/QueryInterface/SQLSelectable.swift +++ b/GRDB/QueryInterface/SQLSelectable.swift @@ -63,22 +63,147 @@ struct SQLSelectionLiteral : SQLSelectable { } } +// MARK: - TableAlias + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +public final class TableAlias { + var qualifier: SQLTableQualifier + + public init(name: String? = nil) { + self.qualifier = SQLTableQualifier(tableName: nil, userProvidedAlias: name) + } + + var userProvidedAlias: String? { + get { return qualifier.userProvidedAlias } + set { + // TODO: test + if let value = newValue { + qualifier.alias = value + qualifier.isUserProvided = true + } else { + qualifier.isUserProvided = false + } + } + } + + /// Returns a qualified value that is able to resolve ambiguities in + /// joined queries. + public subscript(_ selectable: SQLSelectable) -> SQLSelectable { + return selectable.qualifiedSelectable(with: qualifier) + } + + /// Returns a qualified expression that is able to resolve ambiguities in + /// joined queries. + public subscript(_ expression: SQLExpression) -> SQLExpression { + return expression.qualifiedExpression(with: qualifier) + } +} + // MARK: - SQLTableQualifier /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// :nodoc: -public class SQLTableQualifier { - var tableName: String - private var alias: String? - - init(tableName: String, alias: String?) { +public class SQLTableQualifier: Hashable { + var tableName: String? + var alias: String? + var isUserProvided: Bool + + init(tableName: String? = nil, userProvidedAlias: String? = nil) { self.tableName = tableName - self.alias = alias + self.alias = userProvidedAlias + self.isUserProvided = (userProvidedAlias != nil) } - var name: String? { - return alias + var qualifiedName: String? { + return alias ?? tableName + } + + var userProvidedAlias: String? { + return isUserProvided ? alias : nil + } + + /// :nodoc: + public var hashValue: Int { + return ObjectIdentifier(self).hashValue + } + + /// :nodoc: + public static func == (lhs: SQLTableQualifier, rhs: SQLTableQualifier) -> Bool { + return ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension Array where Element == SQLTableQualifier { + /// Resolve ambiguities in qualifiers' names. + /// + /// Precondition: all qualifiers have a non-nil qualifiedName: + /// + /// var qualifier = SQLTableQualifier() // nil qualifiedName + /// let query = query.qualified(by: &leftQualifier) + /// // Now qualifier is guaranteed to have a non-nil qualifiedName. + func resolveAmbiguities() { + // Special case + guard let first = first else { + return + } + + // Special case for single qualifier: don't output any column name + if count == 1 { + if !first.isUserProvided { + first.alias = nil + first.tableName = nil + } + return + } + + // It is a programmer error to reuse the same (===) TableAlias for + // multiple tables. + GRDBPrecondition(count == Set(self).count, "A TableAlias most not be used to refer to multiple tables") + + // Group qualifiers by lowercase name + let groups = Dictionary.init(grouping: self) { $0.qualifiedName!.lowercased() } + + var uniqueLowercaseNames: Set = [] + var ambiguousGroups: [[SQLTableQualifier]] = [] + + for (lowercaseName, group) in groups { + if group.count > 1 { + // It is a programmer error to reuse the same alias for multiple tables + GRDBPrecondition(group.filter({ $0.isUserProvided }).count < 2, "ambiguous alias: \(group[0].qualifiedName!)") + ambiguousGroups.append(group) + } else { + uniqueLowercaseNames.insert(lowercaseName) + } + } + + for group in ambiguousGroups { + var index = 1 + for qualifier in group { + if qualifier.isUserProvided { continue } + let radical = qualifier.qualifiedName!.databaseQualifierRadical + var alias: String + repeat { + alias = "\(radical)\(index)" + index += 1 + } while uniqueLowercaseNames.contains(alias.lowercased()) + uniqueLowercaseNames.insert(alias.lowercased()) + qualifier.alias = alias + } + } + } +} + +extension String { + /// "foo12" => "foo" + var databaseQualifierRadical: String { + let digits: ClosedRange = "0"..."9" + let radicalEndIndex = self // "foo12" + .reversed() // "21oof" + .prefix(while: { digits.contains($0) }) // "21" + .endIndex // reversed(foo^12) + .base // foo^12 + return String(prefix(upTo: radicalEndIndex)) } } diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index 389035274..96a3f82b1 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -126,6 +126,15 @@ public struct PersistenceContainer { } } + // Returns nil if column is not defined + func value(forCaseInsensitiveColumn column: String) -> DatabaseValue? { + let lowercaseColumn = column.lowercased() + for (key, value) in storage where key.lowercased() == lowercaseColumn { + return value?.databaseValue ?? .null + } + return nil + } + var isEmpty: Bool { return storage.isEmpty } diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index db1483e0c..d1c4d424c 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -86,7 +86,7 @@ extension TableRecord { /// // SELECT "p".* FROM players AS p /// let sql = "SELECT \(Player.selectionSQL(alias: "p")) FROM players AS p" public static func selectionSQL(alias: String? = nil) -> String { - let qualifier = SQLTableQualifier(tableName: databaseTableName, alias: alias ?? databaseTableName) + let qualifier = SQLTableQualifier(tableName: databaseTableName, userProvidedAlias: alias) let selection = databaseSelection.map { $0.qualifiedSelectable(with: qualifier) } var arguments: StatementArguments? = nil return selection @@ -113,10 +113,9 @@ extension TableRecord { /// try Player.numberOfSelectedColumns(db) /// } public static func numberOfSelectedColumns(_ db: Database) throws -> Int { - let qualifier = SQLTableQualifier(tableName: databaseTableName, alias: nil) + let qualifier = SQLTableQualifier(tableName: databaseTableName) return try databaseSelection .map { try $0.qualifiedSelectable(with: qualifier).columnCount(db) } .reduce(0, +) } } - diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 1f5d77772..8b911d1ec 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -195,6 +195,82 @@ 564F9C241F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; }; 564F9C2F1F07611400877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; 564F9C321F07611700877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; + 5653EB8F20961FC000F46237 /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8520961FBF00F46237 /* BelongsToAssociation.swift */; }; + 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 */; }; + 5653EB9F20961FC000F46237 /* AssociationMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8D20961FBF00F46237 /* AssociationMapping.swift */; }; + 5653EBA020961FC000F46237 /* AssociationMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8D20961FBF00F46237 /* AssociationMapping.swift */; }; + 5653EBA220961FCA00F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA120961FCA00F46237 /* QueryInterfaceRequest+Association.swift */; }; + 5653EBA320961FCA00F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA120961FCA00F46237 /* QueryInterfaceRequest+Association.swift */; }; + 5653EBB820961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA620961FE600F46237 /* AssociationParallelSQLTests.swift */; }; + 5653EBB920961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA620961FE600F46237 /* AssociationParallelSQLTests.swift */; }; + 5653EBBA20961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA620961FE600F46237 /* AssociationParallelSQLTests.swift */; }; + 5653EBBB20961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA620961FE600F46237 /* AssociationParallelSQLTests.swift */; }; + 5653EBBC20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA720961FE600F46237 /* AssociationBelongsToFetchableRecordTests.swift */; }; + 5653EBBD20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA720961FE600F46237 /* AssociationBelongsToFetchableRecordTests.swift */; }; + 5653EBBE20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA720961FE600F46237 /* AssociationBelongsToFetchableRecordTests.swift */; }; + 5653EBBF20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA720961FE600F46237 /* AssociationBelongsToFetchableRecordTests.swift */; }; + 5653EBC020961FE800F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA820961FE600F46237 /* AssociationParallelDecodableRecordTests.swift */; }; + 5653EBC120961FE800F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA820961FE600F46237 /* AssociationParallelDecodableRecordTests.swift */; }; + 5653EBC220961FE800F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA820961FE600F46237 /* AssociationParallelDecodableRecordTests.swift */; }; + 5653EBC320961FE800F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA820961FE600F46237 /* AssociationParallelDecodableRecordTests.swift */; }; + 5653EBC420961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA920961FE700F46237 /* AssociationBelongsToSQLDerivationTests.swift */; }; + 5653EBC520961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA920961FE700F46237 /* AssociationBelongsToSQLDerivationTests.swift */; }; + 5653EBC620961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA920961FE700F46237 /* AssociationBelongsToSQLDerivationTests.swift */; }; + 5653EBC720961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA920961FE700F46237 /* AssociationBelongsToSQLDerivationTests.swift */; }; + 5653EBC820961FE800F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAA20961FE700F46237 /* AssociationTableAliasTestsSQLTests.swift */; }; + 5653EBC920961FE800F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAA20961FE700F46237 /* AssociationTableAliasTestsSQLTests.swift */; }; + 5653EBCA20961FE800F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAA20961FE700F46237 /* AssociationTableAliasTestsSQLTests.swift */; }; + 5653EBCB20961FE800F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAA20961FE700F46237 /* AssociationTableAliasTestsSQLTests.swift */; }; + 5653EBCC20961FE800F46237 /* AssociationHasOneSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAB20961FE700F46237 /* AssociationHasOneSQLTests.swift */; }; + 5653EBCD20961FE800F46237 /* AssociationHasOneSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAB20961FE700F46237 /* AssociationHasOneSQLTests.swift */; }; + 5653EBCE20961FE800F46237 /* AssociationHasOneSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAB20961FE700F46237 /* AssociationHasOneSQLTests.swift */; }; + 5653EBCF20961FE800F46237 /* AssociationHasOneSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAB20961FE700F46237 /* AssociationHasOneSQLTests.swift */; }; + 5653EBD020961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAC20961FE700F46237 /* AssociationRowScopeSearchTests.swift */; }; + 5653EBD120961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAC20961FE700F46237 /* AssociationRowScopeSearchTests.swift */; }; + 5653EBD220961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAC20961FE700F46237 /* AssociationRowScopeSearchTests.swift */; }; + 5653EBD320961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAC20961FE700F46237 /* AssociationRowScopeSearchTests.swift */; }; + 5653EBD420961FE800F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAD20961FE700F46237 /* AssociationHasOneSQLDerivationTests.swift */; }; + 5653EBD520961FE800F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAD20961FE700F46237 /* AssociationHasOneSQLDerivationTests.swift */; }; + 5653EBD620961FE800F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAD20961FE700F46237 /* AssociationHasOneSQLDerivationTests.swift */; }; + 5653EBD720961FE800F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAD20961FE700F46237 /* AssociationHasOneSQLDerivationTests.swift */; }; + 5653EBD820961FE800F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAE20961FE700F46237 /* AssociationChainRowScopesTests.swift */; }; + 5653EBD920961FE800F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAE20961FE700F46237 /* AssociationChainRowScopesTests.swift */; }; + 5653EBDA20961FE800F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAE20961FE700F46237 /* AssociationChainRowScopesTests.swift */; }; + 5653EBDB20961FE800F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAE20961FE700F46237 /* AssociationChainRowScopesTests.swift */; }; + 5653EBDC20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAF20961FE700F46237 /* AssociationParallelRowScopesTests.swift */; }; + 5653EBDD20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAF20961FE700F46237 /* AssociationParallelRowScopesTests.swift */; }; + 5653EBDE20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAF20961FE700F46237 /* AssociationParallelRowScopesTests.swift */; }; + 5653EBDF20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAF20961FE700F46237 /* AssociationParallelRowScopesTests.swift */; }; + 5653EBE020961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB020961FE700F46237 /* AssociationBelongsToSQLTests.swift */; }; + 5653EBE120961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB020961FE700F46237 /* AssociationBelongsToSQLTests.swift */; }; + 5653EBE220961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB020961FE700F46237 /* AssociationBelongsToSQLTests.swift */; }; + 5653EBE320961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB020961FE700F46237 /* AssociationBelongsToSQLTests.swift */; }; + 5653EBE420961FE800F46237 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB120961FE800F46237 /* AssociationChainSQLTests.swift */; }; + 5653EBE520961FE800F46237 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB120961FE800F46237 /* AssociationChainSQLTests.swift */; }; + 5653EBE620961FE800F46237 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB120961FE800F46237 /* AssociationChainSQLTests.swift */; }; + 5653EBE720961FE800F46237 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB120961FE800F46237 /* AssociationChainSQLTests.swift */; }; + 5653EBE820961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB220961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; + 5653EBE920961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB220961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; + 5653EBEA20961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB220961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; + 5653EBEB20961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB220961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; + 5653EBEC20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB320961FE800F46237 /* AssociationBelongsToRowScopeTests.swift */; }; + 5653EBED20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB320961FE800F46237 /* AssociationBelongsToRowScopeTests.swift */; }; + 5653EBEE20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB320961FE800F46237 /* AssociationBelongsToRowScopeTests.swift */; }; + 5653EBEF20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB320961FE800F46237 /* AssociationBelongsToRowScopeTests.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 */; }; @@ -885,6 +961,30 @@ 564E73EB203DA29B000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 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 = ""; }; + 5653EB8D20961FBF00F46237 /* AssociationMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationMapping.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 = ""; }; + 5653EBA720961FE600F46237 /* AssociationBelongsToFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToFetchableRecordTests.swift; sourceTree = ""; }; + 5653EBA820961FE600F46237 /* AssociationParallelDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelDecodableRecordTests.swift; sourceTree = ""; }; + 5653EBA920961FE700F46237 /* AssociationBelongsToSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToSQLDerivationTests.swift; sourceTree = ""; }; + 5653EBAA20961FE700F46237 /* AssociationTableAliasTestsSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationTableAliasTestsSQLTests.swift; sourceTree = ""; }; + 5653EBAB20961FE700F46237 /* AssociationHasOneSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneSQLTests.swift; sourceTree = ""; }; + 5653EBAC20961FE700F46237 /* AssociationRowScopeSearchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRowScopeSearchTests.swift; sourceTree = ""; }; + 5653EBAD20961FE700F46237 /* AssociationHasOneSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneSQLDerivationTests.swift; sourceTree = ""; }; + 5653EBAE20961FE700F46237 /* AssociationChainRowScopesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainRowScopesTests.swift; sourceTree = ""; }; + 5653EBAF20961FE700F46237 /* AssociationParallelRowScopesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelRowScopesTests.swift; sourceTree = ""; }; + 5653EBB020961FE700F46237 /* AssociationBelongsToSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToSQLTests.swift; sourceTree = ""; }; + 5653EBB120961FE800F46237 /* AssociationChainSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainSQLTests.swift; sourceTree = ""; }; + 5653EBB220961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToDecodableRecordTests.swift; sourceTree = ""; }; + 5653EBB320961FE800F46237 /* AssociationBelongsToRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToRowScopeTests.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 = ""; }; @@ -1317,6 +1417,7 @@ 56300B5C1C53C38F005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 5653EBA420961FD300F46237 /* Association */, 56B6EF62208CB762002F0ACB /* ColumnExpressionTests.swift */, 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, @@ -1333,11 +1434,13 @@ 56300B6D1C53F592005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 5653EB8420961FBF00F46237 /* Association */, 56CEB5401EAA359A00BFAF62 /* Column.swift */, 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */, 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, + 5653EBA120961FCA00F46237 /* QueryInterfaceRequest+Association.swift */, 5616AAF8207CD5A900AC3664 /* RequestProtocols.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, @@ -1368,6 +1471,43 @@ name = DatabaseQueue; sourceTree = ""; }; + 5653EB8420961FBF00F46237 /* Association */ = { + isa = PBXGroup; + children = ( + 5653EB8520961FBF00F46237 /* BelongsToAssociation.swift */, + 5653EB8620961FBF00F46237 /* HasOneAssociation.swift */, + 5653EB8720961FBF00F46237 /* AssociationQuery.swift */, + 5653EB8820961FBF00F46237 /* HasManyAssociation.swift */, + 5653EB8920961FBF00F46237 /* ForeignKey.swift */, + 5653EB8A20961FBF00F46237 /* ForeignKeyRequest.swift */, + 5653EB8B20961FBF00F46237 /* AssociationRequest.swift */, + 5653EB8C20961FBF00F46237 /* Association.swift */, + 5653EB8D20961FBF00F46237 /* AssociationMapping.swift */, + ); + path = Association; + sourceTree = ""; + }; + 5653EBA420961FD300F46237 /* Association */ = { + isa = PBXGroup; + children = ( + 5653EBB220961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift */, + 5653EBA720961FE600F46237 /* AssociationBelongsToFetchableRecordTests.swift */, + 5653EBB320961FE800F46237 /* AssociationBelongsToRowScopeTests.swift */, + 5653EBA920961FE700F46237 /* AssociationBelongsToSQLDerivationTests.swift */, + 5653EBB020961FE700F46237 /* AssociationBelongsToSQLTests.swift */, + 5653EBAE20961FE700F46237 /* AssociationChainRowScopesTests.swift */, + 5653EBB120961FE800F46237 /* AssociationChainSQLTests.swift */, + 5653EBAD20961FE700F46237 /* AssociationHasOneSQLDerivationTests.swift */, + 5653EBAB20961FE700F46237 /* AssociationHasOneSQLTests.swift */, + 5653EBA820961FE600F46237 /* AssociationParallelDecodableRecordTests.swift */, + 5653EBAF20961FE700F46237 /* AssociationParallelRowScopesTests.swift */, + 5653EBA620961FE600F46237 /* AssociationParallelSQLTests.swift */, + 5653EBAC20961FE700F46237 /* AssociationRowScopeSearchTests.swift */, + 5653EBAA20961FE700F46237 /* AssociationTableAliasTestsSQLTests.swift */, + ); + name = Association; + sourceTree = ""; + }; 5659F4861EA8D94E004A4992 /* Utils */ = { isa = PBXGroup; children = ( @@ -1996,15 +2136,18 @@ 56BB6EAA1D3009B100A1CA52 /* SchedulingWatchdog.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 */, 56CEB4F21EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 560FC51C1CB003810014AA8E /* QueryInterfaceRequest.swift in Sources */, 560FC51D1CB003810014AA8E /* SQLCollatedExpression.swift in Sources */, + 5653EB9920961FC000F46237 /* ForeignKeyRequest.swift in Sources */, 566B91341FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56D1215B1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 566475D41D981D5E00FF74B8 /* SQLOperators.swift in Sources */, + 5653EB9120961FC000F46237 /* HasOneAssociation.swift in Sources */, 56CEB5621EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56CEB4FB1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD361DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, @@ -2020,6 +2163,7 @@ 5698AC381D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 564F9C2F1F07611400877A00 /* DatabaseFunction.swift in Sources */, 5659F4991EA8D989004A4992 /* Pool.swift in Sources */, + 5653EB8F20961FC000F46237 /* BelongsToAssociation.swift in Sources */, 569B7FA8201C904C0069DE70 /* Swift4.1.swift in Sources */, 5674A6FA1F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 56CEB54D1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, @@ -2027,6 +2171,7 @@ 567404891CEF84C8003ED5CC /* RowAdapter.swift in Sources */, 56E06F131E859068008AE2A4 /* Fixits-0.102.0.swift in Sources */, 560FC5241CB003810014AA8E /* DatabaseWriter.swift in Sources */, + 5653EBA220961FCA00F46237 /* QueryInterfaceRequest+Association.swift in Sources */, 5698AD191DAAD17B0056AF8C /* FTS5Tokenizer.swift in Sources */, 56F3E7641E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */, 56B964B21DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, @@ -2053,6 +2198,8 @@ 560FC5341CB003810014AA8E /* QueryInterfaceQuery.swift in Sources */, 566B912C1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 560FC5351CB003810014AA8E /* Statement.swift in Sources */, + 5653EB9F20961FC000F46237 /* AssociationMapping.swift in Sources */, + 5653EB9320961FC000F46237 /* AssociationQuery.swift in Sources */, 5690C3411D23E82A00E59934 /* Data.swift in Sources */, 5659F4891EA8D94E004A4992 /* Utils.swift in Sources */, 56FC98791D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, @@ -2071,7 +2218,9 @@ 566AD8B31D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5698AD221DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 560FC53C1CB003810014AA8E /* DatabaseQueue.swift in Sources */, + 5653EB9720961FC000F46237 /* ForeignKey.swift in Sources */, 569A98FC2039B72D008D7DBF /* Fixits-3.0.swift in Sources */, + 5653EB9520961FC000F46237 /* HasManyAssociation.swift in Sources */, 560FC53D1CB003810014AA8E /* NSNumber.swift in Sources */, 567071F8208A00D4006AD95A /* SQLiteDateParser.swift in Sources */, 560FC53F1CB003810014AA8E /* Row.swift in Sources */, @@ -2079,6 +2228,7 @@ 560FC5411CB003810014AA8E /* PersistableRecord.swift in Sources */, 566475A31D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5674A6EA1F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, + 5653EB9D20961FC000F46237 /* Association.swift in Sources */, 5657AABA1D107001006283EF /* NSData.swift in Sources */, 560FC5421CB003810014AA8E /* StatementColumnConvertible.swift in Sources */, 56CEB5541EAA359A00BFAF62 /* SQLExpression.swift in Sources */, @@ -2097,6 +2247,7 @@ 5698ACD81DA925420056AF8C /* RowTestCase.swift in Sources */, 56A8C2411D1918EE0096E9D4 /* FoundationNSUUIDTests.swift in Sources */, 562EA8301F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, + 5653EBC020961FE800F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 562206031E420EA3005860AC /* DatabasePoolBackupTests.swift in Sources */, 5657AB571D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, 564448841EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, @@ -2115,6 +2266,7 @@ 562393191DECC02000A6B01F /* RowFetchTests.swift in Sources */, 560FC56B1CB00B880014AA8E /* DatabaseCollationTests.swift in Sources */, 560FC56C1CB00B880014AA8E /* UpdateStatementTests.swift in Sources */, + 5653EBE020961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 560FC56D1CB00B880014AA8E /* DatabaseMigratorTests.swift in Sources */, 560FC5701CB00B880014AA8E /* DatabasePoolCollationTests.swift in Sources */, 560FC5711CB00B880014AA8E /* RecordPrimaryKeySingleTests.swift in Sources */, @@ -2123,11 +2275,14 @@ 56B021CA1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, 562205F61E420E48005860AC /* DatabaseQueueReleaseMemoryTests.swift in Sources */, 560FC5741CB00B880014AA8E /* DatabasePoolFunctionTests.swift in Sources */, + 5653EBDC20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */, 560FC5761CB00B880014AA8E /* RowCopiedFromStatementTests.swift in Sources */, 560FC5771CB00B880014AA8E /* DatabaseQueueSchemaCacheTests.swift in Sources */, + 5653EBCC20961FE800F46237 /* AssociationHasOneSQLTests.swift in Sources */, 562756441E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, 56AF746C1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, 56B14E801D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, + 5653EBE420961FE800F46237 /* AssociationChainSQLTests.swift in Sources */, 562206051E420EA3005860AC /* DatabasePoolReadOnlyTests.swift in Sources */, 562206041E420EA3005860AC /* DatabasePoolConcurrencyTests.swift in Sources */, 56176C611EACCCC7000F3F2B /* FTS5RecordTests.swift in Sources */, @@ -2155,6 +2310,7 @@ 560FC57F1CB00B880014AA8E /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 5698ACB71DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 5672DE5A1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, + 5653EBE820961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 56176C601EACCCC7000F3F2B /* FTS5PatternTests.swift in Sources */, 564E73EF203DA2A2000C443C /* JoinSupportTests.swift in Sources */, 5674A7111F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, @@ -2165,8 +2321,10 @@ 567E55ED1D2BDD3D00CC6F79 /* EncryptionTests.swift in Sources */, 56741EA91E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 56176C641EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, + 5653EBB820961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */, 560FC5841CB00B880014AA8E /* PersistableRecordTests.swift in Sources */, 560FC5871CB00B880014AA8E /* RecordSubClassTests.swift in Sources */, + 5653EBBC20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 560FC5891CB00B880014AA8E /* TransactionObserverTests.swift in Sources */, 5674A72C1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, 56C3F7541CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, @@ -2179,8 +2337,10 @@ 56071A4E1DB54ED200CA6E47 /* FetchedRecordsControllerTests.swift in Sources */, 56A4CDB11D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 567156141CB141D0007DC145 /* DatabaseQueueInMemoryTests.swift in Sources */, + 5653EBEC20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, 560FC58E1CB00B880014AA8E /* RecordPrimaryKeyRowIDTests.swift in Sources */, 560FC58F1CB00B880014AA8E /* DatabaseReaderTests.swift in Sources */, + 5653EBD020961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 560FC5901CB00B880014AA8E /* RecordEditedTests.swift in Sources */, 560FC5911CB00B880014AA8E /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 56CC924C201E059100CB597E /* DropFirstCursorTests.swift in Sources */, @@ -2188,9 +2348,12 @@ 560FC5921CB00B880014AA8E /* FetchableRecordTests.swift in Sources */, 56A5EF101EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, 5657AB371D108BA9006283EF /* FoundationDataTests.swift in Sources */, + 5653EBD820961FE800F46237 /* AssociationChainRowScopesTests.swift in Sources */, 560FC5941CB00B880014AA8E /* DatabaseValueConvertibleSubclassTests.swift in Sources */, + 5653EBC820961FE800F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, 565EFAEF1D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */, 560FC5961CB00B880014AA8E /* DatabaseValueConvertibleFetchTests.swift in Sources */, + 5653EBC420961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 560FC5971CB00B880014AA8E /* DatabaseErrorTests.swift in Sources */, 560FC5991CB00B880014AA8E /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, 564F9C1F1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, @@ -2222,6 +2385,7 @@ 5698AC8A1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, 5698AC041D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, 5690C3381D23E7D200E59934 /* FoundationDateTests.swift in Sources */, + 5653EBD420961FE800F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, 6340BF811E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, 5622060B1E420EB3005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */, 562205F41E420E48005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */, @@ -2244,6 +2408,7 @@ 5698ACD91DA925420056AF8C /* RowTestCase.swift in Sources */, 567156221CB16729007DC145 /* StatementColumnConvertibleFetchTests.swift in Sources */, 562EA8311F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, + 5653EBC120961FE800F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 562206001E420EA3005860AC /* DatabasePoolBackupTests.swift in Sources */, 567156231CB16729007DC145 /* RecordPrimaryKeyNoneTests.swift in Sources */, 564448851EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, @@ -2262,6 +2427,7 @@ 5623931A1DECC02000A6B01F /* RowFetchTests.swift in Sources */, 5671562E1CB16729007DC145 /* DatabasePoolCollationTests.swift in Sources */, 5671562F1CB16729007DC145 /* RecordPrimaryKeySingleTests.swift in Sources */, + 5653EBE120961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 567156301CB16729007DC145 /* StatementColumnConvertibleTests.swift in Sources */, 56C3F7551CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, 5672DE5B1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, @@ -2270,11 +2436,14 @@ 56B14E811D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, 562205F91E420E49005860AC /* DatabaseQueueReleaseMemoryTests.swift in Sources */, 566AD8C81D531BEB002EC1A8 /* TableDefinitionTests.swift in Sources */, + 5653EBDD20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */, 567156321CB16729007DC145 /* DatabasePoolFunctionTests.swift in Sources */, 567156341CB16729007DC145 /* RowCopiedFromStatementTests.swift in Sources */, + 5653EBCD20961FE800F46237 /* AssociationHasOneSQLTests.swift in Sources */, 562756451E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, 569C1EB41CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */, 56AF746D1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, + 5653EBE520961FE800F46237 /* AssociationChainSQLTests.swift in Sources */, 562206021E420EA3005860AC /* DatabasePoolReadOnlyTests.swift in Sources */, 562206011E420EA3005860AC /* DatabasePoolConcurrencyTests.swift in Sources */, 56176C671EACCCC8000F3F2B /* FTS5RecordTests.swift in Sources */, @@ -2302,6 +2471,7 @@ 5671563F1CB16729007DC145 /* RecordCopyTests.swift in Sources */, 5698ACB81DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 567156401CB16729007DC145 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */, + 5653EBE920961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 56176C661EACCCC8000F3F2B /* FTS5PatternTests.swift in Sources */, 564E73F0203DA2A3000C443C /* JoinSupportTests.swift in Sources */, 5674A7131F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, @@ -2312,8 +2482,10 @@ 5690C3391D23E7D200E59934 /* FoundationDateTests.swift in Sources */, 56741EAA1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 56176C6A1EACCCC8000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, + 5653EBB920961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */, 567156461CB16729007DC145 /* TransactionObserverTests.swift in Sources */, 567A80551D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, + 5653EBBD20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 567156481CB16729007DC145 /* DatabaseValueTests.swift in Sources */, 5674A72E1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, 5671564A1CB16729007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */, @@ -2326,8 +2498,10 @@ 56071A4F1DB54ED300CA6E47 /* FetchedRecordsControllerTests.swift in Sources */, 5671564D1CB16729007DC145 /* RecordPrimaryKeyRowIDTests.swift in Sources */, 5671564E1CB16729007DC145 /* DatabaseReaderTests.swift in Sources */, + 5653EBED20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, 5671564F1CB16729007DC145 /* RecordEditedTests.swift in Sources */, 567156501CB16729007DC145 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, + 5653EBD120961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 567156511CB16729007DC145 /* FetchableRecordTests.swift in Sources */, 56A8C2441D1918EE0096E9D4 /* FoundationUUIDTests.swift in Sources */, 56CC924D201E059100CB597E /* DropFirstCursorTests.swift in Sources */, @@ -2335,9 +2509,12 @@ 567156531CB16729007DC145 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 56A5EF111EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, 5690C3281D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */, + 5653EBD920961FE800F46237 /* AssociationChainRowScopesTests.swift in Sources */, 5657AB381D108BA9006283EF /* FoundationDataTests.swift in Sources */, + 5653EBC920961FE800F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, 561667031D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */, 565EFAF01D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */, + 5653EBC520961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 567156551CB16729007DC145 /* DatabaseValueConvertibleFetchTests.swift in Sources */, 567156561CB16729007DC145 /* DatabaseErrorTests.swift in Sources */, 564F9C201F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, @@ -2369,6 +2546,7 @@ 5698AC8B1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, 5698AC051D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, 567156621CB16729007DC145 /* CGFloatTests.swift in Sources */, + 5653EBD520961FE800F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, 6340BF821E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, 5622060A1E420EB2005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */, 562205F71E420E49005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */, @@ -2391,15 +2569,18 @@ 56BB6EAD1D3009B100A1CA52 /* SchedulingWatchdog.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 */, 56CEB4F51EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 56AFC9F11CB1A8BB00F48B96 /* QueryInterfaceRequest.swift in Sources */, 56AFC9F21CB1A8BB00F48B96 /* SQLCollatedExpression.swift in Sources */, + 5653EB9A20961FC000F46237 /* ForeignKeyRequest.swift in Sources */, 566B91371FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56D1215E1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 566475D71D981D5E00FF74B8 /* SQLOperators.swift in Sources */, + 5653EB9220961FC000F46237 /* HasOneAssociation.swift in Sources */, 56CEB5651EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56CEB4FE1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD391DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, @@ -2415,6 +2596,7 @@ 5698AC3B1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 564F9C321F07611700877A00 /* DatabaseFunction.swift in Sources */, 5659F49C1EA8D989004A4992 /* Pool.swift in Sources */, + 5653EB9020961FC000F46237 /* BelongsToAssociation.swift in Sources */, 569B7FA9201C904C0069DE70 /* Swift4.1.swift in Sources */, 5674A6F71F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 56CEB5501EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, @@ -2422,6 +2604,7 @@ 5674048B1CEF84C8003ED5CC /* RowAdapter.swift in Sources */, 56E06F161E85906C008AE2A4 /* Fixits-0.102.0.swift in Sources */, 56AFC9F91CB1A8BB00F48B96 /* DatabaseWriter.swift in Sources */, + 5653EBA320961FCA00F46237 /* QueryInterfaceRequest+Association.swift in Sources */, 5698AD1A1DAAD17C0056AF8C /* FTS5Tokenizer.swift in Sources */, 56F3E7671E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */, 56B964B51DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, @@ -2448,6 +2631,8 @@ 56AFCA091CB1A8BB00F48B96 /* QueryInterfaceQuery.swift in Sources */, 566B912F1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 56AFCA0A1CB1A8BB00F48B96 /* Migration.swift in Sources */, + 5653EBA020961FC000F46237 /* AssociationMapping.swift in Sources */, + 5653EB9420961FC000F46237 /* AssociationQuery.swift in Sources */, 5690C3441D23E82A00E59934 /* Data.swift in Sources */, 5659F48C1EA8D94E004A4992 /* Utils.swift in Sources */, 56FC987C1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, @@ -2466,7 +2651,9 @@ 566AD8B61D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5698AD251DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 56AFCA121CB1A8BB00F48B96 /* NSNumber.swift in Sources */, + 5653EB9820961FC000F46237 /* ForeignKey.swift in Sources */, 569A98FD2039B72D008D7DBF /* Fixits-3.0.swift in Sources */, + 5653EB9620961FC000F46237 /* HasManyAssociation.swift in Sources */, 56AFCA141CB1A8BB00F48B96 /* StandardLibrary.swift in Sources */, 56AFCA151CB1A8BB00F48B96 /* PersistableRecord.swift in Sources */, 567071F9208A00D4006AD95A /* SQLiteDateParser.swift in Sources */, @@ -2474,6 +2661,7 @@ 566475A61D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABD1D107001006283EF /* NSData.swift in Sources */, 5674A6E71F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, + 5653EB9E20961FC000F46237 /* Association.swift in Sources */, 56AFCA181CB1A8BB00F48B96 /* FetchedRecordsController.swift in Sources */, 56AFCA191CB1A8BB00F48B96 /* DatabaseValue.swift in Sources */, 56CEB5571EAA359A00BFAF62 /* SQLExpression.swift in Sources */, @@ -2492,6 +2680,7 @@ 56AFCA311CB1AA9900F48B96 /* RecordPrimaryKeyNoneTests.swift in Sources */, 56AFCA321CB1AA9900F48B96 /* DatabaseQueueConcurrencyTests.swift in Sources */, 562EA8341F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, + 5653EBC220961FE800F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 5698ACD31DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, 56AFCA331CB1AA9900F48B96 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 564448881EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, @@ -2510,6 +2699,7 @@ 56AFCA3B1CB1AA9900F48B96 /* DatabaseMigratorTests.swift in Sources */, 5657AB4B1D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, 56AFCA3E1CB1AA9900F48B96 /* DatabasePoolCollationTests.swift in Sources */, + 5653EBE220961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 56FF455B1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, 56AFCA3F1CB1AA9900F48B96 /* RecordPrimaryKeySingleTests.swift in Sources */, 56AFCA411CB1AA9900F48B96 /* StatementColumnConvertibleTests.swift in Sources */, @@ -2518,11 +2708,14 @@ 56AFCA441CB1AA9900F48B96 /* RowCopiedFromStatementTests.swift in Sources */, 56C3F7571CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, 562393351DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, + 5653EBDE20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */, 5698ACDC1DA925430056AF8C /* RowTestCase.swift in Sources */, 56AFCA451CB1AA9900F48B96 /* DatabaseQueueSchemaCacheTests.swift in Sources */, + 5653EBCE20961FE800F46237 /* AssociationHasOneSQLTests.swift in Sources */, 562756481E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, 56AFCA461CB1AA9900F48B96 /* RecordPrimaryKeyMultipleTests.swift in Sources */, 56AFCA471CB1AA9900F48B96 /* RowFromStatementTests.swift in Sources */, + 5653EBE620961FE800F46237 /* AssociationChainSQLTests.swift in Sources */, 56AFCA491CB1AA9900F48B96 /* StatementArgumentsTests.swift in Sources */, 5672DE6B1CDB751D0022BA81 /* DatabasePoolBackupTests.swift in Sources */, 56176C731EACCCCA000F3F2B /* FTS5RecordTests.swift in Sources */, @@ -2550,6 +2743,7 @@ 56AFCA521CB1AA9900F48B96 /* PersistableRecordTests.swift in Sources */, 56AFCA531CB1AA9900F48B96 /* DatabaseValueConversionTests.swift in Sources */, 5657AB531D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */, + 5653EBEA20961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 5698AC9B1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 56176C721EACCCCA000F3F2B /* FTS5PatternTests.swift in Sources */, 564E73F1203DA2A3000C443C /* JoinSupportTests.swift in Sources */, @@ -2560,8 +2754,10 @@ 56AFCA561CB1AA9900F48B96 /* DatabasePoolConcurrencyTests.swift in Sources */, 56AFCA571CB1AA9900F48B96 /* TransactionObserverTests.swift in Sources */, 56741EAD1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, + 5653EBBA20961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */, 56176C761EACCCCA000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, 5623935C1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, + 5653EBBE20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 5698AC851DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, 5698AC451DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 5674A72B1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, @@ -2574,8 +2770,10 @@ 56A4CDB51D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 56AFCA5B1CB1AA9900F48B96 /* DatabaseValueTests.swift in Sources */, 56AFCA5C1CB1AA9900F48B96 /* DatabaseQueueReadOnlyTests.swift in Sources */, + 5653EBEE20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, 56AFCA5D1CB1AA9900F48B96 /* DatabaseReaderTests.swift in Sources */, 56A8C2491D1918F10096E9D4 /* FoundationNSUUIDTests.swift in Sources */, + 5653EBD220961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 56AFCA5E1CB1AA9900F48B96 /* FetchableRecordTests.swift in Sources */, 56AFCA5F1CB1AA9900F48B96 /* DatabaseValueConvertibleFetchTests.swift in Sources */, 56AFCA601CB1AA9900F48B96 /* RecordPrimaryKeyRowIDTests.swift in Sources */, @@ -2583,9 +2781,12 @@ 56AFCA611CB1AA9900F48B96 /* RecordEditedTests.swift in Sources */, 56AFCA621CB1AA9900F48B96 /* DatabasePoolSchemaCacheTests.swift in Sources */, 56A5EF141EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, + 5653EBDA20961FE800F46237 /* AssociationChainRowScopesTests.swift in Sources */, 5623931D1DECC02000A6B01F /* RowFetchTests.swift in Sources */, + 5653EBCA20961FE800F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, 56AFCA631CB1AA9900F48B96 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 5698AC8E1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, + 5653EBC620961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 56AFCA641CB1AA9900F48B96 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 56A8C24A1D1918F10096E9D4 /* FoundationUUIDTests.swift in Sources */, 56AFCA651CB1AA9900F48B96 /* DatabaseErrorTests.swift in Sources */, @@ -2617,6 +2818,7 @@ 56AFCA731CB1AA9900F48B96 /* DatabaseQueueInMemoryTests.swift in Sources */, 56AFCA741CB1AA9900F48B96 /* RecordWithColumnNameManglingTests.swift in Sources */, 567A80581D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, + 5653EBD620961FE800F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, 6340BF851E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, 56AFCA751CB1AA9900F48B96 /* CGFloatTests.swift in Sources */, 562393531DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, @@ -2639,6 +2841,7 @@ 56AFCA8A1CB1ABC800F48B96 /* RecordPrimaryKeyNoneTests.swift in Sources */, 56AFCA8B1CB1ABC800F48B96 /* DatabaseQueueConcurrencyTests.swift in Sources */, 562EA8351F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, + 5653EBC320961FE800F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 5698ACD41DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, 56AFCA8C1CB1ABC800F48B96 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 564448891EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, @@ -2657,6 +2860,7 @@ 56AFCA911CB1ABC800F48B96 /* QueryInterfaceExpressionsTests.swift in Sources */, 56AFCA921CB1ABC800F48B96 /* SelectStatementTests.swift in Sources */, 56AFCA931CB1ABC800F48B96 /* UpdateStatementTests.swift in Sources */, + 5653EBE320961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 56AFCA941CB1ABC800F48B96 /* DatabaseMigratorTests.swift in Sources */, 5657AB641D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, 56FF455C1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, @@ -2665,11 +2869,14 @@ 5657AB5C1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, 56AFCA981CB1ABC800F48B96 /* RecordPrimaryKeySingleTests.swift in Sources */, 562393361DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, + 5653EBDF20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */, 5698ACDD1DA925430056AF8C /* RowTestCase.swift in Sources */, 56AFCA9A1CB1ABC800F48B96 /* StatementColumnConvertibleTests.swift in Sources */, + 5653EBCF20961FE800F46237 /* AssociationHasOneSQLTests.swift in Sources */, 562756491E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, 56AFCA9B1CB1ABC800F48B96 /* DatabasePoolFunctionTests.swift in Sources */, 5672DE5E1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, + 5653EBE720961FE800F46237 /* AssociationChainSQLTests.swift in Sources */, 56AFCA9D1CB1ABC800F48B96 /* RowCopiedFromStatementTests.swift in Sources */, 56AFCA9E1CB1ABC800F48B96 /* DatabaseQueueSchemaCacheTests.swift in Sources */, 56176C791EACCCCB000F3F2B /* FTS5RecordTests.swift in Sources */, @@ -2697,6 +2904,7 @@ 56A8C24B1D1918F10096E9D4 /* FoundationNSUUIDTests.swift in Sources */, 56AFCAAB1CB1ABC800F48B96 /* PersistableRecordTests.swift in Sources */, 56FF45461D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */, + 5653EBEB20961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 5698AC9C1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 56176C781EACCCCB000F3F2B /* FTS5PatternTests.swift in Sources */, 564E73F2203DA2A4000C443C /* JoinSupportTests.swift in Sources */, @@ -2707,8 +2915,10 @@ 5657AB441D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, 5623935D1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 56741EAE1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, + 5653EBBB20961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */, 56176C7C1EACCCCB000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, 5698AC861DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, + 5653EBBF20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 5698AC461DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 56AF74711D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, 5674A7281F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, @@ -2721,8 +2931,10 @@ 56A4CDB61D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 5657AB4C1D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, 56AFCAB31CB1ABC800F48B96 /* RecordSubClassTests.swift in Sources */, + 5653EBEF20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, 56AFCAB41CB1ABC800F48B96 /* DatabaseValueTests.swift in Sources */, 5657AB3C1D108BA9006283EF /* FoundationDataTests.swift in Sources */, + 5653EBD320961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 5634B10C1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */, 56AFCAB51CB1ABC800F48B96 /* DatabaseQueueReadOnlyTests.swift in Sources */, 56AFCAB61CB1ABC800F48B96 /* DatabaseReaderTests.swift in Sources */, @@ -2730,9 +2942,12 @@ 56AFCAB71CB1ABC800F48B96 /* FetchableRecordTests.swift in Sources */, 56B15D0D1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */, 56A5EF151EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, + 5653EBDB20961FE800F46237 /* AssociationChainRowScopesTests.swift in Sources */, 5623931E1DECC02000A6B01F /* RowFetchTests.swift in Sources */, + 5653EBCB20961FE800F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, 56AFCAB81CB1ABC800F48B96 /* DatabaseValueConvertibleFetchTests.swift in Sources */, 5698AC8F1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, + 5653EBC720961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 56AFCAB91CB1ABC800F48B96 /* RecordPrimaryKeyRowIDTests.swift in Sources */, 56AFCABA1CB1ABC800F48B96 /* RecordEditedTests.swift in Sources */, 56AFCABB1CB1ABC800F48B96 /* DatabasePoolSchemaCacheTests.swift in Sources */, @@ -2764,6 +2979,7 @@ 56AFCACC1CB1ABC800F48B96 /* DatabaseQueueInMemoryTests.swift in Sources */, 56AFCACD1CB1ABC800F48B96 /* RecordWithColumnNameManglingTests.swift in Sources */, 56AFCACE1CB1ABC800F48B96 /* CGFloatTests.swift in Sources */, + 5653EBD720961FE800F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, 6340BF861E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, 567A80591D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 562393541DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index ecf88c2b8..9f2aa8291 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -51,6 +51,54 @@ 564F9C251F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; }; 564F9C301F07611500877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; 564F9C331F07611800877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; + 5653EB4120961F6100F46237 /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3720961F6000F46237 /* BelongsToAssociation.swift */; }; + 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 */; }; + 5653EB5120961F6100F46237 /* AssociationMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3F20961F6100F46237 /* AssociationMapping.swift */; }; + 5653EB5220961F6100F46237 /* AssociationMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3F20961F6100F46237 /* AssociationMapping.swift */; }; + 5653EB5420961F7D00F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5320961F7D00F46237 /* QueryInterfaceRequest+Association.swift */; }; + 5653EB5520961F7D00F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5320961F7D00F46237 /* QueryInterfaceRequest+Association.swift */; }; + 5653EB6820961FB200F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5820961FB000F46237 /* AssociationParallelSQLTests.swift */; }; + 5653EB6920961FB200F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5820961FB000F46237 /* AssociationParallelSQLTests.swift */; }; + 5653EB6A20961FB200F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5920961FB100F46237 /* AssociationBelongsToFetchableRecordTests.swift */; }; + 5653EB6B20961FB200F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5920961FB100F46237 /* AssociationBelongsToFetchableRecordTests.swift */; }; + 5653EB6C20961FB200F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5A20961FB100F46237 /* AssociationParallelDecodableRecordTests.swift */; }; + 5653EB6D20961FB200F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5A20961FB100F46237 /* AssociationParallelDecodableRecordTests.swift */; }; + 5653EB6E20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5B20961FB100F46237 /* AssociationBelongsToSQLDerivationTests.swift */; }; + 5653EB6F20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5B20961FB100F46237 /* AssociationBelongsToSQLDerivationTests.swift */; }; + 5653EB7020961FB200F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5C20961FB100F46237 /* AssociationTableAliasTestsSQLTests.swift */; }; + 5653EB7120961FB200F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5C20961FB100F46237 /* AssociationTableAliasTestsSQLTests.swift */; }; + 5653EB7220961FB200F46237 /* AssociationHasOneSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5D20961FB100F46237 /* AssociationHasOneSQLTests.swift */; }; + 5653EB7320961FB200F46237 /* AssociationHasOneSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5D20961FB100F46237 /* AssociationHasOneSQLTests.swift */; }; + 5653EB7420961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5E20961FB100F46237 /* AssociationRowScopeSearchTests.swift */; }; + 5653EB7520961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5E20961FB100F46237 /* AssociationRowScopeSearchTests.swift */; }; + 5653EB7620961FB200F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5F20961FB100F46237 /* AssociationHasOneSQLDerivationTests.swift */; }; + 5653EB7720961FB200F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5F20961FB100F46237 /* AssociationHasOneSQLDerivationTests.swift */; }; + 5653EB7820961FB200F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6020961FB100F46237 /* AssociationChainRowScopesTests.swift */; }; + 5653EB7920961FB200F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6020961FB100F46237 /* AssociationChainRowScopesTests.swift */; }; + 5653EB7A20961FB200F46237 /* AssociationParallelRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6120961FB100F46237 /* AssociationParallelRowScopesTests.swift */; }; + 5653EB7B20961FB200F46237 /* AssociationParallelRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6120961FB100F46237 /* AssociationParallelRowScopesTests.swift */; }; + 5653EB7C20961FB200F46237 /* AssociationBelongsToSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6220961FB200F46237 /* AssociationBelongsToSQLTests.swift */; }; + 5653EB7D20961FB200F46237 /* AssociationBelongsToSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6220961FB200F46237 /* AssociationBelongsToSQLTests.swift */; }; + 5653EB7E20961FB200F46237 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6320961FB200F46237 /* AssociationChainSQLTests.swift */; }; + 5653EB7F20961FB200F46237 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6320961FB200F46237 /* AssociationChainSQLTests.swift */; }; + 5653EB8020961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6420961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; + 5653EB8120961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6420961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; + 5653EB8220961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */; }; + 5653EB8320961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.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 */; }; @@ -586,6 +634,30 @@ 564E73E7203DA278000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 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 = ""; }; + 5653EB3F20961F6100F46237 /* AssociationMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationMapping.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 = ""; }; + 5653EB5920961FB100F46237 /* AssociationBelongsToFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToFetchableRecordTests.swift; sourceTree = ""; }; + 5653EB5A20961FB100F46237 /* AssociationParallelDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelDecodableRecordTests.swift; sourceTree = ""; }; + 5653EB5B20961FB100F46237 /* AssociationBelongsToSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToSQLDerivationTests.swift; sourceTree = ""; }; + 5653EB5C20961FB100F46237 /* AssociationTableAliasTestsSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationTableAliasTestsSQLTests.swift; sourceTree = ""; }; + 5653EB5D20961FB100F46237 /* AssociationHasOneSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneSQLTests.swift; sourceTree = ""; }; + 5653EB5E20961FB100F46237 /* AssociationRowScopeSearchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRowScopeSearchTests.swift; sourceTree = ""; }; + 5653EB5F20961FB100F46237 /* AssociationHasOneSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneSQLDerivationTests.swift; sourceTree = ""; }; + 5653EB6020961FB100F46237 /* AssociationChainRowScopesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainRowScopesTests.swift; sourceTree = ""; }; + 5653EB6120961FB100F46237 /* AssociationParallelRowScopesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelRowScopesTests.swift; sourceTree = ""; }; + 5653EB6220961FB200F46237 /* AssociationBelongsToSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToSQLTests.swift; sourceTree = ""; }; + 5653EB6320961FB200F46237 /* AssociationChainSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainSQLTests.swift; sourceTree = ""; }; + 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 = ""; }; 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 = ""; }; @@ -991,6 +1063,7 @@ 56300B5C1C53C38F005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 5653EB5620961F8900F46237 /* Association */, 56B6EF5E208CB746002F0ACB /* ColumnExpressionTests.swift */, 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, @@ -1007,11 +1080,13 @@ 56300B6D1C53F592005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 5653EB3620961F6000F46237 /* Association */, 56CEB5401EAA359A00BFAF62 /* Column.swift */, 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */, 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, + 5653EB5320961F7D00F46237 /* QueryInterfaceRequest+Association.swift */, 5616AAF4207CD59300AC3664 /* RequestProtocols.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, @@ -1042,6 +1117,43 @@ name = DatabaseQueue; sourceTree = ""; }; + 5653EB3620961F6000F46237 /* Association */ = { + isa = PBXGroup; + children = ( + 5653EB3720961F6000F46237 /* BelongsToAssociation.swift */, + 5653EB3820961F6000F46237 /* HasOneAssociation.swift */, + 5653EB3920961F6000F46237 /* AssociationQuery.swift */, + 5653EB3A20961F6000F46237 /* HasManyAssociation.swift */, + 5653EB3B20961F6000F46237 /* ForeignKey.swift */, + 5653EB3C20961F6000F46237 /* ForeignKeyRequest.swift */, + 5653EB3D20961F6100F46237 /* AssociationRequest.swift */, + 5653EB3E20961F6100F46237 /* Association.swift */, + 5653EB3F20961F6100F46237 /* AssociationMapping.swift */, + ); + path = Association; + sourceTree = ""; + }; + 5653EB5620961F8900F46237 /* Association */ = { + isa = PBXGroup; + children = ( + 5653EB6420961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift */, + 5653EB5920961FB100F46237 /* AssociationBelongsToFetchableRecordTests.swift */, + 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */, + 5653EB5B20961FB100F46237 /* AssociationBelongsToSQLDerivationTests.swift */, + 5653EB6220961FB200F46237 /* AssociationBelongsToSQLTests.swift */, + 5653EB6020961FB100F46237 /* AssociationChainRowScopesTests.swift */, + 5653EB6320961FB200F46237 /* AssociationChainSQLTests.swift */, + 5653EB5F20961FB100F46237 /* AssociationHasOneSQLDerivationTests.swift */, + 5653EB5D20961FB100F46237 /* AssociationHasOneSQLTests.swift */, + 5653EB5A20961FB100F46237 /* AssociationParallelDecodableRecordTests.swift */, + 5653EB6120961FB100F46237 /* AssociationParallelRowScopesTests.swift */, + 5653EB5820961FB000F46237 /* AssociationParallelSQLTests.swift */, + 5653EB5E20961FB100F46237 /* AssociationRowScopeSearchTests.swift */, + 5653EB5C20961FB100F46237 /* AssociationTableAliasTestsSQLTests.swift */, + ); + name = Association; + sourceTree = ""; + }; 5659F4861EA8D94E004A4992 /* Utils */ = { isa = PBXGroup; children = ( @@ -1699,15 +1811,18 @@ F3BA801B1CFB2886003DC1BA /* CGFloat.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 */, 56CEB4F61EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 56BB6EAE1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, F3BA801A1CFB2876003DC1BA /* StatementColumnConvertible.swift in Sources */, + 5653EB4C20961F6100F46237 /* ForeignKeyRequest.swift in Sources */, 566B91381FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56D1215F1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 566475D81D981D5E00FF74B8 /* SQLOperators.swift in Sources */, + 5653EB4420961F6100F46237 /* HasOneAssociation.swift in Sources */, 56CEB5661EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56CEB4FF1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD3A1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, @@ -1723,6 +1838,7 @@ F3BA80101CFB2876003DC1BA /* DatabaseReader.swift in Sources */, 564F9C331F07611800877A00 /* DatabaseFunction.swift in Sources */, 5659F49D1EA8D989004A4992 /* Pool.swift in Sources */, + 5653EB4220961F6100F46237 /* BelongsToAssociation.swift in Sources */, 569B7FA5201C90430069DE70 /* Swift4.1.swift in Sources */, 5674A6F61F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 56CEB5511EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, @@ -1730,6 +1846,7 @@ 566475D11D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, 5664759F1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 56E06F171E85906D008AE2A4 /* Fixits-0.102.0.swift in Sources */, + 5653EB5520961F7D00F46237 /* QueryInterfaceRequest+Association.swift in Sources */, F3BA802B1CFB289B003DC1BA /* QueryInterfaceRequest.swift in Sources */, 5698AD171DAAD16F0056AF8C /* FTS5Tokenizer.swift in Sources */, 56F3E7681E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */, @@ -1756,6 +1873,8 @@ F3BA800C1CFB286F003DC1BA /* DatabaseError.swift in Sources */, 566B91301FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, F3BA80221CFB288C003DC1BA /* NSNumber.swift in Sources */, + 5653EB5220961F6100F46237 /* AssociationMapping.swift in Sources */, + 5653EB4620961F6100F46237 /* AssociationQuery.swift in Sources */, F3BA80321CFB28A4003DC1BA /* FetchedRecordsController.swift in Sources */, 5659F48D1EA8D94E004A4992 /* Utils.swift in Sources */, F3BA80231CFB288C003DC1BA /* NSString.swift in Sources */, @@ -1774,7 +1893,9 @@ 566AD8B71D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, F3BA802C1CFB289B003DC1BA /* SQLCollatedExpression.swift in Sources */, + 5653EB4A20961F6100F46237 /* ForeignKey.swift in Sources */, 569A98F92039B716008D7DBF /* Fixits-3.0.swift in Sources */, + 5653EB4820961F6100F46237 /* HasManyAssociation.swift in Sources */, F3BA80301CFB289F003DC1BA /* DatabaseMigrator.swift in Sources */, F3BA80361CFB28A4003DC1BA /* TableRecord.swift in Sources */, 567071F5208A00BE006AD95A /* SQLiteDateParser.swift in Sources */, @@ -1782,6 +1903,7 @@ 566475A71D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABE1D107001006283EF /* NSData.swift in Sources */, 5674A6E61F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, + 5653EB5020961F6100F46237 /* Association.swift in Sources */, F3BA800E1CFB2876003DC1BA /* DatabaseQueue.swift in Sources */, F3BA80191CFB2876003DC1BA /* Statement.swift in Sources */, 56CEB5581EAA359A00BFAF62 /* SQLExpression.swift in Sources */, @@ -1800,6 +1922,7 @@ F3BA80B91CFB2FD1003DC1BA /* DatabasePoolBackupTests.swift in Sources */, F3BA811E1CFB3063003DC1BA /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 562EA8361F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, + 5653EB6D20961FB200F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, F3BA80DD1CFB300E003DC1BA /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 5644488A1EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, F3BA80521CFB2B59003DC1BA /* DatabaseQueueSchemaCacheTests.swift in Sources */, @@ -1818,6 +1941,7 @@ F3BA80511CFB2B59003DC1BA /* DatabaseQueueReleaseMemoryTests.swift in Sources */, F3BA81221CFB3063003DC1BA /* RecordPrimaryKeyRowIDTests.swift in Sources */, F3BA80F81CFB3021003DC1BA /* StatementArgumentsTests.swift in Sources */, + 5653EB7D20961FB200F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 5698AC0A1D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, F3BA80E91CFB3016003DC1BA /* RowAdapterTests.swift in Sources */, 562393371DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, @@ -1826,11 +1950,14 @@ 5623935E1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 56B14E861D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, 566AD8CD1D531BEE002EC1A8 /* TableDefinitionTests.swift in Sources */, + 5653EB7B20961FB200F46237 /* AssociationParallelRowScopesTests.swift in Sources */, 5698AC871DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, F3BA80D11CFB2FF3003DC1BA /* MutablePersistableRecordTests.swift in Sources */, + 5653EB7320961FB200F46237 /* AssociationHasOneSQLTests.swift in Sources */, F3BA80CF1CFB2FEA003DC1BA /* SchedulingWatchdogTests.swift in Sources */, F3BA80E71CFB3016003DC1BA /* RowCopiedFromStatementTests.swift in Sources */, F3BA812A1CFB3063003DC1BA /* RecordSubClassTests.swift in Sources */, + 5653EB7F20961FB200F46237 /* AssociationChainSQLTests.swift in Sources */, 6340BF871E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, 56AF74721D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, F3BA80D21CFB2FF3003DC1BA /* PersistableRecordTests.swift in Sources */, @@ -1858,6 +1985,7 @@ F3BA81151CFB305E003DC1BA /* Record+QueryInterfaceRequestTests.swift in Sources */, F3BA80DC1CFB300E003DC1BA /* DatabaseValueConvertibleFetchTests.swift in Sources */, 5698AD021DAA8ACB0056AF8C /* FTS5CustomTokenizerTests.swift in Sources */, + 5653EB8120961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 56B964CA1DA521450002DA19 /* FTS5PatternTests.swift in Sources */, 564E73F4203DA2AD000C443C /* JoinSupportTests.swift in Sources */, 5674A70E1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, @@ -1868,8 +1996,10 @@ F3BA80F11CFB3019003DC1BA /* DatabaseSavepointTests.swift in Sources */, 56ED8A801DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift in Sources */, F3BA81031CFB303D003DC1BA /* FetchedRecordsControllerTests.swift in Sources */, + 5653EB6920961FB200F46237 /* AssociationParallelSQLTests.swift in Sources */, F3BA80B71CFB2FCD003DC1BA /* DatabaseErrorTests.swift in Sources */, 5698ACCC1DA62A2D0056AF8C /* FTS5TokenizerTests.swift in Sources */, + 5653EB6B20961FB200F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 5690C33E1D23E7D200E59934 /* FoundationDateTests.swift in Sources */, 567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 5674A7291F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, @@ -1882,8 +2012,10 @@ F3BA80BD1CFB2FD1003DC1BA /* DatabasePoolFunctionTests.swift in Sources */, F3BA81261CFB3063003DC1BA /* RecordCopyTests.swift in Sources */, 56A8C24D1D1918F30096E9D4 /* FoundationNSUUIDTests.swift in Sources */, + 5653EB8320961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, 5698AC471DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, F3BA80D61CFB2FFD003DC1BA /* DatabaseReaderTests.swift in Sources */, + 5653EB7520961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 5698AC9D1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 56A4CDB71D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 56CC924A201E058900CB597E /* DropFirstCursorTests.swift in Sources */, @@ -1891,9 +2023,12 @@ F3BA80F91CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */, 56A5EF161EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, F3BA80DA1CFB300E003DC1BA /* DatabaseTimestampTests.swift in Sources */, + 5653EB7920961FB200F46237 /* AssociationChainRowScopesTests.swift in Sources */, F3BA81201CFB3063003DC1BA /* RecordPrimaryKeyMultipleTests.swift in Sources */, + 5653EB7120961FB200F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, F3BA812B1CFB3063003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */, 5698ACA51DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, + 5653EB6F20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, F3BA80B11CFB2FC4003DC1BA /* DatabaseTests.swift in Sources */, 56A8C24E1D1918F30096E9D4 /* FoundationUUIDTests.swift in Sources */, 564F9C251F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, @@ -1925,6 +2060,7 @@ F3BA80501CFB2B59003DC1BA /* DatabasePoolSchemaCacheTests.swift in Sources */, F3BA80BB1CFB2FD1003DC1BA /* DatabasePoolConcurrencyTests.swift in Sources */, F3BA81141CFB305E003DC1BA /* QueryInterfaceRequestTests.swift in Sources */, + 5653EB7720961FB200F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, F3BA81271CFB3063003DC1BA /* RecordEditedTests.swift in Sources */, 56FF455D1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, F3BA80C51CFB2FD8003DC1BA /* DatabaseQueueBackupTests.swift in Sources */, @@ -1947,15 +2083,18 @@ F3BA80771CFB2E5C003DC1BA /* CGFloat.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 */, 56CEB4F31EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 56BB6EAB1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, F3BA80761CFB2E55003DC1BA /* StatementColumnConvertible.swift in Sources */, + 5653EB4B20961F6100F46237 /* ForeignKeyRequest.swift in Sources */, 566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56D1215C1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 566475D51D981D5E00FF74B8 /* SQLOperators.swift in Sources */, + 5653EB4320961F6100F46237 /* HasOneAssociation.swift in Sources */, 56CEB5631EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56CEB4FC1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD371DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, @@ -1971,6 +2110,7 @@ F3BA806C1CFB2E55003DC1BA /* DatabaseReader.swift in Sources */, 564F9C301F07611500877A00 /* DatabaseFunction.swift in Sources */, 5659F49A1EA8D989004A4992 /* Pool.swift in Sources */, + 5653EB4120961F6100F46237 /* BelongsToAssociation.swift in Sources */, 569B7FA4201C90430069DE70 /* Swift4.1.swift in Sources */, 5674A6F51F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 56CEB54E1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, @@ -1978,6 +2118,7 @@ 566475CE1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, 5664759C1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 56E06F141E859069008AE2A4 /* Fixits-0.102.0.swift in Sources */, + 5653EB5420961F7D00F46237 /* QueryInterfaceRequest+Association.swift in Sources */, F3BA80871CFB2E70003DC1BA /* QueryInterfaceRequest.swift in Sources */, 5698AD161DAAD16F0056AF8C /* FTS5Tokenizer.swift in Sources */, 56F3E7651E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */, @@ -2004,6 +2145,8 @@ F3BA80681CFB2E55003DC1BA /* DatabaseError.swift in Sources */, 566B912D1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, F3BA807E1CFB2E61003DC1BA /* NSNumber.swift in Sources */, + 5653EB5120961F6100F46237 /* AssociationMapping.swift in Sources */, + 5653EB4520961F6100F46237 /* AssociationQuery.swift in Sources */, F3BA808E1CFB2E7A003DC1BA /* FetchedRecordsController.swift in Sources */, 5659F48A1EA8D94E004A4992 /* Utils.swift in Sources */, F3BA807F1CFB2E61003DC1BA /* NSString.swift in Sources */, @@ -2022,7 +2165,9 @@ 566AD8B41D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5698AD231DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, F3BA80881CFB2E70003DC1BA /* SQLCollatedExpression.swift in Sources */, + 5653EB4920961F6100F46237 /* ForeignKey.swift in Sources */, 569A98F82039B716008D7DBF /* Fixits-3.0.swift in Sources */, + 5653EB4720961F6100F46237 /* HasManyAssociation.swift in Sources */, F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */, F3BA80921CFB2E7A003DC1BA /* TableRecord.swift in Sources */, 567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */, @@ -2030,6 +2175,7 @@ 566475A41D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABB1D107001006283EF /* NSData.swift in Sources */, 5674A6E51F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, + 5653EB4F20961F6100F46237 /* Association.swift in Sources */, F3BA806A1CFB2E55003DC1BA /* DatabaseQueue.swift in Sources */, F3BA80751CFB2E55003DC1BA /* Statement.swift in Sources */, 56CEB5551EAA359A00BFAF62 /* SQLExpression.swift in Sources */, @@ -2048,6 +2194,7 @@ F3BA812C1CFB3064003DC1BA /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 5698AC991DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 562EA8321F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, + 5653EB6C20961FB200F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 56A8C2451D1918EF0096E9D4 /* FoundationNSUUIDTests.swift in Sources */, 5657AB591D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, 564448861EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, @@ -2066,6 +2213,7 @@ 56A8C2461D1918EF0096E9D4 /* FoundationUUIDTests.swift in Sources */, F3BA80F61CFB301E003DC1BA /* StatementColumnConvertibleFetchTests.swift in Sources */, F3BA80E61CFB3012003DC1BA /* DatabaseFunctionTests.swift in Sources */, + 5653EB7C20961FB200F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 5698ACDA1DA925430056AF8C /* RowTestCase.swift in Sources */, F3BA811D1CFB305F003DC1BA /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, F3BA80AD1CFB2FA6003DC1BA /* DataMemoryTests.swift in Sources */, @@ -2074,11 +2222,14 @@ 567A80561D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, F3BA81301CFB3064003DC1BA /* RecordPrimaryKeyRowIDTests.swift in Sources */, 56DAA2D51DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */, + 5653EB7A20961FB200F46237 /* AssociationParallelRowScopesTests.swift in Sources */, F3BA80FB1CFB3021003DC1BA /* StatementArgumentsTests.swift in Sources */, F3BA80EE1CFB3017003DC1BA /* RowAdapterTests.swift in Sources */, + 5653EB7220961FB200F46237 /* AssociationHasOneSQLTests.swift in Sources */, F3BA80D31CFB2FF4003DC1BA /* MutablePersistableRecordTests.swift in Sources */, 562393751DEE104400A6B01F /* MapCursorTests.swift in Sources */, F3BA80D01CFB2FEC003DC1BA /* SchedulingWatchdogTests.swift in Sources */, + 5653EB7E20961FB200F46237 /* AssociationChainSQLTests.swift in Sources */, F3BA80EC1CFB3017003DC1BA /* RowCopiedFromStatementTests.swift in Sources */, F3BA80D41CFB2FF4003DC1BA /* PersistableRecordTests.swift in Sources */, 6340BF831E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, @@ -2106,6 +2257,7 @@ F3BA811C1CFB305F003DC1BA /* QueryInterfaceExpressionsTests.swift in Sources */, 5698ACD11DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, 562205FB1E420E49005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */, + 5653EB8020961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 5657AB611D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, 564E73F3203DA2AC000C443C /* JoinSupportTests.swift in Sources */, 5674A70C1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, @@ -2116,8 +2268,10 @@ F3BA80F01CFB3017003DC1BA /* FetchableRecordTests.swift in Sources */, 5657AB491D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, F3BA80E21CFB300F003DC1BA /* DatabaseValueConvertibleFetchTests.swift in Sources */, + 5653EB6820961FB200F46237 /* AssociationParallelSQLTests.swift in Sources */, F3BA80F21CFB301A003DC1BA /* DatabaseSavepointTests.swift in Sources */, F3BA80B81CFB2FCD003DC1BA /* DatabaseErrorTests.swift in Sources */, + 5653EB6A20961FB200F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 5698AC061D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, F3BA80FA1CFB3021003DC1BA /* SelectStatementTests.swift in Sources */, 5674A7271F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, @@ -2130,8 +2284,10 @@ F3BA80C01CFB2FD2003DC1BA /* DatabasePoolCollationTests.swift in Sources */, 5698ACA11DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, F3BA80C31CFB2FD2003DC1BA /* DatabasePoolFunctionTests.swift in Sources */, + 5653EB8220961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, F3BA80D51CFB2FFB003DC1BA /* DatabaseReaderTests.swift in Sources */, F3BA81321CFB3064003DC1BA /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, + 5653EB7420961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 5623935A1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, F3BA80FC1CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */, 56CC9249201E058900CB597E /* DropFirstCursorTests.swift in Sources */, @@ -2139,9 +2295,12 @@ F3BA80E01CFB300F003DC1BA /* DatabaseTimestampTests.swift in Sources */, 56A5EF121EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, F3BA80B21CFB2FC5003DC1BA /* DatabaseTests.swift in Sources */, + 5653EB7820961FB200F46237 /* AssociationChainRowScopesTests.swift in Sources */, F3BA80AE1CFB2FA6003DC1BA /* DatabaseRegionTests.swift in Sources */, + 5653EB7020961FB200F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, F3BA81311CFB3064003DC1BA /* RecordPrimaryKeySingleTests.swift in Sources */, 5698AC431DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, + 5653EB6E20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, F3BA80E11CFB300F003DC1BA /* DatabaseValueConversionTests.swift in Sources */, 5623931B1DECC02000A6B01F /* RowFetchTests.swift in Sources */, 564F9C211F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, @@ -2173,6 +2332,7 @@ F3BA811A1CFB305F003DC1BA /* Record+QueryInterfaceRequestTests.swift in Sources */, F3BA81111CFB3057003DC1BA /* StatementArguments+FoundationTests.swift in Sources */, F3BA81371CFB3064003DC1BA /* RecordInitializersTests.swift in Sources */, + 5653EB7620961FB200F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, F3BA80C91CFB2FD8003DC1BA /* DatabaseQueueBackupTests.swift in Sources */, 56AF746E1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, 56ED8A7F1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift in Sources */, diff --git a/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift new file mode 100644 index 000000000..dc2815443 --- /dev/null +++ b/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift @@ -0,0 +1,111 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +private struct Team: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "teams" + var id: Int64 + var name: String +} + +private struct Player: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "players" + static let team = Player.belongsTo(Team.self) + var id: Int64 + var teamId: Int64? + var name: String +} + +private struct PlayerWithRequiredTeam: Decodable, FetchableRecord { + var player: Player + var team: Team + static let team = Player.team.forKey(CodingKeys.team) +} + +private struct PlayerWithOptionalTeam: Decodable, FetchableRecord { + var player: Player + var team: Team? + static let team = Player.team.forKey(CodingKeys.team) +} + +/// Test support for Decodable records +class AssociationBelongsToDecodableRecordTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "teams") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "players") { t in + t.column("id", .integer).primaryKey() + t.column("teamId", .integer).references("teams") + t.column("name", .text) + } + + try Team(id: 1, name: "Reds").insert(db) + try Player(id: 1, teamId: 1, name: "Arthur").insert(db) + try Player(id: 2, teamId: nil, name: "Barbara").insert(db) + } + } + + func testIncludingRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player + .including(required: PlayerWithRequiredTeam.team) + .asRequest(of: PlayerWithRequiredTeam.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(records.count, 1) + XCTAssertEqual(records[0].player.id, 1) + XCTAssertEqual(records[0].player.teamId, 1) + XCTAssertEqual(records[0].player.name, "Arthur") + XCTAssertEqual(records[0].team.id, 1) + XCTAssertEqual(records[0].team.name, "Reds") + } + + func testIncludingOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player + .including(optional: PlayerWithOptionalTeam.team) + .asRequest(of: PlayerWithOptionalTeam.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(records.count, 2) + XCTAssertEqual(records[0].player.id, 1) + XCTAssertEqual(records[0].player.teamId, 1) + XCTAssertEqual(records[0].player.name, "Arthur") + XCTAssertEqual(records[0].team!.id, 1) + XCTAssertEqual(records[0].team!.name, "Reds") + XCTAssertEqual(records[1].player.id, 2) + XCTAssertNil(records[1].player.teamId) + XCTAssertEqual(records[1].player.name, "Barbara") + XCTAssertNil(records[1].team) + } + + func testJoiningRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.joining(required: Player.team) + let players = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(players.count, 1) + XCTAssertEqual(players[0].id, 1) + XCTAssertEqual(players[0].teamId, 1) + XCTAssertEqual(players[0].name, "Arthur") + } + + func testJoiningsOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.joining(optional: Player.team) + let players = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(players.count, 2) + XCTAssertEqual(players[0].id, 1) + XCTAssertEqual(players[0].teamId, 1) + XCTAssertEqual(players[0].name, "Arthur") + XCTAssertEqual(players[1].id, 2) + XCTAssertNil(players[1].teamId) + XCTAssertEqual(players[1].name, "Barbara") + } +} diff --git a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift new file mode 100644 index 000000000..db5411021 --- /dev/null +++ b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift @@ -0,0 +1,120 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +private struct Team: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "teams" + var id: Int64 + var name: String +} + +private struct Player: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "players" + static let teamScope = "team" + static let team = Player.belongsTo(Team.self, key: teamScope) + var id: Int64 + var teamId: Int64? + var name: String +} + +private struct PlayerWithRequiredTeam: FetchableRecord { + var player: Player + var team: Team + + init(row: Row) { + player = Player(row: row) + team = row[Player.teamScope] + } +} + +private struct PlayerWithOptionalTeam: FetchableRecord { + var player: Player + var team: Team? + + init(row: Row) { + player = Player(row: row) + team = row[Player.teamScope] + } +} + +/// Test support for FetchableRecord records +class AssociationBelongsToFetchableRecordTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "teams") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "players") { t in + t.column("id", .integer).primaryKey() + t.column("teamId", .integer).references("teams") + t.column("name", .text) + } + + try Team(id: 1, name: "Reds").insert(db) + try Player(id: 1, teamId: 1, name: "Arthur").insert(db) + try Player(id: 2, teamId: nil, name: "Barbara").insert(db) + } + } + + func testIncludingRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player + .including(required: Player.team) + .asRequest(of: PlayerWithRequiredTeam.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(records.count, 1) + XCTAssertEqual(records[0].player.id, 1) + XCTAssertEqual(records[0].player.teamId, 1) + XCTAssertEqual(records[0].player.name, "Arthur") + XCTAssertEqual(records[0].team.id, 1) + XCTAssertEqual(records[0].team.name, "Reds") + } + + func testIncludingOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player + .including(optional: Player.team) + .asRequest(of: PlayerWithOptionalTeam.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(records.count, 2) + XCTAssertEqual(records[0].player.id, 1) + XCTAssertEqual(records[0].player.teamId, 1) + XCTAssertEqual(records[0].player.name, "Arthur") + XCTAssertEqual(records[0].team!.id, 1) + XCTAssertEqual(records[0].team!.name, "Reds") + XCTAssertEqual(records[1].player.id, 2) + XCTAssertNil(records[1].player.teamId) + XCTAssertEqual(records[1].player.name, "Barbara") + XCTAssertNil(records[1].team) + } + + func testJoiningRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.joining(required: Player.team) + let players = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(players.count, 1) + XCTAssertEqual(players[0].id, 1) + XCTAssertEqual(players[0].teamId, 1) + XCTAssertEqual(players[0].name, "Arthur") + } + + func testJoiningsOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.joining(optional: Player.team) + let players = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(players.count, 2) + XCTAssertEqual(players[0].id, 1) + XCTAssertEqual(players[0].teamId, 1) + XCTAssertEqual(players[0].name, "Arthur") + XCTAssertEqual(players[1].id, 2) + XCTAssertNil(players[1].teamId) + XCTAssertEqual(players[1].name, "Barbara") + } +} diff --git a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift new file mode 100644 index 000000000..5f23e36a6 --- /dev/null +++ b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift @@ -0,0 +1,131 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +private struct Team: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "teams" + var id: Int64 + var name: String +} + +private struct Player: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "players" + static let defaultTeam = belongsTo(Team.self) + static let customTeam = belongsTo(Team.self, key: "customTeam") + var id: Int64 + var teamId: Int64? + var name: String +} + +/// Test row scopes +class AssociationBelongsToRowScopeTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "teams") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "players") { t in + t.column("id", .integer).primaryKey() + t.column("teamId", .integer).references("teams") + t.column("name", .text) + } + + try Team(id: 1, name: "Reds").insert(db) + try Player(id: 1, teamId: 1, name: "Arthur").insert(db) + try Player(id: 2, teamId: nil, name: "Barbara").insert(db) + } + } + + func testDefaultScopeIncludingRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.including(required: Player.defaultTeam) + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["teams"]) + XCTAssertEqual(rows[0].scopes["teams"]!, ["id":1, "name":"Reds"]) + } + + func testDefaultScopeIncludingOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.including(optional: Player.defaultTeam) + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["teams"]) + XCTAssertEqual(rows[0].scopes["teams"]!, ["id":1, "name":"Reds"]) + XCTAssertEqual(rows[1].unscoped, ["id":2, "teamId":nil, "name":"Barbara"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["teams"]) + XCTAssertEqual(rows[1].scopes["teams"]!, ["id":nil, "name":nil]) + } + + func testDefaultScopeJoiningRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.joining(required: Player.defaultTeam) + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + } + + func testDefaultScopeJoiningOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.joining(optional: Player.defaultTeam) + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + XCTAssertEqual(rows[1].unscoped, ["id":2, "teamId":nil, "name":"Barbara"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + } + + func testCustomScopeIncludingRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.including(required: Player.customTeam) + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customTeam"]) + XCTAssertEqual(rows[0].scopes["customTeam"]!, ["id":1, "name":"Reds"]) + } + + func testCustomScopeIncludingOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.including(optional: Player.customTeam) + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customTeam"]) + XCTAssertEqual(rows[0].scopes["customTeam"]!, ["id":1, "name":"Reds"]) + XCTAssertEqual(rows[1].unscoped, ["id":2, "teamId":nil, "name":"Barbara"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customTeam"]) + XCTAssertEqual(rows[1].scopes["customTeam"]!, ["id":nil, "name":nil]) + } + + func testCustomScopeJoiningRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.joining(required: Player.customTeam) + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + } + + func testCustomScopeJoiningOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.joining(optional: Player.customTeam) + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + XCTAssertEqual(rows[1].unscoped, ["id":2, "teamId":nil, "name":"Barbara"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + } +} diff --git a/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift new file mode 100644 index 000000000..4bf1c848f --- /dev/null +++ b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift @@ -0,0 +1,406 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +// A -> B +private struct A : TableRecord { + static let databaseTableName = "a" + static let b = belongsTo(B.self) + static let restrictedB = belongsTo(RestrictedB.self) + static let extendedB = belongsTo(ExtendedB.self) +} + +private struct B : TableRecord { + static let a = hasOne(A.self) + static let databaseTableName = "b" +} + +private struct RestrictedB : TableRecord { + static let databaseTableName = "b" + static let databaseSelection: [SQLSelectable] = [Column("name")] +} + +private struct ExtendedB : TableRecord { + static let databaseTableName = "b" + static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] +} + +/// Test SQL generation +class AssociationBelongsToSQLDerivationTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + } + } + } + + func testDefaultSelection() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") + """) + try assertEqualSQL(db, A.including(required: A.restrictedB), """ + SELECT "a".*, "b"."name" \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") + """) + try assertEqualSQL(db, A.including(required: A.extendedB), """ + SELECT "a".*, "b".*, "b"."rowid" \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") + """) + } + } + + func testCustomSelection() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + let request = A.including(required: A.b + .select(Column("name"))) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b"."name" \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") + """) + } + do { + let request = A.including(required: A.b + .select( + AllColumns(), + Column.rowID)) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".*, "b"."rowid" \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") + """) + } + do { + let aAlias = TableAlias() + let request = A + .aliased(aAlias) + .including(required: A.b + .select( + Column("name"), + (Column("id") + aAlias[Column("id")]).aliased("foo"))) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b"."name", ("b"."id" + "a"."id") AS "foo" \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") + """) + } + } + } + + func testFilteredAssociationImpactsJoinOnClause() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + let request = A.including(required: A.b.filter(Column("name") != nil)) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."id" = "a"."bid") AND ("b"."name" IS NOT NULL)) + """) + } + do { + let request = A.including(required: A.b.filter(key: 1)) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."id" = "a"."bid") AND ("b"."id" = 1)) + """) + } + do { + let request = A.including(required: A.b.filter(keys: [1, 2, 3])) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."id" = "a"."bid") AND ("b"."id" IN (1, 2, 3))) + """) + } + do { + let request = A.including(required: A.b.filter(key: ["id": 1])) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."id" = "a"."bid") AND ("b"."id" = 1)) + """) + } + do { + let request = A.including(required: A.b.filter(keys: [["id": 1], ["id": 2]])) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."id" = "a"."bid") AND (("b"."id" = 1) OR ("b"."id" = 2))) + """) + } + do { + let bAlias = TableAlias(name: "customB") + let request = A.including(required: A.b + .aliased(bAlias) + .filter(sql: "customB.name = ?", arguments: ["foo"])) + try assertEqualSQL(db, request, """ + SELECT "a".*, "customB".* \ + FROM "a" \ + JOIN "b" "customB" ON (("customB"."id" = "a"."bid") AND (customB.name = 'foo')) + """) + } + } + } + + func testFilterAssociationInWhereClause() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let bAlias = TableAlias() + let request = A + .including(required: A.b.aliased(bAlias)) + .filter(bAlias[Column("name")] != nil) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + WHERE ("b"."name" IS NOT NULL) + """) + } + } + + func testAssociationOrderBubbleUp() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let aBase = A.all().aliased(TableAlias(name: "a")) + let abBase = A.b.aliased(TableAlias(name: "ab")) + let abaBase = B.a.aliased(TableAlias(name: "aba")) + + let aTransforms = [ + { (r: QueryInterfaceRequest) in return r }, + { (r: QueryInterfaceRequest) in return r.order(Column("id")) }, + { (r: QueryInterfaceRequest) in return r.order(Column("id")).reversed() }, + ] + let abTransforms = [ + { (r: BelongsToAssociation) in return r }, + { (r: BelongsToAssociation) in return r.order(Column("name"), Column("id").desc) }, + { (r: BelongsToAssociation) in return r.order(Column("name")).order(Column("id").desc) }, + { (r: BelongsToAssociation) in return r.order(Column("name")).reversed() }, + { (r: BelongsToAssociation) in return r.reversed() }, + ] + let abaTransforms = [ + { (r: HasOneAssociation) in return r }, + { (r: HasOneAssociation) in return r.order(Column("id")) }, + { (r: HasOneAssociation) in return r.order(Column("id")).reversed() }, + ] + + var sqls: [String] = [] + for aTransform in aTransforms { + for abTransform in abTransforms { + for abaTransform in abaTransforms { + let request = aTransform(aBase) + .including(required: abTransform(abBase) + .including(required: abaTransform(abaBase))) + let sqlRequest = try SQLRequest(db, request: request) + sqls.append(sqlRequest.sql) + } + } + } + + let prefix = """ + SELECT "a".*, "ab".*, "aba".* \ + FROM "a" \ + JOIN "b" "ab" ON ("ab"."id" = "a"."bid") \ + JOIN "a" "aba" ON ("aba"."bid" = "ab"."id") + """ + let orderClauses = sqls.map { sql -> String in + let prefixEndIndex = sql.index(sql.startIndex, offsetBy: prefix.count) + return String(sql.suffix(from: prefixEndIndex)) + } + XCTAssertEqual(orderClauses, [ + // a: { (r: QueryInterfaceRequest) in return r }, + // ab: { (r: BelongsToAssociation) in return r } + // aba: { (r: HasOneAssociation) in return r } + "", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name"), Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"ab\".\"name\", \"ab\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).order(Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"ab\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"ab\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"ab\".\"name\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"ab\".\"name\" DESC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"ab\".\"name\" DESC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.reversed() } + // aba: { (r: HasOneAssociation) in return r } + "", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"aba\".\"id\"", + + + // a: { (r: QueryInterfaceRequest) in return r.order(Column("id")) }, + // ab: { (r: BelongsToAssociation) in return r } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name"), Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\", \"ab\".\"name\", \"ab\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).order(Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\", \"ab\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"ab\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\", \"ab\".\"name\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"ab\".\"name\" DESC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"ab\".\"name\" DESC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"aba\".\"id\"", + + + // a: { (r: QueryInterfaceRequest) in return r.order(Column("id")).reversed() } + // ab: { (r: BelongsToAssociation) in return r } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name"), Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\" DESC, \"ab\".\"id\" ASC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).order(Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"id\" ASC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\", \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\", \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\" DESC", + ]) + } + } + + // TODO: Test if and only if we really want to build an association from any request +// func testAssociationFromRequest() throws { +// let dbQueue = try makeDatabaseQueue() +// try dbQueue.inDatabase { db in +// do { +// let bRequest = B +// .filter(Column("name") != nil) +// .order(Column("id")) +// let association = A.belongsTo(bRequest) +// let request = A.including(required: association) +// try assertEqualSQL(db, request, """ +// SELECT "a".*, "b".* \ +// FROM "a" \ +// JOIN "b" ON (("b"."id" = "a"."bid") AND ("b"."name" IS NOT NULL)) \ +// ORDER BY "b"."id" +// """) +// } +// do { +// let bRequest = RestrictedB +// .filter(Column("name") != nil) +// .order(Column("id")) +// let association = A.belongsTo(bRequest) +// let request = A.including(required: association) +// try assertEqualSQL(db, request, """ +// SELECT "a".*, "b"."name" \ +// FROM "a" \ +// JOIN "b" ON (("b"."id" = "a"."bid") AND ("b"."name" IS NOT NULL)) \ +// ORDER BY "b"."id" +// """) +// } +// do { +// let bRequest = ExtendedB +// .select([Column("name")]) +// .filter(Column("name") != nil) +// .order(Column("id")) +// let association = A.belongsTo(bRequest) +// let request = A.including(required: association) +// try assertEqualSQL(db, request, """ +// SELECT "a".*, "b"."name" \ +// FROM "a" \ +// JOIN "b" ON (("b"."id" = "a"."bid") AND ("b"."name" IS NOT NULL)) \ +// ORDER BY "b"."id" +// """) +// } +// } +// } +} diff --git a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift new file mode 100644 index 000000000..3e781f56c --- /dev/null +++ b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift @@ -0,0 +1,771 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +/// Test SQL generation +class AssociationBelongsToSQLTests: GRDBTestCase { + + func testSingleColumnNoForeignKeyNoPrimaryKey() throws { + struct Child : TableRecord, MutablePersistableRecord { + static let databaseTableName = "children" + func encode(to container: inout PersistenceContainer) { + container["parentId"] = 1 + } + } + + struct Parent : TableRecord { + static let databaseTableName = "parents" + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("id", .integer) + } + try db.create(table: "children") { t in + t.column("parentId", .integer) + } + } + + try dbQueue.inDatabase { db in + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."rowid" = "children"."parentId") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."rowid" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."rowid" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."rowid" = "children"."parentId") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"rowid\" = 1)") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + } + } + } + + func testSingleColumnNoForeignKey() throws { + struct Child : TableRecord, MutablePersistableRecord { + static let databaseTableName = "children" + func encode(to container: inout PersistenceContainer) { + container["parentId"] = 1 + } + } + + struct Parent : TableRecord { + static let databaseTableName = "parents" + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "children") { t in + t.column("parentId", .integer) + } + } + + try dbQueue.inDatabase { db in + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + } + } + } + + func testSingleColumnSingleForeignKey() throws { + struct Child : TableRecord, MutablePersistableRecord { + static let databaseTableName = "children" + func encode(to container: inout PersistenceContainer) { + container["parentId"] = 1 + } + } + + struct Parent : TableRecord { + static let databaseTableName = "parents" + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "children") { t in + t.column("parentId", .integer).references("parents") + } + } + + try dbQueue.inDatabase { db in + do { + let association = Child.belongsTo(Parent.self) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + } + } + } + + func testSingleColumnSeveralForeignKeys() throws { + struct Child : TableRecord, MutablePersistableRecord { + static let databaseTableName = "children" + func encode(to container: inout PersistenceContainer) { + container["parent1Id"] = 1 + container["parent2Id"] = 2 + } + } + + struct Parent : TableRecord { + static let databaseTableName = "parents" + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "children") { t in + t.column("parent1Id", .integer).references("parents") + t.column("parent2Id", .integer).references("parents") + } + } + + try dbQueue.inDatabase { db in + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent1Id")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parent1Id") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parent1Id") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parent1Id") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parent1Id") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent1Id")], to: [Column("id")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parent1Id") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parent1Id") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parent1Id") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parent1Id") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent2Id")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parent2Id") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parent2Id") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parent2Id") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parent2Id") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 2)") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent2Id")], to: [Column("id")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parent2Id") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parent2Id") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parent2Id") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parent2Id") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 2)") + } + } + } + + func testCompoundColumnNoForeignKeyNoPrimaryKey() throws { + struct Child : TableRecord, MutablePersistableRecord { + static let databaseTableName = "children" + func encode(to container: inout PersistenceContainer) { + container["parentA"] = 1 + container["parentB"] = 2 + } + } + + struct Parent : TableRecord { + static let databaseTableName = "parents" + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("a", .integer) + t.column("b", .integer) + } + try db.create(table: "children") { t in + t.column("parentA", .integer) + t.column("parentB", .integer) + } + } + + try dbQueue.inDatabase { db in + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + } + } + } + + func testCompoundColumnNoForeignKey() throws { + struct Child : TableRecord, MutablePersistableRecord { + static let databaseTableName = "children" + func encode(to container: inout PersistenceContainer) { + container["parentA"] = 1 + container["parentB"] = 2 + } + } + + struct Parent : TableRecord { + static let databaseTableName = "parents" + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("a", .integer) + t.column("b", .integer) + t.primaryKey(["a", "b"]) + } + try db.create(table: "children") { t in + t.column("parentA", .integer) + t.column("parentB", .integer) + } + } + + try dbQueue.inDatabase { db in + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children\".\"parentB\")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children\".\"parentB\")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + } + } + } + + func testCompoundColumnSingleForeignKey() throws { + struct Child : TableRecord, MutablePersistableRecord { + static let databaseTableName = "children" + func encode(to container: inout PersistenceContainer) { + container["parentA"] = 1 + container["parentB"] = 2 + } + } + + struct Parent : TableRecord { + static let databaseTableName = "parents" + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("a", .integer) + t.column("b", .integer) + t.primaryKey(["a", "b"]) + } + try db.create(table: "children") { t in + t.column("parentA", .integer) + t.column("parentB", .integer) + t.foreignKey(["parentA", "parentB"], references: "parents") + } + } + + try dbQueue.inDatabase { db in + do { + let association = Child.belongsTo(Parent.self) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + } + } + } + + func testCompoundColumnSeveralForeignKeys() throws { + struct Child : TableRecord, MutablePersistableRecord { + static let databaseTableName = "children" + func encode(to container: inout PersistenceContainer) { + container["parent1A"] = 1 + container["parent1B"] = 2 + container["parent2A"] = 3 + container["parent2B"] = 4 + } + } + + struct Parent : TableRecord { + static let databaseTableName = "parents" + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("a", .integer) + t.column("b", .integer) + t.primaryKey(["a", "b"]) + } + try db.create(table: "children") { t in + t.column("parent1A", .integer) + t.column("parent1B", .integer) + t.column("parent2A", .integer) + t.column("parent2B", .integer) + t.foreignKey(["parent1A", "parent1B"], references: "parents") + t.foreignKey(["parent2A", "parent2B"], references: "parents") + } + } + + try dbQueue.inDatabase { db in + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent1A"), Column("parent1B")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent2A"), Column("parent2B")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 3) AND (\"b\" = 4))") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 3) AND (\"b\" = 4))") + } + } + } + + func testForeignKeyDefinitionFromColumn() { + // This test pass if code compiles + struct Parent : TableRecord { + static let databaseTableName = "parents" + enum Columns { + static let id = Column("id") + } + } + + struct Child : TableRecord { + static let databaseTableName = "children" + enum Columns { + static let parentId = Column("parentId") + } + enum ForeignKeys { + static let parent1 = ForeignKey([Columns.parentId]) + static let parent2 = ForeignKey([Columns.parentId], to: [Parent.Columns.id]) + } + static let parent1 = belongsTo(Parent.self, using: ForeignKeys.parent1) + static let parent2 = belongsTo(Parent.self, using: ForeignKeys.parent2) + } + } +} diff --git a/Tests/GRDBTests/AssociationChainRowScopesTests.swift b/Tests/GRDBTests/AssociationChainRowScopesTests.swift new file mode 100644 index 000000000..a05e58cdb --- /dev/null +++ b/Tests/GRDBTests/AssociationChainRowScopesTests.swift @@ -0,0 +1,694 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +// A -> B <- C -> D +private struct A: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "a" + static let defaultB = belongsTo(B.self) + var id: Int64 + var bid: Int64? + var name: String +} + +private struct B: Codable, FetchableRecord, PersistableRecord { + static let defaultC = hasOne(C.self) + static let databaseTableName = "b" + var id: Int64 + var name: String +} + +private struct C: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "c" + static let defaultD = belongsTo(D.self) + var id: Int64 + var bid: Int64? + var did: Int64? + var name: String +} + +private struct D: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "d" + var id: Int64 + var name: String +} + +/// Test row scopes +class AssociationChainRowScopesTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "d") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + t.column("name", .text) + } + try db.create(table: "c") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + t.column("did", .integer).references("d") + t.column("name", .text) + } + + try B(id: 1, name: "b1").insert(db) + try B(id: 2, name: "b2").insert(db) + try A(id: 1, bid: 1, name: "a1").insert(db) + try A(id: 2, bid: 2, name: "a2").insert(db) + try A(id: 3, bid: nil, name: "a3").insert(db) + try D(id: 1, name: "d1").insert(db) + try C(id: 1, bid: 1, did: 1, name: "c1").insert(db) + try C(id: 2, bid: 1, did: nil, name: "c2").insert(db) + } + } + + func testChainOfTwoIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.including(required: A.defaultB.including(required: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["b"]!.scopes["c"]!, ["id":2, "bid":1, "did":nil, "name":"c2"]) + } + do { + let request = A.including(required: A.defaultB.including(optional: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["b"]!.scopes["c"]!, ["id":2, "bid":1, "did":nil, "name":"c2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "bid":2, "name":"a2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!.unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["b"]!.scopes["c"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + } + do { + // TODO: chainOptionalRequired +// let request = A.including(optional: A.defaultB.including(required: B.defaultC)).order(sql: "a.id, b.id, c.id") +// let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + } + do { + let request = A.including(optional: A.defaultB.including(optional: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["b"]!.scopes["c"]!, ["id":2, "bid":1, "did":nil, "name":"c2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "bid":2, "name":"a2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!.unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["b"]!.scopes["c"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":3, "bid":nil, "name":"a3"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) + XCTAssertEqual(rows[3].scopes["b"]!.unscoped, ["id":nil, "name":nil]) + XCTAssertEqual(Set(rows[3].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[3].scopes["b"]!.scopes["c"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + } + do { + let request = B.including(required: B.defaultC.including(required: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!.unscoped, ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertEqual(Set(rows[0].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + } + do { + let request = B.including(required: B.defaultC.including(optional: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!.unscoped, ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertEqual(Set(rows[0].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!.unscoped, ["id":2, "bid":1, "did":nil, "name":"c2"]) + XCTAssertEqual(Set(rows[1].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[1].scopes["c"]!.scopes["d"]!, ["id":nil, "name":nil]) + } + do { + // TODO: chainOptionalRequired +// let request = B.including(optional: B.defaultC.including(required: C.defaultD)).order(sql: "b.id, c.id, d.id") +// let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + } + do { + let request = B.including(optional: B.defaultC.including(optional: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!.unscoped, ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertEqual(Set(rows[0].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!.unscoped, ["id":2, "bid":1, "did":nil, "name":"c2"]) + XCTAssertEqual(Set(rows[1].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[1].scopes["c"]!.scopes["d"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["c"]!.unscoped, ["id":nil, "bid":nil, "did":nil, "name":nil]) + XCTAssertEqual(Set(rows[2].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[2].scopes["c"]!.scopes["d"]!, ["id":nil, "name":nil]) + } + } + + func testChainOfTwoIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.including(required: A.defaultB.joining(required: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes["b"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes["b"]!.scopes.names.isEmpty) + } + do { + let request = A.including(required: A.defaultB.joining(optional: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes["b"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes["b"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "bid":2, "name":"a2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[2].scopes["b"]!.scopes.names.isEmpty) + } + do { + // TODO: chainOptionalRequired +// let request = A.including(optional: A.defaultB.joining(required: B.defaultC)).order(sql: "a.id, b.id, c.id") +// let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + } + do { + let request = A.including(optional: A.defaultB.joining(optional: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes["b"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes["b"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "bid":2, "name":"a2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[2].scopes["b"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":3, "bid":nil, "name":"a3"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) + XCTAssertEqual(rows[3].scopes["b"]!, ["id":nil, "name":nil]) + XCTAssertTrue(rows[3].scopes["b"]!.scopes.names.isEmpty) + } + do { + let request = B.including(required: B.defaultC.joining(required: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertTrue(rows[0].scopes["c"]!.scopes.names.isEmpty) + } + do { + let request = B.including(required: B.defaultC.joining(optional: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertTrue(rows[0].scopes["c"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":2, "bid":1, "did":nil, "name":"c2"]) + XCTAssertTrue(rows[1].scopes["c"]!.scopes.names.isEmpty) + } + do { + // TODO: chainOptionalRequired +// let request = B.including(optional: B.defaultC.joining(required: C.defaultD)).order(sql: "b.id, c.id, d.id") +// let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + } + do { + let request = B.including(optional: B.defaultC.joining(optional: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertTrue(rows[0].scopes["c"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":2, "bid":1, "did":nil, "name":"c2"]) + XCTAssertTrue(rows[1].scopes["c"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["c"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + XCTAssertTrue(rows[2].scopes["c"]!.scopes.names.isEmpty) + } + } + + func testChainOfTwoJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.joining(required: A.defaultB.including(required: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[1].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["b"]!.scopes["c"]!, ["id":2, "bid":1, "did":nil, "name":"c2"]) + } + do { + let request = A.joining(required: A.defaultB.including(optional: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[1].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["b"]!.scopes["c"]!, ["id":2, "bid":1, "did":nil, "name":"c2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "bid":2, "name":"a2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[2].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["b"]!.scopes["c"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + } + do { + // TODO: chainOptionalRequired +// let request = A.joining(optional: A.defaultB.including(required: B.defaultC)).order(sql: "a.id, b.id, c.id") +// let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + } + do { + let request = A.joining(optional: A.defaultB.including(optional: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[1].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["b"]!.scopes["c"]!, ["id":2, "bid":1, "did":nil, "name":"c2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "bid":2, "name":"a2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[2].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["b"]!.scopes["c"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":3, "bid":nil, "name":"a3"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) + XCTAssertEqual(rows[3].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[3].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[3].scopes["b"]!.scopes["c"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + } + do { + let request = B.joining(required: B.defaultC.including(required: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + } + do { + let request = B.joining(required: B.defaultC.including(optional: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[1].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[1].scopes["c"]!.scopes["d"]!, ["id":nil, "name":nil]) + } + do { + // TODO: chainOptionalRequired +// let request = B.joining(optional: B.defaultC.including(required: C.defaultD)).order(sql: "b.id, c.id, d.id") +// let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + } + do { + let request = B.joining(optional: B.defaultC.including(optional: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[1].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[1].scopes["c"]!.scopes["d"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["c"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[2].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[2].scopes["c"]!.scopes["d"]!, ["id":nil, "name":nil]) + } + } + + func testChainOfTwoJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.joining(required: A.defaultB.joining(required: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0], ["id":1, "bid":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1], ["id":1, "bid":1, "name":"a1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + } + do { + let request = A.joining(required: A.defaultB.joining(optional: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0], ["id":1, "bid":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1], ["id":1, "bid":1, "name":"a1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2], ["id":2, "bid":2, "name":"a2"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + } + do { + // TODO: chainOptionalRequired +// let request = A.joining(optional: A.defaultB.joining(required: B.defaultC)).order(sql: "a.id, b.id, c.id") +// let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + } + do { + let request = A.joining(optional: A.defaultB.joining(optional: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0], ["id":1, "bid":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1], ["id":1, "bid":1, "name":"a1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2], ["id":2, "bid":2, "name":"a2"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3], ["id":3, "bid":nil, "name":"a3"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + } + do { + let request = B.joining(required: B.defaultC.joining(required: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0], ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + } + do { + let request = B.joining(required: B.defaultC.joining(optional: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0], ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1], ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + } + do { + // TODO: chainOptionalRequired +// let request = B.joining(optional: B.defaultC.joining(required: C.defaultD)).order(sql: "b.id, c.id, d.id") +// let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + } + do { + let request = B.joining(optional: B.defaultC.joining(optional: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0], ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1], ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2], ["id":2, "name":"b2"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + } + } + + func testChainOfThreeIncludingIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.including(required: A.defaultB.including(required: B.defaultC.including(required: C.defaultD))).order(sql: "a.id, b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.unscoped, ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + } + + func testChainOfThreeIncludingIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.including(required: A.defaultB.including(required: B.defaultC.joining(required: C.defaultD))).order(sql: "a.id, b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"], ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertTrue(rows[0].scopes["b"]!.scopes["c"]!.scopes.names.isEmpty) + } + + func testChainOfThreeIncludingJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.including(required: A.defaultB.joining(required: B.defaultC.including(required: C.defaultD))).order(sql: "a.id, b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + } + + func testChainOfThreeIncludingJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.including(required: A.defaultB.joining(required: B.defaultC.joining(required: C.defaultD))).order(sql: "a.id, b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes["b"]!.scopes.names.isEmpty) + } + + func testChainOfThreeJoiningIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.joining(required: A.defaultB.including(required: B.defaultC.including(required: C.defaultD))).order(sql: "a.id, b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.unscoped, ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + } + + func testChainOfThreeJoiningIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.joining(required: A.defaultB.including(required: B.defaultC.joining(required: C.defaultD))).order(sql: "a.id, b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"], ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertTrue(rows[0].scopes["b"]!.scopes["c"]!.scopes.names.isEmpty) + } + + func testChainOfThreeJoiningJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.joining(required: A.defaultB.joining(required: B.defaultC.including(required: C.defaultD))).order(sql: "a.id, b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + } + + func testChainOfThreeJoiningJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.joining(required: A.defaultB.joining(required: B.defaultC.joining(required: C.defaultD))).order(sql: "a.id, b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0], ["id":1, "bid":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + } +} diff --git a/Tests/GRDBTests/AssociationChainSQLTests.swift b/Tests/GRDBTests/AssociationChainSQLTests.swift new file mode 100644 index 000000000..f604ace52 --- /dev/null +++ b/Tests/GRDBTests/AssociationChainSQLTests.swift @@ -0,0 +1,557 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +// A -> B <- C -> D +private struct A: TableRecord { + static let databaseTableName = "a" + static let b = belongsTo(B.self) +} + +private struct B: TableRecord { + static let c = hasOne(C.self) + static let databaseTableName = "b" +} + +private struct C: TableRecord { + static let databaseTableName = "c" + static let b = belongsTo(B.self) + static let d = belongsTo(D.self) +} + +private struct D: TableRecord { + static let databaseTableName = "d" +} + +/// Test SQL generation +class AssociationChainSQLTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "d") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + } + try db.create(table: "c") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + t.column("did", .integer).references("d") + } + } + } + + func testChainOfTwoIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b.including(required: B.c)), """ + SELECT "a".*, "b".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, A.including(required: A.b.including(optional: B.c)), """ + SELECT "a".*, "b".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(optional: A.b.including(required: B.c)), "TODO") + try assertEqualSQL(db, A.including(optional: A.b.including(optional: B.c)), """ + SELECT "a".*, "b".*, "c".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(required: B.c.including(required: C.d)), """ + SELECT "b".*, "c".*, "d".* \ + FROM "b" \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, B.including(required: B.c.including(optional: C.d)), """ + SELECT "b".*, "c".*, "d".* \ + FROM "b" \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, B.including(optional: B.c.including(required: C.d)), "TODO") + try assertEqualSQL(db, B.including(optional: B.c.including(optional: C.d)), """ + SELECT "b".*, "c".*, "d".* \ + FROM "b" \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfTwoIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b.joining(required: B.c)), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, A.including(required: A.b.joining(optional: B.c)), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(optional: A.b.joining(required: B.c)), "") + try assertEqualSQL(db, A.including(optional: A.b.joining(optional: B.c)), """ + SELECT "a".*, "b".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(required: B.c.joining(required: C.d)), """ + SELECT "b".*, "c".* \ + FROM "b" \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, B.including(required: B.c.joining(optional: C.d)), """ + SELECT "b".*, "c".* \ + FROM "b" \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, B.including(optional: B.c.joining(required: C.d)), "TODO") + try assertEqualSQL(db, B.including(optional: B.c.joining(optional: C.d)), """ + SELECT "b".*, "c".* \ + FROM "b" \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfTwoJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.joining(required: A.b.including(required: B.c)), """ + SELECT "a".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, A.joining(required: A.b.including(optional: B.c)), """ + SELECT "a".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(optional: A.b.including(required: B.c)), "TODO") + try assertEqualSQL(db, A.joining(optional: A.b.including(optional: B.c)), """ + SELECT "a".*, "c".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.joining(required: B.c.including(required: C.d)), """ + SELECT "b".*, "d".* \ + FROM "b" \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, B.joining(required: B.c.including(optional: C.d)), """ + SELECT "b".*, "d".* \ + FROM "b" \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, B.joining(optional: B.c.including(required: C.d)), "TODO") + try assertEqualSQL(db, B.joining(optional: B.c.including(optional: C.d)), """ + SELECT "b".*, "d".* \ + FROM "b" \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfTwoJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.joining(required: A.b.joining(required: B.c)), """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, A.joining(required: A.b.joining(optional: B.c)), """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(optional: A.b.joining(required: B.c)), "TODO") + try assertEqualSQL(db, A.joining(optional: A.b.joining(optional: B.c)), """ + SELECT "a".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.joining(required: B.c.joining(required: C.d)), """ + SELECT "b".* \ + FROM "b" \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, B.joining(required: B.c.joining(optional: C.d)), """ + SELECT "b".* \ + FROM "b" \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, B.joining(optional: B.c.joining(required: C.d)), "TODO") + try assertEqualSQL(db, B.joining(optional: B.c.joining(optional: C.d)), """ + SELECT "b".* \ + FROM "b" \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfThreeIncludingIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b.including(required: B.c.including(required: C.d))), """ + SELECT "a".*, "b".*, "c".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, A.including(required: A.b.including(required: B.c.including(optional: C.d))), """ + SELECT "a".*, "b".*, "c".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(required: A.b.including(optional: B.c.including(required: C.d))), "TODO") + try assertEqualSQL(db, A.including(required: A.b.including(optional: B.c.including(optional: C.d))), """ + SELECT "a".*, "b".*, "c".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(optional: A.b.including(required: B.c.including(required: C.d))), "TODO") +// try assertEqualSQL(db, A.including(optional: A.b.including(required: B.c.including(optional: C.d))), "TODO") +// try assertEqualSQL(db, A.including(optional: A.b.including(optional: B.c.including(required: C.d))), "TODO") + try assertEqualSQL(db, A.including(optional: A.b.including(optional: B.c.including(optional: C.d))), """ + SELECT "a".*, "b".*, "c".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfThreeIncludingIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b.including(required: B.c.joining(required: C.d))), """ + SELECT "a".*, "b".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, A.including(required: A.b.including(required: B.c.joining(optional: C.d))), """ + SELECT "a".*, "b".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(required: A.b.including(optional: B.c.joining(required: C.d))), "TODO") + try assertEqualSQL(db, A.including(required: A.b.including(optional: B.c.joining(optional: C.d))), """ + SELECT "a".*, "b".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(optional: A.b.including(required: B.c.joining(required: C.d))), "TODO") +// try assertEqualSQL(db, A.including(optional: A.b.including(required: B.c.joining(optional: C.d))), "TODO") +// try assertEqualSQL(db, A.including(optional: A.b.including(optional: B.c.joining(required: C.d))), "TODO") + try assertEqualSQL(db, A.including(optional: A.b.including(optional: B.c.joining(optional: C.d))), """ + SELECT "a".*, "b".*, "c".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfThreeIncludingJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b.joining(required: B.c.including(required: C.d))), """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, A.including(required: A.b.joining(required: B.c.including(optional: C.d))), """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(required: A.b.joining(optional: B.c.including(required: C.d))), "TODO") + try assertEqualSQL(db, A.including(required: A.b.joining(optional: B.c.including(optional: C.d))), """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(optional: A.b.joining(required: B.c.including(required: C.d))), "TODO") +// try assertEqualSQL(db, A.including(optional: A.b.joining(required: B.c.including(optional: C.d))), "TODO") +// try assertEqualSQL(db, A.including(optional: A.b.joining(optional: B.c.including(required: C.d))), "TODO") + try assertEqualSQL(db, A.including(optional: A.b.joining(optional: B.c.including(optional: C.d))), """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfThreeIncludingJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b.joining(required: B.c.joining(required: C.d))), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, A.including(required: A.b.joining(required: B.c.joining(optional: C.d))), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(required: A.b.joining(optional: B.c.joining(required: C.d))), "TODO") + try assertEqualSQL(db, A.including(required: A.b.joining(optional: B.c.joining(optional: C.d))), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(optional: A.b.joining(required: B.c.joining(required: C.d))), "TODO") +// try assertEqualSQL(db, A.including(optional: A.b.joining(required: B.c.joining(optional: C.d))), "TODO") +// try assertEqualSQL(db, A.including(optional: A.b.joining(optional: B.c.joining(required: C.d))), "TODO") + try assertEqualSQL(db, A.including(optional: A.b.joining(optional: B.c.joining(optional: C.d))), """ + SELECT "a".*, "b".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfThreeJoiningIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.joining(required: A.b.including(required: B.c.including(required: C.d))), """ + SELECT "a".*, "c".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, A.joining(required: A.b.including(required: B.c.including(optional: C.d))), """ + SELECT "a".*, "c".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(required: A.b.including(optional: B.c.including(required: C.d))), "TODO") + try assertEqualSQL(db, A.joining(required: A.b.including(optional: B.c.including(optional: C.d))), """ + SELECT "a".*, "c".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(optional: A.b.including(required: B.c.including(required: C.d))), "TODO") +// try assertEqualSQL(db, A.joining(optional: A.b.including(required: B.c.including(optional: C.d))), "TODO") +// try assertEqualSQL(db, A.joining(optional: A.b.including(optional: B.c.including(required: C.d))), "TODO") + try assertEqualSQL(db, A.joining(optional: A.b.including(optional: B.c.including(optional: C.d))), """ + SELECT "a".*, "c".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfThreeJoiningIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.joining(required: A.b.including(required: B.c.joining(required: C.d))), """ + SELECT "a".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, A.joining(required: A.b.including(required: B.c.joining(optional: C.d))), """ + SELECT "a".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(required: A.b.including(optional: B.c.joining(required: C.d))), "TODO") + try assertEqualSQL(db, A.joining(required: A.b.including(optional: B.c.joining(optional: C.d))), """ + SELECT "a".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(optional: A.b.including(required: B.c.joining(required: C.d))), "TODO") +// try assertEqualSQL(db, A.joining(optional: A.b.including(required: B.c.joining(optional: C.d))), "TODO") +// try assertEqualSQL(db, A.joining(optional: A.b.including(optional: B.c.joining(required: C.d))), "TODO") + try assertEqualSQL(db, A.joining(optional: A.b.including(optional: B.c.joining(optional: C.d))), """ + SELECT "a".*, "c".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfThreeJoiningJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.joining(required: A.b.joining(required: B.c.including(required: C.d))), """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, A.joining(required: A.b.joining(required: B.c.including(optional: C.d))), """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(required: A.b.joining(optional: B.c.including(required: C.d))), "TODO") + try assertEqualSQL(db, A.joining(required: A.b.joining(optional: B.c.including(optional: C.d))), """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(optional: A.b.joining(required: B.c.including(required: C.d))), "TODO") +// try assertEqualSQL(db, A.joining(optional: A.b.joining(required: B.c.including(optional: C.d))), "TODO") +// try assertEqualSQL(db, A.joining(optional: A.b.joining(optional: B.c.including(required: C.d))), "TODO") + try assertEqualSQL(db, A.joining(optional: A.b.joining(optional: B.c.including(optional: C.d))), """ + SELECT "a".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfThreeJoiningJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.joining(required: A.b.joining(required: B.c.joining(required: C.d))), """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, A.joining(required: A.b.joining(required: B.c.joining(optional: C.d))), """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(required: A.b.joining(optional: B.c.joining(required: C.d))), "TODO") + try assertEqualSQL(db, A.joining(required: A.b.joining(optional: B.c.joining(optional: C.d))), """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(optional: A.b.joining(required: B.c.joining(required: C.d))), "TODO") +// try assertEqualSQL(db, A.joining(optional: A.b.joining(required: B.c.joining(optional: C.d))), "TODO) +// try assertEqualSQL(db, A.joining(optional: A.b.joining(optional: B.c.joining(required: C.d))), "TODO") + try assertEqualSQL(db, A.joining(optional: A.b.joining(optional: B.c.joining(optional: C.d))), """ + SELECT "a".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } +} diff --git a/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift new file mode 100644 index 000000000..d15bbd908 --- /dev/null +++ b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift @@ -0,0 +1,406 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +// A <- B +private struct A : TableRecord { + static let databaseTableName = "a" + static let b = hasOne(B.self) + static let restrictedB = hasOne(RestrictedB.self) + static let extendedB = hasOne(ExtendedB.self) +} + +private struct B : TableRecord { + static let a = belongsTo(A.self) + static let databaseTableName = "b" +} + +private struct RestrictedB : TableRecord { + static let databaseTableName = "b" + static let databaseSelection: [SQLSelectable] = [Column("name")] +} + +private struct ExtendedB : TableRecord { + static let databaseTableName = "b" + static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] +} + +/// Test SQL generation +class AssociationHasOneSQLDerivationTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + t.column("aid", .integer).references("a") + t.column("name", .text) + } + } + } + + func testDefaultSelection() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."aid" = "a"."id") + """) + try assertEqualSQL(db, A.including(required: A.restrictedB), """ + SELECT "a".*, "b"."name" \ + FROM "a" \ + JOIN "b" ON ("b"."aid" = "a"."id") + """) + try assertEqualSQL(db, A.including(required: A.extendedB), """ + SELECT "a".*, "b".*, "b"."rowid" \ + FROM "a" \ + JOIN "b" ON ("b"."aid" = "a"."id") + """) + } + } + + func testCustomSelection() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + let request = A.including(required: A.b + .select(Column("name"))) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b"."name" \ + FROM "a" \ + JOIN "b" ON ("b"."aid" = "a"."id") + """) + } + do { + let request = A.including(required: A.b + .select( + AllColumns(), + Column.rowID)) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".*, "b"."rowid" \ + FROM "a" \ + JOIN "b" ON ("b"."aid" = "a"."id") + """) + } + do { + let aAlias = TableAlias() + let request = A + .aliased(aAlias) + .including(required: A.b + .select( + Column("name"), + (Column("id") + aAlias[Column("id")]).aliased("foo"))) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b"."name", ("b"."id" + "a"."id") AS "foo" \ + FROM "a" \ + JOIN "b" ON ("b"."aid" = "a"."id") + """) + } + } + } + + func testFilteredAssociationImpactsJoinOnClause() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + let request = A.including(required: A.b.filter(Column("name") != nil)) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."aid" = "a"."id") AND ("b"."name" IS NOT NULL)) + """) + } + do { + let request = A.including(required: A.b.filter(key: 1)) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."aid" = "a"."id") AND ("b"."id" = 1)) + """) + } + do { + let request = A.including(required: A.b.filter(keys: [1, 2, 3])) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."aid" = "a"."id") AND ("b"."id" IN (1, 2, 3))) + """) + } + do { + let request = A.including(required: A.b.filter(key: ["id": 1])) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."aid" = "a"."id") AND ("b"."id" = 1)) + """) + } + do { + let request = A.including(required: A.b.filter(keys: [["id": 1], ["id": 2]])) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."aid" = "a"."id") AND (("b"."id" = 1) OR ("b"."id" = 2))) + """) + } + do { + let bAlias = TableAlias(name: "customB") + let request = A.including(required: A.b + .aliased(bAlias) + .filter(sql: "customB.name = ?", arguments: ["foo"])) + try assertEqualSQL(db, request, """ + SELECT "a".*, "customB".* \ + FROM "a" \ + JOIN "b" "customB" ON (("customB"."aid" = "a"."id") AND (customB.name = 'foo')) + """) + } + } + } + + func testFilterAssociationInWhereClause() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let bAlias = TableAlias() + let request = A + .including(required: A.b.aliased(bAlias)) + .filter(bAlias[Column("name")] != nil) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."aid" = "a"."id") \ + WHERE ("b"."name" IS NOT NULL) + """) + } + } + + func testAssociationOrderBubbleUp() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let aBase = A.all().aliased(TableAlias(name: "a")) + let abBase = A.b.aliased(TableAlias(name: "ab")) + let abaBase = B.a.aliased(TableAlias(name: "aba")) + + let aTransforms = [ + { (r: QueryInterfaceRequest) in return r }, + { (r: QueryInterfaceRequest) in return r.order(Column("id")) }, + { (r: QueryInterfaceRequest) in return r.order(Column("id")).reversed() }, + ] + let abTransforms = [ + { (r: HasOneAssociation) in return r }, + { (r: HasOneAssociation) in return r.order(Column("name"), Column("id").desc) }, + { (r: HasOneAssociation) in return r.order(Column("name")).order(Column("id").desc) }, + { (r: HasOneAssociation) in return r.order(Column("name")).reversed() }, + { (r: HasOneAssociation) in return r.reversed() }, + ] + let abaTransforms = [ + { (r: BelongsToAssociation) in return r }, + { (r: BelongsToAssociation) in return r.order(Column("id")) }, + { (r: BelongsToAssociation) in return r.order(Column("id")).reversed() }, + ] + + var sqls: [String] = [] + for aTransform in aTransforms { + for abTransform in abTransforms { + for abaTransform in abaTransforms { + let request = aTransform(aBase) + .including(required: abTransform(abBase) + .including(required: abaTransform(abaBase))) + let sqlRequest = try SQLRequest(db, request: request) + sqls.append(sqlRequest.sql) + } + } + } + + let prefix = """ + SELECT "a".*, "ab".*, "aba".* \ + FROM "a" \ + JOIN "b" "ab" ON ("ab"."aid" = "a"."id") \ + JOIN "a" "aba" ON ("aba"."id" = "ab"."aid") + """ + let orderClauses = sqls.map { sql -> String in + let prefixEndIndex = sql.index(sql.startIndex, offsetBy: prefix.count) + return String(sql.suffix(from: prefixEndIndex)) + } + XCTAssertEqual(orderClauses, [ + // a: { (r: QueryInterfaceRequest) in return r }, + // ab: { (r: BelongsToAssociation) in return r } + // aba: { (r: HasOneAssociation) in return r } + "", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name"), Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"ab\".\"name\", \"ab\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).order(Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"ab\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"ab\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"ab\".\"name\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"ab\".\"name\" DESC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"ab\".\"name\" DESC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.reversed() } + // aba: { (r: HasOneAssociation) in return r } + "", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"aba\".\"id\"", + + + // a: { (r: QueryInterfaceRequest) in return r.order(Column("id")) }, + // ab: { (r: BelongsToAssociation) in return r } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name"), Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\", \"ab\".\"name\", \"ab\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).order(Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\", \"ab\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"ab\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\", \"ab\".\"name\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"ab\".\"name\" DESC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"ab\".\"name\" DESC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"aba\".\"id\"", + + + // a: { (r: QueryInterfaceRequest) in return r.order(Column("id")).reversed() } + // ab: { (r: BelongsToAssociation) in return r } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name"), Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\" DESC, \"ab\".\"id\" ASC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).order(Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"id\" ASC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\", \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\", \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\" DESC", + ]) + } + } + + // TODO: Test if and only if we really want to build an association from any request +// func testAssociationFromRequest() throws { +// let dbQueue = try makeDatabaseQueue() +// try dbQueue.inDatabase { db in +// do { +// let bRequest = B +// .filter(Column("name") != nil) +// .order(Column("id")) +// let association = A.hasOne(bRequest) +// let request = A.including(required: association) +// try assertEqualSQL(db, request, """ +// SELECT "a".*, "b".* \ +// FROM "a" \ +// JOIN "b" ON (("b"."aid" = "a"."id") AND ("b"."name" IS NOT NULL)) \ +// ORDER BY "b"."id" +// """) +// } +// do { +// let bRequest = RestrictedB +// .filter(Column("name") != nil) +// .order(Column("id")) +// let association = A.hasOne(bRequest) +// let request = A.including(required: association) +// try assertEqualSQL(db, request, """ +// SELECT "a".*, "b"."name" \ +// FROM "a" \ +// JOIN "b" ON (("b"."aid" = "a"."id") AND ("b"."name" IS NOT NULL)) \ +// ORDER BY "b"."id" +// """) +// } +// do { +// let bRequest = ExtendedB +// .select([Column("name")]) +// .filter(Column("name") != nil) +// .order(Column("id")) +// let association = A.hasOne(bRequest) +// let request = A.including(required: association) +// try assertEqualSQL(db, request, """ +// SELECT "a".*, "b"."name" \ +// FROM "a" \ +// JOIN "b" ON (("b"."aid" = "a"."id") AND ("b"."name" IS NOT NULL)) \ +// ORDER BY "b"."id" +// """) +// } +// } +// } +} diff --git a/Tests/GRDBTests/AssociationHasOneSQLTests.swift b/Tests/GRDBTests/AssociationHasOneSQLTests.swift new file mode 100644 index 000000000..182502be4 --- /dev/null +++ b/Tests/GRDBTests/AssociationHasOneSQLTests.swift @@ -0,0 +1,769 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +/// Test SQL generation +class AssociationHasOneSQLTests: GRDBTestCase { + + func testSingleColumnNoForeignKeyNoPrimaryKey() throws { + struct Child : TableRecord { + static let databaseTableName = "children" + } + + struct Parent : TableRecord, MutablePersistableRecord { + static let databaseTableName = "parents" + func encode(to container: inout PersistenceContainer) { + container["id"] = 1 + container["rowid"] = 2 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("id", .integer) + } + try db.create(table: "children") { t in + t.column("parentId", .integer) + } + } + + try dbQueue.inDatabase { db in + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentId")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."rowid") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."rowid") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."rowid") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."rowid") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parentId\" = 2)") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parentId\" = 1)") + } + } + } + + func testSingleColumnNoForeignKey() throws { + struct Child : TableRecord { + static let databaseTableName = "children" + } + + struct Parent : TableRecord, MutablePersistableRecord { + static let databaseTableName = "parents" + func encode(to container: inout PersistenceContainer) { + container["id"] = 1 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "children") { t in + t.column("parentId", .integer) + } + } + + try dbQueue.inDatabase { db in + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentId")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parentId\" = 1)") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parentId\" = 1)") + } + } + } + + func testSingleColumnSingleForeignKey() throws { + struct Child : TableRecord { + static let databaseTableName = "children" + } + + struct Parent : TableRecord, MutablePersistableRecord { + static let databaseTableName = "parents" + func encode(to container: inout PersistenceContainer) { + container["id"] = 1 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "children") { t in + t.column("parentId", .integer).references("parents") + } + } + + try dbQueue.inDatabase { db in + do { + let association = Parent.hasOne(Child.self) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parentId\" = 1)") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentId")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parentId\" = 1)") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parentId\" = 1)") + } + } + } + + func testSingleColumnSeveralForeignKeys() throws { + struct Child : TableRecord { + static let databaseTableName = "children" + } + + struct Parent : TableRecord, MutablePersistableRecord { + static let databaseTableName = "parents" + func encode(to container: inout PersistenceContainer) { + container["id"] = 1 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "children") { t in + t.column("parent1Id", .integer).references("parents") + t.column("parent2Id", .integer).references("parents") + } + } + + try dbQueue.inDatabase { db in + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent1Id")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parent1Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parent1Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parent1Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parent1Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parent1Id\" = 1)") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent1Id")], to: [Column("id")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parent1Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parent1Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parent1Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parent1Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parent1Id\" = 1)") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent2Id")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parent2Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parent2Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parent2Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parent2Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parent2Id\" = 1)") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent2Id")], to: [Column("id")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parent2Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parent2Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parent2Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parent2Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parent2Id\" = 1)") + } + } + } + + func testCompoundColumnNoForeignKeyNoPrimaryKey() throws { + struct Child : TableRecord { + static let databaseTableName = "children" + } + + struct Parent : TableRecord, MutablePersistableRecord { + static let databaseTableName = "parents" + func encode(to container: inout PersistenceContainer) { + container["a"] = 1 + container["b"] = 2 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("a", .integer) + t.column("b", .integer) + } + try db.create(table: "children") { t in + t.column("parentA", .integer) + t.column("parentB", .integer) + } + } + + try dbQueue.inDatabase { db in + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parentA\" = 1) AND (\"parentB\" = 2))") + } + } + } + + func testCompoundColumnNoForeignKey() throws { + struct Child : TableRecord { + static let databaseTableName = "children" + } + + struct Parent : TableRecord, MutablePersistableRecord { + static let databaseTableName = "parents" + func encode(to container: inout PersistenceContainer) { + container["a"] = 1 + container["b"] = 2 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("a", .integer) + t.column("b", .integer) + t.primaryKey(["a", "b"]) + } + try db.create(table: "children") { t in + t.column("parentA", .integer) + t.column("parentB", .integer) + } + } + + try dbQueue.inDatabase { db in + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parentA\" = 1) AND (\"parentB\" = 2))") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parentA\" = 1) AND (\"parentB\" = 2))") + } + } + } + + func testCompoundColumnSingleForeignKey() throws { + struct Child : TableRecord { + static let databaseTableName = "children" + } + + struct Parent : TableRecord, MutablePersistableRecord { + static let databaseTableName = "parents" + func encode(to container: inout PersistenceContainer) { + container["a"] = 1 + container["b"] = 2 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("a", .integer) + t.column("b", .integer) + t.primaryKey(["a", "b"]) + } + try db.create(table: "children") { t in + t.column("parentA", .integer) + t.column("parentB", .integer) + t.foreignKey(["parentA", "parentB"], references: "parents") + } + } + + try dbQueue.inDatabase { db in + do { + let association = Parent.hasOne(Child.self) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parentA\" = 1) AND (\"parentB\" = 2))") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parentA\" = 1) AND (\"parentB\" = 2))") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parentA\" = 1) AND (\"parentB\" = 2))") + } + } + } + + func testCompoundColumnSeveralForeignKeys() throws { + struct Child : TableRecord { + static let databaseTableName = "children" + } + + struct Parent : TableRecord, MutablePersistableRecord { + static let databaseTableName = "parents" + func encode(to container: inout PersistenceContainer) { + container["a"] = 1 + container["b"] = 2 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("a", .integer) + t.column("b", .integer) + t.primaryKey(["a", "b"]) + } + try db.create(table: "children") { t in + t.column("parent1A", .integer) + t.column("parent1B", .integer) + t.column("parent2A", .integer) + t.column("parent2B", .integer) + t.foreignKey(["parent1A", "parent1B"], references: "parents") + t.foreignKey(["parent2A", "parent2B"], references: "parents") + } + } + + try dbQueue.inDatabase { db in + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent1A"), Column("parent1B")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parent1A\" = 1) AND (\"parent1B\" = 2))") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parent1A\" = 1) AND (\"parent1B\" = 2))") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent2A"), Column("parent2B")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parent2A\" = 1) AND (\"parent2B\" = 2))") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parent2A\" = 1) AND (\"parent2B\" = 2))") + } + } + } + + func testForeignKeyDefinitionFromColumn() { + // This test pass if code compiles + struct Parent : TableRecord { + static let databaseTableName = "parents" + enum Columns { + static let id = Column("id") + } + static let child1 = hasOne(Child.self, using: Child.ForeignKeys.parent1) + static let child2 = hasOne(Child.self, using: Child.ForeignKeys.parent2) + } + + struct Child : TableRecord { + static let databaseTableName = "children" + enum Columns { + static let parentId = Column("parentId") + } + enum ForeignKeys { + static let parent1 = ForeignKey([Columns.parentId]) + static let parent2 = ForeignKey([Columns.parentId], to: [Parent.Columns.id]) + } + } + } +} diff --git a/Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift b/Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift new file mode 100644 index 000000000..4795ac7e0 --- /dev/null +++ b/Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift @@ -0,0 +1,237 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +// A -> B +// A -> D +private struct A: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "a" + static let b = belongsTo(B.self) + static let d = belongsTo(D.self) + var id: Int64 + var bid: Int64? + var did: Int64? + var name: String +} + +private struct B: Codable, FetchableRecord, PersistableRecord { + static let a = hasOne(A.self) + static let databaseTableName = "b" + var id: Int64 + var name: String +} + +private struct D: Codable, FetchableRecord, PersistableRecord { + static let a = hasOne(A.self) + static let databaseTableName = "d" + var id: Int64 + var name: String +} + +private struct AWithRequiredBD: Decodable, FetchableRecord { + var a: A + var b: B + var d: D + static let b = A.b.forKey(CodingKeys.b) + static let d = A.d.forKey(CodingKeys.d) +} + +private struct AWithOptionalBD: Decodable, FetchableRecord { + var a: A + var b: B? + var d: D? + static let b = A.b.forKey(CodingKeys.b) + static let d = A.d.forKey(CodingKeys.d) +} + +/// Test support for Decodable records +class AssociationParallelDecodableRecordTests: GRDBTestCase { + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "d") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + t.column("did", .integer).references("d") + t.column("name", .text) + } + + try B(id: 1, name: "b1").insert(db) + try B(id: 2, name: "b2").insert(db) + try B(id: 3, name: "b3").insert(db) + try D(id: 1, name: "d1").insert(db) + try A(id: 1, bid: 1, did: 1, name: "a1").insert(db) + try A(id: 2, bid: 1, did: nil, name: "a2").insert(db) + try A(id: 3, bid: 2, did: 1, name: "a3").insert(db) + try A(id: 4, bid: 2, did: nil, name: "a4").insert(db) + try A(id: 5, bid: nil, did: 1, name: "a5").insert(db) + try A(id: 6, bid: nil, did: nil, name: "a6").insert(db) + } + } + + func testParallelTwoIncludingRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = A + .including(required: AWithRequiredBD.b) + .including(required: AWithRequiredBD.d) + .order(sql: "a.id, b.id, d.id") + .asRequest(of: AWithRequiredBD.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + + XCTAssertEqual(records.count, 2) + + XCTAssertEqual(records[0].a.id, 1) + XCTAssertEqual(records[0].a.bid, 1) + XCTAssertEqual(records[0].a.did, 1) + XCTAssertEqual(records[0].a.name, "a1") + XCTAssertEqual(records[0].b.id, 1) + XCTAssertEqual(records[0].b.name, "b1") + XCTAssertEqual(records[0].d.id, 1) + XCTAssertEqual(records[0].d.name, "d1") + + XCTAssertEqual(records[1].a.id, 3) + XCTAssertEqual(records[1].a.bid, 2) + XCTAssertEqual(records[1].a.did, 1) + XCTAssertEqual(records[1].a.name, "a3") + XCTAssertEqual(records[1].b.id, 2) + XCTAssertEqual(records[1].b.name, "b2") + XCTAssertEqual(records[1].d.id, 1) + XCTAssertEqual(records[1].d.name, "d1") + } + + func testParallelTwoIncludingOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = A + .including(optional: AWithOptionalBD.b) + .including(optional: AWithOptionalBD.d) + .order(sql: "a.id, b.id, d.id") + .asRequest(of: AWithOptionalBD.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + + XCTAssertEqual(records.count, 6) + + XCTAssertEqual(records[0].a.id, 1) + XCTAssertEqual(records[0].a.bid, 1) + XCTAssertEqual(records[0].a.did, 1) + XCTAssertEqual(records[0].a.name, "a1") + XCTAssertEqual(records[0].b!.id, 1) + XCTAssertEqual(records[0].b!.name, "b1") + XCTAssertEqual(records[0].d!.id, 1) + XCTAssertEqual(records[0].d!.name, "d1") + + XCTAssertEqual(records[1].a.id, 2) + XCTAssertEqual(records[1].a.bid, 1) + XCTAssertEqual(records[1].a.did, nil) + XCTAssertEqual(records[1].a.name, "a2") + XCTAssertEqual(records[1].b!.id, 1) + XCTAssertEqual(records[1].b!.name, "b1") + XCTAssertNil(records[1].d) + + XCTAssertEqual(records[2].a.id, 3) + XCTAssertEqual(records[2].a.bid, 2) + XCTAssertEqual(records[2].a.did, 1) + XCTAssertEqual(records[2].a.name, "a3") + XCTAssertEqual(records[2].b!.id, 2) + XCTAssertEqual(records[2].b!.name, "b2") + XCTAssertEqual(records[2].d!.id, 1) + XCTAssertEqual(records[2].d!.name, "d1") + + XCTAssertEqual(records[3].a.id, 4) + XCTAssertEqual(records[3].a.bid, 2) + XCTAssertEqual(records[3].a.did, nil) + XCTAssertEqual(records[3].a.name, "a4") + XCTAssertEqual(records[3].b!.id, 2) + XCTAssertEqual(records[3].b!.name, "b2") + XCTAssertNil(records[3].d) + + XCTAssertEqual(records[4].a.id, 5) + XCTAssertEqual(records[4].a.bid, nil) + XCTAssertEqual(records[4].a.did, 1) + XCTAssertEqual(records[4].a.name, "a5") + XCTAssertNil(records[4].b) + XCTAssertEqual(records[4].d!.id, 1) + XCTAssertEqual(records[4].d!.name, "d1") + + XCTAssertEqual(records[5].a.id, 6) + XCTAssertEqual(records[5].a.bid, nil) + XCTAssertEqual(records[5].a.did, nil) + XCTAssertEqual(records[5].a.name, "a6") + XCTAssertNil(records[5].b) + XCTAssertNil(records[5].d) + } + + func testParallelTwoJoiningRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = A + .joining(required: A.b) + .joining(required: A.d) + .order(sql: "a.id, b.id, d.id") + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + + XCTAssertEqual(records.count, 2) + + XCTAssertEqual(records[0].id, 1) + XCTAssertEqual(records[0].bid, 1) + XCTAssertEqual(records[0].did, 1) + XCTAssertEqual(records[0].name, "a1") + + XCTAssertEqual(records[1].id, 3) + XCTAssertEqual(records[1].bid, 2) + XCTAssertEqual(records[1].did, 1) + XCTAssertEqual(records[1].name, "a3") + } + + func testParallelTwoJoiningOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = A + .joining(optional: A.b) + .joining(optional: A.d) + .order(sql: "a.id, b.id, d.id") + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + + XCTAssertEqual(records.count, 6) + + XCTAssertEqual(records[0].id, 1) + XCTAssertEqual(records[0].bid, 1) + XCTAssertEqual(records[0].did, 1) + XCTAssertEqual(records[0].name, "a1") + + XCTAssertEqual(records[1].id, 2) + XCTAssertEqual(records[1].bid, 1) + XCTAssertEqual(records[1].did, nil) + XCTAssertEqual(records[1].name, "a2") + + XCTAssertEqual(records[2].id, 3) + XCTAssertEqual(records[2].bid, 2) + XCTAssertEqual(records[2].did, 1) + XCTAssertEqual(records[2].name, "a3") + + XCTAssertEqual(records[3].id, 4) + XCTAssertEqual(records[3].bid, 2) + XCTAssertEqual(records[3].did, nil) + XCTAssertEqual(records[3].name, "a4") + + XCTAssertEqual(records[4].id, 5) + XCTAssertEqual(records[4].bid, nil) + XCTAssertEqual(records[4].did, 1) + XCTAssertEqual(records[4].name, "a5") + + XCTAssertEqual(records[5].id, 6) + XCTAssertEqual(records[5].bid, nil) + XCTAssertEqual(records[5].did, nil) + XCTAssertEqual(records[5].name, "a6") + } +} + diff --git a/Tests/GRDBTests/AssociationParallelRowScopesTests.swift b/Tests/GRDBTests/AssociationParallelRowScopesTests.swift new file mode 100644 index 000000000..f833518a5 --- /dev/null +++ b/Tests/GRDBTests/AssociationParallelRowScopesTests.swift @@ -0,0 +1,1400 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +// A -> B <- C +// A -> D +private struct A: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "a" + static let defaultB = belongsTo(B.self) + static let defaultD = belongsTo(D.self) + static let customB = belongsTo(B.self, key: "customB") + static let customD = belongsTo(D.self, key: "customD") + var id: Int64 + var bid: Int64? + var did: Int64? + var name: String +} + +private struct B: Codable, FetchableRecord, PersistableRecord { + static let defaultA = hasOne(A.self) + static let defaultC = hasOne(C.self) + static let customA = hasOne(A.self, key: "customA") + static let customC = hasOne(C.self, key: "customC") + static let databaseTableName = "b" + var id: Int64 + var name: String +} + +private struct C: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "c" + var id: Int64 + var bid: Int64? + var name: String +} + +private struct D: Codable, FetchableRecord, PersistableRecord { + static let defaultA = hasOne(A.self) + static let customA = hasOne(A.self, key: "customA") + static let databaseTableName = "d" + var id: Int64 + var name: String +} + +/// Test row scopes +class AssociationParallelRowScopesTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "d") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + t.column("did", .integer).references("d") + t.column("name", .text) + } + try db.create(table: "c") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + t.column("name", .text) + } + + try B(id: 1, name: "b1").insert(db) + try B(id: 2, name: "b2").insert(db) + try B(id: 3, name: "b3").insert(db) + try D(id: 1, name: "d1").insert(db) + try A(id: 1, bid: 1, did: 1, name: "a1").insert(db) + try A(id: 2, bid: 1, did: nil, name: "a2").insert(db) + try A(id: 3, bid: 2, did: 1, name: "a3").insert(db) + try A(id: 4, bid: 2, did: nil, name: "a4").insert(db) + try A(id: 5, bid: nil, did: 1, name: "a5").insert(db) + try A(id: 6, bid: nil, did: nil, name: "a6").insert(db) + try C(id: 1, bid: 1, name: "c1").insert(db) + } + } + + func testDefaultScopeParallelTwoIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.including(required: A.defaultB).including(required: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[1].scopes["d"]!, ["id":1, "name":"d1"]) + } + do { + let request = A.including(required: A.defaultB).including(optional: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[1].scopes["d"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[2].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[3].scopes["d"]!, ["id":nil, "name":nil]) + } + do { + let request = A.including(optional: A.defaultB).including(required: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[1].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[2].scopes["b"]!, ["id":nil, "name":nil]) + XCTAssertEqual(rows[2].scopes["d"]!, ["id":1, "name":"d1"]) + } + do { + let request = A.including(optional: A.defaultB).including(optional: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 6) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[1].scopes["d"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[2].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[3].scopes["d"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[4].scopes["b"]!, ["id":nil, "name":nil]) + XCTAssertEqual(rows[4].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) + XCTAssertEqual(Set(rows[5].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[5].scopes["b"]!, ["id":nil, "name":nil]) + XCTAssertEqual(rows[5].scopes["d"]!, ["id":nil, "name":nil]) + } + do { + let request = B.including(required: B.defaultA).including(required: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + } + do { + let request = B.including(required: B.defaultA).including(optional: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(rows[2].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(rows[3].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + } + do { + let request = B.including(optional: B.defaultA).including(required: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + } + do { + let request = B.including(optional: B.defaultA).including(optional: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(rows[2].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(rows[3].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[4].scopes["a"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + XCTAssertEqual(rows[4].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + } + } + + func testDefaultScopeParallelTwoIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.including(required: A.defaultB).joining(required: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":2, "name":"b2"]) + } + do { + let request = A.including(required: A.defaultB).joining(optional: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) + XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) + } + do { + let request = A.including(optional: A.defaultB).joining(required: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":2, "name":"b2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!, ["id":nil, "name":nil]) + } + do { + let request = A.including(optional: A.defaultB).joining(optional: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 6) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) + XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) + + XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["b"]) + XCTAssertEqual(rows[4].scopes["b"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) + XCTAssertEqual(Set(rows[5].scopes.names), ["b"]) + XCTAssertEqual(rows[5].scopes["b"]!, ["id":nil, "name":nil]) + } + do { + let request = B.including(required: B.defaultA).joining(required: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) + XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) + XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + } + do { + let request = B.including(required: B.defaultA).joining(optional: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) + XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) + XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["a"]) + XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["a"]) + XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) + } + do { + let request = B.including(optional: B.defaultA).joining(required: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) + XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) + XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + } + do { + let request = B.including(optional: B.defaultA).joining(optional: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) + XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) + XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["a"]) + XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["a"]) + XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) + + XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["a"]) + XCTAssertEqual(rows[4].scopes["a"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + } + } + + func testDefaultScopeParallelTwoJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.joining(required: A.defaultB).including(required: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["d"]) + XCTAssertEqual(rows[1].scopes["d"]!, ["id":1, "name":"d1"]) + } + do { + let request = A.joining(required: A.defaultB).including(optional: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["d"]) + XCTAssertEqual(rows[1].scopes["d"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["d"]) + XCTAssertEqual(rows[2].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["d"]) + XCTAssertEqual(rows[3].scopes["d"]!, ["id":nil, "name":nil]) + } + do { + let request = A.joining(optional: A.defaultB).including(required: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["d"]) + XCTAssertEqual(rows[1].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["d"]) + XCTAssertEqual(rows[2].scopes["d"]!, ["id":1, "name":"d1"]) + } + do { + let request = A.joining(optional: A.defaultB).including(optional: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 6) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["d"]) + XCTAssertEqual(rows[1].scopes["d"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["d"]) + XCTAssertEqual(rows[2].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["d"]) + XCTAssertEqual(rows[3].scopes["d"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["d"]) + XCTAssertEqual(rows[4].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) + XCTAssertEqual(Set(rows[5].scopes.names), ["d"]) + XCTAssertEqual(rows[5].scopes["d"]!, ["id":nil, "name":nil]) + } + do { + let request = B.joining(required: B.defaultA).including(required: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + } + do { + let request = B.joining(required: B.defaultA).including(optional: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["c"]) + XCTAssertEqual(rows[3].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + } + do { + let request = B.joining(optional: B.defaultA).including(required: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + } + do { + let request = B.joining(optional: B.defaultA).including(optional: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["c"]) + XCTAssertEqual(rows[3].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["c"]) + XCTAssertEqual(rows[4].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + } + } + + func testDefaultScopeParallelTwoJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.joining(required: A.defaultB).joining(required: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + } + do { + let request = A.joining(required: A.defaultB).joining(optional: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + } + do { + let request = A.joining(optional: A.defaultB).joining(required: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + } + do { + let request = A.joining(optional: A.defaultB).joining(optional: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 6) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + + XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertTrue(rows[4].scopes.names.isEmpty) + + XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) + XCTAssertTrue(rows[5].scopes.names.isEmpty) + } + do { + let request = B.joining(required: B.defaultA).joining(required: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + } + do { + let request = B.joining(required: B.defaultA).joining(optional: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + } + do { + let request = B.joining(optional: B.defaultA).joining(required: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + } + do { + let request = B.joining(optional: B.defaultA).joining(optional: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + + XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) + XCTAssertTrue(rows[4].scopes.names.isEmpty) + } + } + + func testCustomScopeParallelTwoIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.including(required: A.customB).including(required: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[1].scopes["customB"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[1].scopes["customD"]!, ["id":1, "name":"d1"]) + } + do { + let request = A.including(required: A.customB).including(optional: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[1].scopes["customD"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[2].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[3].scopes["customD"]!, ["id":nil, "name":nil]) + } + do { + let request = A.including(optional: A.customB).including(required: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[1].scopes["customB"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[1].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[2].scopes["customB"]!, ["id":nil, "name":nil]) + XCTAssertEqual(rows[2].scopes["customD"]!, ["id":1, "name":"d1"]) + } + do { + let request = A.including(optional: A.customB).including(optional: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 6) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[1].scopes["customD"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[2].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[3].scopes["customD"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[4].scopes["customB"]!, ["id":nil, "name":nil]) + XCTAssertEqual(rows[4].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) + XCTAssertEqual(Set(rows[5].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[5].scopes["customB"]!, ["id":nil, "name":nil]) + XCTAssertEqual(rows[5].scopes["customD"]!, ["id":nil, "name":nil]) + } + do { + let request = B.including(required: B.customA).including(required: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + } + do { + let request = B.including(required: B.customA).including(optional: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(rows[2].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(rows[3].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + } + do { + let request = B.including(optional: B.customA).including(required: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + } + do { + let request = B.including(optional: B.customA).including(optional: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(rows[2].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(rows[3].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[4].scopes["customA"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + XCTAssertEqual(rows[4].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + } + } + + func testCustomScopeParallelTwoIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.including(required: A.customB).joining(required: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) + XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) + XCTAssertEqual(rows[1].scopes["customB"]!, ["id":2, "name":"b2"]) + } + do { + let request = A.including(required: A.customB).joining(optional: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) + XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) + XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customB"]) + XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customB"]) + XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) + } + do { + let request = A.including(optional: A.customB).joining(required: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) + XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) + XCTAssertEqual(rows[1].scopes["customB"]!, ["id":2, "name":"b2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customB"]) + XCTAssertEqual(rows[2].scopes["customB"]!, ["id":nil, "name":nil]) + } + do { + let request = A.including(optional: A.customB).joining(optional: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 6) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) + XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) + XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customB"]) + XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customB"]) + XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) + + XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["customB"]) + XCTAssertEqual(rows[4].scopes["customB"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) + XCTAssertEqual(Set(rows[5].scopes.names), ["customB"]) + XCTAssertEqual(rows[5].scopes["customB"]!, ["id":nil, "name":nil]) + } + do { + let request = B.including(required: B.customA).joining(required: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) + XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) + XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + } + do { + let request = B.including(required: B.customA).joining(optional: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) + XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) + XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customA"]) + XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customA"]) + XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) + } + do { + let request = B.including(optional: B.customA).joining(required: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) + XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) + XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + } + do { + let request = B.including(optional: B.customA).joining(optional: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) + XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) + XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customA"]) + XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customA"]) + XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) + + XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["customA"]) + XCTAssertEqual(rows[4].scopes["customA"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + } + } + + func testCustomScopeParallelTwoJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.joining(required: A.customB).including(required: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customD"]) + XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customD"]) + XCTAssertEqual(rows[1].scopes["customD"]!, ["id":1, "name":"d1"]) + } + do { + let request = A.joining(required: A.customB).including(optional: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customD"]) + XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customD"]) + XCTAssertEqual(rows[1].scopes["customD"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customD"]) + XCTAssertEqual(rows[2].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customD"]) + XCTAssertEqual(rows[3].scopes["customD"]!, ["id":nil, "name":nil]) + } + do { + let request = A.joining(optional: A.customB).including(required: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customD"]) + XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customD"]) + XCTAssertEqual(rows[1].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customD"]) + XCTAssertEqual(rows[2].scopes["customD"]!, ["id":1, "name":"d1"]) + } + do { + let request = A.joining(optional: A.customB).including(optional: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 6) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customD"]) + XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customD"]) + XCTAssertEqual(rows[1].scopes["customD"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customD"]) + XCTAssertEqual(rows[2].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customD"]) + XCTAssertEqual(rows[3].scopes["customD"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["customD"]) + XCTAssertEqual(rows[4].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) + XCTAssertEqual(Set(rows[5].scopes.names), ["customD"]) + XCTAssertEqual(rows[5].scopes["customD"]!, ["id":nil, "name":nil]) + } + do { + let request = B.joining(required: B.customA).including(required: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customC"]) + XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customC"]) + XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + } + do { + let request = B.joining(required: B.customA).including(optional: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customC"]) + XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customC"]) + XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customC"]) + XCTAssertEqual(rows[2].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customC"]) + XCTAssertEqual(rows[3].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + } + do { + let request = B.joining(optional: B.customA).including(required: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customC"]) + XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customC"]) + XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + } + do { + let request = B.joining(optional: B.customA).including(optional: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customC"]) + XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customC"]) + XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customC"]) + XCTAssertEqual(rows[2].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customC"]) + XCTAssertEqual(rows[3].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["customC"]) + XCTAssertEqual(rows[4].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + } + } + + func testCustomScopeParallelTwoJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.joining(required: A.customB).joining(required: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + } + do { + let request = A.joining(required: A.customB).joining(optional: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + } + do { + let request = A.joining(optional: A.customB).joining(required: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + } + do { + let request = A.joining(optional: A.customB).joining(optional: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 6) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + + XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertTrue(rows[4].scopes.names.isEmpty) + + XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) + XCTAssertTrue(rows[5].scopes.names.isEmpty) + } + do { + let request = B.joining(required: B.customA).joining(required: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + } + do { + let request = B.joining(required: B.customA).joining(optional: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + } + do { + let request = B.joining(optional: B.customA).joining(required: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + } + do { + let request = B.joining(optional: B.customA).joining(optional: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + + XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) + XCTAssertTrue(rows[4].scopes.names.isEmpty) + } + } +} + diff --git a/Tests/GRDBTests/AssociationParallelSQLTests.swift b/Tests/GRDBTests/AssociationParallelSQLTests.swift new file mode 100644 index 000000000..db57c3f06 --- /dev/null +++ b/Tests/GRDBTests/AssociationParallelSQLTests.swift @@ -0,0 +1,272 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +// A -> B <- C +// A -> D +private struct A: TableRecord { + static let databaseTableName = "a" + static let b = belongsTo(B.self) + static let d = belongsTo(D.self) +} + +private struct B: TableRecord { + static let a = hasOne(A.self) + static let c = hasOne(C.self) + static let databaseTableName = "b" +} + +private struct C: TableRecord { + static let databaseTableName = "c" + static let b = belongsTo(B.self) +} + +private struct D: TableRecord { + static let a = hasOne(A.self) + static let databaseTableName = "d" +} + +/// Test SQL generation +class AssociationParallelSQLTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "d") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + t.column("did", .integer).references("d") + } + try db.create(table: "c") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + } + } + } + + func testParallelTwoIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b).including(required: A.d), """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.including(required: A.b).including(optional: A.d), """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.including(optional: A.b).including(required: A.d), """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.including(optional: A.b).including(optional: A.d), """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, B.including(required: B.a).including(required: B.c), """ + SELECT "b".*, "a".*, "c".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(required: B.a).including(optional: B.c), """ + SELECT "b".*, "a".*, "c".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(optional: B.a).including(required: B.c), """ + SELECT "b".*, "a".*, "c".* \ + FROM "b" \ + LEFT JOIN "a" ON ("a"."bid" = "b"."id") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(optional: B.a).including(optional: B.c), """ + SELECT "b".*, "a".*, "c".* \ + FROM "b" \ + LEFT JOIN "a" ON ("a"."bid" = "b"."id") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + } + } + + func testParallelTwoIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b).joining(required: A.d), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.including(required: A.b).joining(optional: A.d), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.including(optional: A.b).joining(required: A.d), """ + SELECT "a".*, "b".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.including(optional: A.b).joining(optional: A.d), """ + SELECT "a".*, "b".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, B.including(required: B.a).joining(required: B.c), """ + SELECT "b".*, "a".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(required: B.a).joining(optional: B.c), """ + SELECT "b".*, "a".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(optional: B.a).joining(required: B.c), """ + SELECT "b".*, "a".* \ + FROM "b" \ + LEFT JOIN "a" ON ("a"."bid" = "b"."id") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(optional: B.a).joining(optional: B.c), """ + SELECT "b".*, "a".* \ + FROM "b" \ + LEFT JOIN "a" ON ("a"."bid" = "b"."id") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + } + } + + func testParallelTwoJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.joining(required: A.b).including(required: A.d), """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.joining(required: A.b).including(optional: A.d), """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.joining(optional: A.b).including(required: A.d), """ + SELECT "a".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.joining(optional: A.b).including(optional: A.d), """ + SELECT "a".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, B.joining(required: B.a).including(required: B.c), """ + SELECT "b".*, "c".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.joining(required: B.a).including(optional: B.c), """ + SELECT "b".*, "c".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.joining(optional: B.a).including(required: B.c), """ + SELECT "b".*, "c".* \ + FROM "b" \ + LEFT JOIN "a" ON ("a"."bid" = "b"."id") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.joining(optional: B.a).including(optional: B.c), """ + SELECT "b".*, "c".* \ + FROM "b" \ + LEFT JOIN "a" ON ("a"."bid" = "b"."id") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + } + } + + func testParallelTwoJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.joining(required: A.b).joining(required: A.d), """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.joining(required: A.b).joining(optional: A.d), """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.joining(optional: A.b).joining(required: A.d), """ + SELECT "a".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.joining(optional: A.b).joining(optional: A.d), """ + SELECT "a".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, B.joining(required: B.a).joining(required: B.c), """ + SELECT "b".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.joining(required: B.a).joining(optional: B.c), """ + SELECT "b".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.joining(optional: B.a).joining(required: B.c), """ + SELECT "b".* \ + FROM "b" \ + LEFT JOIN "a" ON ("a"."bid" = "b"."id") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.joining(optional: B.a).joining(optional: B.c), """ + SELECT "b".* \ + FROM "b" \ + LEFT JOIN "a" ON ("a"."bid" = "b"."id") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + } + } +} diff --git a/Tests/GRDBTests/AssociationRowScopeSearchTests.swift b/Tests/GRDBTests/AssociationRowScopeSearchTests.swift new file mode 100644 index 000000000..6e1f1f8b9 --- /dev/null +++ b/Tests/GRDBTests/AssociationRowScopeSearchTests.swift @@ -0,0 +1,244 @@ +import XCTest +#if GRDBCIPHER + @testable import GRDBCipher +#elseif GRDBCUSTOMSQLITE + @testable import GRDBCustomSQLite +#else + @testable import GRDB +#endif + +// a -> b* -> c +// -> d* +// -> c* +private struct A: TableRecord, FetchableRecord, Decodable { + static let databaseTableName = "a" + static let b = hasOne(B.self) + static let c = hasOne(C.self) + var id: Int64 +} +private struct B: TableRecord, FetchableRecord, Decodable { + static let databaseTableName = "b" + static let c = hasOne(C.self) + static let d = hasOne(D.self) + var id: Int64 + var aid: Int64 +} +private struct C: TableRecord, FetchableRecord, Decodable { + static let databaseTableName = "c" + var id: Int64 + var aid: Int64? + var bid: Int64? +} +private struct D: TableRecord, FetchableRecord, Decodable { + static let databaseTableName = "d" + var id: Int64 + var bid: Int64 +} + +class AssociationRowScopeSearchTests: GRDBTestCase { + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + // 1. Prepare data + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + t.column("aid", .integer).references("a") + } + try db.create(table: "c") { t in + t.column("id", .integer).primaryKey() + t.column("aid", .integer).references("a") + t.column("bid", .integer).references("b") + } + try db.create(table: "d") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + } + try db.execute("INSERT INTO a (id) VALUES (1)") + try db.execute("INSERT INTO b (id, aid) VALUES (2, 1)") + try db.execute("INSERT INTO c (id, aid, bid) VALUES (3, NULL, 2)") + try db.execute("INSERT INTO c (id, aid, bid) VALUES (4, 1, NULL)") + try db.execute("INSERT INTO d (id, bid) VALUES (5, 2)") + } + } + + private let testedRequest = A + .including(required: A.b + .including(required: B.c) + .including(required: B.d) + ) + .including(required: A.c) + + func testTestedRequest() throws { + // Assert that we fetch the expected nested scopes before we start testing breadth-first lookup + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let rows = try testedRequest.asRequest(of: Row.self).fetchAll(db) + + XCTAssertEqual(rows.count, 1) + let row = rows[0] + + XCTAssertEqual(row.unscoped, ["id": 1]) + XCTAssertEqual(row.scopes["b"]!.unscoped, ["id": 2, "aid": 1]) + XCTAssertEqual(row.scopes["b"]!.scopes["c"]!, ["id": 3, "aid": nil, "bid": 2]) + XCTAssertEqual(row.scopes["b"]!.scopes["d"]!, ["id": 5, "bid": 2]) + XCTAssertEqual(row.scopes["c"]!, ["id": 4, "aid": 1, "bid": nil]) + } + } + + func testBreadthFirstScopeLookup() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let row = try testedRequest.asRequest(of: Row.self).fetchOne(db)! + XCTAssertEqual(row.scopesTree["b"]!.unscoped, ["id": 2, "aid": 1]) + XCTAssertEqual(row.scopesTree["c"]!, ["id": 4, "aid": 1, "bid": nil]) + XCTAssertEqual(row.scopesTree["d"]!, ["id": 5, "bid": 2]) + } + } + + func testFetchableRecordDecoding() throws { + struct Record: FetchableRecord { + var a: A + var b: B + var c: C + var d: D + init(row: Row) { + a = A(row: row) + b = row["b"] + c = row["c"] + d = row["d"] + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = try testedRequest.asRequest(of: Record.self).fetchOne(db)! + XCTAssertEqual(record.a.id, 1) + XCTAssertEqual(record.b.id, 2) + XCTAssertEqual(record.b.aid, 1) + XCTAssertEqual(record.c.id, 4) + XCTAssertEqual(record.c.aid, 1) + XCTAssertNil(record.c.bid) + XCTAssertEqual(record.d.id, 5) + XCTAssertEqual(record.d.bid, 2) + } + } + + func testFlatDecodableRecordDecoding() throws { + struct Record: FetchableRecord, Decodable { + var a: A + var b: B + var c: C + var d: D + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = try testedRequest.asRequest(of: Record.self).fetchOne(db)! + XCTAssertEqual(record.a.id, 1) + XCTAssertEqual(record.b.id, 2) + XCTAssertEqual(record.b.aid, 1) + XCTAssertEqual(record.c.id, 4) + XCTAssertEqual(record.c.aid, 1) + XCTAssertNil(record.c.bid) + XCTAssertEqual(record.d.id, 5) + XCTAssertEqual(record.d.bid, 2) + } + } + + func testNestedDecodableRecordDecoding() throws { + struct NestedB: Decodable { + var b: B + var c: C + var d: D + } + struct Record: FetchableRecord, Decodable { + var a: A + var b: NestedB + var c: C + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = try testedRequest.asRequest(of: Record.self).fetchOne(db)! + XCTAssertEqual(record.a.id, 1) + XCTAssertEqual(record.b.b.id, 2) + XCTAssertEqual(record.b.b.aid, 1) + XCTAssertEqual(record.b.c.id, 3) + XCTAssertNil(record.b.c.aid) + XCTAssertEqual(record.b.c.bid, 2) + XCTAssertEqual(record.b.d.id, 5) + XCTAssertEqual(record.b.d.bid, 2) + XCTAssertEqual(record.c.id, 4) + XCTAssertEqual(record.c.aid, 1) + XCTAssertNil(record.c.bid) + } + } + + func testDecodableWithCustomRowDecoding() throws { + struct CustomA: FetchableRecord, Decodable { + var id: Int64 + var custom: Bool? + init(row: Row) { + id = row["id"] + custom = true + } + } + struct CustomB: FetchableRecord, Decodable { + var id: Int64 + var aid: Int64 + var custom: Bool? + init(row: Row) { + id = row["id"] + aid = row["aid"] + custom = true + } + } + struct CustomC: FetchableRecord, Decodable { + var id: Int64 + var aid: Int64? + var bid: Int64? + var custom: Bool? + init(row: Row) { + id = row["id"] + aid = row["aid"] + bid = row["bid"] + custom = true + } + } + struct CustomD: FetchableRecord, Decodable { + var id: Int64 + var bid: Int64 + var custom: Bool? + init(row: Row) { + id = row["id"] + bid = row["bid"] + custom = true + } + } + struct Record: FetchableRecord, Decodable { + var a: CustomA + var b: CustomB + var c: CustomC + var d: CustomD + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = try testedRequest.asRequest(of: Record.self).fetchOne(db)! + XCTAssertEqual(record.a.id, 1) + XCTAssertEqual(record.a.custom, true) + XCTAssertEqual(record.b.id, 2) + XCTAssertEqual(record.b.aid, 1) + XCTAssertEqual(record.b.custom, true) + XCTAssertEqual(record.c.id, 4) + XCTAssertEqual(record.c.aid, 1) + XCTAssertNil(record.c.bid) + XCTAssertEqual(record.c.custom, true) + XCTAssertEqual(record.d.id, 5) + XCTAssertEqual(record.d.bid, 2) + XCTAssertEqual(record.d.custom, true) + } + } +} diff --git a/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift b/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift new file mode 100644 index 000000000..c3d3041bf --- /dev/null +++ b/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift @@ -0,0 +1,340 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +// A -> A +// A -> B1 +// A -> B2 +private struct A : TableRecord { + static let databaseTableName = "a" + static let parent = belongsTo(A.self) + static let child = hasOne(A.self) + static let b1 = belongsTo(B.self, key: "b1", using: ForeignKey(["bid1"])) + static let b2 = belongsTo(B.self, key: "b2", using: ForeignKey(["bid2"])) +} +private struct B : TableRecord { + static let databaseTableName = "b" + static let a1 = hasOne(A.self, key: "a1", using: ForeignKey(["bid1"])) + static let a2 = hasOne(A.self, key: "a1", using: ForeignKey(["bid2"])) +} + +/// Tests for table name conflicts, recursive associations, +/// user-defined table aliases, and expressions that involve several tables. +class AssociationTableAliasTestsSQLTests : GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + t.column("bid1", .integer).references("b") + t.column("bid2", .integer).references("b") + t.column("parentId", .integer).references("a") + t.column("name", .text) + } + } + } + + func testTableAliasBasics() throws { + // A table reference qualifies all unqualified selectables, expressions, and orderings + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + let alias = TableAlias() + let name = Column("name") + let condition = name != nil && alias[name] == "foo" + + let expectedSQL = """ + SELECT "name" \ + FROM "a" \ + WHERE (("id" = 1) AND (("name" IS NOT NULL) AND ("name" = 'foo'))) \ + GROUP BY "name" \ + HAVING "name" \ + ORDER BY "name" + """ + + do { + let request = A + .aliased(alias) + .select(name) + .filter(key: 1) + .filter(condition) + .group(name) + .having(name) + .order(name) + try assertEqualSQL(db, request, expectedSQL) + } + do { + let request = A + .select(name) + .filter(key: 1) + .filter(condition) + .group(name) + .having(name) + .order(name) + .aliased(alias) + try assertEqualSQL(db, request, expectedSQL) + } + } + do { + let alias = TableAlias(name: "customA") + let name = Column("name") + let condition = name != nil && alias[name] == "foo" + + let expectedSQL = """ + SELECT "customA"."name" \ + FROM "a" "customA" \ + WHERE (("customA"."id" = 1) AND (("customA"."name" IS NOT NULL) AND ("customA"."name" = 'foo'))) \ + GROUP BY "customA"."name" \ + HAVING "customA"."name" \ + ORDER BY "customA"."name" + """ + + do { + let request = A + .aliased(alias) + .select(name) + .filter(key: 1) + .filter(condition) + .group(name) + .having(name) + .order(name) + try assertEqualSQL(db, request, expectedSQL) + } + do { + let request = A + .select(name) + .filter(key: 1) + .filter(condition) + .group(name) + .having(name) + .order(name) + .aliased(alias) + try assertEqualSQL(db, request, expectedSQL) + } + } + } + } + + func testRecursiveRelationDepth1() throws { + // A.include(A.parent) + // A.include(A.child) + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.parent), """ + SELECT "a1".*, "a2".* \ + FROM "a" "a1" \ + JOIN "a" "a2" ON ("a2"."id" = "a1"."parentId") + """) + try assertEqualSQL(db, A.including(required: A.child), """ + SELECT "a1".*, "a2".* \ + FROM "a" "a1" \ + JOIN "a" "a2" ON ("a2"."parentId" = "a1"."id") + """) + } + } + + func testRecursiveRelationDepth2() throws { + // A.include(B1).include(A) + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = A + .including(required: A.b1 + .including(required: B.a2)) + try assertEqualSQL(db, request, """ + SELECT "a1".*, "b".*, "a2".* \ + FROM "a" "a1" \ + JOIN "b" ON ("b"."id" = "a1"."bid1") \ + JOIN "a" "a2" ON ("a2"."bid2" = "b"."id") + """) + } + } + + func testMultipleForeignKeys() throws { + // A + // .include(B1) + // .include(B2) + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = A + .including(required: A.b1) + .including(required: A.b2) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b1".*, "b2".* \ + FROM "a" \ + JOIN "b" "b1" ON ("b1"."id" = "a"."bid1") \ + JOIN "b" "b2" ON ("b2"."id" = "a"."bid2") + """) + } + } + + func testRecursiveThroughMultipleForeignKeys() throws { + // A + // .include(B1.include(A)) + // .include(B2.include(A)) + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = A + .including(required: A.b1 + .including(required: B.a2)) + .including(required: A.b2 + .including(required: B.a1)) + try assertEqualSQL(db, request, """ + SELECT "a1".*, "b1".*, "a2".*, "b2".*, "a3".* \ + FROM "a" "a1" \ + JOIN "b" "b1" ON ("b1"."id" = "a1"."bid1") \ + JOIN "a" "a2" ON ("a2"."bid2" = "b1"."id") \ + JOIN "b" "b2" ON ("b2"."id" = "a1"."bid2") \ + JOIN "a" "a3" ON ("a3"."bid1" = "b2"."id") + """) + } + } + + func testUserDefinedAlias() throws { + // A + // .aliased("customA") + // .include(B1.aliased("customB")) + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let aAlias1 = TableAlias(name: "customA1") // On TableMapping and QueryInterfaceRequest + let bAlias = TableAlias(name: "customB") // On BelongsToAssociation + let aAlias2 = TableAlias(name: "customA2") // On HasOneAssociation + + let expectedSQL = """ + SELECT "customA1".*, "customB".*, "customA2".* \ + FROM "a" "customA1" \ + JOIN "b" "customB" ON ("customB"."id" = "customA1"."bid1") \ + JOIN "a" "customA2" ON ("customA2"."bid2" = "customB"."id") + """ + + do { + // Alias first + let request = A + .aliased(aAlias1) + .including(required: A.b1 + .aliased(bAlias) + .including(required: B.a2 + .aliased(aAlias2))) + try assertEqualSQL(db, request, expectedSQL) + } + + do { + // Alias last + let request = A + .including(required: A.b1 + .including(required: B.a2 + .aliased(aAlias2)) + .aliased(bAlias)) + .aliased(aAlias1) + try assertEqualSQL(db, request, expectedSQL) + } + } + } + + func testUserInducedNameConflict() throws { + // A.include(B1.aliased("a")) + // A.aliased("b").include(B1) + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + let bAlias = TableAlias(name: A.databaseTableName.lowercased()) + let request = A.including(required: A.b1.aliased(bAlias)) + try assertEqualSQL(db, request, """ + SELECT "a1".*, "a".* \ + FROM "a" "a1" \ + JOIN "b" "a" ON ("a"."id" = "a1"."bid1") + """) + } + do { + let bAlias = TableAlias(name: A.databaseTableName.uppercased()) + let request = A.including(required: A.b1.aliased(bAlias)) + try assertEqualSQL(db, request, """ + SELECT "a1".*, "A".* \ + FROM "a" "a1" \ + JOIN "b" "A" ON ("A"."id" = "a1"."bid1") + """) + } + do { + let aAlias = TableAlias(name: B.databaseTableName.lowercased()) + let request = A.aliased(aAlias).including(required: A.b1) + try assertEqualSQL(db, request, """ + SELECT "b".*, "b1".* \ + FROM "a" "b" \ + JOIN "b" "b1" ON ("b1"."id" = "b"."bid1") + """) + } + do { + let aAlias = TableAlias(name: B.databaseTableName.uppercased()) + let request = A.aliased(aAlias).including(required: A.b1) + try assertEqualSQL(db, request, """ + SELECT "B".*, "b1".* \ + FROM "a" "B" \ + JOIN "b" "b1" ON ("b1"."id" = "B"."bid1") + """) + } + } + } + + func testCrossTableExpressions() throws { + // A + // .include(B1.include(A)) + // .include(B2.include(A)) + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let rootA = TableAlias() + let A1 = TableAlias() + let A2 = TableAlias() + let name = Column("name") + + let condition = name != nil && rootA[name] > A1[name] && A2[name] == "foo" + + let expectedSQL = """ + SELECT "a1".*, "b1".*, "a2".*, "b2".*, "a3".* \ + FROM "a" "a1" \ + JOIN "b" "b1" ON ("b1"."id" = "a1"."bid1") \ + JOIN "a" "a2" ON ("a2"."bid2" = "b1"."id") \ + JOIN "b" "b2" ON ("b2"."id" = "a1"."bid2") \ + JOIN "a" "a3" ON ("a3"."bid1" = "b2"."id") \ + WHERE ((("a1"."name" IS NOT NULL) AND ("a1"."name" > "a3"."name")) AND ("a2"."name" = 'foo')) + """ + + do { + // Filter first + let request = A + .filter(condition) + .aliased(rootA) + .including(required: A.b1 + .including(required: B.a2.aliased(A2))) + .including(required: A.b2 + .including(required: B.a1.aliased(A1))) + try assertEqualSQL(db, request, expectedSQL) + } + + do { + // Filter last + let request = A + .aliased(rootA) + .including(required: A.b1 + .including(required: B.a2.aliased(A2))) + .including(required: A.b2 + .including(required: B.a1.aliased(A1))) + .filter(condition) + try assertEqualSQL(db, request, expectedSQL) + } + } + } +}