diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 3fbb46a02..a9a61a52d 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -99,9 +99,9 @@ 56176C701EACCCC9000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */; }; 56176C7D1EACCD2D000F3F2B /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; }; 56176C7F1EACCD2F000F3F2B /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; }; - 561CFA7823735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* MutablePersistableRecordUpdateTests.swift */; }; - 561CFA7923735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* MutablePersistableRecordUpdateTests.swift */; }; - 561CFA7A23735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* MutablePersistableRecordUpdateTests.swift */; }; + 561CFA7823735016000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */; }; + 561CFA7923735016000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */; }; + 561CFA7A23735016000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */; }; 561CFA982376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; }; 561CFA992376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; }; 561CFA9A2376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; }; @@ -129,6 +129,10 @@ 5623936D1DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */; }; 562393721DEE104400A6B01F /* MapCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393711DEE104400A6B01F /* MapCursorTests.swift */; }; 562393761DEE104400A6B01F /* MapCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393711DEE104400A6B01F /* MapCursorTests.swift */; }; + 56256ED025D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; }; + 56256ED125D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; }; + 56256ED225D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; }; + 56256ED325D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; }; 56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; }; 56256EDA25D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; }; 56256EDB25D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; }; @@ -179,6 +183,9 @@ 563B071621862C4700B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */; }; 563B071821862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; }; 563B071921862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; }; + 563B5336267E2F90009549B5 /* TableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B5335267E2F90009549B5 /* TableTests.swift */; }; + 563B5337267E2F90009549B5 /* TableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B5335267E2F90009549B5 /* TableTests.swift */; }; + 563B5338267E2F90009549B5 /* TableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B5335267E2F90009549B5 /* TableTests.swift */; }; 563B8F92249E6171007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F91249E6171007A48C9 /* Trace.swift */; }; 563B8F93249E6171007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F91249E6171007A48C9 /* Trace.swift */; }; 563B8F94249E6171007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F91249E6171007A48C9 /* Trace.swift */; }; @@ -773,7 +780,7 @@ 56D496681D813086008276D7 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */; }; 56D496691D813086008276D7 /* QueryInterfaceExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */; }; 56D4966A1D813086008276D7 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */; }; - 56D4966B1D81309E008276D7 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; }; + 56D4966B1D81309E008276D7 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */; }; 56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238261B9C74A90082EB20 /* RecordMinimalPrimaryKeyRowIDTests.swift */; }; 56D4966D1D81309E008276D7 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238271B9C74A90082EB20 /* RecordMinimalPrimaryKeySingleTests.swift */; }; 56D4966E1D81309E008276D7 /* RecordPrimaryKeyMultipleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238281B9C74A90082EB20 /* RecordPrimaryKeyMultipleTests.swift */; }; @@ -901,7 +908,7 @@ 56FEB8FA248403020081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */; }; 56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; 56FEE7FF1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; - 56FF45441D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; }; + 56FF45441D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */; }; 56FF455A1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; 6340BF801E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */; }; 6340BF841E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */; }; @@ -1019,7 +1026,7 @@ AAA4DD0D230F262000C74B15 /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */; }; AAA4DD0E230F262000C74B15 /* RowAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* RowAdapterTests.swift */; }; AAA4DD0F230F262000C74B15 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; - AAA4DD10230F262000C74B15 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; }; + AAA4DD10230F262000C74B15 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */; }; AAA4DD11230F262000C74B15 /* RecordPrimaryKeyNoneTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238291B9C74A90082EB20 /* RecordPrimaryKeyNoneTests.swift */; }; AAA4DD12230F262000C74B15 /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; }; AAA4DD13230F262000C74B15 /* DatabaseQueueConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */; }; @@ -1279,7 +1286,7 @@ 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = ""; }; 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RequestProtocols.swift; sourceTree = ""; }; 56172947223533F40006E219 /* EncodableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncodableRecord.swift; sourceTree = ""; }; - 561CFA7123735015000C8BAA /* MutablePersistableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordUpdateTests.swift; sourceTree = ""; }; + 561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordUpdateTests.swift; sourceTree = ""; }; 561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = ""; }; 561CFA9B2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; @@ -1290,6 +1297,7 @@ 562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FlattenCursorTests.swift; sourceTree = ""; }; 562393711DEE104400A6B01F /* MapCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MapCursorTests.swift; sourceTree = ""; }; 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = ""; }; + 56256ECF25D1ACD0008C2BDD /* Table.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = ""; }; 56256ED825D1B316008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = ""; }; 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = ""; }; 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = ""; }; @@ -1318,6 +1326,7 @@ 563B0704218627F700B38F35 /* ValueObservationRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRowTests.swift; sourceTree = ""; }; 563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = ""; }; 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = ""; }; + 563B5335267E2F90009549B5 /* TableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableTests.swift; sourceTree = ""; }; 563B8F91249E6171007A48C9 /* Trace.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Trace.swift; sourceTree = ""; }; 563B8FA0249E8ACB007A48C9 /* ValueObservationPrintTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationPrintTests.swift; sourceTree = ""; }; 563B8FAB24A1CE43007A48C9 /* DatabasePublishers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabasePublishers.swift; sourceTree = ""; }; @@ -1605,7 +1614,7 @@ 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = ""; }; 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseTraceTests.swift; sourceTree = ""; }; 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = ""; }; - 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordDeleteTests.swift; sourceTree = ""; }; + 56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordDeleteTests.swift; sourceTree = ""; }; 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = ""; }; 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = ""; }; AAA4DCFE230F1E0600C74B15 /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -1759,11 +1768,9 @@ 5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */, 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */, 566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */, - 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */, 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */, 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */, 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */, - 561CFA7123735015000C8BAA /* MutablePersistableRecordUpdateTests.swift */, 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */, ); name = PersistableRecord; @@ -1803,7 +1810,9 @@ 56176C9C1EACEA8C000F3F2B /* TableRecord */ = { isa = PBXGroup; children = ( + 56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */, 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */, + 561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */, ); name = TableRecord; sourceTree = ""; @@ -1873,6 +1882,7 @@ 56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */, 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */, 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */, + 563B5335267E2F90009549B5 /* TableTests.swift */, 5698AC7F1DA380A20056AF8C /* VirtualTableModuleTests.swift */, 5653EABF20944B1300F46237 /* Association */, ); @@ -2060,6 +2070,7 @@ 56D91AA12205E03700770D8D /* SQLRelation.swift */, 568ECA8925D7013000B71526 /* SQLSelection.swift */, 568ECB1725D9161500B71526 /* SQLSubquery.swift */, + 56256ECF25D1ACD0008C2BDD /* Table.swift */, ); path = SQL; sourceTree = ""; @@ -2867,6 +2878,7 @@ buildActionMask = 2147483647; files = ( 5616AAF3207CD45E00AC3664 /* RequestProtocols.swift in Sources */, + 56256ED225D1ACD0008C2BDD /* Table.swift in Sources */, 56B964BF1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, 56D51D061EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 565490CE1D5AE252005622CB /* NSNull.swift in Sources */, @@ -3030,6 +3042,7 @@ 566475D61D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 5698AD381DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, 56012BA8257404E000B4925B /* CommonTableExpression.swift in Sources */, + 56256ED125D1ACD0008C2BDD /* Table.swift in Sources */, 5653EB0A20944C7C00F46237 /* Association.swift in Sources */, 56A2387E1B9C75030082EB20 /* Database.swift in Sources */, 56CEB4FD1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, @@ -3155,7 +3168,7 @@ 56300B861C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift in Sources */, 56F26C1C1CEE3F32007969C4 /* RowAdapterTests.swift in Sources */, 56DAA2D61DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */, - 56FF45441D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */, + 56FF45441D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */, 56A238561B9C74A90082EB20 /* RecordPrimaryKeyNoneTests.swift in Sources */, 562EA8331F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, 563363BE1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift in Sources */, @@ -3302,7 +3315,7 @@ 56A5EF131EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, 5653EAE920944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */, 5698ACD21DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, - 561CFA7923735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */, + 561CFA7923735016000C8BAA /* TableRecordUpdateTests.swift in Sources */, 56A238621B9C74A90082EB20 /* RecordEditedTests.swift in Sources */, 5653EAE120944B4F00F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, 5604484A25DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */, @@ -3315,6 +3328,7 @@ 56677C0E241CD0D00050755D /* ValueObservationRecorder.swift in Sources */, 5698ACA21DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, 56A2385C1B9C74A90082EB20 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, + 563B5337267E2F90009549B5 /* TableTests.swift in Sources */, 56A238401B9C74A90082EB20 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 564F9C221F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, 56A8C2481D1918F00096E9D4 /* FoundationUUIDTests.swift in Sources */, @@ -3413,7 +3427,7 @@ 56D4968C1D81316E008276D7 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */, 56419C6D24A519A2004967E1 /* ValueObservationPublisherTests.swift in Sources */, 56D496981D81317B008276D7 /* DatabaseValueTests.swift in Sources */, - 56D4966B1D81309E008276D7 /* MutablePersistableRecordDeleteTests.swift in Sources */, + 56D4966B1D81309E008276D7 /* TableRecordDeleteTests.swift in Sources */, 563B06F721861D8400B38F35 /* ValueObservationCountTests.swift in Sources */, 56DF001B228DDBA300D611F3 /* AssociationPrefetchingRowTests.swift in Sources */, 56D4965B1D81304E008276D7 /* FoundationNSDecimalNumberTests.swift in Sources */, @@ -3533,7 +3547,7 @@ 5698AC401DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 562393571DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 5653EAE820944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */, - 561CFA7823735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */, + 561CFA7823735016000C8BAA /* TableRecordUpdateTests.swift in Sources */, 56A5EF0F1EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, 5604484925DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */, 56D496B61D813434008276D7 /* DatabaseRegionTests.swift in Sources */, @@ -3545,6 +3559,7 @@ 562393181DECC02000A6B01F /* RowFetchTests.swift in Sources */, 56677C0D241CD0D00050755D /* ValueObservationRecorder.swift in Sources */, 5653EADA20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */, + 563B5336267E2F90009549B5 /* TableTests.swift in Sources */, 56D4965A1D81304E008276D7 /* FoundationNSDataTests.swift in Sources */, 56D496741D81309E008276D7 /* RecordCopyTests.swift in Sources */, 56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */, @@ -3621,6 +3636,7 @@ AAA4DC7F230F1E0600C74B15 /* SQLOperators.swift in Sources */, AAA4DC80230F1E0600C74B15 /* FTS5CustomTokenizer.swift in Sources */, 56012BB2257404E200B4925B /* CommonTableExpression.swift in Sources */, + 56256ED325D1ACD0008C2BDD /* Table.swift in Sources */, AAA4DC81230F1E0600C74B15 /* Association.swift in Sources */, AAA4DC82230F1E0600C74B15 /* Database.swift in Sources */, AAA4DC83230F1E0600C74B15 /* FTS3.swift in Sources */, @@ -3746,7 +3762,7 @@ AAA4DD0D230F262000C74B15 /* Record+QueryInterfaceRequestTests.swift in Sources */, AAA4DD0E230F262000C74B15 /* RowAdapterTests.swift in Sources */, AAA4DD0F230F262000C74B15 /* DatabaseCursorTests.swift in Sources */, - AAA4DD10230F262000C74B15 /* MutablePersistableRecordDeleteTests.swift in Sources */, + AAA4DD10230F262000C74B15 /* TableRecordDeleteTests.swift in Sources */, AAA4DD11230F262000C74B15 /* RecordPrimaryKeyNoneTests.swift in Sources */, AAA4DD12230F262000C74B15 /* CompilationSubClassTests.swift in Sources */, AAA4DD13230F262000C74B15 /* DatabaseQueueConcurrencyTests.swift in Sources */, @@ -3893,7 +3909,7 @@ AAA4DD8B230F262000C74B15 /* ForeignKeyInfoTests.swift in Sources */, AAA4DD8C230F262000C74B15 /* AssociationChainSQLTests.swift in Sources */, AAA4DD8D230F262000C74B15 /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, - 561CFA7A23735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */, + 561CFA7A23735016000C8BAA /* TableRecordUpdateTests.swift in Sources */, AAA4DD8E230F262000C74B15 /* RecordEditedTests.swift in Sources */, AAA4DD8F230F262000C74B15 /* AssociationTableAliasTestsSQLTests.swift in Sources */, 5604484B25DEEEF8002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */, @@ -3906,6 +3922,7 @@ 56677C0F241CD0D00050755D /* ValueObservationRecorder.swift in Sources */, AAA4DD94230F262000C74B15 /* FTS4TableBuilderTests.swift in Sources */, AAA4DD95230F262000C74B15 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, + 563B5338267E2F90009549B5 /* TableTests.swift in Sources */, AAA4DD96230F262000C74B15 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, AAA4DD97230F262000C74B15 /* DatabaseAggregateTests.swift in Sources */, AAA4DD98230F262000C74B15 /* FoundationUUIDTests.swift in Sources */, @@ -3982,6 +3999,7 @@ 566B91091FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91231FA4CF810012D5B0 /* Database+Schema.swift in Sources */, 56012B9F257404DF00B4925B /* CommonTableExpression.swift in Sources */, + 56256ED025D1ACD0008C2BDD /* Table.swift in Sources */, 563B06AB217EF0CC00B38F35 /* ValueObservation.swift in Sources */, 56CEB5111EAA324B00BFAF62 /* FTS3+QueryInterface.swift in Sources */, 5659F4901EA8D964004A4992 /* ReadWriteBox.swift in Sources */, diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index 97820b2f8..4d46a616d 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -62,6 +62,7 @@ extension AssociationToMany { /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) /// /// let teams: [Team] = try Team.having(Team.players.average(Column("score")) > 100).fetchAll(db) + @available(*, deprecated, message: "Did you mean average(Column(...))? If not, prefer average(value.databaseValue) instead.") // swiftlint:disable:this line_length public func average(_ expression: SQLExpressible) -> AssociationAggregate { let aggregate = makeAggregate(.aggregate("AVG", [expression.sqlExpression])) if let column = expression as? ColumnExpression { @@ -72,6 +73,33 @@ extension AssociationToMany { } } + /// Creates an aggregate which evaluate to the average value of the given + /// expression in associated records. + /// + /// When the averaged expression is a column, the aggregate has a default + /// name which is "average[Key][Column]", where key is the key of the + /// association. For example: + /// + /// For example: + /// + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var averagePlayerScore: Double + /// } + /// let request = Team.annotated(with: Team.players.average(Column("score"))) + /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// + /// let teams: [Team] = try Team.having(Team.players.average(Column("score")) > 100).fetchAll(db) + public func average(_ expression: SQLSpecificExpressible) -> AssociationAggregate { + let aggregate = makeAggregate(.aggregate("AVG", [expression.sqlExpression])) + if let column = expression as? ColumnExpression { + let name = key.singularizedName + return aggregate.forKey("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") + } else { + return aggregate + } + } + /// Creates an aggregate which evaluate to the maximum value of the given /// expression in associated records. /// @@ -89,6 +117,7 @@ extension AssociationToMany { /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) /// /// let teams: [Team] = try Team.having(Team.players.max(Column("score")) < 100).fetchAll(db) + @available(*, deprecated, message: "Did you mean max(Column(...))? If not, prefer max(value.databaseValue) instead.") // swiftlint:disable:this line_length public func max(_ expression: SQLExpressible) -> AssociationAggregate { let aggregate = makeAggregate(.aggregate("MAX", [expression.sqlExpression])) if let column = expression as? ColumnExpression { @@ -99,6 +128,33 @@ extension AssociationToMany { } } + /// Creates an aggregate which evaluate to the maximum value of the given + /// expression in associated records. + /// + /// When the maximized expression is a column, the aggregate has a default + /// name which is "maximum[Key][Column]", where key is the key of the + /// association. For example: + /// + /// For example: + /// + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var maxPlayerScore: Double + /// } + /// let request = Team.annotated(with: Team.players.max(Column("score"))) + /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// + /// let teams: [Team] = try Team.having(Team.players.max(Column("score")) < 100).fetchAll(db) + public func max(_ expression: SQLSpecificExpressible) -> AssociationAggregate { + let aggregate = makeAggregate(.aggregate("MAX", [expression.sqlExpression])) + if let column = expression as? ColumnExpression { + let name = key.singularizedName + return aggregate.forKey("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") + } else { + return aggregate + } + } + /// Creates an aggregate which evaluate to the minimum value of the given /// expression in associated records. /// @@ -116,6 +172,7 @@ extension AssociationToMany { /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) /// /// let teams: [Team] = try Team.having(Team.players.min(Column("score")) > 100).fetchAll(db) + @available(*, deprecated, message: "Did you mean min(Column(...))? If not, prefer min(value.databaseValue) instead.") // swiftlint:disable:this line_length public func min(_ expression: SQLExpressible) -> AssociationAggregate { let aggregate = makeAggregate(.aggregate("MIN", [expression.sqlExpression])) if let column = expression as? ColumnExpression { @@ -126,6 +183,33 @@ extension AssociationToMany { } } + /// Creates an aggregate which evaluate to the minimum value of the given + /// expression in associated records. + /// + /// When the minimized expression is a column, the aggregate has a default + /// name which is "minimum[Key][Column]", where key is the key of the + /// association. For example: + /// + /// For example: + /// + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var minPlayerScore: Double + /// } + /// let request = Team.annotated(with: Team.players.min(Column("score"))) + /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// + /// let teams: [Team] = try Team.having(Team.players.min(Column("score")) > 100).fetchAll(db) + public func min(_ expression: SQLSpecificExpressible) -> AssociationAggregate { + let aggregate = makeAggregate(.aggregate("MIN", [expression.sqlExpression])) + if let column = expression as? ColumnExpression { + let name = key.singularizedName + return aggregate.forKey("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") + } else { + return aggregate + } + } + /// Creates an aggregate which evaluate to the sum of the given expression /// in associated records. /// @@ -143,6 +227,7 @@ extension AssociationToMany { /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) /// /// let teams: [Team] = try Team.having(Team.players.sum(Column("score")) > 100).fetchAll(db) + @available(*, deprecated, message: "Did you mean sum(Column(...))? If not, prefer sum(value.databaseValue) instead.") // swiftlint:disable:this line_length public func sum(_ expression: SQLExpressible) -> AssociationAggregate { let aggregate = makeAggregate(.aggregate("SUM", [expression.sqlExpression])) if let column = expression as? ColumnExpression { @@ -152,6 +237,33 @@ extension AssociationToMany { return aggregate } } + + /// Creates an aggregate which evaluate to the sum of the given expression + /// in associated records. + /// + /// When the summed expression is a column, the aggregate has a default + /// name which is "[key][Column]Sum", where key is the key of the + /// association. For example: + /// + /// For example: + /// + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var playerScoreSum: Double + /// } + /// let request = Team.annotated(with: Team.players.sum(Column("score"))) + /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// + /// let teams: [Team] = try Team.having(Team.players.sum(Column("score")) > 100).fetchAll(db) + public func sum(_ expression: SQLSpecificExpressible) -> AssociationAggregate { + let aggregate = makeAggregate(.aggregate("SUM", [expression.sqlExpression])) + if let column = expression as? ColumnExpression { + let name = key.singularizedName + return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum") + } else { + return aggregate + } + } } /// An AssociationAggregate is able to compute aggregated values from a diff --git a/GRDB/QueryInterface/Request/CommonTableExpression.swift b/GRDB/QueryInterface/Request/CommonTableExpression.swift index ebbdd54e1..5e5389e0c 100644 --- a/GRDB/QueryInterface/Request/CommonTableExpression.swift +++ b/GRDB/QueryInterface/Request/CommonTableExpression.swift @@ -378,7 +378,8 @@ extension CommonTableExpression { /// /// The key of the returned association is the table name of `Destination`. /// - /// - parameter cte: A common table expression. + /// - parameter destination: The record type at the other side of + /// the association. /// - parameter condition: A function that returns the joining clause. /// - parameter left: A `TableAlias` for the left table. /// - parameter right: A `TableAlias` for the right table. @@ -399,7 +400,8 @@ extension CommonTableExpression { /// /// The key of the returned association is the table name of `Destination`. /// - /// - parameter cte: A common table expression. + /// - parameter destination: The record type at the other side of + /// the association. /// - returns: An association to the common table expression. public func association( to destination: Destination.Type) @@ -408,4 +410,38 @@ extension CommonTableExpression { { JoinAssociation(to: Destination.relationForAll, condition: .none) } + + /// Creates an association to a table that you can join + /// or include in another request. + /// + /// The key of the returned association is the table name of `Destination`. + /// + /// - parameter destination: The table at the other side of the association. + /// - parameter condition: A function that returns the joining clause. + /// - parameter left: A `TableAlias` for the left table. + /// - parameter right: A `TableAlias` for the right table. + /// - returns: An association to the common table expression. + public func association( + to destination: Table, + on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> SQLExpressible) + -> JoinAssociation + { + JoinAssociation( + to: destination.relationForAll, + condition: .expression { condition($0, $1).sqlExpression }) + } + + /// Creates an association to a table that you can join + /// or include in another request. + /// + /// The key of the returned association is the table name of `Destination`. + /// + /// - parameter destination: The table at the other side of the association. + /// - returns: An association to the common table expression. + public func association( + to destination: Table) + -> JoinAssociation + { + JoinAssociation(to: destination.relationForAll, condition: .none) + } } diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index d7496b904..861751180 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -366,7 +366,7 @@ extension QueryInterfaceRequest { // MARK: - Batch Delete -extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord { +extension QueryInterfaceRequest { /// Deletes matching rows; returns the number of deleted rows. /// /// - parameter db: A database connection. @@ -381,7 +381,20 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord { // MARK: - Batch Update -extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord { +extension QueryInterfaceRequest { + /// The conflict resolution to use for batch updates + private var defaultConflictResolutionForUpdate: Database.ConflictResolution { + // In order to look for the default conflict resolution, we perform a + // runtime check for MutablePersistableRecord, and look for a + // user-defined default. Such dynamic dispatch is unusual in GRDB, but + // static dispatch is likely to create bad surprises in generic contexts. + if let recordType = RowDecoder.self as? MutablePersistableRecord.Type { + return recordType.persistenceConflictPolicy.conflictResolutionForUpdate + } else { + return .abort + } + } + /// Updates matching rows; returns the number of updated rows. /// /// For example: @@ -392,8 +405,7 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord { /// } /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution, - /// defaulting to the record's persistenceConflictPolicy. + /// - parameter conflictResolution: A policy for conflict resolution. /// - parameter assignments: An array of column assignments. /// - returns: The number of updated rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. @@ -403,7 +415,7 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord { onConflict conflictResolution: Database.ConflictResolution? = nil, _ assignments: [ColumnAssignment]) throws -> Int { - let conflictResolution = conflictResolution ?? RowDecoder.persistenceConflictPolicy.conflictResolutionForUpdate + let conflictResolution = conflictResolution ?? defaultConflictResolutionForUpdate guard let updateStatement = try SQLQueryGenerator(relation: relation).makeUpdateStatement( db, conflictResolution: conflictResolution, @@ -426,8 +438,7 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord { /// } /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution, - /// defaulting to the record's persistenceConflictPolicy. + /// - parameter conflictResolution: A policy for conflict resolution. /// - parameter assignment: A column assignment. /// - parameter otherAssignments: Eventual other column assignments. /// - returns: The number of updated rows. diff --git a/GRDB/QueryInterface/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift new file mode 100644 index 000000000..0fef926a7 --- /dev/null +++ b/GRDB/QueryInterface/SQL/Table.swift @@ -0,0 +1,1517 @@ +/// `Table` can build query interface requests. +/// +/// // SELECT * FROM player WHERE score >= 1000 +/// let table = Table("player") +/// let rows: [Row] = try dbQueue.read { db in +/// table.all() +/// .filter(Column("score") >= 1000) +/// .fetchAll(db) +/// } +public struct Table { + /// The table name + public var tableName: String + + private init(_ tableName: String, _ type: RowDecoder.Type) { + self.tableName = tableName + } + + /// Create a `Table` + /// + /// let table = Table("player") + /// let table = Table("player") + public init(_ tableName: String) { + self.init(tableName, RowDecoder.self) + } +} + +extension Table where RowDecoder == Row { + /// Create a `Table` of `Row`. + /// + /// let table = Table("player") // Table + public init(_ tableName: String) { + self.init(tableName, Row.self) + } +} + +// MARK: Request Derivation + +extension Table { + var relationForAll: SQLRelation { + .all(fromTable: tableName) + } + + /// Creates a request for all rows of the table. + /// + /// // Fetch all players + /// let table = Table("player") + /// let request = table.all() + /// let players: [Player] = try request.fetchAll(db) + public func all() -> QueryInterfaceRequest { + QueryInterfaceRequest(relation: relationForAll) + } + + /// Creates a request which fetches no row. + /// + /// // Fetch no players + /// let table = Table("player") + /// let request = table.none() + /// let players: [Player] = try request.fetchAll(db) // Empty array + public func none() -> QueryInterfaceRequest { + all().none() // don't laugh + } + + /// Creates a request which selects *selection*. + /// + /// // SELECT id, email FROM player + /// let table = Table("player") + /// let request = table.select(Column("id"), Column("email")) + public func select(_ selection: SQLSelectable...) -> QueryInterfaceRequest { + all().select(selection) + } + + /// Creates a request which selects *selection*. + /// + /// // SELECT id, email FROM player + /// let table = Table("player") + /// let request = table.select([Column("id"), Column("email")]) + public func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest { + all().select(selection) + } + + /// Creates a request which selects *sql*. + /// + /// // SELECT id, email FROM player + /// let table = Table("player") + /// let request = table.select(sql: "id, email") + public func select( + sql: String, + arguments: StatementArguments = StatementArguments()) + -> QueryInterfaceRequest + { + all().select(SQL(sql: sql, arguments: arguments)) + } + + /// Creates a request which selects an SQL *literal*. + /// + /// Literals allow you to safely embed raw values in your SQL, without any + /// risk of syntax errors or SQL injection: + /// + /// // SELECT id, email, score + 1000 FROM player + /// let table = Table("player") + /// let bonus = 1000 + /// let request = table.select(literal: """ + /// id, email, score + \(bonus) + /// """) + public func select(literal sqlLiteral: SQL) -> QueryInterfaceRequest { + all().select(sqlLiteral) + } + + /// Creates a request which selects *selection*, and fetches values of + /// type *type*. + /// + /// try dbQueue.read { db in + /// // SELECT max(score) FROM player + /// let table = Table("player") + /// let request = table.select([max(Column("score"))], as: Int.self) + /// let maxScore: Int? = try request.fetchOne(db) + /// } + public func select( + _ selection: [SQLSelectable], + as type: RowDecoder.Type = RowDecoder.self) + -> QueryInterfaceRequest + { + all().select(selection, as: type) + } + + /// Creates a request which selects *selection*, and fetches values of + /// type *type*. + /// + /// try dbQueue.read { db in + /// // SELECT max(score) FROM player + /// let table = Table("player") + /// let request = table.select(max(Column("score")), as: Int.self) + /// let maxScore: Int? = try request.fetchOne(db) + /// } + public func select( + _ selection: SQLSelectable..., + as type: RowDecoder.Type = RowDecoder.self) + -> QueryInterfaceRequest + { + all().select(selection, as: type) + } + + /// Creates a request which selects *sql*, and fetches values of + /// type *type*. + /// + /// try dbQueue.read { db in + /// // SELECT max(score) FROM player + /// let table = Table("player") + /// let request = table.select(sql: "max(score)", as: Int.self) + /// let maxScore: Int? = try request.fetchOne(db) + /// } + public func select( + sql: String, + arguments: StatementArguments = StatementArguments(), + as type: RowDecoder.Type = RowDecoder.self) + -> QueryInterfaceRequest + { + all().select(SQL(sql: sql, arguments: arguments), as: type) + } + + /// Creates a request which selects an SQL *literal*, and fetches values of + /// type *type*. + /// + /// Literals allow you to safely embed raw values in your SQL, without any + /// risk of syntax errors or SQL injection: + /// + /// // SELECT IFNULL(name, 'Anonymous') FROM player + /// let table = Table("player") + /// let defaultName = "Anonymous" + /// let request = table.select( + /// literal: "IFNULL(name, \(defaultName))", + /// as: String.self) + /// let name: String? = try request.fetchOne(db) + public func select( + literal sqlLiteral: SQL, + as type: RowDecoder.Type = RowDecoder.self) + -> QueryInterfaceRequest + { + all().select(sqlLiteral, as: type) + } + + /// Creates a request which appends *selection*. + /// + /// // SELECT id, email, name FROM player + /// let table = Table("player") + /// let request = table + /// .select([Column("id"), Column("email")]) + /// .annotated(with: [Column("name")]) + public func annotated(with selection: [SQLSelectable]) -> QueryInterfaceRequest { + all().annotated(with: selection) + } + + /// Creates a request which appends *selection*. + /// + /// // SELECT id, email, name FROM player + /// let table = Table("player") + /// let request = table + /// .select([Column("id"), Column("email")]) + /// .annotated(with: Column("name")) + public func annotated(with selection: SQLSelectable...) -> QueryInterfaceRequest { + all().annotated(with: selection) + } + + /// Creates a request with the provided *predicate*. + /// + /// // SELECT * FROM player WHERE email = 'arthur@example.com' + /// let table = Table("player") + /// let request = table.filter(Column("email") == "arthur@example.com") + public func filter(_ predicate: SQLSpecificExpressible) -> QueryInterfaceRequest { + all().filter(predicate) + } + + /// Creates a request with the provided primary key *predicate*. + /// + /// // SELECT * FROM player WHERE id = 1 + /// let table = Table("player") + /// let request = table.filter(key: 1) + public func filter(key: PrimaryKeyType?) + -> QueryInterfaceRequest + where PrimaryKeyType: DatabaseValueConvertible + { + all().filter(key: key) + } + + /// Creates a request with the provided primary key *predicate*. + /// + /// // SELECT * FROM player WHERE id IN (1, 2, 3) + /// let table = Table("player") + /// let request = table.filter(keys: [1, 2, 3]) + public func filter(keys: Sequence) + -> QueryInterfaceRequest + where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible + { + all().filter(keys: keys) + } + + /// Creates a request with the provided primary key *predicate*. + /// + /// // SELECT * FROM passport WHERE personId = 1 AND countryCode = 'FR' + /// let table = Table("passport") + /// let request = table.filter(key: ["personId": 1, "countryCode": "FR"]) + /// + /// When executed, this request raises a fatal error if there is no unique + /// index on the key columns. + public func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest { + all().filter(key: key) + } + + /// Creates a request with the provided primary key *predicate*. + /// + /// // SELECT * FROM passport WHERE (personId = 1 AND countryCode = 'FR') OR ... + /// let table = Table("passport") + /// let request = table.filter(keys: [["personId": 1, "countryCode": "FR"], ...]) + /// + /// When executed, this request raises a fatal error if there is no unique + /// index on the key columns. + public func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest { + all().filter(keys: keys) + } + + /// Creates a request with the provided *predicate*. + /// + /// // SELECT * FROM player WHERE email = 'arthur@example.com' + /// let table = Table("player") + /// let request = table.filter(sql: "email = ?", arguments: ["arthur@example.com"]) + public func filter( + sql: String, + arguments: StatementArguments = StatementArguments()) + -> QueryInterfaceRequest + { + filter(SQL(sql: sql, arguments: arguments)) + } + + /// Creates a request with the provided *predicate* added to the + /// eventual set of already applied predicates. + /// + /// Literals allow you to safely embed raw values in your SQL, without any + /// risk of syntax errors or SQL injection: + /// + /// // SELECT * FROM player WHERE name = 'O''Brien' + /// let table = Table("player") + /// let name = "O'Brien" + /// let request = table.filter(literal: "email = \(email)") + public func filter(literal sqlLiteral: SQL) -> QueryInterfaceRequest { + all().filter(sqlLiteral) + } + + /// Creates a request sorted according to the + /// provided *orderings*. + /// + /// // SELECT * FROM player ORDER BY name + /// let table = Table("player") + /// let request = table.order(Column("name")) + public func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest { + all().order(orderings) + } + + /// Creates a request sorted according to the + /// provided *orderings*. + /// + /// // SELECT * FROM player ORDER BY name + /// let table = Table("player") + /// let request = table.order([Column("name")]) + public func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest { + all().order(orderings) + } + + /// Creates a request sorted by primary key. + /// + /// // SELECT * FROM player ORDER BY id + /// let table = Table("player") + /// let request = table.orderByPrimaryKey() + /// + /// // SELECT * FROM country ORDER BY code + /// let request = Country.orderByPrimaryKey() + public func orderByPrimaryKey() -> QueryInterfaceRequest { + all().orderByPrimaryKey() + } + + /// Creates a request sorted according to *sql*. + /// + /// // SELECT * FROM player ORDER BY name + /// let table = Table("player") + /// let request = table.order(sql: "name") + public func order( + sql: String, + arguments: StatementArguments = StatementArguments()) + -> QueryInterfaceRequest + { + all().order(SQL(sql: sql, arguments: arguments)) + } + + /// Creates a request sorted according to an SQL *literal*. + /// + /// // SELECT * FROM player ORDER BY name + /// let table = Table("player") + /// let request = table.order(literal: "name") + public func order(literal sqlLiteral: SQL) -> QueryInterfaceRequest { + all().order(sqlLiteral) + } + + /// Creates a request which fetches *limit* rows, starting at + /// *offset*. + /// + /// // SELECT * FROM player LIMIT 1 + /// let table = Table("player") + /// let request = table.limit(1) + public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { + all().limit(limit, offset: offset) + } + + /// Creates a request that allows you to define expressions that target + /// a specific database table. + /// + /// See `TableRecord.aliased(_:)` for more information. + public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { + all().aliased(alias) + } + + /// Returns a request which embeds the common table expression. + /// + /// See `TableRecord.with(_:)` for more information. + /// + /// - parameter cte: A common table expression. + /// - returns: A request. + public func with(_ cte: CommonTableExpression) -> QueryInterfaceRequest { + all().with(cte) + } +} + +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible { + /// Creates a request filtered by primary key. + /// + /// // SELECT * FROM player WHERE id = 1 + /// let table = Table("player") + /// let request = table.filter(id: 1) + /// + /// - parameter id: A primary key + public func filter(id: RowDecoder.ID) -> QueryInterfaceRequest { + all().filter(id: id) + } + + /// Creates a request filtered by primary key. + /// + /// // SELECT * FROM player WHERE id IN (1, 2, 3) + /// let table = Table("player") + /// let request = table.filter(ids: [1, 2, 3]) + /// + /// - parameter ids: A collection of primary keys + public func filter(ids: Collection) + -> QueryInterfaceRequest + where Collection: Swift.Collection, Collection.Element == RowDecoder.ID + { + all().filter(ids: ids) + } + + /// Creates a request which selects the primary key. + /// + /// // SELECT id FROM player + /// let table = Table("player") + /// let request = try table.selectID() + public func selectID() -> QueryInterfaceRequest { + all().selectID() + } +} + +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension Table +where RowDecoder: Identifiable, + RowDecoder.ID: _OptionalProtocol, + RowDecoder.ID.Wrapped: DatabaseValueConvertible +{ + /// Creates a request filtered by primary key. + /// + /// // SELECT * FROM player WHERE id = 1 + /// let table = Table("player") + /// let request = table.filter(id: 1) + /// + /// - parameter id: A primary key + public func filter(id: RowDecoder.ID.Wrapped) -> QueryInterfaceRequest { + all().filter(id: id) + } + + /// Creates a request filtered by primary key. + /// + /// // SELECT * FROM player WHERE id IN (1, 2, 3) + /// let table = Table("player") + /// let request = table.filter(ids: [1, 2, 3]) + /// + /// - parameter ids: A collection of primary keys + public func filter(ids: Collection) + -> QueryInterfaceRequest + where Collection: Swift.Collection, Collection.Element == RowDecoder.ID.Wrapped + { + all().filter(ids: ids) + } + + /// Creates a request which selects the primary key. + /// + /// // SELECT id FROM player + /// let table = Table("player") + /// let request = try table.selectID() + public func selectID() -> QueryInterfaceRequest { + all().selectID() + } +} + +extension Table { + + // MARK: - Counting All + + /// The number of rows. + /// + /// - parameter db: A database connection. + public func fetchCount(_ db: Database) throws -> Int { + try all().fetchCount(db) + } +} + +// MARK: - Fetching Records from Table + +extension Table where RowDecoder: FetchableRecord { + /// A cursor over all records fetched from the database. + /// + /// // SELECT * FROM player + /// let table = Table("player") + /// let players = try table.fetchCursor(db) // Cursor of Player + /// while let player = try players.next() { // Player + /// ... + /// } + /// + /// Records are iterated in the natural ordering of the table. + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispatch queue. + /// + /// - parameter db: A database connection. + /// - returns: A cursor over fetched records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchCursor(_ db: Database) throws -> RecordCursor { + try all().fetchCursor(db) + } + + /// An array of all records fetched from the database. + /// + /// // SELECT * FROM player + /// let table = Table("player") + /// let players = try table.fetchAll(db) // [Player] + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchAll(_ db: Database) throws -> [RowDecoder] { + try all().fetchAll(db) + } + + /// The first found record. + /// + /// // SELECT * FROM player LIMIT 1 + /// let table = Table("player") + /// let player = try table.fetchOne(db) // Player? + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchOne(_ db: Database) throws -> RowDecoder? { + try all().fetchOne(db) + } +} + +extension Table where RowDecoder: FetchableRecord & Hashable { + /// A set of all records fetched from the database. + /// + /// // SELECT * FROM player + /// let table = Table("player") + /// let players = try table.fetchSet(db) // Set + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchSet(_ db: Database) throws -> Set { + try all().fetchSet(db) + } +} + +// MARK: - Fetching Rows from Table + +extension Table where RowDecoder == Row { + /// A cursor over all rows fetched from the database. + /// + /// // SELECT * FROM player + /// let table = Table("player") + /// let rows = try table.fetchCursor(db) // Cursor of Row + /// while let row = try rows.next() { // Row + /// ... + /// } + /// + /// Rows are iterated in the natural ordering of the table. + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispatch queue. + /// + /// - parameter db: A database connection. + /// - returns: A cursor over fetched records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchCursor(_ db: Database) throws -> RowCursor { + try all().fetchCursor(db) + } + + /// An array of all rows fetched from the database. + /// + /// // SELECT * FROM player + /// let table = Table("player") + /// let players = try table.fetchAll(db) // [Row] + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchAll(_ db: Database) throws -> [Row] { + try all().fetchAll(db) + } + + /// The first found row. + /// + /// // SELECT * FROM player LIMIT 1 + /// let table = Table("player") + /// let row = try table.fetchOne(db) // Row? + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchOne(_ db: Database) throws -> Row? { + try all().fetchOne(db) + } + + /// A set of all rows fetched from the database. + /// + /// // SELECT * FROM player + /// let table = Table("player") + /// let rows = try table.fetchSet(db) // Set + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchSet(_ db: Database) throws -> Set { + try all().fetchSet(db) + } +} + +// MARK: - Fetching Values from Table + +extension Table where RowDecoder: DatabaseValueConvertible { + /// A cursor over all values fetched from the leftmost column. + /// + /// // SELECT * FROM name + /// let table = Table("name") + /// let names = try table.fetchCursor(db) // Cursor of String + /// while let name = try names.next() { // String + /// ... + /// } + /// + /// Values are iterated in the natural ordering of the table. + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispatch queue. + /// + /// - parameter db: A database connection. + /// - returns: A cursor over fetched records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor { + try all().fetchCursor(db) + } + + /// An array of all values fetched from the leftmost column. + /// + /// // SELECT * FROM name + /// let table = Table("name") + /// let names = try table.fetchAll(db) // [String] + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchAll(_ db: Database) throws -> [RowDecoder] { + try all().fetchAll(db) + } + + /// The value from the leftmost column of the first row. + /// + /// // SELECT * FROM name LIMIT 1 + /// let table = Table("name") + /// let name = try table.fetchOne(db) // String? + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchOne(_ db: Database) throws -> RowDecoder? { + try all().fetchOne(db) + } +} + +extension Table where RowDecoder: DatabaseValueConvertible & Hashable { + /// A set of all values fetched from the leftmost column. + /// + /// // SELECT * FROM name + /// let table = Table("name") + /// let names = try table.fetchSet(db) // Set + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchSet(_ db: Database) throws -> Set { + try all().fetchSet(db) + } +} + +extension Table where RowDecoder: _OptionalProtocol, RowDecoder.Wrapped: DatabaseValueConvertible { + /// A cursor over all values fetched from the leftmost column. + /// + /// // SELECT * FROM name + /// let table = Table("name") + /// let names = try table.fetchCursor(db) // Cursor of String? + /// while let name = try names.next() { // String? + /// ... + /// } + /// + /// Values are iterated in the natural ordering of the table. + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispatch queue. + /// + /// - parameter db: A database connection. + /// - returns: A cursor over fetched records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor { + try all().fetchCursor(db) + } + + /// An array of all values fetched from the leftmost column. + /// + /// // SELECT * FROM name + /// let table = Table("name") + /// let names = try table.fetchAll(db) // [String?] + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchAll(_ db: Database) throws -> [RowDecoder.Wrapped?] { + try all().fetchAll(db) + } + + /// The value from the leftmost column of the first row. + /// + /// // SELECT * FROM name LIMIT 1 + /// let table = Table("name") + /// let name = try table.fetchOne(db) // String? + /// + /// The result is nil if the query returns no row, or if no value can be + /// extracted from the first row. + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchOne(_ db: Database) throws -> RowDecoder.Wrapped? { + try all().fetchOne(db) + } +} + +extension Table where RowDecoder: _OptionalProtocol, RowDecoder.Wrapped: DatabaseValueConvertible & Hashable { + /// A set of all values fetched from the leftmost column. + /// + /// // SELECT * FROM name + /// let table = Table("name") + /// let names = try table.fetchSet(db) // Set + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchSet(_ db: Database) throws -> Set { + try all().fetchSet(db) + } +} + +// MARK: - Fetching Fast Values from Table + +extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible { + /// A cursor over all values fetched from the leftmost column. + /// + /// // SELECT * FROM name + /// let table = Table("name") + /// let names = try table.fetchCursor(db) // Cursor of String + /// while let name = try names.next() { // String + /// ... + /// } + /// + /// Values are iterated in the natural ordering of the table. + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispatch queue. + /// + /// - parameter db: A database connection. + /// - returns: A cursor over fetched records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchCursor(_ db: Database) throws -> FastDatabaseValueCursor { + try all().fetchCursor(db) + } + + /// An array of all values fetched from the leftmost column. + /// + /// // SELECT * FROM name + /// let table = Table("name") + /// let names = try table.fetchAll(db) // [String] + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchAll(_ db: Database) throws -> [RowDecoder] { + try all().fetchAll(db) + } + + /// The value from the leftmost column of the first row. + /// + /// // SELECT * FROM name LIMIT 1 + /// let table = Table("name") + /// let name = try table.fetchOne(db) // String? + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchOne(_ db: Database) throws -> RowDecoder? { + try all().fetchOne(db) + } +} + +extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible & Hashable { + /// A set of all values fetched from the leftmost column. + /// + /// // SELECT * FROM name + /// let table = Table("name") + /// let names = try table.fetchSet(db) // Set + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchSet(_ db: Database) throws -> Set { + try all().fetchSet(db) + } +} + +extension Table +where RowDecoder: _OptionalProtocol, + RowDecoder.Wrapped: DatabaseValueConvertible & StatementColumnConvertible +{ + /// A cursor over all values fetched from the leftmost column. + /// + /// // SELECT * FROM name + /// let table = Table("name") + /// let names = try table.fetchCursor(db) // Cursor of String? + /// while let name = try names.next() { // String? + /// ... + /// } + /// + /// Values are iterated in the natural ordering of the table. + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispatch queue. + /// + /// - parameter db: A database connection. + /// - returns: A cursor over fetched records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchCursor(_ db: Database) throws -> FastNullableDatabaseValueCursor { + try all().fetchCursor(db) + } + + /// An array of all values fetched from the leftmost column. + /// + /// // SELECT * FROM name + /// let table = Table("name") + /// let names = try table.fetchAll(db) // [String?] + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchAll(_ db: Database) throws -> [RowDecoder.Wrapped?] { + try all().fetchAll(db) + } + + /// The value from the leftmost column of the first row. + /// + /// // SELECT * FROM name LIMIT 1 + /// let table = Table("name") + /// let name = try table.fetchOne(db) // String? + /// + /// The result is nil if the query returns no row, or if no value can be + /// extracted from the first row. + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchOne(_ db: Database) throws -> RowDecoder.Wrapped? { + try all().fetchOne(db) + } +} + +extension Table +where RowDecoder: _OptionalProtocol, + RowDecoder.Wrapped: DatabaseValueConvertible & StatementColumnConvertible & Hashable +{ + /// A set of all values fetched from the leftmost column. + /// + /// // SELECT * FROM name + /// let table = Table("name") + /// let names = try table.fetchSet(db) // Set + /// + /// - parameter db: A database connection. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchSet(_ db: Database) throws -> Set { + try all().fetchSet(db) + } +} + +// MARK: - Associations to TableRecord + +extension Table { + /// Creates a "Belongs To" association between Self and the destination + /// type, based on a database foreign key. + /// + /// For more information, see `TableRecord.belongsTo(_:key:using:)`. + /// + /// - parameters: + /// - destination: The record type at the other side of the association. + /// - key: An eventual decoding key for the association. By default, it + /// is `destination.databaseTableName`. + /// - foreignKey: An eventual foreign key. You need to provide an + /// explicit foreign key when GRDB can't infer one from the database + /// schema. This happens when the schema does not define any foreign + /// key to the destination table, or when the schema defines several + /// foreign keys to the destination table. + public func belongsTo( + _ destination: Destination.Type, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> BelongsToAssociation + where Destination: TableRecord + { + BelongsToAssociation( + to: Destination.relationForAll, + key: key, + using: foreignKey) + } + + /// Creates a "Has many" association between Self and the destination type, + /// based on a database foreign key. + /// + /// For more information, see `TableRecord.hasMany(_:key:using:)`. + /// + /// - parameters: + /// - destination: The record type at the other side of the association. + /// - key: An eventual decoding key for the association. By default, it + /// is `destination.databaseTableName`. + /// - foreignKey: An eventual foreign key. You need to provide an + /// explicit foreign key when GRDB can't infer one from the database + /// schema. This happens when the schema does not define any foreign + /// key from the destination table, or when the schema defines several + /// foreign keys from the destination table. + public func hasMany( + _ destination: Destination.Type, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasManyAssociation + where Destination: TableRecord + { + HasManyAssociation( + to: Destination.relationForAll, + key: key, + using: foreignKey) + } + + /// Creates a "Has one" association between Self and the destination type, + /// based on a database foreign key. + /// + /// For more information, see `TableRecord.hasOne(_:key:using:)`. + /// + /// - parameters: + /// - destination: The record type at the other side of the association. + /// - key: An eventual decoding key for the association. By default, it + /// is `destination.databaseTableName`. + /// - foreignKey: An eventual foreign key. You need to provide an + /// explicit foreign key when GRDB can't infer one from the database + /// schema. This happens when the schema does not define any foreign + /// key from the destination table, or when the schema defines several + /// foreign keys from the destination table. + public func hasOne( + _ destination: Destination.Type, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasOneAssociation + where Destination: TableRecord + { + HasOneAssociation( + to: Destination.relationForAll, + key: key, + using: foreignKey) + } +} + +// MARK: - Associations to Table + +extension Table { + /// Creates a "Belongs To" association between Self and the destination + /// table, based on a database foreign key. + /// + /// For more information, see `TableRecord.belongsTo(_:key:using:)`. + /// + /// - parameters: + /// - destination: The table at the other side of the association. + /// - key: An eventual decoding key for the association. By default, it + /// is `destination.tableName`. + /// - foreignKey: An eventual foreign key. You need to provide an + /// explicit foreign key when GRDB can't infer one from the database + /// schema. This happens when the schema does not define any foreign + /// key to the destination table, or when the schema defines several + /// foreign keys to the destination table. + public func belongsTo( + _ destination: Table, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> BelongsToAssociation + { + BelongsToAssociation( + to: destination.relationForAll, + key: key, + using: foreignKey) + } + + /// Creates a "Has many" association between Self and the destination table, + /// based on a database foreign key. + /// + /// For more information, see `TableRecord.hasMany(_:key:using:)`. + /// + /// - parameters: + /// - destination: The table at the other side of the association. + /// - key: An eventual decoding key for the association. By default, it + /// is `destination.tableName`. + /// - foreignKey: An eventual foreign key. You need to provide an + /// explicit foreign key when GRDB can't infer one from the database + /// schema. This happens when the schema does not define any foreign + /// key from the destination table, or when the schema defines several + /// foreign keys from the destination table. + public func hasMany( + _ destination: Table, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasManyAssociation + { + HasManyAssociation( + to: destination.relationForAll, + key: key, + using: foreignKey) + } + + /// Creates a "Has one" association between Self and the destination table, + /// based on a database foreign key. + /// + /// For more information, see `TableRecord.hasOne(_:key:using:)`. + /// + /// - parameters: + /// - destination: The table at the other side of the association. + /// - key: An eventual decoding key for the association. By default, it + /// is `destination.databaseTableName`. + /// - foreignKey: An eventual foreign key. You need to provide an + /// explicit foreign key when GRDB can't infer one from the database + /// schema. This happens when the schema does not define any foreign + /// key from the destination table, or when the schema defines several + /// foreign keys from the destination table. + public func hasOne( + _ destination: Table, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasOneAssociation + { + HasOneAssociation( + to: destination.relationForAll, + key: key, + using: foreignKey) + } +} + +// MARK: - Associations to CommonTableExpression + +extension Table { + /// Creates an association to a common table expression that you can join + /// or include in another request. + /// + /// For more information, see `TableRecord.association(to:on:)`. + /// + /// - parameter cte: A common table expression. + /// - parameter condition: A function that returns the joining clause. + /// - parameter left: A `TableAlias` for the left table. + /// - parameter right: A `TableAlias` for the right table. + /// - returns: An association to the common table expression. + public func association( + to cte: CommonTableExpression, + on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> SQLExpressible) + -> JoinAssociation + { + JoinAssociation( + to: cte.relationForAll, + condition: .expression { condition($0, $1).sqlExpression }) + } + + /// Creates an association to a common table expression that you can join + /// or include in another request. + /// + /// The key of the returned association is the table name of the common + /// table expression. + /// + /// - parameter cte: A common table expression. + /// - returns: An association to the common table expression. + public func association( + to cte: CommonTableExpression) + -> JoinAssociation + { + JoinAssociation(to: cte.relationForAll, condition: .none) + } +} + +// MARK: - "Through" Associations + +extension Table { + /// Creates a "Has Many Through" association between Self and the + /// destination type. + /// + /// For more information, see `TableRecord.hasMany(_:through:using:key:)`. + /// + /// - parameters: + /// - destination: The record type at the other side of the association. + /// - pivot: An association from Self to the intermediate type. + /// - target: A target association from the intermediate type to the + /// destination type. + /// - key: An eventual decoding key for the association. By default, it + /// is the same key as the target. + public func hasMany( + _ destination: Target.RowDecoder.Type, + through pivot: Pivot, + using target: Target, + key: String? = nil) + -> HasManyThroughAssociation + where Pivot: Association, + Target: Association, + Pivot.OriginRowDecoder == RowDecoder, + Pivot.RowDecoder == Target.OriginRowDecoder + { + let association = HasManyThroughAssociation( + sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation)) + + if let key = key { + return association.forKey(key) + } else { + return association + } + } + + /// Creates a "Has One Through" association between Self and the + /// destination type. + /// + /// For more information, see `TableRecord.hasOne(_:through:using:key:)`. + /// + /// - parameters: + /// - destination: The record type at the other side of the association. + /// - pivot: An association from Self to the intermediate type. + /// - target: A target association from the intermediate type to the + /// destination type. + /// - key: An eventual decoding key for the association. By default, it + /// is the same key as the target. + public func hasOne( + _ destination: Target.RowDecoder.Type, + through pivot: Pivot, + using target: Target, + key: String? = nil) + -> HasOneThroughAssociation + where Pivot: AssociationToOne, + Target: AssociationToOne, + Pivot.OriginRowDecoder == RowDecoder, + Pivot.RowDecoder == Target.OriginRowDecoder + { + let association = HasOneThroughAssociation( + sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation)) + + if let key = key { + return association.forKey(key) + } else { + return association + } + } +} + +// MARK: - Joining Methods + +extension Table { + /// Creates a request that prefetches an association. + public func including(all association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == RowDecoder + { + all().including(all: association) + } + + /// Creates a request that includes an association. The columns of the + /// associated record are selected. The returned association does not + /// require that the associated database table contains a matching row. + public func including(optional association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == RowDecoder + { + 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 func including(required association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == RowDecoder + { + 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 func joining(optional association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == RowDecoder + { + 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 func joining(required association: A) + -> QueryInterfaceRequest + where A.OriginRowDecoder == RowDecoder + { + all().joining(required: association) + } +} + +// MARK: - Association Aggregates + +extension Table { + /// Creates a request with *aggregates* appended to the selection. + /// + /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount + /// // FROM player LEFT JOIN book ... + /// let table = Table("player") + /// let request = table.annotated(with: Player.books.count) + public func annotated(with aggregates: AssociationAggregate...) -> QueryInterfaceRequest { + all().annotated(with: aggregates) + } + + /// Creates a request with *aggregates* appended to the selection. + /// + /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount + /// // FROM player LEFT JOIN book ... + /// let table = Table("player") + /// let request = table.annotated(with: [Player.books.count]) + public func annotated(with aggregates: [AssociationAggregate]) -> QueryInterfaceRequest { + all().annotated(with: aggregates) + } + + /// Creates a request with the provided aggregate *predicate*. + /// + /// // SELECT player.* + /// // FROM player LEFT JOIN book ... + /// // HAVING COUNT(DISTINCT book.id) = 0 + /// let table = Table("player") + /// var request = table.all() + /// request = request.having(Player.books.isEmpty) + /// + /// 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 having(_ predicate: AssociationAggregate) -> QueryInterfaceRequest { + all().having(predicate) + } +} + +// MARK: - Batch Delete + +extension Table { + /// Deletes all rows; returns the number of deleted rows. + /// + /// - parameter db: A database connection. + /// - returns: The number of deleted rows + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + @discardableResult + public func deleteAll(_ db: Database) throws -> Int { + try all().deleteAll(db) + } +} + +// MARK: - Deleting by Single-Column Primary Key + +extension Table { + /// Delete rows identified by their primary keys; returns the number of + /// deleted rows. + /// + /// // DELETE FROM player WHERE id IN (1, 2, 3) + /// try Table("player").deleteAll(db, keys: [1, 2, 3]) + /// + /// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE') + /// try Table("country").deleteAll(db, keys: ["FR", "US", "DE"]) + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// // DELETE FROM document WHERE rowid IN (1, 2, 3) + /// try Table("document").deleteAll(db, keys: [1, 2, 3]) + /// + /// - parameters: + /// - db: A database connection. + /// - keys: A sequence of primary keys. + /// - returns: The number of deleted rows + @discardableResult + public func deleteAll(_ db: Database, keys: Sequence) + throws -> Int + where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible + { + let keys = Array(keys) + if keys.isEmpty { + // Avoid hitting the database + return 0 + } + return try filter(keys: keys).deleteAll(db) + } + + /// Delete a row, identified by its primary key; returns whether a + /// database row was deleted. + /// + /// // DELETE FROM player WHERE id = 123 + /// try Table("player").deleteOne(db, key: 123) + /// + /// // DELETE FROM country WHERE code = 'FR' + /// try Table("country").deleteOne(db, key: "FR") + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// // DELETE FROM document WHERE rowid = 1 + /// try Table("document").deleteOne(db, key: 1) + /// + /// - parameters: + /// - db: A database connection. + /// - key: A primary key value. + /// - returns: Whether a database row was deleted. + @discardableResult + public func deleteOne(_ db: Database, key: PrimaryKeyType?) + throws -> Bool + where PrimaryKeyType: DatabaseValueConvertible + { + guard let key = key else { + // Avoid hitting the database + return false + } + return try deleteAll(db, keys: [key]) > 0 + } +} + +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension Table +where RowDecoder: Identifiable, + RowDecoder.ID: DatabaseValueConvertible +{ + /// Delete rows identified by their primary keys; returns the number of + /// deleted rows. + /// + /// // DELETE FROM player WHERE id IN (1, 2, 3) + /// try Table("player").deleteAll(db, ids: [1, 2, 3]) + /// + /// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE') + /// try Table("country").deleteAll(db, ids: ["FR", "US", "DE"]) + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// // DELETE FROM document WHERE rowid IN (1, 2, 3) + /// try Table("document").deleteAll(db, ids: [1, 2, 3]) + /// + /// - parameters: + /// - db: A database connection. + /// - ids: A collection of primary keys. + /// - returns: The number of deleted rows + @discardableResult + public func deleteAll(_ db: Database, ids: Collection) + throws -> Int + where Collection: Swift.Collection, Collection.Element == RowDecoder.ID + { + if ids.isEmpty { + // Avoid hitting the database + return 0 + } + return try filter(ids: ids).deleteAll(db) + } + + /// Delete a row, identified by its primary key; returns whether a + /// database row was deleted. + /// + /// // DELETE FROM player WHERE id = 123 + /// try Player.deleteOne(db, id: 123) + /// + /// // DELETE FROM country WHERE code = 'FR' + /// try Country.deleteOne(db, id: "FR") + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// // DELETE FROM document WHERE rowid = 1 + /// try Document.deleteOne(db, id: 1) + /// + /// - parameters: + /// - db: A database connection. + /// - id: A primary key value. + /// - returns: Whether a database row was deleted. + @discardableResult + public func deleteOne(_ db: Database, id: RowDecoder.ID) throws -> Bool { + try deleteAll(db, ids: [id]) > 0 + } +} + +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension Table +where RowDecoder: Identifiable, + RowDecoder.ID: _OptionalProtocol, + RowDecoder.ID.Wrapped: DatabaseValueConvertible +{ + /// Delete rows identified by their primary keys; returns the number of + /// deleted rows. + /// + /// // DELETE FROM player WHERE id IN (1, 2, 3) + /// try Table("player").deleteAll(db, ids: [1, 2, 3]) + /// + /// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE') + /// try Table("country").deleteAll(db, ids: ["FR", "US", "DE"]) + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// // DELETE FROM document WHERE rowid IN (1, 2, 3) + /// try Table("document").deleteAll(db, ids: [1, 2, 3]) + /// + /// - parameters: + /// - db: A database connection. + /// - ids: A collection of primary keys. + /// - returns: The number of deleted rows + @discardableResult + public func deleteAll(_ db: Database, ids: Collection) + throws -> Int + where Collection: Swift.Collection, Collection.Element == RowDecoder.ID.Wrapped + { + if ids.isEmpty { + // Avoid hitting the database + return 0 + } + return try filter(ids: ids).deleteAll(db) + } + + /// Delete a row, identified by its primary key; returns whether a + /// database row was deleted. + /// + /// // DELETE FROM player WHERE id = 123 + /// try Table("player").deleteOne(db, id: 123) + /// + /// // DELETE FROM country WHERE code = 'FR' + /// try Table("country").deleteOne(db, id: "FR") + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// // DELETE FROM document WHERE rowid = 1 + /// try Table("document").deleteOne(db, id: 1) + /// + /// - parameters: + /// - db: A database connection. + /// - id: A primary key value. + /// - returns: Whether a database row was deleted. + @discardableResult + public func deleteOne(_ db: Database, id: RowDecoder.ID.Wrapped) throws -> Bool { + try deleteAll(db, ids: [id]) > 0 + } +} + +// MARK: - Deleting by Key + +extension Table { + /// Delete rows identified by the provided unique keys (primary key or + /// any key with a unique index on it); returns the number of deleted rows. + /// + /// try Table("player").deleteAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) + /// + /// - parameters: + /// - db: A database connection. + /// - keys: An array of key dictionaries. + /// - returns: The number of deleted rows + @discardableResult + public func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int { + if keys.isEmpty { + // Avoid hitting the database + return 0 + } + return try filter(keys: keys).deleteAll(db) + } + + /// Delete a row, identified by a unique key (the primary key or any key + /// with a unique index on it); returns whether a database row was deleted. + /// + /// Table("player").deleteOne(db, key: ["name": Arthur"]) + /// + /// - parameters: + /// - db: A database connection. + /// - key: A dictionary of values. + /// - returns: Whether a database row was deleted. + @discardableResult + public func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool { + try deleteAll(db, keys: [key]) > 0 + } +} + +// MARK: - Batch Update + +extension Table { + /// Updates all rows; returns the number of updated rows. + /// + /// For example: + /// + /// try dbQueue.write { db in + /// // UPDATE player SET score = 0 + /// try Table("player").updateAll(db, [Column("score").set(to: 0)]) + /// } + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter assignments: An array of column assignments. + /// - returns: The number of updated rows. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + @discardableResult + public func updateAll( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + _ assignments: [ColumnAssignment]) + throws -> Int + { + try all().updateAll(db, onConflict: conflictResolution, assignments) + } + + /// Updates all rows; returns the number of updated rows. + /// + /// For example: + /// + /// try dbQueue.write { db in + /// // UPDATE player SET score = 0 + /// try Table("player").updateAll(db, Column("score").set(to: 0)) + /// } + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter assignment: A column assignment. + /// - parameter otherAssignments: Eventual other column assignments. + /// - returns: The number of updated rows. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + @discardableResult + public func updateAll( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + _ assignment: ColumnAssignment, + _ otherAssignments: ColumnAssignment...) + throws -> Int + { + try updateAll(db, onConflict: conflictResolution, [assignment] + otherAssignments) + } +} diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index def776476..12fa6d111 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -209,6 +209,91 @@ extension TableRecord { } } +// MARK: - Associations to Table + +extension TableRecord { + /// Creates a "Belongs To" association between Self and the destination + /// table, based on a database foreign key. + /// + /// For more information, see `TableRecord.belongsTo(_:key:using:)` where + /// the first argument is `TableRecord`. + /// + /// - parameters: + /// - destination: The table at the other side of the association. + /// - key: An eventual decoding key for the association. By default, it + /// is `destination.tableName`. + /// - foreignKey: An eventual foreign key. You need to provide an + /// explicit foreign key when GRDB can't infer one from the database + /// schema. This happens when the schema does not define any foreign + /// key to the destination table, or when the schema defines several + /// foreign keys to the destination table. + public static func belongsTo( + _ destination: Table, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> BelongsToAssociation + { + BelongsToAssociation( + to: destination.relationForAll, + key: key, + using: foreignKey) + } + + /// Creates a "Has many" association between Self and the destination table, + /// based on a database foreign key. + /// + /// For more information, see `TableRecord.hasMany(_:key:using:)` where + /// the first argument is `TableRecord`. + /// + /// - parameters: + /// - destination: The table at the other side of the association. + /// - key: An eventual decoding key for the association. By default, it + /// is `destination.tableName`. + /// - foreignKey: An eventual foreign key. You need to provide an + /// explicit foreign key when GRDB can't infer one from the database + /// schema. This happens when the schema does not define any foreign + /// key from the destination table, or when the schema defines several + /// foreign keys from the destination table. + public static func hasMany( + _ destination: Table, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasManyAssociation + { + HasManyAssociation( + to: destination.relationForAll, + key: key, + using: foreignKey) + } + + /// Creates a "Has one" association between Self and the destination table, + /// based on a database foreign key. + /// + /// For more information, see `TableRecord.hasOne(_:key:using:)` where + /// the first argument is `TableRecord`. + /// + /// - parameters: + /// - destination: The table at the other side of the association. + /// - key: An eventual decoding key for the association. By default, it + /// is `destination.databaseTableName`. + /// - foreignKey: An eventual foreign key. You need to provide an + /// explicit foreign key when GRDB can't infer one from the database + /// schema. This happens when the schema does not define any foreign + /// key from the destination table, or when the schema defines several + /// foreign keys from the destination table. + public static func hasOne( + _ destination: Table, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasOneAssociation + { + HasOneAssociation( + to: destination.relationForAll, + key: key, + using: foreignKey) + } +} + // MARK: - Associations to CommonTableExpression extension TableRecord { @@ -544,7 +629,7 @@ extension TableRecord { /// /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount /// // FROM player LEFT JOIN book ... - /// var request = Player.annotated(with: Player.books.count) + /// let request = Player.annotated(with: Player.books.count) public static func annotated(with aggregates: AssociationAggregate...) -> QueryInterfaceRequest { all().annotated(with: aggregates) } @@ -553,7 +638,7 @@ extension TableRecord { /// /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount /// // FROM player LEFT JOIN book ... - /// var request = Player.annotated(with: [Player.books.count]) + /// let request = Player.annotated(with: [Player.books.count]) public static func annotated(with aggregates: [AssociationAggregate]) -> QueryInterfaceRequest { all().annotated(with: aggregates) } diff --git a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift index 343433059..78ce4f920 100644 --- a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift @@ -133,7 +133,7 @@ extension TableRecord { /// Creates a request which appends *selection*. /// /// // SELECT id, email, name FROM player - /// le request = Player + /// let request = Player /// .select([Column("id"), Column("email")]) /// .annotated(with: [Column("name")]) public static func annotated(with selection: [SQLSelectable]) -> QueryInterfaceRequest { @@ -143,7 +143,7 @@ extension TableRecord { /// Creates a request which appends *selection*. /// /// // SELECT id, email, name FROM player - /// le request = Player + /// let request = Player /// .select([Column("id"), Column("email")]) /// .annotated(with: Column("name")) public static func annotated(with selection: SQLSelectable...) -> QueryInterfaceRequest { diff --git a/GRDB/Record/FetchableRecord+TableRecord.swift b/GRDB/Record/FetchableRecord+TableRecord.swift index d048ed6bb..1dae5ad2d 100644 --- a/GRDB/Record/FetchableRecord+TableRecord.swift +++ b/GRDB/Record/FetchableRecord+TableRecord.swift @@ -45,7 +45,7 @@ extension FetchableRecord where Self: TableRecord { /// The first found record. /// - /// // SELECT * FROM player + /// // SELECT * FROM player LIMIT 1 /// let player = try Player.fetchOne(db) // Player? /// /// The selection defaults to all columns. This default can be changed for diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index 85535feac..58663b3a0 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -504,305 +504,6 @@ extension MutablePersistableRecord where Self: AnyObject { } } -extension MutablePersistableRecord { - - // MARK: Batch Delete - - /// Deletes all records; returns the number of deleted rows. - /// - /// - parameter db: A database connection. - /// - returns: The number of deleted rows - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - @discardableResult - public static func deleteAll(_ db: Database) throws -> Int { - try all().deleteAll(db) - } - - // MARK: Batch Update - - /// Updates all records; returns the number of updated records. - /// - /// For example: - /// - /// try dbQueue.write { db in - /// // UPDATE player SET score = 0 - /// try Player.updateAll(db, [Column("score").set(to: 0)]) - /// } - /// - /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution, - /// defaulting to the record's persistenceConflictPolicy. - /// - parameter assignments: An array of column assignments. - /// - returns: The number of updated rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - @discardableResult - public static func updateAll( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, - _ assignments: [ColumnAssignment]) - throws -> Int - { - try all().updateAll(db, onConflict: conflictResolution, assignments) - } - - /// Updates all records; returns the number of updated records. - /// - /// For example: - /// - /// try dbQueue.write { db in - /// // UPDATE player SET score = 0 - /// try Player.updateAll(db, Column("score").set(to: 0)) - /// } - /// - /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution, - /// defaulting to the record's persistenceConflictPolicy. - /// - parameter assignment: A column assignment. - /// - parameter otherAssignments: Eventual other column assignments. - /// - returns: The number of updated rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - @discardableResult - public static func updateAll( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, - _ assignment: ColumnAssignment, - _ otherAssignments: ColumnAssignment...) - throws -> Int - { - try updateAll(db, onConflict: conflictResolution, [assignment] + otherAssignments) - } -} - -extension MutablePersistableRecord { - - // MARK: - Deleting by Single-Column Primary Key - - /// Delete records identified by their primary keys; returns the number of - /// deleted rows. - /// - /// // DELETE FROM player WHERE id IN (1, 2, 3) - /// try Player.deleteAll(db, keys: [1, 2, 3]) - /// - /// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE') - /// try Country.deleteAll(db, keys: ["FR", "US", "DE"]) - /// - /// When the table has no explicit primary key, GRDB uses the hidden - /// "rowid" column: - /// - /// // DELETE FROM document WHERE rowid IN (1, 2, 3) - /// try Document.deleteAll(db, keys: [1, 2, 3]) - /// - /// - parameters: - /// - db: A database connection. - /// - keys: A sequence of primary keys. - /// - returns: The number of deleted rows - @discardableResult - public static func deleteAll(_ db: Database, keys: Sequence) - throws -> Int - where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible - { - let keys = Array(keys) - if keys.isEmpty { - // Avoid hitting the database - return 0 - } - return try filter(keys: keys).deleteAll(db) - } - - /// Delete a record, identified by its primary key; returns whether a - /// database row was deleted. - /// - /// // DELETE FROM player WHERE id = 123 - /// try Player.deleteOne(db, key: 123) - /// - /// // DELETE FROM country WHERE code = 'FR' - /// try Country.deleteOne(db, key: "FR") - /// - /// When the table has no explicit primary key, GRDB uses the hidden - /// "rowid" column: - /// - /// // DELETE FROM document WHERE rowid = 1 - /// try Document.deleteOne(db, key: 1) - /// - /// - parameters: - /// - db: A database connection. - /// - key: A primary key value. - /// - returns: Whether a database row was deleted. - @discardableResult - public static func deleteOne(_ db: Database, key: PrimaryKeyType?) - throws -> Bool - where PrimaryKeyType: DatabaseValueConvertible - { - guard let key = key else { - // Avoid hitting the database - return false - } - return try deleteAll(db, keys: [key]) > 0 - } -} - -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) -extension MutablePersistableRecord where Self: Identifiable, ID: DatabaseValueConvertible { - - // MARK: - Deleting by Single-Column Primary Key - - /// Delete records identified by their primary keys; returns the number of - /// deleted rows. - /// - /// // DELETE FROM player WHERE id IN (1, 2, 3) - /// try Player.deleteAll(db, ids: [1, 2, 3]) - /// - /// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE') - /// try Country.deleteAll(db, ids: ["FR", "US", "DE"]) - /// - /// When the table has no explicit primary key, GRDB uses the hidden - /// "rowid" column: - /// - /// // DELETE FROM document WHERE rowid IN (1, 2, 3) - /// try Document.deleteAll(db, ids: [1, 2, 3]) - /// - /// - parameters: - /// - db: A database connection. - /// - ids: A collection of primary keys. - /// - returns: The number of deleted rows - @discardableResult - public static func deleteAll(_ db: Database, ids: Collection) - throws -> Int - where Collection: Swift.Collection, Collection.Element == ID - { - if ids.isEmpty { - // Avoid hitting the database - return 0 - } - return try filter(ids: ids).deleteAll(db) - } - - /// Delete a record, identified by its primary key; returns whether a - /// database row was deleted. - /// - /// // DELETE FROM player WHERE id = 123 - /// try Player.deleteOne(db, key: 123) - /// - /// // DELETE FROM country WHERE code = 'FR' - /// try Country.deleteOne(db, key: "FR") - /// - /// When the table has no explicit primary key, GRDB uses the hidden - /// "rowid" column: - /// - /// // DELETE FROM document WHERE rowid = 1 - /// try Document.deleteOne(db, key: 1) - /// - /// - parameters: - /// - db: A database connection. - /// - id: A primary key value. - /// - returns: Whether a database row was deleted. - @discardableResult - public static func deleteOne(_ db: Database, id: ID) throws -> Bool { - try deleteAll(db, ids: [id]) > 0 - } -} - -@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) -extension MutablePersistableRecord -where Self: Identifiable, - ID: _OptionalProtocol, - ID.Wrapped: DatabaseValueConvertible -{ - // MARK: - Deleting by Single-Column Primary Key - - /// Delete records identified by their primary keys; returns the number of - /// deleted rows. - /// - /// // DELETE FROM player WHERE id IN (1, 2, 3) - /// try Player.deleteAll(db, ids: [1, 2, 3]) - /// - /// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE') - /// try Country.deleteAll(db, ids: ["FR", "US", "DE"]) - /// - /// When the table has no explicit primary key, GRDB uses the hidden - /// "rowid" column: - /// - /// // DELETE FROM document WHERE rowid IN (1, 2, 3) - /// try Document.deleteAll(db, ids: [1, 2, 3]) - /// - /// - parameters: - /// - db: A database connection. - /// - ids: A collection of primary keys. - /// - returns: The number of deleted rows - @discardableResult - public static func deleteAll(_ db: Database, ids: Collection) - throws -> Int - where Collection: Swift.Collection, Collection.Element == ID.Wrapped - { - if ids.isEmpty { - // Avoid hitting the database - return 0 - } - return try filter(ids: ids).deleteAll(db) - } - - /// Delete a record, identified by its primary key; returns whether a - /// database row was deleted. - /// - /// // DELETE FROM player WHERE id = 123 - /// try Player.deleteOne(db, key: 123) - /// - /// // DELETE FROM country WHERE code = 'FR' - /// try Country.deleteOne(db, key: "FR") - /// - /// When the table has no explicit primary key, GRDB uses the hidden - /// "rowid" column: - /// - /// // DELETE FROM document WHERE rowid = 1 - /// try Document.deleteOne(db, key: 1) - /// - /// - parameters: - /// - db: A database connection. - /// - id: A primary key value. - /// - returns: Whether a database row was deleted. - @discardableResult - public static func deleteOne(_ db: Database, id: ID.Wrapped) throws -> Bool { - try deleteAll(db, ids: [id]) > 0 - } -} - -extension MutablePersistableRecord { - - // MARK: - Deleting by Key - - /// Delete records identified by the provided unique keys (primary key or - /// any key with a unique index on it); returns the number of deleted rows. - /// - /// try Player.deleteAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) - /// - /// - parameters: - /// - db: A database connection. - /// - keys: An array of key dictionaries. - /// - returns: The number of deleted rows - @discardableResult - public static func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int { - if keys.isEmpty { - // Avoid hitting the database - return 0 - } - return try filter(keys: keys).deleteAll(db) - } - - /// Delete a record, identified by a unique key (the primary key or any key - /// with a unique index on it); returns whether a database row was deleted. - /// - /// Player.deleteOne(db, key: ["name": Arthur"]) - /// - /// - parameters: - /// - db: A database connection. - /// - key: A dictionary of values. - /// - returns: Whether a database row was deleted. - @discardableResult - public static func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool { - try deleteAll(db, keys: [key]) > 0 - } -} - // MARK: - PersistableRecord /// Types that adopt `PersistableRecord` can be inserted, updated, and deleted. diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index f6d658e6f..9f3f8e623 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -140,6 +140,302 @@ extension TableRecord { } } +// MARK: - Batch Delete + +extension TableRecord { + + /// Deletes all records; returns the number of deleted rows. + /// + /// - parameter db: A database connection. + /// - returns: The number of deleted rows + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + @discardableResult + public static func deleteAll(_ db: Database) throws -> Int { + try all().deleteAll(db) + } +} + +// MARK: - Deleting by Single-Column Primary Key + +extension TableRecord { + + /// Delete records identified by their primary keys; returns the number of + /// deleted rows. + /// + /// // DELETE FROM player WHERE id IN (1, 2, 3) + /// try Player.deleteAll(db, keys: [1, 2, 3]) + /// + /// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE') + /// try Country.deleteAll(db, keys: ["FR", "US", "DE"]) + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// // DELETE FROM document WHERE rowid IN (1, 2, 3) + /// try Document.deleteAll(db, keys: [1, 2, 3]) + /// + /// - parameters: + /// - db: A database connection. + /// - keys: A sequence of primary keys. + /// - returns: The number of deleted rows + @discardableResult + public static func deleteAll(_ db: Database, keys: Sequence) + throws -> Int + where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible + { + let keys = Array(keys) + if keys.isEmpty { + // Avoid hitting the database + return 0 + } + return try filter(keys: keys).deleteAll(db) + } + + /// Delete a record, identified by its primary key; returns whether a + /// database row was deleted. + /// + /// // DELETE FROM player WHERE id = 123 + /// try Player.deleteOne(db, key: 123) + /// + /// // DELETE FROM country WHERE code = 'FR' + /// try Country.deleteOne(db, key: "FR") + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// // DELETE FROM document WHERE rowid = 1 + /// try Document.deleteOne(db, key: 1) + /// + /// - parameters: + /// - db: A database connection. + /// - key: A primary key value. + /// - returns: Whether a database row was deleted. + @discardableResult + public static func deleteOne(_ db: Database, key: PrimaryKeyType?) + throws -> Bool + where PrimaryKeyType: DatabaseValueConvertible + { + guard let key = key else { + // Avoid hitting the database + return false + } + return try deleteAll(db, keys: [key]) > 0 + } +} + +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { + /// Delete records identified by their primary keys; returns the number of + /// deleted rows. + /// + /// // DELETE FROM player WHERE id IN (1, 2, 3) + /// try Player.deleteAll(db, ids: [1, 2, 3]) + /// + /// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE') + /// try Country.deleteAll(db, ids: ["FR", "US", "DE"]) + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// // DELETE FROM document WHERE rowid IN (1, 2, 3) + /// try Document.deleteAll(db, ids: [1, 2, 3]) + /// + /// - parameters: + /// - db: A database connection. + /// - ids: A collection of primary keys. + /// - returns: The number of deleted rows + @discardableResult + public static func deleteAll(_ db: Database, ids: Collection) + throws -> Int + where Collection: Swift.Collection, Collection.Element == ID + { + if ids.isEmpty { + // Avoid hitting the database + return 0 + } + return try filter(ids: ids).deleteAll(db) + } + + /// Delete a record, identified by its primary key; returns whether a + /// database row was deleted. + /// + /// // DELETE FROM player WHERE id = 123 + /// try Player.deleteOne(db, id: 123) + /// + /// // DELETE FROM country WHERE code = 'FR' + /// try Country.deleteOne(db, id: "FR") + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// // DELETE FROM document WHERE rowid = 1 + /// try Document.deleteOne(db, id: 1) + /// + /// - parameters: + /// - db: A database connection. + /// - id: A primary key value. + /// - returns: Whether a database row was deleted. + @discardableResult + public static func deleteOne(_ db: Database, id: ID) throws -> Bool { + try deleteAll(db, ids: [id]) > 0 + } +} + +@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) +extension TableRecord +where Self: Identifiable, + ID: _OptionalProtocol, + ID.Wrapped: DatabaseValueConvertible +{ + /// Delete records identified by their primary keys; returns the number of + /// deleted rows. + /// + /// // DELETE FROM player WHERE id IN (1, 2, 3) + /// try Player.deleteAll(db, ids: [1, 2, 3]) + /// + /// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE') + /// try Country.deleteAll(db, ids: ["FR", "US", "DE"]) + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// // DELETE FROM document WHERE rowid IN (1, 2, 3) + /// try Document.deleteAll(db, ids: [1, 2, 3]) + /// + /// - parameters: + /// - db: A database connection. + /// - ids: A collection of primary keys. + /// - returns: The number of deleted rows + @discardableResult + public static func deleteAll(_ db: Database, ids: Collection) + throws -> Int + where Collection: Swift.Collection, Collection.Element == ID.Wrapped + { + if ids.isEmpty { + // Avoid hitting the database + return 0 + } + return try filter(ids: ids).deleteAll(db) + } + + /// Delete a record, identified by its primary key; returns whether a + /// database row was deleted. + /// + /// // DELETE FROM player WHERE id = 123 + /// try Player.deleteOne(db, id: 123) + /// + /// // DELETE FROM country WHERE code = 'FR' + /// try Country.deleteOne(db, id: "FR") + /// + /// When the table has no explicit primary key, GRDB uses the hidden + /// "rowid" column: + /// + /// // DELETE FROM document WHERE rowid = 1 + /// try Document.deleteOne(db, id: 1) + /// + /// - parameters: + /// - db: A database connection. + /// - id: A primary key value. + /// - returns: Whether a database row was deleted. + @discardableResult + public static func deleteOne(_ db: Database, id: ID.Wrapped) throws -> Bool { + try deleteAll(db, ids: [id]) > 0 + } +} + +// MARK: - Deleting by Key + +extension TableRecord { + /// Delete records identified by the provided unique keys (primary key or + /// any key with a unique index on it); returns the number of deleted rows. + /// + /// try Player.deleteAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) + /// + /// - parameters: + /// - db: A database connection. + /// - keys: An array of key dictionaries. + /// - returns: The number of deleted rows + @discardableResult + public static func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int { + if keys.isEmpty { + // Avoid hitting the database + return 0 + } + return try filter(keys: keys).deleteAll(db) + } + + /// Delete a record, identified by a unique key (the primary key or any key + /// with a unique index on it); returns whether a database row was deleted. + /// + /// Player.deleteOne(db, key: ["name": Arthur"]) + /// + /// - parameters: + /// - db: A database connection. + /// - key: A dictionary of values. + /// - returns: Whether a database row was deleted. + @discardableResult + public static func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool { + try deleteAll(db, keys: [key]) > 0 + } +} + +// MARK: - Batch Update + +extension TableRecord { + + /// Updates all records; returns the number of updated records. + /// + /// For example: + /// + /// try dbQueue.write { db in + /// // UPDATE player SET score = 0 + /// try Player.updateAll(db, [Column("score").set(to: 0)]) + /// } + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution, + /// defaulting to the record's persistenceConflictPolicy. + /// - parameter assignments: An array of column assignments. + /// - returns: The number of updated rows. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + @discardableResult + public static func updateAll( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + _ assignments: [ColumnAssignment]) + throws -> Int + { + try all().updateAll(db, onConflict: conflictResolution, assignments) + } + + /// Updates all records; returns the number of updated records. + /// + /// For example: + /// + /// try dbQueue.write { db in + /// // UPDATE player SET score = 0 + /// try Player.updateAll(db, Column("score").set(to: 0)) + /// } + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution, + /// defaulting to the record's persistenceConflictPolicy. + /// - parameter assignment: A column assignment. + /// - parameter otherAssignments: Eventual other column assignments. + /// - returns: The number of updated rows. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + @discardableResult + public static func updateAll( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + _ assignment: ColumnAssignment, + _ otherAssignments: ColumnAssignment...) + throws -> Int + { + try updateAll(db, onConflict: conflictResolution, [assignment] + otherAssignments) + } +} + /// Calculating `defaultDatabaseTableName` is somewhat expensive due to the regular expression evaluation /// /// This cache mitigates the cost of the calculation by storing the name for later retrieval diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 220ca551e..aa2cde0e0 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -43,8 +43,8 @@ 561729562235340E0006E219 /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561729532235340E0006E219 /* EncodableRecord.swift */; }; 56176C7E1EACCD2F000F3F2B /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; }; 56176C801EACCD31000F3F2B /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; }; - 561CFA7D2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7B2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift */; }; - 561CFA7E2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7B2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift */; }; + 561CFA7D2373503D000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7B2373503D000C8BAA /* TableRecordUpdateTests.swift */; }; + 561CFA7E2373503D000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7B2373503D000C8BAA /* TableRecordUpdateTests.swift */; }; 561CFAA12376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA9F2376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift */; }; 561CFAA22376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA9F2376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift */; }; 561CFAA42376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFAA32376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; }; @@ -98,6 +98,8 @@ 563B071321862C3E00B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */; }; 563B071B21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; }; 563B071C21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; }; + 563B533B267E2FA4009549B5 /* TableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B5339267E2FA4009549B5 /* TableTests.swift */; }; + 563B533C267E2FA4009549B5 /* TableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B5339267E2FA4009549B5 /* TableTests.swift */; }; 563B8F9B249E74E5007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F99249E74E5007A48C9 /* Trace.swift */; }; 563B8F9C249E74E5007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F99249E74E5007A48C9 /* Trace.swift */; }; 563B8F9E249E8AB0007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F9D249E8AB0007A48C9 /* ValueObservationPrintTests.swift */; }; @@ -358,6 +360,8 @@ 567F45AF1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; 568068341EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; 568068381EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; + 56894F332604FC1E00268F4D /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F322604FC1E00268F4D /* Table.swift */; }; + 56894F342604FC1E00268F4D /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F322604FC1E00268F4D /* Table.swift */; }; 56894FE3260658A400268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FA0260657F600268F4D /* Decimal.swift */; }; 56894FE8260658A500268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FA0260657F600268F4D /* Decimal.swift */; }; 56894FF2260658E600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FF1260658E600268F4D /* FoundationDecimalTests.swift */; }; @@ -523,8 +527,8 @@ 56FEB8FF248403270081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */; }; 56FEE7FE1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; 56FEE8021F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; - 56FF45431D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; }; - 56FF45471D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; }; + 56FF45431D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */; }; + 56FF45471D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */; }; 56FF45591D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; 56FF455D1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; 6340BF831E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */; }; @@ -795,7 +799,7 @@ 5615B284222B17B900061C1C /* AssociationHasOneThroughDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughDecodableRecordTests.swift; sourceTree = ""; }; 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = ""; }; 561729532235340E0006E219 /* EncodableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncodableRecord.swift; sourceTree = ""; }; - 561CFA7B2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordUpdateTests.swift; sourceTree = ""; }; + 561CFA7B2373503D000C8BAA /* TableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordUpdateTests.swift; sourceTree = ""; }; 561CFA9F2376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = ""; }; 561CFAA32376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = ""; }; 56231E6025CEBF06001DFD2F /* RowDecodingError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowDecodingError.swift; sourceTree = ""; }; @@ -833,6 +837,7 @@ 563B0701218627DE00B38F35 /* ValueObservationRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRowTests.swift; sourceTree = ""; }; 563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = ""; }; 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = ""; }; + 563B5339267E2FA4009549B5 /* TableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableTests.swift; sourceTree = ""; }; 563B8F99249E74E5007A48C9 /* Trace.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Trace.swift; sourceTree = ""; }; 563B8F9D249E8AB0007A48C9 /* ValueObservationPrintTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationPrintTests.swift; sourceTree = ""; }; 563B8FB024A1CE9E007A48C9 /* DatabasePublishers.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePublishers.swift; sourceTree = ""; }; @@ -974,6 +979,7 @@ 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = ""; }; 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = ""; }; 5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; + 56894F322604FC1E00268F4D /* Table.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = ""; }; 56894FA0260657F600268F4D /* Decimal.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Decimal.swift; sourceTree = ""; }; 56894FF1260658E600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = ""; }; 568ECB0C25D904CA00B71526 /* SQLSelection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelection.swift; sourceTree = ""; }; @@ -1109,7 +1115,7 @@ 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = ""; }; 56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTraceTests.swift; sourceTree = ""; }; 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = ""; }; - 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordDeleteTests.swift; sourceTree = ""; }; + 56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordDeleteTests.swift; sourceTree = ""; }; 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = ""; }; 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = ""; }; DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = ""; }; @@ -1243,11 +1249,9 @@ 5665FA3B2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift */, 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */, 566A84422041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift */, - 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */, 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */, 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */, 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */, - 561CFA7B2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift */, 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */, ); name = PersistableRecord; @@ -1302,7 +1306,9 @@ 56176C9C1EACEA8C000F3F2B /* TableRecord */ = { isa = PBXGroup; children = ( + 56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */, 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */, + 561CFA7B2373503D000C8BAA /* TableRecordUpdateTests.swift */, ); name = TableRecord; sourceTree = ""; @@ -1371,6 +1377,7 @@ 56F34FC524B0A0C8007513FC /* SQLIdentifyingColumnsTests.swift */, 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */, 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */, + 563B5339267E2FA4009549B5 /* TableTests.swift */, 5698AC7F1DA380A20056AF8C /* VirtualTableModuleTests.swift */, 5653EB5620961F8900F46237 /* Association */, ); @@ -1562,6 +1569,7 @@ 5656A84E2295BD56001FF3FF /* SQLRelation.swift */, 568ECB0C25D904CA00B71526 /* SQLSelection.swift */, 568ECB3425D91CEE00B71526 /* SQLSubquery.swift */, + 56894F322604FC1E00268F4D /* Table.swift */, ); path = SQL; sourceTree = ""; @@ -2280,6 +2288,7 @@ 56CEB4F61EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 5656A8522295BD56001FF3FF /* SQLInterpolation+QueryInterface.swift in Sources */, 56BB6EAE1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, + 56894F342604FC1E00268F4D /* Table.swift in Sources */, F3BA801A1CFB2876003DC1BA /* StatementColumnConvertible.swift in Sources */, 566B91381FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56CEB4FF1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, @@ -2395,7 +2404,7 @@ files = ( F3BA80D71CFB300A003DC1BA /* DatabaseValueTests.swift in Sources */, F3BA80C81CFB2FD8003DC1BA /* DatabaseQueueTests.swift in Sources */, - 56FF45471D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */, + 56FF45471D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */, F3BA810C1CFB3056003DC1BA /* StatementArguments+FoundationTests.swift in Sources */, F3BA80B91CFB2FD1003DC1BA /* DatabasePoolBackupTests.swift in Sources */, F3BA811E1CFB3063003DC1BA /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, @@ -2544,7 +2553,7 @@ 5644DE8020F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */, 56A4CDB71D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 56CC924A201E058900CB597E /* DropFirstCursorTests.swift in Sources */, - 561CFA7E2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */, + 561CFA7E2373503D000C8BAA /* TableRecordUpdateTests.swift in Sources */, 56B964D21DA521450002DA19 /* FTS5RecordTests.swift in Sources */, F3BA80F91CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */, 5604484F25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */, @@ -2559,6 +2568,7 @@ 5653EB7120961FB200F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, F3BA812B1CFB3063003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */, 5698ACA51DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, + 563B533C267E2FA4009549B5 /* TableTests.swift in Sources */, 5653EB6F20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 564CE5C721B8FFE600652B19 /* DatabaseRegionObservationTests.swift in Sources */, F3BA80B11CFB2FC4003DC1BA /* DatabaseTests.swift in Sources */, @@ -2641,6 +2651,7 @@ 56CEB4F31EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 5656A8512295BD56001FF3FF /* SQLInterpolation+QueryInterface.swift in Sources */, 56BB6EAB1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, + 56894F332604FC1E00268F4D /* Table.swift in Sources */, F3BA80761CFB2E55003DC1BA /* StatementColumnConvertible.swift in Sources */, 566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56CEB4FC1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, @@ -2862,7 +2873,7 @@ 5665F868203EF4640084C6C0 /* ColumnInfoTests.swift in Sources */, F3BA81391CFB3064003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */, 56419C7F24A51D6E004967E1 /* DatabaseReaderReadPublisherTests.swift in Sources */, - 56FF45431D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */, + 56FF45431D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */, F3BA80F01CFB3017003DC1BA /* FetchableRecordTests.swift in Sources */, 5657AB491D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, 56419C8924A51D7D004967E1 /* RecordingError.swift in Sources */, @@ -2905,7 +2916,7 @@ 5644DE7F20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */, F3BA80FC1CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */, 56CC9249201E058900CB597E /* DropFirstCursorTests.swift in Sources */, - 561CFA7D2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */, + 561CFA7D2373503D000C8BAA /* TableRecordUpdateTests.swift in Sources */, 5623936C1DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */, F3BA80E01CFB300F003DC1BA /* DatabaseTimestampTests.swift in Sources */, 5604484E25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */, @@ -2920,6 +2931,7 @@ 5653EB7020961FB200F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, F3BA81311CFB3064003DC1BA /* RecordPrimaryKeySingleTests.swift in Sources */, 5698AC431DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, + 563B533B267E2FA4009549B5 /* TableTests.swift in Sources */, 5653EB6E20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 564CE5C621B8FFE600652B19 /* DatabaseRegionObservationTests.swift in Sources */, F3BA80E11CFB300F003DC1BA /* DatabaseValueConversionTests.swift in Sources */, diff --git a/README.md b/README.md index 14b9c34db..8b5d0bbe7 100644 --- a/README.md +++ b/README.md @@ -2398,7 +2398,7 @@ try Player .updateAll(db, Column("score") += 1) ``` -:point_right: update methods are available for subclasses of the [Record](#record-class) class, and types that adopt the [PersistableRecord] protocol. +:point_right: update methods are available for subclasses of the [Record](#record-class) class, and types that adopt the [PersistableRecord] protocol. Batch updates are available on the [TableRecord] protocol. ### Deleting Records @@ -2421,7 +2421,7 @@ try Player .deleteAll(db) ``` -:point_right: delete methods are available for subclasses of the [Record](#record-class) class, and types that adopt the [PersistableRecord] protocol. +:point_right: delete methods are available for subclasses of the [Record](#record-class) class, and types that adopt the [PersistableRecord] protocol. Batch deletes are available on the [TableRecord] protocol. ### Counting Records @@ -2755,7 +2755,11 @@ try place.updateChanges(db) { ... } // Maybe UPDATE try place.updateChanges(db) // Maybe UPDATE (Record class only) try place.delete(db) // DELETE try place.exists(db) +``` +The [TableRecord] protocol comes with batch operations: + +```swift // Type methods try Place.updateAll(db, ...) // UPDATE try Place.deleteAll(db) // DELETE @@ -3840,16 +3844,16 @@ This is the list of record methods, along with their required protocols. The [Re | `record.updateChanges(db, from:...)` | [PersistableRecord] | [*](#record-comparison) | | `record.updateChanges(db) { ... }` | [PersistableRecord] | [*](#record-comparison) | | `record.updateChanges(db)` | [Record](#record-class) | [*](#record-comparison) | -| `Type.updateAll(db, ...)` | [PersistableRecord] | | -| `Type.filter(...).updateAll(db, ...)` | [PersistableRecord] | ² | +| `Type.updateAll(db, ...)` | [TableRecord] | | +| `Type.filter(...).updateAll(db, ...)` | [TableRecord] | ² | | **Delete Records** | | | | `record.delete(db)` | [PersistableRecord] | | -| `Type.deleteOne(db, key:...)` | [PersistableRecord] | ¹ | -| `Type.deleteOne(db, id:...)` | [PersistableRecord] & [Identifiable] | ¹ | -| `Type.deleteAll(db)` | [PersistableRecord] | | -| `Type.deleteAll(db, keys:...)` | [PersistableRecord] | ¹ | -| `Type.deleteAll(db, ids:...)` | [PersistableRecord] & [Identifiable] | ¹ | -| `Type.filter(...).deleteAll(db)` | [PersistableRecord] | ² | +| `Type.deleteOne(db, key:...)` | [TableRecord] | ¹ | +| `Type.deleteOne(db, id:...)` | [TableRecord] & [Identifiable] | ¹ | +| `Type.deleteAll(db)` | [TableRecord] | | +| `Type.deleteAll(db, keys:...)` | [TableRecord] | ¹ | +| `Type.deleteAll(db, ids:...)` | [TableRecord] & [Identifiable] | ¹ | +| `Type.filter(...).deleteAll(db)` | [TableRecord] | ² | | **Check Record Existence** | | | | `record.exists(db)` | [PersistableRecord] | | | **Convert Record to Dictionary** | | | @@ -4251,13 +4255,33 @@ let players = try request.fetchAll(db) // [Player] let count = try request.fetchCount(db) // Int ``` -All requests start from **a type** that adopts the `TableRecord` protocol, such as a `Record` subclass (see [Records](#records)): +Query interface requests usually start from **a type** that adopts the `TableRecord` protocol, such as a `Record` subclass (see [Records](#records)): ```swift -class Player : Record { ... } +class Player: Record { ... } + +// The request for all players: +let request = Player.all() +let players = try request.fetchAll(db) // [Player] ``` -Declare the table **columns** that you want to use for filtering, or sorting: +When you need to build a request from a table name, use `Table`: + +```swift +// The request for all rows from the player table: +let table = Table("player") +let request = table.all() +let rows = try request.fetchAll(db) // [Row] + +// The request for all players from the player table: +let table = Table("player") +let request = table.all() +let players = try request.fetchAll(db) // [Player] +``` + +> :point_up: **Note**: all examples in the documentation below use a record type, but you can always substitute a `Table` instead. + +Next, declare the table **columns** that you want to use for filtering, or sorting: ```swift let idColumn = Column("id") @@ -4536,16 +4560,24 @@ By default, query interface requests select all columns: ```swift // SELECT * FROM player +struct Player: TableRecord { ... } let request = Player.all() + +// SELECT * FROM player +let table = Table("player") +let request = table.all() ``` -**The selection can be changed for each individual requests, or for all requests built from a given type.** +**The selection can be changed for each individual requests, or in the case of record-based requests, for all requests built from this record type.** The `select(...)` and `select(..., as:)` methods change the selection of a single request (see [Fetching from Requests] for detailed information): ```swift -let request = Player.select(max(scoreColumn)) -let maxScore: Int? = try Int.fetchOne(db, request) +let request = Player.select(max(Column("score"))) +let maxScore = try Int.fetchOne(db, request) // Int? + +let request = Player.select(max(Column("score")), as: Int.self) +let maxScore = try request.fetchOne(db) // Int? ``` The default selection for a record type is controlled by the `databaseSelection` property: @@ -5061,7 +5093,13 @@ try Player .deleteAll(db) ``` -> :point_up: **Note** Deletion methods are only available for records that adopts the [PersistableRecord] protocol. +> :point_up: **Note** Deletion methods are available on types that adopt the [TableRecord] protocol, and `Table`: +> +> ```swift +> struct Player: TableRecord { ... } +> try Player.deleteAll(db) // Fine +> try Table("player").deleteAll(db) // Just as fine +> ``` **Deleting records according to their primary key** is a common task. @@ -5138,7 +5176,13 @@ Default [Conflict Resolution] rules apply, and you may also provide a specific o try Player.updateAll(db, onConflict: .ignore, /* assignments... */) ``` -> :point_up: **Note** The `updateAll` method is only available for records that adopts the [PersistableRecord] protocol. +> :point_up: **Note** The `updateAll` method is available on types that adopt the [TableRecord] protocol, and `Table`: +> +> ```swift +> struct Player: TableRecord { ... } +> try Player.updateAll(db, ...) // Fine +> try Table("player").updateAll(db, ...) // Just as fine +> ``` ## Custom Requests diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index 564ec8423..45a096adb 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -113,8 +113,8 @@ 56419DD024A54062004967E1 /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD024A54057004967E1 /* GRDBTestCase.swift */; }; 56419DD124A54062004967E1 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD124A54057004967E1 /* ValueObservationRecordTests.swift */; }; 56419DD224A54062004967E1 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD124A54057004967E1 /* ValueObservationRecordTests.swift */; }; - 56419DD324A54062004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD224A54057004967E1 /* MutablePersistableRecordUpdateTests.swift */; }; - 56419DD424A54062004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD224A54057004967E1 /* MutablePersistableRecordUpdateTests.swift */; }; + 56419DD324A54062004967E1 /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD224A54057004967E1 /* TableRecordUpdateTests.swift */; }; + 56419DD424A54062004967E1 /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD224A54057004967E1 /* TableRecordUpdateTests.swift */; }; 56419DD524A54062004967E1 /* FTS5TokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD324A54057004967E1 /* FTS5TokenizerTests.swift */; }; 56419DD624A54062004967E1 /* FTS5TokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD324A54057004967E1 /* FTS5TokenizerTests.swift */; }; 56419DD724A54062004967E1 /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD424A54057004967E1 /* CGFloatTests.swift */; }; @@ -321,8 +321,8 @@ 56419EA024A54063004967E1 /* FetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3824A5405E004967E1 /* FetchableRecordTests.swift */; }; 56419EA124A54063004967E1 /* QueryInterfaceExtensibilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3924A5405F004967E1 /* QueryInterfaceExtensibilityTests.swift */; }; 56419EA224A54063004967E1 /* QueryInterfaceExtensibilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3924A5405F004967E1 /* QueryInterfaceExtensibilityTests.swift */; }; - 56419EA324A54063004967E1 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3A24A5405F004967E1 /* MutablePersistableRecordDeleteTests.swift */; }; - 56419EA424A54063004967E1 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3A24A5405F004967E1 /* MutablePersistableRecordDeleteTests.swift */; }; + 56419EA324A54063004967E1 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3A24A5405F004967E1 /* TableRecordDeleteTests.swift */; }; + 56419EA424A54063004967E1 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3A24A5405F004967E1 /* TableRecordDeleteTests.swift */; }; 56419EA524A54063004967E1 /* MutablePersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3B24A5405F004967E1 /* MutablePersistableRecordTests.swift */; }; 56419EA624A54063004967E1 /* MutablePersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3B24A5405F004967E1 /* MutablePersistableRecordTests.swift */; }; 56419EA724A54063004967E1 /* CursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3C24A5405F004967E1 /* CursorTests.swift */; }; @@ -504,7 +504,7 @@ 56419CCF24A54057004967E1 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = ""; }; 56419CD024A54057004967E1 /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = ""; }; 56419CD124A54057004967E1 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = ""; }; - 56419CD224A54057004967E1 /* MutablePersistableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordUpdateTests.swift; sourceTree = ""; }; + 56419CD224A54057004967E1 /* TableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordUpdateTests.swift; sourceTree = ""; }; 56419CD324A54057004967E1 /* FTS5TokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TokenizerTests.swift; sourceTree = ""; }; 56419CD424A54057004967E1 /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = ""; }; 56419CD524A54057004967E1 /* AssociationBelongsToSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToSQLTests.swift; sourceTree = ""; }; @@ -608,7 +608,7 @@ 56419D3724A5405E004967E1 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = ""; }; 56419D3824A5405E004967E1 /* FetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchableRecordTests.swift; sourceTree = ""; }; 56419D3924A5405F004967E1 /* QueryInterfaceExtensibilityTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceExtensibilityTests.swift; sourceTree = ""; }; - 56419D3A24A5405F004967E1 /* MutablePersistableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordDeleteTests.swift; sourceTree = ""; }; + 56419D3A24A5405F004967E1 /* TableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordDeleteTests.swift; sourceTree = ""; }; 56419D3B24A5405F004967E1 /* MutablePersistableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordTests.swift; sourceTree = ""; }; 56419D3C24A5405F004967E1 /* CursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CursorTests.swift; sourceTree = ""; }; 56419D3D24A5405F004967E1 /* DatabasePoolReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReleaseMemoryTests.swift; sourceTree = ""; }; @@ -892,11 +892,11 @@ 56419D0024A5405A004967E1 /* JoinSupportTests.swift */, 56419CDC24A54058004967E1 /* MapCursorTests.swift */, 56419D0224A5405A004967E1 /* MutablePersistableRecordChangesTests.swift */, - 56419D3A24A5405F004967E1 /* MutablePersistableRecordDeleteTests.swift */, + 56419D3A24A5405F004967E1 /* TableRecordDeleteTests.swift */, 56419D2F24A5405E004967E1 /* MutablePersistableRecordEncodableTests.swift */, 56419D4424A5405F004967E1 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */, 56419D3B24A5405F004967E1 /* MutablePersistableRecordTests.swift */, - 56419CD224A54057004967E1 /* MutablePersistableRecordUpdateTests.swift */, + 56419CD224A54057004967E1 /* TableRecordUpdateTests.swift */, 56419CFD24A5405A004967E1 /* NumericOverflowTests.swift */, 56419D4F24A54060004967E1 /* OrderedDictionaryTests.swift */, 56419D4524A5405F004967E1 /* PersistableRecordTests.swift */, @@ -1358,7 +1358,7 @@ 56419EA924A54063004967E1 /* DatabasePoolReleaseMemoryTests.swift in Sources */, 56419E7F24A54063004967E1 /* DatabaseQueueConcurrencyTests.swift in Sources */, 56419EF124A54063004967E1 /* StatementColumnConvertibleFetchTests.swift in Sources */, - 56419EA324A54063004967E1 /* MutablePersistableRecordDeleteTests.swift in Sources */, + 56419EA324A54063004967E1 /* TableRecordDeleteTests.swift in Sources */, 56419EFB24A54063004967E1 /* FoundationDateComponentsTests.swift in Sources */, 56419E3D24A54062004967E1 /* FTS3TableBuilderTests.swift in Sources */, 56419DDF24A54062004967E1 /* FTS4TableBuilderTests.swift in Sources */, @@ -1367,7 +1367,7 @@ 56419D9B24A54062004967E1 /* TransactionObserverSavepointsTests.swift in Sources */, 56419E0F24A54062004967E1 /* InflectionsTests.swift in Sources */, 56419E2724A54062004967E1 /* FoundationURLTests.swift in Sources */, - 56419DD324A54062004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */, + 56419DD324A54062004967E1 /* TableRecordUpdateTests.swift in Sources */, 56419D6D24A54062004967E1 /* Record+QueryInterfaceRequestTests.swift in Sources */, 56419E2124A54062004967E1 /* AssociationHasOneThroughRowScopeTests.swift in Sources */, 56419EDF24A54063004967E1 /* AssociationRowScopeSearchTests.swift in Sources */, @@ -1581,7 +1581,7 @@ 56419EAA24A54063004967E1 /* DatabasePoolReleaseMemoryTests.swift in Sources */, 56419E8024A54063004967E1 /* DatabaseQueueConcurrencyTests.swift in Sources */, 56419EF224A54063004967E1 /* StatementColumnConvertibleFetchTests.swift in Sources */, - 56419EA424A54063004967E1 /* MutablePersistableRecordDeleteTests.swift in Sources */, + 56419EA424A54063004967E1 /* TableRecordDeleteTests.swift in Sources */, 56419EFC24A54063004967E1 /* FoundationDateComponentsTests.swift in Sources */, 56419E3E24A54062004967E1 /* FTS3TableBuilderTests.swift in Sources */, 56419DE024A54062004967E1 /* FTS4TableBuilderTests.swift in Sources */, @@ -1590,7 +1590,7 @@ 56419D9C24A54062004967E1 /* TransactionObserverSavepointsTests.swift in Sources */, 56419E1024A54062004967E1 /* InflectionsTests.swift in Sources */, 56419E2824A54062004967E1 /* FoundationURLTests.swift in Sources */, - 56419DD424A54062004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */, + 56419DD424A54062004967E1 /* TableRecordUpdateTests.swift in Sources */, 56419D6E24A54062004967E1 /* Record+QueryInterfaceRequestTests.swift in Sources */, 56419E2224A54062004967E1 /* AssociationHasOneThroughRowScopeTests.swift in Sources */, 56419EE024A54063004967E1 /* AssociationRowScopeSearchTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index 998a8c2cd..e62fc8a7f 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -11,8 +11,8 @@ 56419FC924A540A1004967E1 /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFD24A54093004967E1 /* FetchRequestTests.swift */; }; 56419FCA24A540A1004967E1 /* DatabasePoolBackupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFE24A54093004967E1 /* DatabasePoolBackupTests.swift */; }; 56419FCB24A540A1004967E1 /* DatabasePoolBackupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFE24A54093004967E1 /* DatabasePoolBackupTests.swift */; }; - 56419FCC24A540A1004967E1 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFF24A54093004967E1 /* MutablePersistableRecordDeleteTests.swift */; }; - 56419FCD24A540A1004967E1 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFF24A54093004967E1 /* MutablePersistableRecordDeleteTests.swift */; }; + 56419FCC24A540A1004967E1 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFF24A54093004967E1 /* TableRecordDeleteTests.swift */; }; + 56419FCD24A540A1004967E1 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFF24A54093004967E1 /* TableRecordDeleteTests.swift */; }; 56419FCE24A540A1004967E1 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0024A54093004967E1 /* AssociationBelongsToSQLDerivationTests.swift */; }; 56419FCF24A540A1004967E1 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0024A54093004967E1 /* AssociationBelongsToSQLDerivationTests.swift */; }; 56419FD024A540A1004967E1 /* MutablePersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0124A54093004967E1 /* MutablePersistableRecordTests.swift */; }; @@ -25,8 +25,8 @@ 56419FD724A540A1004967E1 /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0424A54093004967E1 /* DatabaseRegionTests.swift */; }; 56419FD824A540A1004967E1 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0524A54093004967E1 /* DatabaseRegionObservationTests.swift */; }; 56419FD924A540A1004967E1 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0524A54093004967E1 /* DatabaseRegionObservationTests.swift */; }; - 56419FDA24A540A1004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0624A54093004967E1 /* MutablePersistableRecordUpdateTests.swift */; }; - 56419FDB24A540A1004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0624A54093004967E1 /* MutablePersistableRecordUpdateTests.swift */; }; + 56419FDA24A540A1004967E1 /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0624A54093004967E1 /* TableRecordUpdateTests.swift */; }; + 56419FDB24A540A1004967E1 /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0624A54093004967E1 /* TableRecordUpdateTests.swift */; }; 56419FDC24A540A1004967E1 /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0724A54093004967E1 /* Record+QueryInterfaceRequestTests.swift */; }; 56419FDD24A540A1004967E1 /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0724A54093004967E1 /* Record+QueryInterfaceRequestTests.swift */; }; 56419FDE24A540A1004967E1 /* NumericOverflowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0824A54093004967E1 /* NumericOverflowTests.swift */; }; @@ -455,14 +455,14 @@ 47C5D1B9AFFE795AA1D6EA5D /* Pods-GRDBTestsEncrypted.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTestsEncrypted.release.xcconfig"; path = "Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted.release.xcconfig"; sourceTree = ""; }; 56419EFD24A54093004967E1 /* FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequestTests.swift; sourceTree = ""; }; 56419EFE24A54093004967E1 /* DatabasePoolBackupTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolBackupTests.swift; sourceTree = ""; }; - 56419EFF24A54093004967E1 /* MutablePersistableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordDeleteTests.swift; sourceTree = ""; }; + 56419EFF24A54093004967E1 /* TableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordDeleteTests.swift; sourceTree = ""; }; 56419F0024A54093004967E1 /* AssociationBelongsToSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToSQLDerivationTests.swift; sourceTree = ""; }; 56419F0124A54093004967E1 /* MutablePersistableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordTests.swift; sourceTree = ""; }; 56419F0224A54093004967E1 /* MutablePersistableRecordEncodableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordEncodableTests.swift; sourceTree = ""; }; 56419F0324A54093004967E1 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = ""; }; 56419F0424A54093004967E1 /* DatabaseRegionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionTests.swift; sourceTree = ""; }; 56419F0524A54093004967E1 /* DatabaseRegionObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationTests.swift; sourceTree = ""; }; - 56419F0624A54093004967E1 /* MutablePersistableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordUpdateTests.swift; sourceTree = ""; }; + 56419F0624A54093004967E1 /* TableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordUpdateTests.swift; sourceTree = ""; }; 56419F0724A54093004967E1 /* Record+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Record+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56419F0824A54093004967E1 /* NumericOverflowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NumericOverflowTests.swift; sourceTree = ""; }; 56419F0924A54093004967E1 /* AssociationChainSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainSQLTests.swift; sourceTree = ""; }; @@ -896,11 +896,11 @@ 56419F6D24A5409A004967E1 /* JoinSupportTests.swift */, 56419F7B24A5409B004967E1 /* MapCursorTests.swift */, 56419F4524A54097004967E1 /* MutablePersistableRecordChangesTests.swift */, - 56419EFF24A54093004967E1 /* MutablePersistableRecordDeleteTests.swift */, + 56419EFF24A54093004967E1 /* TableRecordDeleteTests.swift */, 56419F0224A54093004967E1 /* MutablePersistableRecordEncodableTests.swift */, 56419F3124A54096004967E1 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */, 56419F0124A54093004967E1 /* MutablePersistableRecordTests.swift */, - 56419F0624A54093004967E1 /* MutablePersistableRecordUpdateTests.swift */, + 56419F0624A54093004967E1 /* TableRecordUpdateTests.swift */, 56419F0824A54093004967E1 /* NumericOverflowTests.swift */, 56419F0324A54093004967E1 /* OrderedDictionaryTests.swift */, 56419F1A24A54094004967E1 /* PersistableRecordTests.swift */, @@ -1316,7 +1316,7 @@ 5641A10424A540A1004967E1 /* DatabaseValueTests.swift in Sources */, 5641A06824A540A1004967E1 /* RowFetchTests.swift in Sources */, 5641A0E024A540A1004967E1 /* QueryInterfaceExtensibilityTests.swift in Sources */, - 56419FDA24A540A1004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */, + 56419FDA24A540A1004967E1 /* TableRecordUpdateTests.swift in Sources */, 5641A01024A540A1004967E1 /* RecordEditedTests.swift in Sources */, 5641A0A624A540A1004967E1 /* AssociationHasManySQLTests.swift in Sources */, 56419FFC24A540A1004967E1 /* QueryInterfaceRequestTests.swift in Sources */, @@ -1366,7 +1366,7 @@ 5641A11424A540A1004967E1 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */, 5641A0D024A540A1004967E1 /* FoundationNSDecimalNumberTests.swift in Sources */, 5641A0C224A540A1004967E1 /* TransactionObserverTests.swift in Sources */, - 56419FCC24A540A1004967E1 /* MutablePersistableRecordDeleteTests.swift in Sources */, + 56419FCC24A540A1004967E1 /* TableRecordDeleteTests.swift in Sources */, 5641A00624A540A1004967E1 /* SQLExpressionLiteralTests.swift in Sources */, 5641A05824A540A1004967E1 /* MutablePersistableRecordChangesTests.swift in Sources */, 5641A05624A540A1004967E1 /* AssociationPrefetchingSQLTests.swift in Sources */, @@ -1539,7 +1539,7 @@ 5641A10524A540A1004967E1 /* DatabaseValueTests.swift in Sources */, 5641A06924A540A1004967E1 /* RowFetchTests.swift in Sources */, 5641A0E124A540A1004967E1 /* QueryInterfaceExtensibilityTests.swift in Sources */, - 56419FDB24A540A1004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */, + 56419FDB24A540A1004967E1 /* TableRecordUpdateTests.swift in Sources */, 5641A01124A540A1004967E1 /* RecordEditedTests.swift in Sources */, 5641A0A724A540A1004967E1 /* AssociationHasManySQLTests.swift in Sources */, 56419FFD24A540A1004967E1 /* QueryInterfaceRequestTests.swift in Sources */, @@ -1589,7 +1589,7 @@ 5641A11524A540A1004967E1 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */, 5641A0D124A540A1004967E1 /* FoundationNSDecimalNumberTests.swift in Sources */, 5641A0C324A540A1004967E1 /* TransactionObserverTests.swift in Sources */, - 56419FCD24A540A1004967E1 /* MutablePersistableRecordDeleteTests.swift in Sources */, + 56419FCD24A540A1004967E1 /* TableRecordDeleteTests.swift in Sources */, 5641A00724A540A1004967E1 /* SQLExpressionLiteralTests.swift in Sources */, 5641A05924A540A1004967E1 /* MutablePersistableRecordChangesTests.swift in Sources */, 5641A05724A540A1004967E1 /* AssociationPrefetchingSQLTests.swift in Sources */, diff --git a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift index 68d42d3d8..405f1a756 100644 --- a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift @@ -28,8 +28,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")])) + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parentId")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parentId")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -62,8 +66,13 @@ class AssociationBelongsToSQLTests: GRDBTestCase { SELECT "custom".* FROM "parents" "custom" WHERE "custom"."rowid" = 1 """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parentId")], to: [Column("id")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parentId")], to: [Column("id")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -89,7 +98,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") AND ("parents"."name" = 'foo') """) - try assertEqualSQL(db, Child().request(for: association), """ + try assertEqualSQL(db, Child().request(for: association), """ SELECT * FROM "parents" WHERE "id" = 1 """) try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ @@ -123,8 +132,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")])) + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parentId")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parentId")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -157,8 +170,13 @@ class AssociationBelongsToSQLTests: GRDBTestCase { SELECT "custom".* FROM "parents" "custom" WHERE "custom"."id" = 1 """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parentId")], to: [Column("id")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parentId")], to: [Column("id")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -218,8 +236,10 @@ class AssociationBelongsToSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Child.belongsTo(Parent.self) + for association in [ + Child.belongsTo(Parent.self), + Child.belongsTo(Table(Parent.databaseTableName)), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -252,8 +272,13 @@ class AssociationBelongsToSQLTests: GRDBTestCase { SELECT "custom".* FROM "parents" "custom" WHERE "custom"."id" = 1 """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parentId")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parentId")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -286,8 +311,13 @@ class AssociationBelongsToSQLTests: GRDBTestCase { SELECT "custom".* FROM "parents" "custom" WHERE "custom"."id" = 1 """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parentId")], to: [Column("id")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parentId")], to: [Column("id")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -349,8 +379,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent1Id")])) + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parent1Id")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parent1Id")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -383,8 +417,13 @@ class AssociationBelongsToSQLTests: GRDBTestCase { SELECT "custom".* FROM "parents" "custom" WHERE "custom"."id" = 1 """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent1Id")], to: [Column("id")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parent1Id")], to: [Column("id")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parent1Id")], to: [Column("id")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -417,8 +456,13 @@ class AssociationBelongsToSQLTests: GRDBTestCase { SELECT "custom".* FROM "parents" "custom" WHERE "custom"."id" = 1 """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent2Id")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parent2Id")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parent2Id")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -451,8 +495,13 @@ class AssociationBelongsToSQLTests: GRDBTestCase { SELECT "custom".* FROM "parents" "custom" WHERE "custom"."id" = 2 """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent2Id")], to: [Column("id")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parent2Id")], to: [Column("id")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parent2Id")], to: [Column("id")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -515,8 +564,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -580,8 +633,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")])) + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parentA"), Column("parentB")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -614,8 +671,13 @@ class AssociationBelongsToSQLTests: GRDBTestCase { SELECT "custom".* FROM "parents" "custom" WHERE ("custom"."a" = 1) AND ("custom"."b" = 2) """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -680,8 +742,10 @@ class AssociationBelongsToSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Child.belongsTo(Parent.self) + for association in [ + Child.belongsTo(Parent.self), + Child.belongsTo(Table(Parent.databaseTableName)), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -714,8 +778,13 @@ class AssociationBelongsToSQLTests: GRDBTestCase { SELECT "custom".* FROM "parents" "custom" WHERE ("custom"."a" = 1) AND ("custom"."b" = 2) """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parentA"), Column("parentB")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -748,8 +817,13 @@ class AssociationBelongsToSQLTests: GRDBTestCase { SELECT "custom".* FROM "parents" "custom" WHERE ("custom"."a" = 1) AND ("custom"."b" = 2) """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -819,8 +893,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent1A"), Column("parent1B")])) + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parent1A"), Column("parent1B")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parent1A"), Column("parent1B")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -853,8 +931,13 @@ class AssociationBelongsToSQLTests: GRDBTestCase { SELECT "custom".* FROM "parents" "custom" WHERE ("custom"."a" = 1) AND ("custom"."b" = 2) """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -887,8 +970,13 @@ class AssociationBelongsToSQLTests: GRDBTestCase { SELECT "custom".* FROM "parents" "custom" WHERE ("custom"."a" = 1) AND ("custom"."b" = 2) """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent2A"), Column("parent2B")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parent2A"), Column("parent2B")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parent2A"), Column("parent2B")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -921,8 +1009,13 @@ class AssociationBelongsToSQLTests: GRDBTestCase { SELECT "custom".* FROM "parents" "custom" WHERE ("custom"."a" = 3) AND ("custom"."b" = 4) """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "children".*, "parents".* \ FROM "children" \ @@ -1023,8 +1116,10 @@ class AssociationBelongsToSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Child.belongsTo(Parent.self) + for association in [ + Child.belongsTo(Parent.self), + Child.belongsTo(Table(Parent.databaseTableName)), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "CHILDREN".*, "PARENTS".* \ FROM "CHILDREN" \ @@ -1057,8 +1152,13 @@ class AssociationBelongsToSQLTests: GRDBTestCase { SELECT "custom".* FROM "PARENTS" "custom" WHERE "custom"."id" = 1 """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("PARENTID")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("PARENTID")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("PARENTID")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "CHILDREN".*, "PARENTS".* \ FROM "CHILDREN" \ @@ -1091,8 +1191,13 @@ class AssociationBelongsToSQLTests: GRDBTestCase { SELECT "custom".* FROM "PARENTS" "custom" WHERE "custom"."id" = 1 """) } - do { - let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("PARENTID")], to: [Column("ID")])) + + for association in [ + Child.belongsTo(Parent.self, + using: ForeignKey([Column("PARENTID")], to: [Column("ID")])), + Child.belongsTo(Table(Parent.databaseTableName), + using: ForeignKey([Column("PARENTID")], to: [Column("ID")])), + ] { try assertEqualSQL(db, Child.including(required: association), """ SELECT "CHILDREN".*, "PARENTS".* \ FROM "CHILDREN" \ @@ -1134,7 +1239,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase { struct Book: TableRecord { static let author = belongsTo(Author.self) } - + struct Author: TableRecord { } @@ -1162,7 +1267,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase { struct Book: TableRecord { static let author = belongsTo(Author.self) } - + struct Author: TableRecord { } diff --git a/Tests/GRDBTests/AssociationHasManySQLTests.swift b/Tests/GRDBTests/AssociationHasManySQLTests.swift index 71ab378b0..1bb46c515 100644 --- a/Tests/GRDBTests/AssociationHasManySQLTests.swift +++ b/Tests/GRDBTests/AssociationHasManySQLTests.swift @@ -3,7 +3,7 @@ import GRDB /// Test SQL generation class AssociationHasManySQLTests: GRDBTestCase { - + func testSingleColumnNoForeignKeyNoPrimaryKey() throws { struct Child : TableRecord { static let databaseTableName = "children" @@ -28,8 +28,12 @@ class AssociationHasManySQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parentId")])) + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parentId")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parentId")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -52,8 +56,13 @@ class AssociationHasManySQLTests: GRDBTestCase { """) try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE \"parentId\" = 2") } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parentId")], to: [Column("id")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parentId")], to: [Column("id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -102,8 +111,12 @@ class AssociationHasManySQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parentId")])) + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parentId")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parentId")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -126,8 +139,13 @@ class AssociationHasManySQLTests: GRDBTestCase { """) try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE \"parentId\" = 1") } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parentId")], to: [Column("id")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parentId")], to: [Column("id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -176,8 +194,10 @@ class AssociationHasManySQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasMany(Child.self) + for association in [ + Parent.hasMany(Child.self), + Parent.hasMany(Table(Child.databaseTableName)), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -200,8 +220,13 @@ class AssociationHasManySQLTests: GRDBTestCase { """) try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE \"parentId\" = 1") } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parentId")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parentId")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parentId")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -224,8 +249,13 @@ class AssociationHasManySQLTests: GRDBTestCase { """) try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE \"parentId\" = 1") } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parentId")], to: [Column("id")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parentId")], to: [Column("id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -275,8 +305,12 @@ class AssociationHasManySQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parent1Id")])) + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parent1Id")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parent1Id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -299,8 +333,13 @@ class AssociationHasManySQLTests: GRDBTestCase { """) try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE \"parent1Id\" = 1") } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parent1Id")], to: [Column("id")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parent1Id")], to: [Column("id")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parent1Id")], to: [Column("id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -323,8 +362,13 @@ class AssociationHasManySQLTests: GRDBTestCase { """) try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE \"parent1Id\" = 1") } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parent2Id")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parent2Id")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parent2Id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -347,8 +391,13 @@ class AssociationHasManySQLTests: GRDBTestCase { """) try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE \"parent2Id\" = 1") } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parent2Id")], to: [Column("id")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parent2Id")], to: [Column("id")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parent2Id")], to: [Column("id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -400,8 +449,12 @@ class AssociationHasManySQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -454,8 +507,12 @@ class AssociationHasManySQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")])) + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parentA"), Column("parentB")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -478,8 +535,13 @@ class AssociationHasManySQLTests: GRDBTestCase { """) try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parentA\" = 1) AND (\"parentB\" = 2)") } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -533,8 +595,10 @@ class AssociationHasManySQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasMany(Child.self) + for association in [ + Parent.hasMany(Child.self), + Parent.hasMany(Table(Child.databaseTableName)), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -557,8 +621,13 @@ class AssociationHasManySQLTests: GRDBTestCase { """) try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parentA\" = 1) AND (\"parentB\" = 2)") } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parentA"), Column("parentB")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -581,8 +650,13 @@ class AssociationHasManySQLTests: GRDBTestCase { """) try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parentA\" = 1) AND (\"parentB\" = 2)") } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -639,8 +713,12 @@ class AssociationHasManySQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parent1A"), Column("parent1B")])) + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parent1A"), Column("parent1B")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parent1A"), Column("parent1B")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -663,8 +741,13 @@ class AssociationHasManySQLTests: GRDBTestCase { """) try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parent1A\" = 1) AND (\"parent1B\" = 2)") } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -687,8 +770,13 @@ class AssociationHasManySQLTests: GRDBTestCase { """) try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parent1A\" = 1) AND (\"parent1B\" = 2)") } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parent2A"), Column("parent2B")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parent2A"), Column("parent2B")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parent2A"), Column("parent2B")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -711,8 +799,13 @@ class AssociationHasManySQLTests: GRDBTestCase { """) try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parent2A\" = 1) AND (\"parent2B\" = 2)") } - do { - let association = Parent.hasMany(Child.self, using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])) + + for association in [ + Parent.hasMany(Child.self, + using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])), + Parent.hasMany(Table(Child.databaseTableName), + using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ diff --git a/Tests/GRDBTests/AssociationHasOneSQLTests.swift b/Tests/GRDBTests/AssociationHasOneSQLTests.swift index 629e2f957..66d704621 100644 --- a/Tests/GRDBTests/AssociationHasOneSQLTests.swift +++ b/Tests/GRDBTests/AssociationHasOneSQLTests.swift @@ -3,7 +3,7 @@ import GRDB /// Test SQL generation class AssociationHasOneSQLTests: GRDBTestCase { - + func testSingleColumnNoForeignKeyNoPrimaryKey() throws { struct Child : TableRecord { static let databaseTableName = "children" @@ -28,8 +28,12 @@ class AssociationHasOneSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentId")])) + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parentId")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parentId")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -52,8 +56,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) 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")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parentId")], to: [Column("id")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parentId")], to: [Column("id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -102,8 +111,12 @@ class AssociationHasOneSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentId")])) + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parentId")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parentId")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -126,8 +139,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) 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")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parentId")], to: [Column("id")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parentId")], to: [Column("id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -176,8 +194,10 @@ class AssociationHasOneSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasOne(Child.self) + for association in [ + Parent.hasOne(Child.self), + Parent.hasOne(Table(Child.databaseTableName)), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -200,8 +220,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE \"parentId\" = 1") } - do { - let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentId")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parentId")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parentId")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -224,8 +249,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) 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")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parentId")], to: [Column("id")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parentId")], to: [Column("id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -275,8 +305,12 @@ class AssociationHasOneSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent1Id")])) + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parent1Id")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parent1Id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -299,8 +333,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) 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")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parent1Id")], to: [Column("id")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parent1Id")], to: [Column("id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -323,8 +362,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE \"parent1Id\" = 1") } - do { - let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent2Id")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parent2Id")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parent2Id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -347,8 +391,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) 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")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parent2Id")], to: [Column("id")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parent2Id")], to: [Column("id")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -400,8 +449,12 @@ class AssociationHasOneSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -454,8 +507,12 @@ class AssociationHasOneSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")])) + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parentA"), Column("parentB")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -478,8 +535,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) 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")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -533,8 +595,10 @@ class AssociationHasOneSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasOne(Child.self) + for association in [ + Parent.hasOne(Child.self), + Parent.hasOne(Table(Child.databaseTableName)), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -557,8 +621,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) 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")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parentA"), Column("parentB")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -581,8 +650,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) 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")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -639,8 +713,12 @@ class AssociationHasOneSQLTests: GRDBTestCase { } try dbQueue.inDatabase { db in - do { - let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent1A"), Column("parent1B")])) + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parent1A"), Column("parent1B")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parent1A"), Column("parent1B")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -663,8 +741,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) 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")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -687,8 +770,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) 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")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parent2A"), Column("parent2B")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parent2A"), Column("parent2B")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ @@ -711,8 +799,13 @@ class AssociationHasOneSQLTests: GRDBTestCase { """) 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")])) + + for association in [ + Parent.hasOne(Child.self, + using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])), + Parent.hasOne(Table(Child.databaseTableName), + using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])), + ] { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parents".*, "children".* \ FROM "parents" \ diff --git a/Tests/GRDBTests/CommonTableExpressionTests.swift b/Tests/GRDBTests/CommonTableExpressionTests.swift index 0689d0105..1352da2de 100644 --- a/Tests/GRDBTests/CommonTableExpressionTests.swift +++ b/Tests/GRDBTests/CommonTableExpressionTests.swift @@ -295,21 +295,25 @@ class CommonTableExpressionTests: GRDBTestCase { literal: "SELECT \("O'Brien")") let assoc1 = T.association(to: cte1) let assoc2 = cte1.association(to: cte2) - let assoc3 = cte2.association(to: T.self) - let request = T.all() - .with(cte1) - .with(cte2) - .including(required: assoc1.including(required: assoc2.including(required: assoc3))) - try assertEqualSQL(db, request, """ - WITH \ - "cte1" AS (SELECT * FROM "t"), \ - "cte2" AS (SELECT 'O''Brien') \ - SELECT "t1".*, "cte1".*, "cte2".*, "t2".* \ - FROM "t" "t1" \ - JOIN "cte1" \ - JOIN "cte2" \ - JOIN "t" "t2" - """) + for assoc3 in [ + cte2.association(to: T.self), + cte2.association(to: Table("t")), + ] { + let request = T.all() + .with(cte1) + .with(cte2) + .including(required: assoc1.including(required: assoc2.including(required: assoc3))) + try assertEqualSQL(db, request, """ + WITH \ + "cte1" AS (SELECT * FROM "t"), \ + "cte2" AS (SELECT 'O''Brien') \ + SELECT "t1".*, "cte1".*, "cte2".*, "t2".* \ + FROM "t" "t1" \ + JOIN "cte1" \ + JOIN "cte2" \ + JOIN "t" "t2" + """) + } } // Use CTE as a subquery diff --git a/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift b/Tests/GRDBTests/TableRecordDeleteTests.swift similarity index 97% rename from Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift rename to Tests/GRDBTests/TableRecordDeleteTests.swift index c817aa5cf..d1b5a2965 100644 --- a/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift +++ b/Tests/GRDBTests/TableRecordDeleteTests.swift @@ -1,31 +1,28 @@ import XCTest import GRDB -private struct Hacker : MutablePersistableRecord { +private struct Hacker : TableRecord { static let databaseTableName = "hackers" - func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } var id: Int64? // Optional } @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) extension Hacker: Identifiable { } -private struct Person : MutablePersistableRecord { +private struct Person : TableRecord { static let databaseTableName = "persons" - func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } var id: Int64 // Non-optional } @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) extension Person: Identifiable { } -private struct Citizenship : MutablePersistableRecord { +private struct Citizenship : TableRecord { static let databaseTableName = "citizenships" - func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } } -class MutablePersistableRecordDeleteTests: GRDBTestCase { +class TableRecordDeleteTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { try dbWriter.write { db in diff --git a/Tests/GRDBTests/MutablePersistableRecordUpdateTests.swift b/Tests/GRDBTests/TableRecordUpdateTests.swift similarity index 90% rename from Tests/GRDBTests/MutablePersistableRecordUpdateTests.swift rename to Tests/GRDBTests/TableRecordUpdateTests.swift index 68c4253d9..4154bdf30 100644 --- a/Tests/GRDBTests/MutablePersistableRecordUpdateTests.swift +++ b/Tests/GRDBTests/TableRecordUpdateTests.swift @@ -1,7 +1,7 @@ import XCTest import GRDB -private struct Player: Codable, PersistableRecord, FetchableRecord { +private struct Player: Codable, TableRecord, FetchableRecord { var id: Int64 var name: String var score: Int @@ -30,7 +30,7 @@ private extension QueryInterfaceRequest where RowDecoder == Player { } } -class MutablePersistableRecordUpdateTests: GRDBTestCase { +class TableRecordUpdateTests: GRDBTestCase { func testRequestUpdateAll() throws { try makeDatabaseQueue().write { db in try Player.createTable(db) @@ -282,10 +282,12 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase { func testUpdateAllReturnsNumberOfUpdatedRows() throws { try makeDatabaseQueue().write { db in try Player.createTable(db) - try Player(id: 1, name: "Arthur", score: 0, bonus: 2).insert(db) - try Player(id: 2, name: "Barbara", score: 0, bonus: 1).insert(db) - try Player(id: 3, name: "Craig", score: 0, bonus: 0).insert(db) - try Player(id: 4, name: "Diane", score: 0, bonus: 3).insert(db) + try db.execute(sql: """ + INSERT INTO player (id, name, score, bonus) VALUES (1, 'Arthur', 0, 2); + INSERT INTO player (id, name, score, bonus) VALUES (2, 'Barbara', 0, 1); + INSERT INTO player (id, name, score, bonus) VALUES (3, 'Craig', 0, 0); + INSERT INTO player (id, name, score, bonus) VALUES (4, 'Diane', 0, 3); + """) let assignment = Columns.score += 1 @@ -305,10 +307,12 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase { func testQueryInterfaceExtension() throws { try makeDatabaseQueue().write { db in try Player.createTable(db) - try Player(id: 1, name: "Arthur", score: 0, bonus: 0).insert(db) - try Player(id: 2, name: "Barbara", score: 0, bonus: 0).insert(db) - try Player(id: 3, name: "Craig", score: 0, bonus: 0).insert(db) - try Player(id: 4, name: "Diane", score: 0, bonus: 0).insert(db) + try db.execute(sql: """ + INSERT INTO player (id, name, score, bonus) VALUES (1, 'Arthur', 0, 0); + INSERT INTO player (id, name, score, bonus) VALUES (2, 'Barbara', 0, 0); + INSERT INTO player (id, name, score, bonus) VALUES (3, 'Craig', 0, 0); + INSERT INTO player (id, name, score, bonus) VALUES (4, 'Diane', 0, 0); + """) try Player.all().incrementScore(db) try XCTAssertEqual(Player.filter(Columns.score == 1).fetchCount(db), 4) @@ -380,6 +384,38 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase { } } + func testConflictPolicyIgnoreWithTable() throws { + struct IgnorePlayer: PersistableRecord { + static let databaseTableName = "player" + static let persistenceConflictPolicy = PersistenceConflictPolicy(insert: .abort, update: .ignore) + func encode(to container: inout PersistenceContainer) { } + } + let table = Table("player") + try makeDatabaseQueue().write { db in + try Player.createTable(db) + + try table.updateAll(db, Column("score").set(to: 0)) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE OR IGNORE "player" SET "score" = 0 + """) + + try table.updateAll(db, [Column("score").set(to: 0)]) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE OR IGNORE "player" SET "score" = 0 + """) + + try table.all().updateAll(db, Column("score").set(to: 0)) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE OR IGNORE "player" SET "score" = 0 + """) + + try table.all().updateAll(db, [Column("score").set(to: 0)]) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE OR IGNORE "player" SET "score" = 0 + """) + } + } + func testConflictPolicyCustom() throws { try makeDatabaseQueue().write { db in try Player.createTable(db) diff --git a/Tests/GRDBTests/TableTests.swift b/Tests/GRDBTests/TableTests.swift new file mode 100644 index 000000000..86f9761bc --- /dev/null +++ b/Tests/GRDBTests/TableTests.swift @@ -0,0 +1,863 @@ +import XCTest +import GRDB + +class TableTests: GRDBTestCase { + func test_Table_nameRoundTrip() { + let table = Table("Player") + XCTAssertEqual(table.tableName, "Player") + } + + func test_Table_defaults_to_Row() { + // This test passes if it compiles + func f(_: Table) { } + let table = Table("Player") + f(table) + } + + func test_Table_accepts_any_type() { + // This test passes if it compiles + struct S { } + class C { } + _ = Table("ignored") + _ = Table("ignored") + } + + func test_request_derivation() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + } + try db.execute(sql: "INSERT INTO player VALUES (1, 'Alice')") + + do { + let t = Table("player") + try assertEqualSQL(db, t.all(), """ + SELECT * FROM "player" + """) + try assertEqualSQL(db, t.none(), """ + SELECT * FROM "player" WHERE 0 + """) + try assertEqualSQL(db, t.select(Column("id"), Column("name")), """ + SELECT "id", "name" FROM "player" + """) + try assertEqualSQL(db, t.select([Column("id"), Column("name")]), """ + SELECT "id", "name" FROM "player" + """) + try assertEqualSQL(db, t.select(sql: "id, ?", arguments: ["O'Brien"]), """ + SELECT id, 'O''Brien' FROM "player" + """) + try assertEqualSQL(db, t.select(literal: "id, \("O'Brien")"), """ + SELECT id, 'O''Brien' FROM "player" + """) + try XCTAssertEqual(t.select(Column("id"), as: Int64.self).fetchOne(db), 1) + try XCTAssertEqual(t.select(Column("id")).fetchOne(db), 1) + try XCTAssertEqual(t.select([Column("name")], as: String.self).fetchOne(db), "Alice") + try XCTAssertEqual(t.select([Column("name")]).fetchOne(db), "Alice") + try XCTAssertEqual(t.select(sql: "id", as: Int64.self).fetchOne(db), 1) + try XCTAssertEqual(t.select(sql: "id").fetchOne(db), 1) + try XCTAssertEqual(t.select(literal: "name", as: String.self).fetchOne(db), "Alice") + try XCTAssertEqual(t.select(literal: "name").fetchOne(db), "Alice") + try assertEqualSQL(db, t.annotated(with: Column.rowID), """ + SELECT *, "rowid" FROM "player" + """) + try assertEqualSQL(db, t.annotated(with: [Column.rowID]), """ + SELECT *, "rowid" FROM "player" + """) + try assertEqualSQL(db, t.filter(Column("id") > 10), """ + SELECT * FROM "player" WHERE "id" > 10 + """) + try assertEqualSQL(db, t.filter(key: 1), """ + SELECT * FROM "player" WHERE "id" = 1 + """) + try assertEqualSQL(db, t.filter(keys: [1, 2, 3]), """ + SELECT * FROM "player" WHERE "id" IN (1, 2, 3) + """) + try assertEqualSQL(db, t.filter(key: ["id": 1]), """ + SELECT * FROM "player" WHERE "id" = 1 + """) + try assertEqualSQL(db, t.filter(keys: [["id": 1], ["id": 2]]), """ + SELECT * FROM "player" WHERE ("id" = 1) OR ("id" = 2) + """) + try assertEqualSQL(db, t.filter(sql: "name = ?", arguments: ["O'Brien"]), """ + SELECT * FROM "player" WHERE name = 'O''Brien' + """) + try assertEqualSQL(db, t.filter(literal: "name = \("O'Brien")"), """ + SELECT * FROM "player" WHERE name = 'O''Brien' + """) + try assertEqualSQL(db, t.order(Column("id"), Column("name").desc), """ + SELECT * FROM "player" ORDER BY "id", "name" DESC + """) + try assertEqualSQL(db, t.order([Column("id"), Column("name").desc]), """ + SELECT * FROM "player" ORDER BY "id", "name" DESC + """) + try assertEqualSQL(db, t.orderByPrimaryKey(), """ + SELECT * FROM "player" ORDER BY "id" + """) + try assertEqualSQL(db, t.order(sql: "IFNULL(name, ?)", arguments: ["O'Brien"]), """ + SELECT * FROM "player" ORDER BY IFNULL(name, 'O''Brien') + """) + try assertEqualSQL(db, t.order(literal: "IFNULL(name, \("O'Brien"))"), """ + SELECT * FROM "player" ORDER BY IFNULL(name, 'O''Brien') + """) + try assertEqualSQL(db, t.limit(1), """ + SELECT * FROM "player" LIMIT 1 + """) + try assertEqualSQL(db, t.limit(1, offset: 3), """ + SELECT * FROM "player" LIMIT 1 OFFSET 3 + """) + try assertEqualSQL(db, t.aliased(TableAlias(name: "p")), """ + SELECT "p".* FROM "player" "p" + """) + try assertEqualSQL(db, t.with(CommonTableExpression(named: "cte", literal: "SELECT \("O'Brien")")), """ + WITH "cte" AS (SELECT 'O''Brien') SELECT * FROM "player" + """) + } + + if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + struct Player: Identifiable { var id: Int64 } + let t = Table("player") + + try assertEqualSQL(db, t.filter(id: 1), """ + SELECT * FROM "player" WHERE "id" = 1 + """) + try assertEqualSQL(db, t.filter(ids: [1, 2, 3]), """ + SELECT * FROM "player" WHERE "id" IN (1, 2, 3) + """) + try XCTAssertEqual(t.selectID().fetchOne(db), 1) + } + + if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + struct Player: Identifiable { var id: Int64? } + let t = Table("player") + + try assertEqualSQL(db, t.filter(id: 1), """ + SELECT * FROM "player" WHERE "id" = 1 + """) + try assertEqualSQL(db, t.filter(ids: [1, 2, 3]), """ + SELECT * FROM "player" WHERE "id" IN (1, 2, 3) + """) + try XCTAssertEqual(t.selectID().fetchOne(db), 1) + } + } + } + + func test_fetchCount() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + } + let t = Table("player") + try XCTAssertEqual(t.fetchCount(db), 0) + try db.execute(sql: "INSERT INTO player VALUES (1, 'Alice')") + try XCTAssertEqual(t.fetchCount(db), 1) + } + } + + func test_fetch_FetchableRecord() throws { + struct Player: FetchableRecord, Decodable, Hashable { + var id: Int64 + var name: String + } + + try makeDatabaseQueue().write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + } + try db.execute(sql: "INSERT INTO player VALUES (1, 'Alice')") + + let t = Table("player") + try XCTAssertEqual(t.fetchCursor(db).next(), Player(id: 1, name: "Alice")) + try XCTAssertEqual(t.fetchAll(db), [Player(id: 1, name: "Alice")]) + try XCTAssertEqual(t.fetchSet(db), [Player(id: 1, name: "Alice")]) + try XCTAssertEqual(t.fetchOne(db), Player(id: 1, name: "Alice")) + } + } + + func test_fetch_Row() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + } + try db.execute(sql: "INSERT INTO player VALUES (1, 'Alice')") + + let t = Table("player") + try XCTAssertEqual(t.fetchCursor(db).map { $0.copy() }.next(), ["id": 1, "name": "Alice"]) + try XCTAssertEqual(t.fetchAll(db), [["id": 1, "name": "Alice"]]) + try XCTAssertEqual(t.fetchSet(db), [["id": 1, "name": "Alice"]]) + try XCTAssertEqual(t.fetchOne(db), ["id": 1, "name": "Alice"]) + } + } + + func test_fetch_DatabaseValueConvertible() throws { + struct Value: DatabaseValueConvertible, Hashable { + var rawValue: Int64 + var databaseValue: DatabaseValue { rawValue.databaseValue } + static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Value? { + Int64.fromDatabaseValue(dbValue).map(Value.init) + } + } + + try makeDatabaseQueue().write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + } + try db.execute(sql: "INSERT INTO player VALUES (1, 'Alice')") + + let t = Table("player") + try XCTAssertEqual(t.fetchCursor(db).next(), Value(rawValue: 1)) + try XCTAssertEqual(t.fetchAll(db), [Value(rawValue: 1)]) + try XCTAssertEqual(t.fetchSet(db), [Value(rawValue: 1)]) + + do { + try db.execute(sql: "DELETE FROM player") + try XCTAssertEqual(t.fetchOne(db), nil) + } + + do { + try db.execute(sql: "DELETE FROM player") + try db.execute(sql: "INSERT INTO player VALUES (1, 'Alice')") + try XCTAssertEqual(t.fetchOne(db), Value(rawValue: 1)) + } + } + } + + func test_fetch_optional_DatabaseValueConvertible() throws { + struct Value: DatabaseValueConvertible, Hashable { + var rawValue: String + var databaseValue: DatabaseValue { rawValue.databaseValue } + static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Value? { + String.fromDatabaseValue(dbValue).map(Value.init) + } + } + + try makeDatabaseQueue().write { db in + try db.create(table: "player") { t in + t.column("name", .text) + } + try db.execute(sql: "INSERT INTO player VALUES ('Alice')") + try db.execute(sql: "INSERT INTO player VALUES (NULL)") + + let t = Table("player") + try XCTAssertEqual(t.fetchCursor(db).next(), Value(rawValue: "Alice")) + try XCTAssertEqual(t.fetchAll(db), [Value(rawValue: "Alice"), nil]) + try XCTAssertEqual(t.fetchSet(db), [Value(rawValue: "Alice"), nil]) + + do { + try db.execute(sql: "DELETE FROM player") + try XCTAssertEqual(t.fetchOne(db), nil) + } + + do { + try db.execute(sql: "DELETE FROM player") + try db.execute(sql: "INSERT INTO player VALUES ('Alice')") + try XCTAssertEqual(t.fetchOne(db), Value(rawValue: "Alice")) + } + + do { + try db.execute(sql: "DELETE FROM player") + try db.execute(sql: "INSERT INTO player VALUES (NULL)") + try XCTAssertEqual(t.fetchOne(db), nil) + } + } + } + + func test_fetch_StatementColumnConvertible() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + } + try db.execute(sql: "INSERT INTO player VALUES (1, 'Alice')") + + let t = Table("player") + try XCTAssertEqual(t.fetchCursor(db).next(), 1) + try XCTAssertEqual(t.fetchAll(db), [1]) + try XCTAssertEqual(t.fetchSet(db), [1]) + + do { + try db.execute(sql: "DELETE FROM player") + try XCTAssertEqual(t.fetchOne(db), nil) + } + + do { + try db.execute(sql: "DELETE FROM player") + try db.execute(sql: "INSERT INTO player VALUES (1, 'Alice')") + try XCTAssertEqual(t.fetchOne(db), 1) + } + } + } + + func test_fetch_optional_StatementColumnConvertible() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "player") { t in + t.column("name", .text) + } + try db.execute(sql: "INSERT INTO player VALUES ('Alice')") + try db.execute(sql: "INSERT INTO player VALUES (NULL)") + + let t = Table("player") + try XCTAssertEqual(t.fetchCursor(db).next(), "Alice") + try XCTAssertEqual(t.fetchAll(db), ["Alice", nil]) + try XCTAssertEqual(t.fetchSet(db), ["Alice", nil]) + + do { + try db.execute(sql: "DELETE FROM player") + try XCTAssertEqual(t.fetchOne(db), nil) + } + + do { + try db.execute(sql: "DELETE FROM player") + try db.execute(sql: "INSERT INTO player VALUES ('Alice')") + try XCTAssertEqual(t.fetchOne(db), "Alice") + } + + do { + try db.execute(sql: "DELETE FROM player") + try db.execute(sql: "INSERT INTO player VALUES (NULL)") + try XCTAssertEqual(t.fetchOne(db), nil) + } + } + } + + func test_association_belongsTo_Table() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("teamID", .integer).references("team") + } + + let player = Table("player") + let association = player.belongsTo(Table("team")) + try assertEqualSQL(db, player.including(optional: association), """ + SELECT "player".*, "team".* \ + FROM "player" \ + LEFT JOIN "team" ON "team"."id" = "player"."teamID" + """) + try assertEqualSQL(db, player.including(required: association), """ + SELECT "player".*, "team".* \ + FROM "player" \ + JOIN "team" ON "team"."id" = "player"."teamID" + """) + try assertEqualSQL(db, player.joining(optional: association), """ + SELECT "player".* \ + FROM "player" \ + LEFT JOIN "team" ON "team"."id" = "player"."teamID" + """) + try assertEqualSQL(db, player.joining(required: association), """ + SELECT "player".* \ + FROM "player" \ + JOIN "team" ON "team"."id" = "player"."teamID" + """) + } + } + + func test_association_belongsTo_TableRecord() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("teamID", .integer).references("team") + } + + struct Team: TableRecord { } + let player = Table("player") + let association = player.belongsTo(Team.self) + try assertEqualSQL(db, player.including(optional: association), """ + SELECT "player".*, "team".* \ + FROM "player" \ + LEFT JOIN "team" ON "team"."id" = "player"."teamID" + """) + try assertEqualSQL(db, player.including(required: association), """ + SELECT "player".*, "team".* \ + FROM "player" \ + JOIN "team" ON "team"."id" = "player"."teamID" + """) + try assertEqualSQL(db, player.joining(optional: association), """ + SELECT "player".* \ + FROM "player" \ + LEFT JOIN "team" ON "team"."id" = "player"."teamID" + """) + try assertEqualSQL(db, player.joining(required: association), """ + SELECT "player".* \ + FROM "player" \ + JOIN "team" ON "team"."id" = "player"."teamID" + """) + } + } + + func test_association_hasOne_Table() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("teamID", .integer).references("team") + } + + let team = Table("team") + let association = team.hasOne(Table("player")) + try assertEqualSQL(db, team.including(optional: association), """ + SELECT "team".*, "player".* \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" + """) + try assertEqualSQL(db, team.including(required: association), """ + SELECT "team".*, "player".* \ + FROM "team" \ + JOIN "player" ON "player"."teamID" = "team"."id" + """) + try assertEqualSQL(db, team.joining(optional: association), """ + SELECT "team".* \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" + """) + try assertEqualSQL(db, team.joining(required: association), """ + SELECT "team".* \ + FROM "team" \ + JOIN "player" ON "player"."teamID" = "team"."id" + """) + } + } + + func test_association_hasOne_TableRecord() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("teamID", .integer).references("team") + } + + struct Player: TableRecord { } + let team = Table("team") + let association = team.hasOne(Player.self) + try assertEqualSQL(db, team.including(optional: association), """ + SELECT "team".*, "player".* \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" + """) + try assertEqualSQL(db, team.including(required: association), """ + SELECT "team".*, "player".* \ + FROM "team" \ + JOIN "player" ON "player"."teamID" = "team"."id" + """) + try assertEqualSQL(db, team.joining(optional: association), """ + SELECT "team".* \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" + """) + try assertEqualSQL(db, team.joining(required: association), """ + SELECT "team".* \ + FROM "team" \ + JOIN "player" ON "player"."teamID" = "team"."id" + """) + } + } + + func test_association_hasMany_Table() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("teamID", .integer).references("team") + } + + let team = Table("team") + let association = team.hasMany(Table("player")) + try assertEqualSQL(db, team.including(optional: association), """ + SELECT "team".*, "player".* \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" + """) + try assertEqualSQL(db, team.including(required: association), """ + SELECT "team".*, "player".* \ + FROM "team" \ + JOIN "player" ON "player"."teamID" = "team"."id" + """) + try assertEqualSQL(db, team.joining(optional: association), """ + SELECT "team".* \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" + """) + try assertEqualSQL(db, team.joining(required: association), """ + SELECT "team".* \ + FROM "team" \ + JOIN "player" ON "player"."teamID" = "team"."id" + """) + _ = team.including(all: association) // TODO: test + } + } + + func test_association_hasMany_TableRecord() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("teamID", .integer).references("team") + } + + struct Player: TableRecord { } + let team = Table("team") + let association = team.hasMany(Player.self) + try assertEqualSQL(db, team.including(optional: association), """ + SELECT "team".*, "player".* \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" + """) + try assertEqualSQL(db, team.including(required: association), """ + SELECT "team".*, "player".* \ + FROM "team" \ + JOIN "player" ON "player"."teamID" = "team"."id" + """) + try assertEqualSQL(db, team.joining(optional: association), """ + SELECT "team".* \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" + """) + try assertEqualSQL(db, team.joining(required: association), """ + SELECT "team".* \ + FROM "team" \ + JOIN "player" ON "player"."teamID" = "team"."id" + """) + _ = team.including(all: association) // TODO: test + } + } + + func test_association_to_CommonTableExpression() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("teamID", .integer).references("team") + } + + let player = Table("player") + let cte = CommonTableExpression(named: "teamBis", request: Table("team").all()) + let association = player.association(to: cte, on: { $0["teamID"] == $1["id"] }) + try assertEqualSQL(db, player.with(cte).including(optional: association), """ + WITH "teamBis" AS (SELECT * FROM "team") \ + SELECT "player".*, "teamBis".* \ + FROM "player" \ + LEFT JOIN "teamBis" ON "player"."teamID" = "teamBis"."id" + """) + try assertEqualSQL(db, player.with(cte).including(required: association), """ + WITH "teamBis" AS (SELECT * FROM "team") \ + SELECT "player".*, "teamBis".* \ + FROM "player" \ + JOIN "teamBis" ON "player"."teamID" = "teamBis"."id" + """) + try assertEqualSQL(db, player.with(cte).joining(optional: association), """ + WITH "teamBis" AS (SELECT * FROM "team") \ + SELECT "player".* \ + FROM "player" \ + LEFT JOIN "teamBis" ON "player"."teamID" = "teamBis"."id" + """) + try assertEqualSQL(db, player.with(cte).joining(required: association), """ + WITH "teamBis" AS (SELECT * FROM "team") \ + SELECT "player".* \ + FROM "player" \ + JOIN "teamBis" ON "player"."teamID" = "teamBis"."id" + """) + } + } + + func test_association_hasOneThrough() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("teamID", .integer).references("team") + } + try db.create(table: "award") { t in + t.autoIncrementedPrimaryKey("id") + t.column("playerID", .integer).references("player") + } + + let team = Table("team") + let player = Table("player") + let award = Table("award") + let association = award.hasOne( + Row.self, + through: award.belongsTo(player), + using: player.belongsTo(team)) + try assertEqualSQL(db, award.including(optional: association), """ + SELECT "award".*, "team".* \ + FROM "award" \ + LEFT JOIN "player" ON "player"."id" = "award"."playerID" \ + LEFT JOIN "team" ON "team"."id" = "player"."teamID" + """) + try assertEqualSQL(db, award.including(required: association), """ + SELECT "award".*, "team".* \ + FROM "award" \ + JOIN "player" ON "player"."id" = "award"."playerID" \ + JOIN "team" ON "team"."id" = "player"."teamID" + """) + try assertEqualSQL(db, award.joining(optional: association), """ + SELECT "award".* \ + FROM "award" \ + LEFT JOIN "player" ON "player"."id" = "award"."playerID" \ + LEFT JOIN "team" ON "team"."id" = "player"."teamID" + """) + try assertEqualSQL(db, award.joining(required: association), """ + SELECT "award".* \ + FROM "award" \ + JOIN "player" ON "player"."id" = "award"."playerID" \ + JOIN "team" ON "team"."id" = "player"."teamID" + """) + } + } + + func test_association_hasManyThrough() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("teamID", .integer).references("team") + } + try db.create(table: "award") { t in + t.autoIncrementedPrimaryKey("id") + t.column("playerID", .integer).references("player") + } + + let team = Table("team") + let player = Table("player") + let award = Table("award") + let association = team.hasMany( + Row.self, + through: team.hasMany(player), + using: player.hasMany(award)) + try assertEqualSQL(db, team.including(optional: association), """ + SELECT "team".*, "award".* \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" \ + LEFT JOIN "award" ON "award"."playerID" = "player"."id" + """) + try assertEqualSQL(db, team.including(required: association), """ + SELECT "team".*, "award".* \ + FROM "team" \ + JOIN "player" ON "player"."teamID" = "team"."id" \ + JOIN "award" ON "award"."playerID" = "player"."id" + """) + try assertEqualSQL(db, team.joining(optional: association), """ + SELECT "team".* \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" \ + LEFT JOIN "award" ON "award"."playerID" = "player"."id" + """) + try assertEqualSQL(db, team.joining(required: association), """ + SELECT "team".* \ + FROM "team" \ + JOIN "player" ON "player"."teamID" = "team"."id" \ + JOIN "award" ON "award"."playerID" = "player"."id" + """) + _ = team.including(all: association) // TODO: test + } + } + + func test_association_aggregates() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("teamID", .integer).references("team") + } + + let team = Table("team") + let association = team.hasMany(Table("player")) + try assertEqualSQL(db, team.annotated(with: association.count, association.max(Column("id"))), """ + SELECT "team".*, COUNT(DISTINCT "player"."id") AS "playerCount", MAX("player"."id") AS "maxPlayerId" \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" \ + GROUP BY "team"."id" + """) + try assertEqualSQL(db, team.annotated(with: [association.count, association.max(Column("id"))]), """ + SELECT "team".*, COUNT(DISTINCT "player"."id") AS "playerCount", MAX("player"."id") AS "maxPlayerId" \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" \ + GROUP BY "team"."id" + """) + try assertEqualSQL(db, team.having(association.isEmpty), """ + SELECT "team".* \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamID" = "team"."id" \ + GROUP BY "team"."id" \ + HAVING COUNT(DISTINCT "player"."id") = 0 + """) + } + } + + func test_delete() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("a").unique() + t.column("b") + t.column("c") + t.uniqueKey(["b", "c"]) + } + try db.create(table: "country") { t in + t.column("code", .text).notNull().primaryKey() + } + try db.create(table: "document") { t in + t.column("a") + } + + // Use Table when we want to make sure the generic type is not used. + + do { + try Table("player").deleteAll(db) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "player" + """) + + try Table("player").all().deleteAll(db) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "player" + """) + } + + do { + try Table("player").deleteOne(db, key: 1) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "player" WHERE "id" = 1 + """) + + try Table("country").deleteOne(db, key: "FR") + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "country" WHERE "code" = 'FR' + """) + + try Table("document").deleteOne(db, key: 1) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "document" WHERE "rowid" = 1 + """) + } + + do { + try Table("player").deleteOne(db, key: ["a": "foo"]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "player" WHERE "a" = 'foo' + """) + + try Table("player").deleteOne(db, key: ["b": "bar", "c": "baz"]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "player" WHERE ("b" = 'bar') AND ("c" = 'baz') + """) + } + + do { + try Table("player").deleteAll(db, keys: [1, 2]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "player" WHERE "id" IN (1, 2) + """) + + try Table("country").deleteAll(db, keys: ["FR", "DE"]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "country" WHERE "code" IN ('FR', 'DE') + """) + + try Table("document").deleteAll(db, keys: [1, 2]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "document" WHERE "rowid" IN (1, 2) + """) + } + + do { + try Table("player").deleteAll(db, keys: [["a": "toto"], ["a": "titi"]]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "player" WHERE ("a" = 'toto') OR ("a" = 'titi') + """) + + try Table("player").deleteAll(db, keys: [["b": "toto", "c": "titi"], ["b": "tata", "c": "tonton"]]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "player" WHERE (("b" = 'toto') AND ("c" = 'titi')) OR (("b" = 'tata') AND ("c" = 'tonton')) + """) + } + + if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + // Non-optional ID + struct Country: Identifiable { var id: String } + + try Table("country").deleteOne(db, id: "FR") + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "country" WHERE "code" = 'FR' + """) + + try Table("country").deleteAll(db, ids: ["FR", "DE"]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "country" WHERE "code" IN ('FR', 'DE') + """) + } + + if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) { + // Optional ID + struct Country: Identifiable { var id: String? } + + try Table("country").deleteOne(db, id: "FR") + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "country" WHERE "code" = 'FR' + """) + + try Table("country").deleteAll(db, ids: ["FR", "DE"]) + XCTAssertEqual(lastSQLQuery, """ + DELETE FROM "country" WHERE "code" IN ('FR', 'DE') + """) + } + } + } + + func test_updateAll() throws { + try makeDatabaseQueue().write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("score", .integer) + } + let assignment = Column("score").set(to: 0) + + // Use Table when we want to make sure the generic type is not used. + + do { + try Table("player").updateAll(db, assignment) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 + """) + } + do { + try Table("player").updateAll(db, [assignment]) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 + """) + } + do { + try Table("player").updateAll(db, onConflict: .ignore, assignment) + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE OR IGNORE "player" SET "score" = 0 + """) + } + } + } +}