From 69ae4c4e96d24f54e27f39fe558dc322aa61b206 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 8 Oct 2023 20:03:52 +0200 Subject: [PATCH] Dump --- GRDB.xcodeproj/project.pbxproj | 64 + GRDB/Core/Database.swift | 9 + GRDB/Core/DatabaseReader.swift | 9 + GRDB/Core/FetchRequest.swift | 6 +- GRDB/Dump/Database+Dump.swift | 260 ++++ GRDB/Dump/DatabaseReader+dump.swift | 125 ++ GRDB/Dump/DumpFormat.swift | 112 ++ GRDB/Dump/DumpFormats/DebugDumpFormat.swift | 153 ++ GRDB/Dump/DumpFormats/JSONDumpFormat.swift | 205 +++ GRDB/Dump/DumpFormats/LineDumpFormat.swift | 129 ++ GRDB/Dump/DumpFormats/ListDumpFormat.swift | 141 ++ GRDB/Dump/DumpFormats/QuoteDumpFormat.swift | 101 ++ GRDBCustom.xcodeproj/project.pbxproj | 64 + .../GRDBTests.xcodeproj/project.pbxproj | 12 + .../GRDBTests.xcodeproj/project.pbxproj | 12 + Tests/GRDBTests/DatabaseDumpTests.swift | 1356 +++++++++++++++++ Tests/GRDBTests/DatabaseReaderDumpTests.swift | 212 +++ 17 files changed, 2969 insertions(+), 1 deletion(-) create mode 100644 GRDB/Dump/Database+Dump.swift create mode 100644 GRDB/Dump/DatabaseReader+dump.swift create mode 100644 GRDB/Dump/DumpFormat.swift create mode 100644 GRDB/Dump/DumpFormats/DebugDumpFormat.swift create mode 100644 GRDB/Dump/DumpFormats/JSONDumpFormat.swift create mode 100644 GRDB/Dump/DumpFormats/LineDumpFormat.swift create mode 100644 GRDB/Dump/DumpFormats/ListDumpFormat.swift create mode 100644 GRDB/Dump/DumpFormats/QuoteDumpFormat.swift create mode 100644 Tests/GRDBTests/DatabaseDumpTests.swift create mode 100644 Tests/GRDBTests/DatabaseReaderDumpTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 5f6ae7ecd..f4e480e86 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -123,6 +123,7 @@ 56419C6D24A519A2004967E1 /* ValueObservationPublisherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6E24A51601004967E1 /* ValueObservationPublisherTests.swift */; }; 56419C7824A51A38004967E1 /* Recorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A5E24A51601004967E1 /* Recorder.swift */; }; 56419C7924A51A38004967E1 /* RecordingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A5F24A51601004967E1 /* RecordingError.swift */; }; + 5642A3182AD66DFE0065F717 /* LineDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5642A3172AD66DFE0065F717 /* LineDumpFormat.swift */; }; 564448831EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; }; 564CE43121AA901800652B19 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */; }; 564CE4E921B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */; }; @@ -202,12 +203,21 @@ 5676FBA622F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FB9F22F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift */; }; 56781B0B243F86E600650A83 /* Refinable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56781B0A243F86E600650A83 /* Refinable.swift */; }; 5679533327E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */; }; + 567B5BE72AD3284100629622 /* DatabaseReader+dump.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE02AD3284100629622 /* DatabaseReader+dump.swift */; }; + 567B5BE82AD3284100629622 /* DumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE12AD3284100629622 /* DumpFormat.swift */; }; + 567B5BE92AD3284100629622 /* QuoteDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE32AD3284100629622 /* QuoteDumpFormat.swift */; }; + 567B5BEA2AD3284100629622 /* JSONDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE42AD3284100629622 /* JSONDumpFormat.swift */; }; + 567B5BEB2AD3284100629622 /* DebugDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE52AD3284100629622 /* DebugDumpFormat.swift */; }; + 567B5BEC2AD3284100629622 /* Database+Dump.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE62AD3284100629622 /* Database+Dump.swift */; }; + 567B5C532AD32FF100629622 /* DatabaseDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BDC2AD3283500629622 /* DatabaseDumpTests.swift */; }; + 567B5C542AD32FF100629622 /* DatabaseReaderDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BDB2AD3283500629622 /* DatabaseReaderDumpTests.swift */; }; 567DAF1C1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; }; 567DAF351EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; }; 567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; 568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; 5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */; }; 56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */; }; + 5685C1932AD52EE600DA4B7A /* ListDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */; }; 56894F752606576600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F742606576600268F4D /* FoundationDecimalTests.swift */; }; 56894FB72606589700268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F94260657D600268F4D /* Decimal.swift */; }; 568C3F7A2A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F792A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift */; }; @@ -539,6 +549,7 @@ 56419A6C24A51601004967E1 /* Support.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Support.swift; sourceTree = ""; }; 56419A6D24A51601004967E1 /* DatabaseRegionObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationPublisherTests.swift; sourceTree = ""; }; 56419A6E24A51601004967E1 /* ValueObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationPublisherTests.swift; sourceTree = ""; }; + 5642A3172AD66DFE0065F717 /* LineDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LineDumpFormat.swift; sourceTree = ""; }; 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; }; 564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueConcurrentObserver.swift; sourceTree = ""; }; @@ -637,12 +648,21 @@ 56781B0A243F86E600650A83 /* Refinable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Refinable.swift; sourceTree = ""; }; 5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueWriteOnlyObserver.swift; sourceTree = ""; }; 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; + 567B5BDB2AD3283500629622 /* DatabaseReaderDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderDumpTests.swift; sourceTree = ""; }; + 567B5BDC2AD3283500629622 /* DatabaseDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDumpTests.swift; sourceTree = ""; }; + 567B5BE02AD3284100629622 /* DatabaseReader+dump.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DatabaseReader+dump.swift"; sourceTree = ""; }; + 567B5BE12AD3284100629622 /* DumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DumpFormat.swift; sourceTree = ""; }; + 567B5BE32AD3284100629622 /* QuoteDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QuoteDumpFormat.swift; sourceTree = ""; }; + 567B5BE42AD3284100629622 /* JSONDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONDumpFormat.swift; sourceTree = ""; }; + 567B5BE52AD3284100629622 /* DebugDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DebugDumpFormat.swift; sourceTree = ""; }; + 567B5BE62AD3284100629622 /* Database+Dump.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Database+Dump.swift"; sourceTree = ""; }; 567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = ""; }; 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = ""; }; 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 = ""; }; 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = ""; }; 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationScheduler.swift; sourceTree = ""; }; + 5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ListDumpFormat.swift; sourceTree = ""; }; 5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 56894F742606576600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = ""; }; 56894F94260657D600268F4D /* Decimal.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Decimal.swift; sourceTree = ""; }; @@ -986,6 +1006,7 @@ 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */, 562EA81E1F17B26F00FA528C /* Compilation */, 56A238111B9C74A90082EB20 /* Core */, + 567B5BDA2AD3281B00629622 /* Dump */, 5698AC3E1DA2BEBB0056AF8C /* FTS */, 56176CA01EACEE2A000F3F2B /* GRDBCipher */, 5603CEC82AC8630300CF097D /* JSON */, @@ -1321,6 +1342,38 @@ name = FetchableRecord; sourceTree = ""; }; + 567B5BDA2AD3281B00629622 /* Dump */ = { + isa = PBXGroup; + children = ( + 567B5BDC2AD3283500629622 /* DatabaseDumpTests.swift */, + 567B5BDB2AD3283500629622 /* DatabaseReaderDumpTests.swift */, + ); + name = Dump; + sourceTree = ""; + }; + 567B5BDF2AD3284100629622 /* Dump */ = { + isa = PBXGroup; + children = ( + 567B5BE62AD3284100629622 /* Database+Dump.swift */, + 567B5BE02AD3284100629622 /* DatabaseReader+dump.swift */, + 567B5BE12AD3284100629622 /* DumpFormat.swift */, + 567B5BE22AD3284100629622 /* DumpFormats */, + ); + path = Dump; + sourceTree = ""; + }; + 567B5BE22AD3284100629622 /* DumpFormats */ = { + isa = PBXGroup; + children = ( + 567B5BE32AD3284100629622 /* QuoteDumpFormat.swift */, + 567B5BE42AD3284100629622 /* JSONDumpFormat.swift */, + 5642A3172AD66DFE0065F717 /* LineDumpFormat.swift */, + 5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */, + 567B5BE52AD3284100629622 /* DebugDumpFormat.swift */, + ); + path = DumpFormats; + sourceTree = ""; + }; 569530FA1C9067CC00CF1A2B /* Crash */ = { isa = PBXGroup; children = ( @@ -1679,6 +1732,7 @@ 56A2FA3524424D2A00E97D23 /* Export.swift */, 566DDE0C288D763C0000DCFB /* Fixits.swift */, 56A2386F1B9C75030082EB20 /* Core */, + 567B5BDF2AD3284100629622 /* Dump */, 5698AC291D9E5A480056AF8C /* FTS */, 5603CEB52AC862EC00CF097D /* JSON */, 56A238911B9C750B0082EB20 /* Migration */, @@ -1865,6 +1919,7 @@ 56DA7CF7260FA9D400A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */, 56D496691D813086008276D7 /* QueryInterfaceExpressionsTests.swift in Sources */, 562393691DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */, + 567B5C532AD32FF100629622 /* DatabaseDumpTests.swift in Sources */, 562205F21E420E47005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */, 56D496B01D813385008276D7 /* DatabaseErrorTests.swift in Sources */, 56176C5C1EACCCC7000F3F2B /* FTS5TableBuilderTests.swift in Sources */, @@ -1997,6 +2052,7 @@ 562393601DEE06D300A6B01F /* CursorTests.swift in Sources */, 5653EAE420944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */, 56D4968F1D81316E008276D7 /* RowFromDictionaryTests.swift in Sources */, + 567B5C542AD32FF100629622 /* DatabaseReaderDumpTests.swift in Sources */, 56915782231BF28B00E1D237 /* PoolTests.swift in Sources */, 56419C6C24A519A2004967E1 /* DatabaseRegionObservationPublisherTests.swift in Sources */, 56D4968E1D81316E008276D7 /* RowCopiedFromStatementTests.swift in Sources */, @@ -2090,6 +2146,7 @@ files = ( 568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */, 56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */, + 5685C1932AD52EE600DA4B7A /* ListDumpFormat.swift in Sources */, 56158780288D875E00A67323 /* Optional.swift in Sources */, 563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */, 5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */, @@ -2138,6 +2195,7 @@ 563B8FB524A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */, 564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */, 564CE5AC21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */, + 567B5BE72AD3284100629622 /* DatabaseReader+dump.swift in Sources */, 5659F4981EA8D989004A4992 /* Pool.swift in Sources */, 56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */, 5674A6F41F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, @@ -2166,6 +2224,7 @@ 56CEB5011EAA2F4D00BFAF62 /* FTS4.swift in Sources */, 56D110C928AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */, 56AE64122229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */, + 567B5BEA2AD3284100629622 /* JSONDumpFormat.swift in Sources */, 56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */, 56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */, 56D51D001EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, @@ -2174,6 +2233,7 @@ 56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */, 5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56A238A41B9C753B0082EB20 /* Record.swift in Sources */, + 567B5BE92AD3284100629622 /* QuoteDumpFormat.swift in Sources */, 56CEB5451EAA359A00BFAF62 /* Column.swift in Sources */, 5657AB0F1D10899D006283EF /* URL.swift in Sources */, 560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */, @@ -2192,6 +2252,7 @@ 56D110C428AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */, 5690C3401D23E82A00E59934 /* Data.swift in Sources */, 5659F4881EA8D94E004A4992 /* Utils.swift in Sources */, + 567B5BE82AD3284100629622 /* DumpFormat.swift in Sources */, 566BE71E2342542F00A8254B /* LockedBox.swift in Sources */, 56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */, 5603CEBB2AC862EC00CF097D /* SQLJSONExpressible.swift in Sources */, @@ -2225,6 +2286,7 @@ 5698AD211DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 5603CEBC2AC862EC00CF097D /* JSONColumn.swift in Sources */, 56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */, + 5642A3182AD66DFE0065F717 /* LineDumpFormat.swift in Sources */, 5605F1671C672E4000235C62 /* NSNumber.swift in Sources */, 56E9FADA221053DD00C703A8 /* SQL.swift in Sources */, 5603CEBA2AC862EC00CF097D /* SQLJSONFunctions.swift in Sources */, @@ -2242,7 +2304,9 @@ 5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */, 5657AAB91D107001006283EF /* NSData.swift in Sources */, 560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */, + 567B5BEC2AD3284100629622 /* Database+Dump.swift in Sources */, 56CEB5531EAA359A00BFAF62 /* SQLExpression.swift in Sources */, + 567B5BEB2AD3284100629622 /* DebugDumpFormat.swift in Sources */, 56B9649D1DA51B4C0002DA19 /* FTS5.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 532054b08..f226b455c 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -65,6 +65,15 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_ /// - ``TransactionCompletion`` /// - ``TransactionKind`` /// +/// ### Printing Database Content +/// +/// - ``dumpContent(format:to:)`` +/// - ``dumpRequest(_:format:to:)`` +/// - ``dumpSQL(_:format:to:)`` +/// - ``dumpTables(_:format:tableHeader:to:)`` +/// - ``DumpFormat`` +/// - ``DumpTableHeaderOptions`` +/// /// ### Database Observation /// /// - ``add(transactionObserver:extent:)`` diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index ae947cae4..2f064dc15 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -33,6 +33,15 @@ import Dispatch /// - ``unsafeReentrantRead(_:)`` /// - ``asyncUnsafeRead(_:)`` /// +/// ### Printing Database Content +/// +/// - ``dumpContent(format:to:)`` +/// - ``dumpRequest(_:format:to:)`` +/// - ``dumpSQL(_:format:to:)`` +/// - ``dumpTables(_:format:tableHeader:to:)`` +/// - ``DumpFormat`` +/// - ``DumpTableHeaderOptions`` +/// /// ### Other Database Operations /// /// - ``backup(to:pagesPerStep:progress:)`` diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index 7ec87607a..87ff4b340 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -123,7 +123,11 @@ typealias WillExecuteSupplementaryRequest = (_ request: AnyFetchRequest, _ /// - parameter rows: The rows that are modified by the supplementary fetch. /// - parameter willExecuteSupplementaryRequest: A closure to execute before /// performing supplementary fetches. -typealias SupplementaryFetch = (_ db: Database, _ rows: [Row], _ willExecuteSupplementaryRequest: WillExecuteSupplementaryRequest?) throws -> Void +typealias SupplementaryFetch = ( + _ db: Database, + _ rows: [Row], + _ willExecuteSupplementaryRequest: WillExecuteSupplementaryRequest?) +throws -> Void /// A `PreparedRequest` is a request that is ready to be executed. public struct PreparedRequest { diff --git a/GRDB/Dump/Database+Dump.swift b/GRDB/Dump/Database+Dump.swift new file mode 100644 index 000000000..eb327eb28 --- /dev/null +++ b/GRDB/Dump/Database+Dump.swift @@ -0,0 +1,260 @@ +import Foundation + +// MARK: - Dump + +extension Database { + /// Prints the results of all statements in the provided SQL. + /// + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// // Prints + /// // 1|Arthur|500 + /// // 2|Barbara|1000 + /// db.dumpSQL("SELECT * FROM player ORDER BY id") + /// } + /// ``` + /// + /// - Parameters: + /// - sql: The executed SQL. + /// - format: The output format. + /// - stream: A stream for text output, which directs output to the + /// console by default. + public func dumpSQL( + _ sql: SQL, + format: some DumpFormat = .debug(), + to stream: (any TextOutputStream)? = nil) + throws + { + var dumpStream = DumpStream(stream) + try _dumpSQL(sql, format: format, to: &dumpStream) + } + + /// Prints the results of a request. + /// + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// // Prints + /// // 1|Arthur|500 + /// // 2|Barbara|1000 + /// db.dumpRequest(Player.orderByPrimaryKey()) + /// } + /// ``` + /// + /// - Parameters: + /// - request : The executed request. + /// - format: The output format. + /// - stream: A stream for text output, which directs output to the + /// console by default. + public func dumpRequest( + _ request: some FetchRequest, + format: some DumpFormat = .debug(), + to stream: (any TextOutputStream)? = nil) + throws + { + var dumpStream = DumpStream(stream) + try _dumpRequest(request, format: format, to: &dumpStream) + } + + /// Prints the contents of the provided tables. + /// + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// // player + /// // 1|Arthur|500 + /// // 2|Barbara|1000 + /// // + /// // team + /// // 1|Red + /// // 2|Blue + /// db.dumpTables(["player", "team"]) + /// } + /// ``` + /// + /// - Parameters: + /// - tables: The table names. + /// - format: The output format. + /// - tableHeader: Options for printing table names. + /// - stream: A stream for text output, which directs output to the + /// console by default. + public func dumpTables( + _ tables: [String], + format: some DumpFormat = .debug(), + tableHeader: DumpTableHeaderOptions = .automatic, + to stream: (any TextOutputStream)? = nil) + throws + { + var dumpStream = DumpStream(stream) + try _dumpTables(tables, format: format, tableHeader: tableHeader, to: &dumpStream) + } + + /// Prints the contents of the database. + /// + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// db.dumpContent() + /// } + /// ``` + /// + /// This prints the database schema as well as the content of all + /// tables. For example: + /// + /// ``` + /// sqlite_master + /// CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, score INTEGER) + /// + /// player + /// 1,'Arthur',500 + /// 2,'Barbara',1000 + /// ``` + /// + /// > Note: Internal SQLite and GRDB schema objects are not recorded + /// > (those with a name that starts with "sqlite_" or "grdb_"). + /// + /// - Parameters: + /// - format: The output format. + /// - stream: A stream for text output, which directs output to the + /// console by default. + public func dumpContent( + format: some DumpFormat = .debug(), + to stream: (any TextOutputStream)? = nil) + throws + { + var dumpStream = DumpStream(stream) + try _dumpContent(format: format, to: &dumpStream) + } +} + +// MARK: - + +extension Database { + func _dumpStatements( + _ statements: some Cursor, + format: some DumpFormat, + to stream: inout DumpStream) + throws + { + while let statement = try statements.next() { + var stepFormat = format + let cursor = try statement.makeCursor() + while try cursor.next() != nil { + try stepFormat.writeRow(self, statement: statement, to: &stream) + } + stepFormat.finalize(self, statement: statement, to: &stream) + } + } + + func _dumpSQL( + _ sql: SQL, + format: some DumpFormat, + to stream: inout DumpStream) + throws + { + try _dumpStatements(allStatements(literal: sql), format: format, to: &stream) + } + + func _dumpRequest( + _ request: some FetchRequest, + format: some DumpFormat, + to stream: inout DumpStream) + throws + { + let preparedRequest = try request.makePreparedRequest(self, forSingleResult: false) + try _dumpStatements(AnyCursor([preparedRequest.statement]), format: format, to: &stream) + + if let supplementaryFetch = preparedRequest.supplementaryFetch { + let rows = try Row.fetchAll(self, request) + try withoutActuallyEscaping( + { request, keyPath in + stream.write("\n") + stream.writeln(keyPath.joined(separator: ".")) + try self._dumpRequest(request, format: format, to: &stream) + }, + do: { willExecuteSupplementaryRequest in + try supplementaryFetch(self, rows, willExecuteSupplementaryRequest) + }) + } + } + + func _dumpTables( + _ tables: [String], + format: some DumpFormat, + tableHeader: DumpTableHeaderOptions = .automatic, + to stream: inout DumpStream) + throws + { + let header: Bool + switch tableHeader { + case .always: header = true + case .automatic: header = tables.count > 1 + } + + var first = true + for table in tables { + if first { + first = false + } else { + stream.write("\n") + } + if header { + stream.writeln(table) + } + try _dumpRequest(Table(table).orderByPrimaryKey(), format: format, to: &stream) + } + } + + func _dumpContent( + format: some DumpFormat, + to stream: inout DumpStream) + throws + { + stream.writeln("sqlite_master") + let sqlRows = try Row.fetchAll(self, sql: """ + SELECT sql || ';', name + FROM sqlite_master + WHERE sql IS NOT NULL + ORDER BY + tbl_name COLLATE NOCASE, + CASE type WHEN 'table' THEN 'a' WHEN 'index' THEN 'aa' ELSE type END, + name COLLATE NOCASE, + sql + """) + for row in sqlRows { + let name: String = row[1] + if Database.isSQLiteInternalTable(name) || Database.isGRDBInternalTable(name) { + continue + } + stream.writeln(row[0]) + } + + let tables = try String + .fetchAll(self, sql: """ + SELECT name + FROM sqlite_master + WHERE type = 'table' + ORDER BY name COLLATE NOCASE + """) + .filter { + !(Database.isSQLiteInternalTable($0) || Database.isGRDBInternalTable($0)) + } + if tables.isEmpty { return } + stream.write("\n") + try _dumpTables(tables, format: format, tableHeader: .always, to: &stream) + } +} + +/// Options for printing table names. +public enum DumpTableHeaderOptions { + /// Table names are only printed when several tables are printed. + case automatic + + /// Table names are always printed. + case always +} diff --git a/GRDB/Dump/DatabaseReader+dump.swift b/GRDB/Dump/DatabaseReader+dump.swift new file mode 100644 index 000000000..bff43b777 --- /dev/null +++ b/GRDB/Dump/DatabaseReader+dump.swift @@ -0,0 +1,125 @@ +extension DatabaseReader { + /// Prints the results of all statements in the provided SQL. + /// + /// For example: + /// + /// ```swift + /// // Prints + /// // 1|Arthur|500 + /// // 2|Barbara|1000 + /// dbQueue.dumpSQL("SELECT * FROM player ORDER BY id") + /// ``` + /// + /// - Parameters: + /// - sql: The executed SQL. + /// - format: The output format. + /// - stream: A stream for text output, which directs output to the + /// console by default. + public func dumpSQL( + _ sql: SQL, + format: some DumpFormat = .debug(), + to stream: (any TextOutputStream)? = nil) + throws + { + try unsafeReentrantRead { db in + try db.dumpSQL(sql, format: format, to: stream) + } + } + + /// Prints the results of a request. + /// + /// For example: + /// + /// ```swift + /// // Prints + /// // 1|Arthur|500 + /// // 2|Barbara|1000 + /// dbQueue.dumpRequest(Player.orderByPrimaryKey()) + /// ``` + /// + /// - Parameters: + /// - request : The executed request. + /// - format: The output format. + /// - stream: A stream for text output, which directs output to the + /// console by default. + public func dumpRequest( + _ request: some FetchRequest, + format: some DumpFormat = .debug(), + to stream: (any TextOutputStream)? = nil) + throws + { + try unsafeReentrantRead { db in + try db.dumpRequest(request, format: format, to: stream) + } + } + + /// Prints the contents of the provided tables. + /// + /// For example: + /// + /// ```swift + /// // player + /// // 1|Arthur|500 + /// // 2|Barbara|1000 + /// // + /// // team + /// // 1|Red + /// // 2|Blue + /// dbQueue.dumpTables(["player", "team"]) + /// ``` + /// + /// - Parameters: + /// - tables: The table names. + /// - format: The output format. + /// - tableHeader: Options for printing table names. + /// - stream: A stream for text output, which directs output to the + /// console by default. + public func dumpTables( + _ tables: [String], + format: some DumpFormat = .debug(), + tableHeader: DumpTableHeaderOptions = .automatic, + to stream: (any TextOutputStream)? = nil) + throws + { + try unsafeReentrantRead { db in + try db.dumpTables(tables, format: format, tableHeader: tableHeader, to: stream) + } + } + + /// Prints the contents of the database. + /// + /// For example: + /// + /// ```swift + /// dbQueue.dumpContent() + /// ``` + /// + /// This prints the database schema as well as the content of all + /// tables. For example: + /// + /// ``` + /// sqlite_master + /// CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, score INTEGER) + /// + /// player + /// 1,'Arthur',500 + /// 2,'Barbara',1000 + /// ``` + /// + /// > Note: Internal SQLite and GRDB schema objects are not recorded + /// > (those with a name that starts with "sqlite_" or "grdb_"). + /// + /// - Parameters: + /// - format: The output format. + /// - stream: A stream for text output, which directs output to the + /// console by default. + public func dumpContent( + format: some DumpFormat = .debug(), + to stream: (any TextOutputStream)? = nil) + throws + { + try unsafeReentrantRead { db in + try db.dumpContent(format: format, to: stream) + } + } +} diff --git a/GRDB/Dump/DumpFormat.swift b/GRDB/Dump/DumpFormat.swift new file mode 100644 index 000000000..8157fc0ca --- /dev/null +++ b/GRDB/Dump/DumpFormat.swift @@ -0,0 +1,112 @@ +/// A type that prints database rows. +/// +/// Types that conform to `DumpFormat` feed the printing methods such as +/// ``DatabaseReader/dumpContent(format:to:)`` and +/// ``Database/dumpSQL(_:format:to:)``. +/// +/// Most built-in formats are inspired from the +/// [output formats of the SQLite command line tool](https://sqlite.org/cli.html#changing_output_formats). +/// +/// ## Topics +/// +/// ### Built-in Formats +/// +/// - ``debug(header:separator:nullValue:)`` +/// - ``json(encoder:)`` +/// - ``line(nullValue:)`` +/// - ``list(header:separator:nullValue:)`` +/// - ``quote(header:separator:)`` +/// +/// ### Supporting Types +/// +/// - ``DebugDumpFormat`` +/// - ``JSONDumpFormat`` +/// - ``LineDumpFormat`` +/// - ``ListDumpFormat`` +/// - ``QuoteDumpFormat`` +/// - ``DumpStream`` +/// +/// ### Implementing a custom format +/// +/// [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) +/// +/// - ``writeRow(_:statement:to:)`` +/// - ``finalize(_:statement:to:)`` +public protocol DumpFormat { + /// Writes a row from the given statement. + /// + /// - Parameters: + /// - db: A connection to the database + /// - statement: The iterated statement + /// - stream: A stream for text output. + mutating func writeRow( + _ db: Database, + statement: Statement, + to stream: inout DumpStream) throws + + /// All rows from the statement have been printed. + /// + /// - Parameters: + /// - db: A connection to the database + /// - statement: The statement that was iterated. + /// - stream: A stream for text output. + mutating func finalize( + _ db: Database, + statement: Statement, + to stream: inout DumpStream) +} + +/// A TextOutputStream that prints to standard output +struct StandardOutputStream: TextOutputStream { + func write(_ string: String) { + print(string, terminator: "") + } +} + +/// A text output stream suited for printing database content. +/// +/// [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) +public struct DumpStream { + var base: any TextOutputStream + var needsMarginLine = false + + init(_ base: (any TextOutputStream)?) { + self.base = base ?? StandardOutputStream() + } + + /// Will write `"\n"` before the next non-empty string. + public mutating func margin() { + needsMarginLine = true + } +} + +extension DumpStream: TextOutputStream { + public mutating func write(_ string: String) { + if needsMarginLine && !string.isEmpty { + needsMarginLine = false + if string.first != "\n" { + base.write("\n") + } + } + base.write(string) + } +} + +extension TextOutputStream { + mutating func writeln(_ string: String) { + write(string) + write("\n") + } +} + +extension String { + func leftPadding(toLength newLength: Int, withPad padString: String) -> String { + precondition(padString.count == 1) + if count < newLength { + return String(repeating: padString, count: newLength - count) + self + } else { + let startIndex = index(startIndex, offsetBy: count - newLength) + return String(self[startIndex...]) + } + } +} diff --git a/GRDB/Dump/DumpFormats/DebugDumpFormat.swift b/GRDB/Dump/DumpFormats/DebugDumpFormat.swift new file mode 100644 index 000000000..58b8f9748 --- /dev/null +++ b/GRDB/Dump/DumpFormats/DebugDumpFormat.swift @@ -0,0 +1,153 @@ +import Foundation + +/// A format that prints one line per database row, suitable +/// for debugging. +/// +/// This format may change in future releases. It is not suitable for +/// processing by other programs, or testing. +/// +/// On each line, database values are separated by a separator (`|` +/// by default). +/// +/// For example: +/// +/// ```swift +/// // Arthur|500 +/// // Barbara|1000 +/// // Craig|200 +/// try db.dumpRequest(Player.all(), format: .debug()) +/// ``` +public struct DebugDumpFormat { + /// A boolean value indicating if column labels are printed as the first + /// line of output. + public var header: Bool + + /// The separator between values. + public var separator: String + + /// The string to print for NULL values. + public var nullValue: String + + private var firstRow = true + + /// Creates a `DebugDumpFormat`. + /// + /// - Parameters: + /// - header: A boolean value indicating if column labels are printed + /// as the first line of output. + /// - separator: The separator between values. + /// - nullValue: The string to print for NULL values. + public init( + header: Bool = false, + separator: String = "|", + nullValue: String = "") + { + self.header = header + self.separator = separator + self.nullValue = nullValue + } +} + +extension DebugDumpFormat: DumpFormat { + public mutating func writeRow( + _ db: Database, + statement: Statement, + to stream: inout DumpStream) + { + if firstRow { + firstRow = false + if header { + stream.writeln(statement.columnNames.joined(separator: separator)) + } + } + + let sqliteStatement = statement.sqliteStatement + var first = true + for index in 0.. String { + switch sqlite3_column_type(sqliteStatement, index) { + case SQLITE_NULL: + return nullValue + + case SQLITE_INTEGER: + return Int64(sqliteStatement: sqliteStatement, index: index).description + + case SQLITE_FLOAT: + return Double(sqliteStatement: sqliteStatement, index: index).description + + case SQLITE_BLOB: + let data = Data(sqliteStatement: sqliteStatement, index: index) + if let string = String(data: data, encoding: .utf8) { + return string + } else if data.count == 16, let blob = sqlite3_column_blob(sqliteStatement, index) { + let uuid = UUID(uuid: blob.assumingMemoryBound(to: uuid_t.self).pointee) + return uuid.uuidString + } else { + return try! data.sqlExpression.quotedSQL(db) + } + + case SQLITE_TEXT: + return String(sqliteStatement: sqliteStatement, index: index) + + default: + return "" + } + } +} + +extension DumpFormat where Self == DebugDumpFormat { + /// A format that prints one line per database row, suitable + /// for debugging. + /// + /// This format may change in future releases. It is not suitable for + /// processing by other programs, or testing. + /// + /// On each line, database values are separated by a separator (`|` + /// by default). + /// + /// For example: + /// + /// ```swift + /// // Arthur|500 + /// // Barbara|1000 + /// // Craig|200 + /// try db.dumpRequest(Player.all(), format: .debug()) + /// ``` + /// + /// - Parameters: + /// - header: A boolean value indicating if column labels are printed + /// as the first line of output. + /// - separator: The separator between values. + /// - nullValue: The string to print for NULL values. + public static func debug( + header: Bool = false, + separator: String = "|", + nullValue: String = "") + -> Self + { + DebugDumpFormat(header: header, separator: separator, nullValue: nullValue) + } +} diff --git a/GRDB/Dump/DumpFormats/JSONDumpFormat.swift b/GRDB/Dump/DumpFormats/JSONDumpFormat.swift new file mode 100644 index 000000000..7837e8581 --- /dev/null +++ b/GRDB/Dump/DumpFormats/JSONDumpFormat.swift @@ -0,0 +1,205 @@ +import Foundation + +/// A format that prints database rows as a JSON array. +/// +/// For example: +/// +/// ```swift +/// // [{"name":"Arthur","score":500}, +/// // {"name":"Barbara","score":1000}] +/// try db.dumpRequest(Player.all(), format: .json()) +/// ``` +/// +/// For a pretty-printed output, customize the JSON encoder: +/// +/// ```swift +/// // [ +/// // { +/// // "name": "Arthur", +/// // "score": 500 +/// // }, +/// // { +/// // "name": "Barbara", +/// // "score": 1000 +/// // } +/// // ] +/// let encoder = JSONDumpFormat.defaultEncoder +/// encoder.outputFormatting = .prettyPrinted +/// try db.dumpRequest(Player.all(), format: .json(encoder)) +/// ``` +public struct JSONDumpFormat { + /// The default `JSONEncoder` for database values. + /// + /// It is configured so that blob values (`Data`) are encoded in the + /// base64 format, and Non-conforming floats are encoded as "inf", + /// "-inf" and "nan". + /// + /// It uses the output formatting option + /// `JSONEncoder.OutputFormatting.withoutEscapingSlashes` when available. + /// + /// Modifying the returned encoder does not affect any encoder returned + /// by future calls to this method. It is always safe to use the + /// returned encoder as a starting point for additional customization. + public static var defaultEncoder: JSONEncoder { + // This encoder MUST NOT CHANGE, because some people rely on this format. + let encoder = JSONEncoder() + if #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) { + encoder.outputFormatting = .withoutEscapingSlashes + } + print(encoder.outputFormatting.contains(.prettyPrinted)) + encoder.nonConformingFloatEncodingStrategy = .convertToString( + positiveInfinity: "inf", + negativeInfinity: "-inf", + nan: "nan") + encoder.dataEncodingStrategy = .base64 + return encoder + } + + /// The JSONEncoder that formats individual database values. + public var encoder: JSONEncoder + + var firstRow = true + + /// Creates a `JSONDumpFormat`. + /// + /// - Parameter encoder: The JSONEncoder that formats individual + /// database values. If the outputFormatting` options contain + /// `.prettyPrinted`, the printed array has one value per line. + public init(encoder: JSONEncoder = JSONDumpFormat.defaultEncoder) { + self.encoder = encoder + } +} + +extension JSONDumpFormat: DumpFormat { + public mutating func writeRow( + _ db: Database, + statement: Statement, + to stream: inout DumpStream) + throws { + if firstRow { + firstRow = false + stream.write("[") + if encoder.outputFormatting.contains(.prettyPrinted) { + stream.write("\n") + } + } else { + stream.write(",\n") + } + + if encoder.outputFormatting.contains(.prettyPrinted) { + stream.write(" ") + } + stream.write("{") + let sqliteStatement = statement.sqliteStatement + var first = true + for index in 0.. String { + switch sqlite3_column_type(sqliteStatement, index) { + case SQLITE_NULL: + return "null" + + case SQLITE_INTEGER: + return try formattedValue(Int64(sqliteStatement: sqliteStatement, index: index)) + + case SQLITE_FLOAT: + return try formattedValue(Double(sqliteStatement: sqliteStatement, index: index)) + + case SQLITE_BLOB: + return try formattedValue(Data(sqliteStatement: sqliteStatement, index: index)) + + case SQLITE_TEXT: + return try formattedValue(String(sqliteStatement: sqliteStatement, index: index)) + + default: + return "" + } + } + + private func formattedValue(_ value: some Encodable) throws -> String { + let data = try encoder.encode(value) + guard let string = String(data: data, encoding: .utf8) else { + throw EncodingError.invalidValue(data, .init(codingPath: [], debugDescription: "Invalid JSON data")) + } + return string + } +} + +extension DumpFormat where Self == JSONDumpFormat { + /// A format that prints database rows as a JSON array. + /// + /// For example: + /// + /// ```swift + /// // [{"name":"Arthur","score":500}, + /// // {"name":"Barbara","score":1000}] + /// try db.dumpRequest(Player.all(), format: .json()) + /// ``` + /// + /// For a pretty-printed output, customize the JSON encoder: + /// + /// ```swift + /// // [ + /// // { + /// // "name": "Arthur", + /// // "score": 500 + /// // }, + /// // { + /// // "name": "Barbara", + /// // "score": 1000 + /// // } + /// // ] + /// let encoder = JSONDumpFormat.defaultEncoder + /// encoder.outputFormatting = .prettyPrinted + /// try db.dumpRequest(Player.all(), format: .json(encoder)) + /// ``` + /// + /// - Parameter encoder: The JSONEncoder that formats individual + /// database values. If the outputFormatting` options contain + /// `.prettyPrinted`, the printed array has one value per line. + public static func json(encoder: JSONEncoder = JSONDumpFormat.defaultEncoder) -> Self { + JSONDumpFormat(encoder: encoder) + } +} diff --git a/GRDB/Dump/DumpFormats/LineDumpFormat.swift b/GRDB/Dump/DumpFormats/LineDumpFormat.swift new file mode 100644 index 000000000..debc28956 --- /dev/null +++ b/GRDB/Dump/DumpFormats/LineDumpFormat.swift @@ -0,0 +1,129 @@ +import Foundation + +/// A format that prints one line per database value. All blob values +/// are interpreted as strings. +/// +/// For example: +/// +/// ```swift +/// // name = Arthur +/// // score = 500 +/// // +/// // name = Barbara +/// // score = 1000 +/// try db.dumpRequest(Player.all(), format: .line()) +/// ``` +public struct LineDumpFormat { + /// The string to print for NULL values. + public var nullValue: String + + var firstRow = true + + /// Creates a `LineDumpFormat`. + /// + /// - Parameters: + /// - nullValue: The string to print for NULL values. + public init( + nullValue: String = "") + { + self.nullValue = nullValue + } +} + +extension LineDumpFormat: DumpFormat { + public mutating func writeRow( + _ db: Database, + statement: Statement, + to stream: inout DumpStream) + { + var lines: [(column: String, value: String)] = [] + let sqliteStatement = statement.sqliteStatement + for index in 0.. Self + { + LineDumpFormat(nullValue: nullValue) + } +} diff --git a/GRDB/Dump/DumpFormats/ListDumpFormat.swift b/GRDB/Dump/DumpFormats/ListDumpFormat.swift new file mode 100644 index 000000000..406209541 --- /dev/null +++ b/GRDB/Dump/DumpFormats/ListDumpFormat.swift @@ -0,0 +1,141 @@ +import Foundation + +/// A format that prints one line per database row. All blob values +/// are interpreted as strings. +/// +/// On each line, database values are separated by a separator (`|` +/// by default). Blob values are interpreted as UTF8 strings. +/// +/// For example: +/// +/// ```swift +/// // Arthur|500 +/// // Barbara|1000 +/// // Craig|200 +/// try db.dumpRequest(Player.all(), format: .list()) +/// ``` +public struct ListDumpFormat { + /// A boolean value indicating if column labels are printed as the first + /// line of output. + public var header: Bool + + /// The separator between values. + public var separator: String + + /// The string to print for NULL values. + public var nullValue: String + + private var firstRow = true + + /// Creates a `ListDumpFormat`. + /// + /// - Parameters: + /// - header: A boolean value indicating if column labels are printed + /// as the first line of output. + /// - separator: The separator between values. + /// - nullValue: The string to print for NULL values. + public init( + header: Bool = false, + separator: String = "|", + nullValue: String = "") + { + self.header = header + self.separator = separator + self.nullValue = nullValue + } +} + +extension ListDumpFormat: DumpFormat { + public mutating func writeRow( + _ db: Database, + statement: Statement, + to stream: inout DumpStream) + { + if firstRow { + firstRow = false + if header { + stream.writeln(statement.columnNames.joined(separator: separator)) + } + } + + let sqliteStatement = statement.sqliteStatement + var first = true + for index in 0.. String + { + switch sqlite3_column_type(sqliteStatement, index) { + case SQLITE_NULL: + return nullValue + + case SQLITE_INTEGER: + return Int64(sqliteStatement: sqliteStatement, index: index).description + + case SQLITE_FLOAT: + return Double(sqliteStatement: sqliteStatement, index: index).description + + case SQLITE_BLOB, SQLITE_TEXT: + return String(sqliteStatement: sqliteStatement, index: index) + + default: + return "" + } + } +} + +extension DumpFormat where Self == ListDumpFormat { + /// A format that prints one line per database row. All blob values + /// are interpreted as strings. + /// + /// On each line, database values are separated by a separator (`|` + /// by default). Blob values are interpreted as UTF8 strings. + /// + /// For example: + /// + /// ```swift + /// // Arthur|500 + /// // Barbara|1000 + /// // Craig|200 + /// try db.dumpRequest(Player.all(), format: .list()) + /// ``` + /// + /// - Parameters: + /// - header: A boolean value indicating if column labels are printed + /// as the first line of output. + /// - separator: The separator between values. + /// - nullValue: The string to print for NULL values. + public static func list( + header: Bool = false, + separator: String = "|", + nullValue: String = "") + -> Self + { + ListDumpFormat(header: header, separator: separator, nullValue: nullValue) + } +} diff --git a/GRDB/Dump/DumpFormats/QuoteDumpFormat.swift b/GRDB/Dump/DumpFormats/QuoteDumpFormat.swift new file mode 100644 index 000000000..2fd8587a9 --- /dev/null +++ b/GRDB/Dump/DumpFormats/QuoteDumpFormat.swift @@ -0,0 +1,101 @@ +/// A format that prints one line per database row, formatting values +/// as SQL literals. +/// +/// For example: +/// +/// ```swift +/// // 'Arthur',500 +/// // 'Barbara',1000 +/// // 'Craig',200 +/// try db.dumpRequest(Player.all(), format: .quote()) +/// ``` +public struct QuoteDumpFormat { + /// A boolean value indicating if column labels are printed as the first + /// line of output. + public var header: Bool + + /// The separator between values. + public var separator: String + + var firstRow = true + + /// Creates a `QuoteDumpFormat`. + /// + /// - Parameters: + /// - header: A boolean value indicating if column labels are printed + /// as the first line of output. + /// - separator: The separator between values. + public init( + header: Bool = false, + separator: String = ",") + { + self.header = header + self.separator = separator + } +} + +extension QuoteDumpFormat: DumpFormat { + public mutating func writeRow( + _ db: Database, + statement: Statement, + to stream: inout DumpStream) + { + if firstRow { + firstRow = false + if header { + stream.writeln(statement.columnNames + .map { try! $0.sqlExpression.quotedSQL(db) } + .joined(separator: separator)) + } + } + + let sqliteStatement = statement.sqliteStatement + var first = true + for index in 0.. Self { + QuoteDumpFormat(header: header, separator: separator) + } +} diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 999b3f945..da2ae3be8 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -98,6 +98,7 @@ 56419C8F24A51D7D004967E1 /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A7F24A51614004967E1 /* Map.swift */; }; 56419C9024A51D7D004967E1 /* Inverted.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A8024A51614004967E1 /* Inverted.swift */; }; 56419C9124A51D7D004967E1 /* PublisherExpectation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A8124A51614004967E1 /* PublisherExpectation.swift */; }; + 5642A31B2AD66E0C0065F717 /* LineDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5642A3192AD66E0C0065F717 /* LineDumpFormat.swift */; }; 564448861EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; }; 5644DE7F20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */; }; 564B3D72239BDBD6007BF308 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */; }; @@ -201,11 +202,20 @@ 5676FBAA22F5CEB9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBA822F5CEB8004717D9 /* ValueObservationRegionRecordingTests.swift */; }; 56781B08243F7B5300650A83 /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = 56781B06243F7B4B00650A83 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; }; 567A80561D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; + 567B5BF62AD3285100629622 /* DatabaseReader+dump.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BEE2AD3285100629622 /* DatabaseReader+dump.swift */; }; + 567B5BF72AD3285100629622 /* DumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BEF2AD3285100629622 /* DumpFormat.swift */; }; + 567B5BF82AD3285100629622 /* QuoteDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BF12AD3285100629622 /* QuoteDumpFormat.swift */; }; + 567B5BF92AD3285100629622 /* JSONDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BF22AD3285100629622 /* JSONDumpFormat.swift */; }; + 567B5BFA2AD3285100629622 /* DebugDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BF32AD3285100629622 /* DebugDumpFormat.swift */; }; + 567B5BFB2AD3285100629622 /* Database+Dump.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BF42AD3285100629622 /* Database+Dump.swift */; }; 567B5C042AD328D900629622 /* DatabaseColumnEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C022AD328D900629622 /* DatabaseColumnEncodingStrategyTests.swift */; }; + 567B5C562AD3301800629622 /* DatabaseDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BFD2AD3287800629622 /* DatabaseDumpTests.swift */; }; + 567B5C572AD3301800629622 /* DatabaseReaderDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BFE2AD3287800629622 /* DatabaseReaderDumpTests.swift */; }; 567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; }; 567E420A242AB3CB00CAAD2C /* FailureTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567E4207242AB3CB00CAAD2C /* FailureTestCase.swift */; }; 567F45AB1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; 568068341EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; + 5685C1962AD52EF200DA4B7A /* ListDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5685C1942AD52EF200DA4B7A /* ListDumpFormat.swift */; }; 56894F332604FC1E00268F4D /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F322604FC1E00268F4D /* Table.swift */; }; 56894FE3260658A400268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FA0260657F600268F4D /* Decimal.swift */; }; 56894FF2260658E600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FF1260658E600268F4D /* FoundationDecimalTests.swift */; }; @@ -550,6 +560,7 @@ 56419A7F24A51614004967E1 /* Map.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Map.swift; sourceTree = ""; }; 56419A8024A51614004967E1 /* Inverted.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Inverted.swift; sourceTree = ""; }; 56419A8124A51614004967E1 /* PublisherExpectation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PublisherExpectation.swift; sourceTree = ""; }; + 5642A3192AD66E0C0065F717 /* LineDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LineDumpFormat.swift; sourceTree = ""; }; 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = ""; }; 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionErrorTests.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; }; @@ -663,11 +674,20 @@ 5676FBA822F5CEB8004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = ""; }; 56781B06243F7B4B00650A83 /* GRDB-Bridging.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "GRDB-Bridging.h"; path = "SQLiteCustom/GRDB-Bridging.h"; sourceTree = ""; }; 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; + 567B5BEE2AD3285100629622 /* DatabaseReader+dump.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DatabaseReader+dump.swift"; sourceTree = ""; }; + 567B5BEF2AD3285100629622 /* DumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DumpFormat.swift; sourceTree = ""; }; + 567B5BF12AD3285100629622 /* QuoteDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QuoteDumpFormat.swift; sourceTree = ""; }; + 567B5BF22AD3285100629622 /* JSONDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONDumpFormat.swift; sourceTree = ""; }; + 567B5BF32AD3285100629622 /* DebugDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DebugDumpFormat.swift; sourceTree = ""; }; + 567B5BF42AD3285100629622 /* Database+Dump.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Database+Dump.swift"; sourceTree = ""; }; + 567B5BFD2AD3287800629622 /* DatabaseDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDumpTests.swift; sourceTree = ""; }; + 567B5BFE2AD3287800629622 /* DatabaseReaderDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderDumpTests.swift; sourceTree = ""; }; 567B5C022AD328D900629622 /* DatabaseColumnEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseColumnEncodingStrategyTests.swift; sourceTree = ""; }; 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = ""; }; 567E4207242AB3CB00CAAD2C /* FailureTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FailureTestCase.swift; sourceTree = ""; }; 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 = ""; }; + 5685C1942AD52EF200DA4B7A /* ListDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ListDumpFormat.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 = ""; }; @@ -1008,6 +1028,7 @@ 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */, 562EA81E1F17B26F00FA528C /* Compilation */, 56A238111B9C74A90082EB20 /* Core */, + 567B5BFC2AD3285C00629622 /* Dump */, 5698AC3E1DA2BEBB0056AF8C /* FTS */, 56176CA01EACEE2A000F3F2B /* GRDBCipher */, 5603CECB2AC8632A00CF097D /* JSON */, @@ -1342,6 +1363,38 @@ name = FetchableRecord; sourceTree = ""; }; + 567B5BED2AD3285100629622 /* Dump */ = { + isa = PBXGroup; + children = ( + 567B5BF42AD3285100629622 /* Database+Dump.swift */, + 567B5BEE2AD3285100629622 /* DatabaseReader+dump.swift */, + 567B5BEF2AD3285100629622 /* DumpFormat.swift */, + 567B5BF02AD3285100629622 /* DumpFormats */, + ); + path = Dump; + sourceTree = ""; + }; + 567B5BF02AD3285100629622 /* DumpFormats */ = { + isa = PBXGroup; + children = ( + 567B5BF12AD3285100629622 /* QuoteDumpFormat.swift */, + 567B5BF22AD3285100629622 /* JSONDumpFormat.swift */, + 5642A3192AD66E0C0065F717 /* LineDumpFormat.swift */, + 5685C1942AD52EF200DA4B7A /* ListDumpFormat.swift */, + 567B5BF32AD3285100629622 /* DebugDumpFormat.swift */, + ); + path = DumpFormats; + sourceTree = ""; + }; + 567B5BFC2AD3285C00629622 /* Dump */ = { + isa = PBXGroup; + children = ( + 567B5BFD2AD3287800629622 /* DatabaseDumpTests.swift */, + 567B5BFE2AD3287800629622 /* DatabaseReaderDumpTests.swift */, + ); + name = Dump; + sourceTree = ""; + }; 5698AC291D9E5A480056AF8C /* FTS */ = { isa = PBXGroup; children = ( @@ -1685,6 +1738,7 @@ 56A2FA3724424F4200E97D23 /* Export.swift */, 566DDE11288D76400000DCFB /* Fixits.swift */, 56A2386F1B9C75030082EB20 /* Core */, + 567B5BED2AD3285100629622 /* Dump */, 5698AC291D9E5A480056AF8C /* FTS */, 5603CEBE2AC862F800CF097D /* JSON */, 56A238911B9C750B0082EB20 /* Migration */, @@ -1920,6 +1974,7 @@ files = ( 5656A8712295BD56001FF3FF /* HasOneThroughAssociation.swift in Sources */, 56713FE32691F487006153C3 /* JSONRequiredEncoder.swift in Sources */, + 5685C1962AD52EF200DA4B7A /* ListDumpFormat.swift in Sources */, 566BD7332927AFD600595649 /* ValueConcurrentObserver.swift in Sources */, 56158786288D878500A67323 /* Optional.swift in Sources */, 5636E9BE1D22574100B9B05F /* FetchRequest.swift in Sources */, @@ -1928,6 +1983,7 @@ 5656A85D2295BD56001FF3FF /* VirtualTableModule.swift in Sources */, 5656A8872295BD56001FF3FF /* SQLOperators.swift in Sources */, 56F89E092A57EBA7002FE2AA /* ForeignKeyDefinition.swift in Sources */, + 567B5BFB2AD3285100629622 /* Database+Dump.swift in Sources */, 566DDE12288D76400000DCFB /* Fixits.swift in Sources */, 563EF44D2161F196007DAACD /* Inflections.swift in Sources */, 566B910B1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, @@ -2040,6 +2096,7 @@ F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */, 56F89E072A57EBA7002FE2AA /* TableAlteration.swift in Sources */, 56FBFED62210731100945324 /* SQLRequest.swift in Sources */, + 567B5BF72AD3285100629622 /* DumpFormat.swift in Sources */, 5674A6FC1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */, 56D110EB28AFC90800E64463 /* MutablePersistableRecord+Insert.swift in Sources */, @@ -2053,10 +2110,13 @@ 5698AD231DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 5656A85B2295BD56001FF3FF /* TableDefinition.swift in Sources */, 5656A8552295BD56001FF3FF /* FTS5+QueryInterface.swift in Sources */, + 567B5BF92AD3285100629622 /* JSONDumpFormat.swift in Sources */, 5603CEC62AC862F800CF097D /* JSONColumn.swift in Sources */, 5656A88F2295BD56001FF3FF /* Column.swift in Sources */, 564CE5B721B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */, + 5642A31B2AD66E0C0065F717 /* LineDumpFormat.swift in Sources */, 5656A8612295BD56001FF3FF /* TableRecord+Association.swift in Sources */, + 567B5BFA2AD3285100629622 /* DebugDumpFormat.swift in Sources */, 5603CEC42AC862F800CF097D /* SQLJSONFunctions.swift in Sources */, F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */, 563CBBE42A595141008905CE /* SQLIndexGenerator.swift in Sources */, @@ -2065,10 +2125,12 @@ 56F89E0A2A57EBA7002FE2AA /* IndexDefinition.swift in Sources */, 567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */, 56D110F328AFC90800E64463 /* MutablePersistableRecord.swift in Sources */, + 567B5BF82AD3285100629622 /* QuoteDumpFormat.swift in Sources */, 56F89E082A57EBA7002FE2AA /* Database+SchemaDefinition.swift in Sources */, F3BA80831CFB2E67003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 5657AABB1D107001006283EF /* NSData.swift in Sources */, 56D3332329C38D7B00430680 /* WALSnapshotTransaction.swift in Sources */, + 567B5BF62AD3285100629622 /* DatabaseReader+dump.swift in Sources */, 5674A6E51F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, 5656A8652295BD56001FF3FF /* BelongsToAssociation.swift in Sources */, F3BA806A1CFB2E55003DC1BA /* DatabaseQueue.swift in Sources */, @@ -2101,6 +2163,7 @@ 56FF45591D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, 56B021CC1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, 561667041D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */, + 567B5C562AD3301800629622 /* DatabaseDumpTests.swift in Sources */, 56419C8F24A51D7D004967E1 /* Map.swift in Sources */, F3BA80E31CFB300F003DC1BA /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 566AD8C91D531BEB002EC1A8 /* TableDefinitionTests.swift in Sources */, @@ -2233,6 +2296,7 @@ 5665FA3D2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, 564D4F9A261E1E0200F55856 /* CaseInsensitiveIdentifierTests.swift in Sources */, 56677C27241E6EA20050755D /* ValueObservationRecorder.swift in Sources */, + 567B5C572AD3301800629622 /* DatabaseReaderDumpTests.swift in Sources */, 563B8F9E249E8AB0007A48C9 /* ValueObservationPrintTests.swift in Sources */, 56419C8B24A51D7D004967E1 /* NextOne.swift in Sources */, 5644DE7F20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index 748f8099a..689b961ac 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -479,6 +479,10 @@ 567B5C402AD32A2D00629622 /* CaseInsensitiveIdentifierTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C272AD32A2D00629622 /* CaseInsensitiveIdentifierTests.swift */; }; 567B5C412AD32A2D00629622 /* SharedValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C282AD32A2D00629622 /* SharedValueObservationTests.swift */; }; 567B5C422AD32A2D00629622 /* SharedValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C282AD32A2D00629622 /* SharedValueObservationTests.swift */; }; + 567B5C4B2AD32F7000629622 /* DatabaseDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C492AD32F7000629622 /* DatabaseDumpTests.swift */; }; + 567B5C4C2AD32F7000629622 /* DatabaseDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C492AD32F7000629622 /* DatabaseDumpTests.swift */; }; + 567B5C4D2AD32F7000629622 /* DatabaseReaderDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C4A2AD32F7000629622 /* DatabaseReaderDumpTests.swift */; }; + 567B5C4E2AD32F7000629622 /* DatabaseReaderDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C4A2AD32F7000629622 /* DatabaseReaderDumpTests.swift */; }; 568C3F7F2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */; }; 568C3F802A5AB36900A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */; }; 5691D97527257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; }; @@ -732,6 +736,8 @@ 567B5C262AD32A2D00629622 /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordMinimalNonOptionalPrimaryKeySingleTests.swift; sourceTree = ""; }; 567B5C272AD32A2D00629622 /* CaseInsensitiveIdentifierTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CaseInsensitiveIdentifierTests.swift; sourceTree = ""; }; 567B5C282AD32A2D00629622 /* SharedValueObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SharedValueObservationTests.swift; sourceTree = ""; }; + 567B5C492AD32F7000629622 /* DatabaseDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDumpTests.swift; sourceTree = ""; }; + 567B5C4A2AD32F7000629622 /* DatabaseReaderDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderDumpTests.swift; sourceTree = ""; }; 568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinitionTests.swift; sourceTree = ""; }; 5691D97427257CE40021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = ""; }; 56F61DEC283D484700AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = ""; }; @@ -886,6 +892,7 @@ 561F38F82AC9CE6D0051EEE9 /* DatabaseDataEncodingStrategyTests.swift */, 56419CCE24A54057004967E1 /* DatabaseDateDecodingStrategyTests.swift */, 56419CE424A54058004967E1 /* DatabaseDateEncodingStrategyTests.swift */, + 567B5C492AD32F7000629622 /* DatabaseDumpTests.swift */, 56419CAF24A54054004967E1 /* DatabaseErrorTests.swift */, 56419CB124A54054004967E1 /* DatabaseFunctionTests.swift */, 56419D0D24A5405B004967E1 /* DatabaseLogErrorTests.swift */, @@ -905,6 +912,7 @@ 56419D0A24A5405B004967E1 /* DatabaseQueueReleaseMemoryTests.swift */, 56419CEF24A54059004967E1 /* DatabaseQueueSchemaCacheTests.swift */, 56419C9E24A54053004967E1 /* DatabaseQueueTests.swift */, + 567B5C4A2AD32F7000629622 /* DatabaseReaderDumpTests.swift */, 56419D2924A5405D004967E1 /* DatabaseReaderTests.swift */, 56419CF724A5405A004967E1 /* DatabaseRegionObservationTests.swift */, 56419D2624A5405D004967E1 /* DatabaseRegionTests.swift */, @@ -1286,6 +1294,7 @@ 568C3F7F2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift in Sources */, 5641A1AA24A540D6004967E1 /* Recorder.swift in Sources */, 56419D7B24A54062004967E1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, + 567B5C4B2AD32F7000629622 /* DatabaseDumpTests.swift in Sources */, 567B5C2D2AD32A2D00629622 /* SingletonRecordTest.swift in Sources */, 56419D6B24A54062004967E1 /* DatabaseQueueTests.swift in Sources */, 56419E2324A54062004967E1 /* SelectStatementTests.swift in Sources */, @@ -1418,6 +1427,7 @@ 56419E4124A54062004967E1 /* TransactionObserverTests.swift in Sources */, 56419DDB24A54062004967E1 /* DatabaseSuspensionTests.swift in Sources */, 567B5C3B2AD32A2D00629622 /* AssociationPrefetchingRelationTests.swift in Sources */, + 567B5C4D2AD32F7000629622 /* DatabaseReaderDumpTests.swift in Sources */, 56419DFB24A54062004967E1 /* DatabaseSnapshotTests.swift in Sources */, 56419DDD24A54062004967E1 /* FTS5PatternTests.swift in Sources */, 56419EBB24A54063004967E1 /* AssociationHasManyThroughSQLTests.swift in Sources */, @@ -1529,6 +1539,7 @@ 568C3F802A5AB36900A2309D /* ForeignKeyDefinitionTests.swift in Sources */, 5641A1AB24A540D6004967E1 /* Recorder.swift in Sources */, 56419D7C24A54062004967E1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, + 567B5C4C2AD32F7000629622 /* DatabaseDumpTests.swift in Sources */, 567B5C2E2AD32A2D00629622 /* SingletonRecordTest.swift in Sources */, 56419D6C24A54062004967E1 /* DatabaseQueueTests.swift in Sources */, 56419E2424A54062004967E1 /* SelectStatementTests.swift in Sources */, @@ -1661,6 +1672,7 @@ 56419E4224A54062004967E1 /* TransactionObserverTests.swift in Sources */, 56419DDC24A54062004967E1 /* DatabaseSuspensionTests.swift in Sources */, 567B5C3C2AD32A2D00629622 /* AssociationPrefetchingRelationTests.swift in Sources */, + 567B5C4E2AD32F7000629622 /* DatabaseReaderDumpTests.swift in Sources */, 56419DFC24A54062004967E1 /* DatabaseSnapshotTests.swift in Sources */, 56419DDE24A54062004967E1 /* FTS5PatternTests.swift in Sources */, 56419EBC24A54063004967E1 /* AssociationHasManyThroughSQLTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index b212c82cd..770dd2470 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -467,6 +467,10 @@ 567B5C192AD32A0000629622 /* TransactionDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C0E2AD32A0000629622 /* TransactionDateTests.swift */; }; 567B5C1A2AD32A0000629622 /* TableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C0F2AD32A0000629622 /* TableTests.swift */; }; 567B5C1B2AD32A0000629622 /* TableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C0F2AD32A0000629622 /* TableTests.swift */; }; + 567B5C452AD32F5900629622 /* DatabaseDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C432AD32F5900629622 /* DatabaseDumpTests.swift */; }; + 567B5C462AD32F5900629622 /* DatabaseDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C432AD32F5900629622 /* DatabaseDumpTests.swift */; }; + 567B5C472AD32F5900629622 /* DatabaseReaderDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C442AD32F5900629622 /* DatabaseReaderDumpTests.swift */; }; + 567B5C482AD32F5900629622 /* DatabaseReaderDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C442AD32F5900629622 /* DatabaseReaderDumpTests.swift */; }; 568C3F822A5AB38300A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F812A5AB38300A2309D /* ForeignKeyDefinitionTests.swift */; }; 568C3F832A5AB38300A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F812A5AB38300A2309D /* ForeignKeyDefinitionTests.swift */; }; 568C3F8B2A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F842A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift */; }; @@ -728,6 +732,8 @@ 567B5C0D2AD32A0000629622 /* SQLIdentifyingColumnsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLIdentifyingColumnsTests.swift; sourceTree = ""; }; 567B5C0E2AD32A0000629622 /* TransactionDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionDateTests.swift; sourceTree = ""; }; 567B5C0F2AD32A0000629622 /* TableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableTests.swift; sourceTree = ""; }; + 567B5C432AD32F5900629622 /* DatabaseDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDumpTests.swift; sourceTree = ""; }; + 567B5C442AD32F5900629622 /* DatabaseReaderDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderDumpTests.swift; sourceTree = ""; }; 568C3F812A5AB38300A2309D /* ForeignKeyDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinitionTests.swift; sourceTree = ""; }; 568C3F842A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = ""; }; 568C3F852A5AB3A800A2309D /* DatabaseColumnEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseColumnEncodingStrategyTests.swift; sourceTree = ""; }; @@ -890,6 +896,7 @@ 561F38FD2AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift */, 56419FBE24A540A0004967E1 /* DatabaseDateDecodingStrategyTests.swift */, 56419F2824A54095004967E1 /* DatabaseDateEncodingStrategyTests.swift */, + 567B5C432AD32F5900629622 /* DatabaseDumpTests.swift */, 56419F5824A54098004967E1 /* DatabaseErrorTests.swift */, 56419FC024A540A0004967E1 /* DatabaseFunctionTests.swift */, 56419F6024A54099004967E1 /* DatabaseLogErrorTests.swift */, @@ -909,6 +916,7 @@ 56419F3424A54096004967E1 /* DatabaseQueueReleaseMemoryTests.swift */, 56419F3224A54096004967E1 /* DatabaseQueueSchemaCacheTests.swift */, 56419F9924A5409D004967E1 /* DatabaseQueueTests.swift */, + 567B5C442AD32F5900629622 /* DatabaseReaderDumpTests.swift */, 56419F5C24A54099004967E1 /* DatabaseReaderTests.swift */, 56419F0524A54093004967E1 /* DatabaseRegionObservationTests.swift */, 56419F0424A54093004967E1 /* DatabaseRegionTests.swift */, @@ -1292,6 +1300,7 @@ 568C3F822A5AB38300A2309D /* ForeignKeyDefinitionTests.swift in Sources */, 5641A06024A540A1004967E1 /* AssociationChainRowScopesTests.swift in Sources */, 5641A0C624A540A1004967E1 /* FetchableRecordDecodableTests.swift in Sources */, + 567B5C452AD32F5900629622 /* DatabaseDumpTests.swift in Sources */, 5641A03424A540A1004967E1 /* RowFromDictionaryTests.swift in Sources */, 5641A00424A540A1004967E1 /* ValueObservationReadonlyTests.swift in Sources */, 5641A06624A540A1004967E1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, @@ -1424,6 +1433,7 @@ 5641A0E024A540A1004967E1 /* QueryInterfaceExtensibilityTests.swift in Sources */, 56419FDA24A540A1004967E1 /* TableRecordUpdateTests.swift in Sources */, 5641A01024A540A1004967E1 /* RecordEditedTests.swift in Sources */, + 567B5C472AD32F5900629622 /* DatabaseReaderDumpTests.swift in Sources */, 5641A0A624A540A1004967E1 /* AssociationHasManySQLTests.swift in Sources */, 56419FFC24A540A1004967E1 /* QueryInterfaceRequestTests.swift in Sources */, 5641A0CC24A540A1004967E1 /* DatabaseQueueConcurrencyTests.swift in Sources */, @@ -1535,6 +1545,7 @@ 568C3F832A5AB38300A2309D /* ForeignKeyDefinitionTests.swift in Sources */, 5641A06124A540A1004967E1 /* AssociationChainRowScopesTests.swift in Sources */, 5641A0C724A540A1004967E1 /* FetchableRecordDecodableTests.swift in Sources */, + 567B5C462AD32F5900629622 /* DatabaseDumpTests.swift in Sources */, 5641A03524A540A1004967E1 /* RowFromDictionaryTests.swift in Sources */, 5641A00524A540A1004967E1 /* ValueObservationReadonlyTests.swift in Sources */, 5641A06724A540A1004967E1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, @@ -1667,6 +1678,7 @@ 5641A0E124A540A1004967E1 /* QueryInterfaceExtensibilityTests.swift in Sources */, 56419FDB24A540A1004967E1 /* TableRecordUpdateTests.swift in Sources */, 5641A01124A540A1004967E1 /* RecordEditedTests.swift in Sources */, + 567B5C482AD32F5900629622 /* DatabaseReaderDumpTests.swift in Sources */, 5641A0A724A540A1004967E1 /* AssociationHasManySQLTests.swift in Sources */, 56419FFD24A540A1004967E1 /* QueryInterfaceRequestTests.swift in Sources */, 5641A0CD24A540A1004967E1 /* DatabaseQueueConcurrencyTests.swift in Sources */, diff --git a/Tests/GRDBTests/DatabaseDumpTests.swift b/Tests/GRDBTests/DatabaseDumpTests.swift new file mode 100644 index 000000000..bedd64de0 --- /dev/null +++ b/Tests/GRDBTests/DatabaseDumpTests.swift @@ -0,0 +1,1356 @@ +import XCTest +import GRDB + +private final class TestStream: TextOutputStream { + var output: String + + init() { + output = "" + } + + func write(_ string: String) { + output.append(string) + } +} + +private struct Player: Codable, MutablePersistableRecord { + static let team = belongsTo(Team.self) + var id: Int64? + var name: String + var teamId: String? + + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID + } +} + +private struct Team: Codable, PersistableRecord { + static let players = hasMany(Player.self) + var id: String + var name: String + var color: String +} + +final class DatabaseDumpTests: GRDBTestCase { + // MARK: - Debug + + func test_debug_value_formatting() throws { + try makeValuesDatabase().read { db in + let stream = TestStream() + try db.dumpSQL("SELECT * FROM value ORDER BY name", format: .debug(), to: stream) + XCTAssertEqual(stream.output, """ + blob: ascii apostrophe|['] + blob: ascii double quote|["] + blob: ascii line feed|[ + ] + blob: ascii long|Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi tristique tempor condimentum. Pellentesque pharetra lacus non ante sollicitudin auctor. Vestibulum sit amet mauris vitae urna non luctus. + blob: ascii short|Hello + blob: ascii tab|[\t] + blob: binary short|X'80' + blob: empty| + blob: utf8 short|您好🙂 + blob: uuid|69BF8A9C-D9F0-4777-BD11-93451D84CBCF + double: -1.0|-1.0 + double: -inf|-inf + double: 0.0|0.0 + double: 123.45|123.45 + double: inf|inf + double: nan| + integer: -1|-1 + integer: 0|0 + integer: 123|123 + integer: max|9223372036854775807 + integer: min|-9223372036854775808 + null| + text: ascii apostrophe|['] + text: ascii backslash|[\\] + text: ascii double quote|["] + text: ascii line feed|[ + ] + text: ascii long|Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi tristique tempor condimentum. Pellentesque pharetra lacus non ante sollicitudin auctor. Vestibulum sit amet mauris vitae urna non luctus. + text: ascii short|Hello + text: ascii slash|[/] + text: ascii tab|[\t] + text: ascii url|https://github.com/groue/GRDB.swift + text: empty| + text: utf8 short|您好🙂 + + """) + } + } + + func test_debug_empty_results() throws { + try makeDatabaseQueue().write { db in + do { + // Columns + let stream = TestStream() + try db.dumpSQL("SELECT NULL WHERE NULL", format: .debug(), to: stream) + XCTAssertEqual(stream.output, "") + } + do { + // No columns + let stream = TestStream() + try db.dumpSQL("CREATE TABLE t(a)", format: .debug(), to: stream) + XCTAssertEqual(stream.output, "") + } + } + } + + func test_debug_headers() throws { + try makeRugbyDatabase().read { db in + do { + // Headers on + let stream = TestStream() + try db.dumpSQL("SELECT * FROM player ORDER BY id", format: .debug(header: true), to: stream) + XCTAssertEqual(stream.output, """ + id|teamId|name + 1|FRA|Antoine Dupond + 2|ENG|Owen Farrell + 3||Gwendal Roué + + """) + } + do { + // Headers on, no result + let stream = TestStream() + try db.dumpSQL("SELECT * FROM player WHERE 0", format: .debug(header: true), to: stream) + XCTAssertEqual(stream.output, "") + } + do { + // Headers off + let stream = TestStream() + try db.dumpSQL("SELECT * FROM player ORDER BY id", format: .debug(header: false), to: stream) + XCTAssertEqual(stream.output, """ + 1|FRA|Antoine Dupond + 2|ENG|Owen Farrell + 3||Gwendal Roué + + """) + } + do { + // Headers off, no result + let stream = TestStream() + try db.dumpSQL("SELECT * FROM player WHERE 0", format: .debug(header: false), to: stream) + XCTAssertEqual(stream.output, "") + } + } + } + + func test_debug_duplicate_columns() throws { + try makeDatabaseQueue().read { db in + let stream = TestStream() + try db.dumpSQL("SELECT 1 AS name, 'foo' AS name", format: .debug(header: true), to: stream) + XCTAssertEqual(stream.output, """ + name|name + 1|foo + + """) + } + } + + func test_debug_multiple_statements() throws { + try makeDatabaseQueue().write { db in + let stream = TestStream() + try db.dumpSQL( + """ + CREATE TABLE t(a, b); + INSERT INTO t VALUES (1, 'foo'); + INSERT INTO t VALUES (2, 'bar'); + SELECT * FROM t ORDER BY a; + SELECT b FROM t ORDER BY b; + SELECT NULL WHERE NULL; + """, + format: .debug(), + to: stream) + XCTAssertEqual(stream.output, """ + 1|foo + 2|bar + bar + foo + + """) + } + } + + func test_debug_separator() throws { + try makeRugbyDatabase().read { db in + do { + // Default separator + let stream = TestStream() + try db.dumpSQL("SELECT * FROM player ORDER BY id", format: .debug(header: true), to: stream) + XCTAssertEqual(stream.output, """ + id|teamId|name + 1|FRA|Antoine Dupond + 2|ENG|Owen Farrell + 3||Gwendal Roué + + """) + } + do { + // Custom separator + let stream = TestStream() + try db.dumpSQL("SELECT * FROM player ORDER BY id", format: .debug(header: true, separator: "---"), to: stream) + XCTAssertEqual(stream.output, """ + id---teamId---name + 1---FRA---Antoine Dupond + 2---ENG---Owen Farrell + 3------Gwendal Roué + + """) + } + } + } + + func test_debug_nullValue() throws { + try makeRugbyDatabase().read { db in + do { + // Default null + let stream = TestStream() + try db.dumpSQL("SELECT * FROM player ORDER BY id", format: .debug(), to: stream) + XCTAssertEqual(stream.output, """ + 1|FRA|Antoine Dupond + 2|ENG|Owen Farrell + 3||Gwendal Roué + + """) + } + do { + // Custom null + let stream = TestStream() + try db.dumpSQL("SELECT * FROM player ORDER BY id", format: .debug(nullValue: "NULL"), to: stream) + XCTAssertEqual(stream.output, """ + 1|FRA|Antoine Dupond + 2|ENG|Owen Farrell + 3|NULL|Gwendal Roué + + """) + } + } + } + + // MARK: - JSON + + func test_json_value_formatting() throws { + guard #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) else { + throw XCTSkip("Skip because this test relies on JSONEncoder.OutputFormatting.withoutEscapingSlashes") + } + + try makeValuesDatabase().read { db in + let stream = TestStream() + try db.dumpSQL("SELECT * FROM value ORDER BY name", format: .json(), to: stream) + XCTAssertEqual(stream.output, """ + [{"name":"blob: ascii apostrophe","value":"Wydd"}, + {"name":"blob: ascii double quote","value":"WyJd"}, + {"name":"blob: ascii line feed","value":"Wwpd"}, + {"name":"blob: ascii long","value":"TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gTW9yYmkgdHJpc3RpcXVlIHRlbXBvciBjb25kaW1lbnR1bS4gUGVsbGVudGVzcXVlIHBoYXJldHJhIGxhY3VzIG5vbiBhbnRlIHNvbGxpY2l0dWRpbiBhdWN0b3IuIFZlc3RpYnVsdW0gc2l0IGFtZXQgbWF1cmlzIHZpdGFlIHVybmEgbm9uIGx1Y3R1cy4="}, + {"name":"blob: ascii short","value":"SGVsbG8="}, + {"name":"blob: ascii tab","value":"Wwld"}, + {"name":"blob: binary short","value":"gA=="}, + {"name":"blob: empty","value":""}, + {"name":"blob: utf8 short","value":"5oKo5aW98J+Zgg=="}, + {"name":"blob: uuid","value":"ab+KnNnwR3e9EZNFHYTLzw=="}, + {"name":"double: -1.0","value":-1}, + {"name":"double: -inf","value":"-inf"}, + {"name":"double: 0.0","value":0}, + {"name":"double: 123.45","value":123.45}, + {"name":"double: inf","value":"inf"}, + {"name":"double: nan","value":null}, + {"name":"integer: -1","value":-1}, + {"name":"integer: 0","value":0}, + {"name":"integer: 123","value":123}, + {"name":"integer: max","value":9223372036854775807}, + {"name":"integer: min","value":-9223372036854775808}, + {"name":"null","value":null}, + {"name":"text: ascii apostrophe","value":"[']"}, + {"name":"text: ascii backslash","value":"[\\\\]"}, + {"name":"text: ascii double quote","value":"[\\"]"}, + {"name":"text: ascii line feed","value":"[\\n]"}, + {"name":"text: ascii long","value":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi tristique tempor condimentum. Pellentesque pharetra lacus non ante sollicitudin auctor. Vestibulum sit amet mauris vitae urna non luctus."}, + {"name":"text: ascii short","value":"Hello"}, + {"name":"text: ascii slash","value":"[/]"}, + {"name":"text: ascii tab","value":"[\\t]"}, + {"name":"text: ascii url","value":"https://github.com/groue/GRDB.swift"}, + {"name":"text: empty","value":""}, + {"name":"text: utf8 short","value":"您好🙂"}] + + """) + } + } + + func test_json_empty_results() throws { + try makeDatabaseQueue().write { db in + do { + // Columns + let stream = TestStream() + try db.dumpSQL("SELECT NULL WHERE NULL", format: .json(), to: stream) + XCTAssertEqual(stream.output, """ + [] + + """) + } + do { + // No columns + let stream = TestStream() + try db.dumpSQL("CREATE TABLE t(a)", format: .json(), to: stream) + XCTAssertEqual(stream.output, "") + } + } + } + + func test_json_duplicate_columns() throws { + try makeDatabaseQueue().read { db in + let stream = TestStream() + try db.dumpSQL("SELECT 1 AS name, 'foo' AS name", format: .json(), to: stream) + XCTAssertEqual(stream.output, """ + [{"name":1,"name":"foo"}] + + """) + } + } + + func test_json_multiple_statements() throws { + try makeDatabaseQueue().write { db in + let stream = TestStream() + try db.dumpSQL( + """ + CREATE TABLE t(a, b); + INSERT INTO t VALUES (1, 'foo'); + INSERT INTO t VALUES (2, 'bar'); + SELECT * FROM t ORDER BY a; + SELECT b FROM t ORDER BY b; + SELECT NULL WHERE NULL; + """, + format: .json(), + to: stream) + XCTAssertEqual(stream.output, """ + [{"a":1,"b":"foo"}, + {"a":2,"b":"bar"}] + [{"b":"bar"}, + {"b":"foo"}] + [] + + """) + } + } + + func test_json_custom_encoder() throws { + try makeDatabaseQueue().write { db in + try db.execute(literal: """ + CREATE TABLE t(id INTEGER PRIMARY KEY, name TEXT, value DOUBLE); + INSERT INTO t VALUES (1, 'a', 0.0); + INSERT INTO t VALUES (2, 'b', \(1.0 / 0)); + INSERT INTO t VALUES (3, 'c', \(-1.0 / 0)); + """) + let encoder = JSONDumpFormat.defaultEncoder + encoder.nonConformingFloatEncodingStrategy = .convertToString( + positiveInfinity: "much too much", + negativeInfinity: "whoops", + nan: "") + encoder.outputFormatting = [.prettyPrinted, .sortedKeys /* ignored */] + let stream = TestStream() + try db.dumpSQL("SELECT * FROM t ORDER BY id", format: .json(encoder: encoder), to: stream) + XCTAssertEqual(stream.output, """ + [ + { + "id":1, + "name":"a", + "value":0 + }, + { + "id":2, + "name":"b", + "value":"much too much" + }, + { + "id":3, + "name":"c", + "value":"whoops" + } + ] + + """) + } + } + + // MARK: - Line + + func test_line_value_formatting() throws { + try makeValuesDatabase().read { db in + let stream = TestStream() + try db.dumpSQL("SELECT * FROM value ORDER BY name", format: .line(), to: stream) + XCTAssertEqual(stream.output, """ + name = blob: ascii apostrophe + value = ['] + + name = blob: ascii double quote + value = ["] + + name = blob: ascii line feed + value = [ + ] + + name = blob: ascii long + value = Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi tristique tempor condimentum. Pellentesque pharetra lacus non ante sollicitudin auctor. Vestibulum sit amet mauris vitae urna non luctus. + + name = blob: ascii short + value = Hello + + name = blob: ascii tab + value = [\t] + + name = blob: binary short + value = � + + name = blob: empty + value = \n\ + + name = blob: utf8 short + value = 您好🙂 + + name = blob: uuid + value = \("i\u{fffd}\u{fffd}\u{fffd}\u{fffd}\u{fffd}Gw\u{fffd}\u{11}\u{fffd}E\u{1d}\u{fffd}\u{fffd}\u{fffd}") + + name = double: -1.0 + value = -1.0 + + name = double: -inf + value = -inf + + name = double: 0.0 + value = 0.0 + + name = double: 123.45 + value = 123.45 + + name = double: inf + value = inf + + name = double: nan + value = \n\ + + name = integer: -1 + value = -1 + + name = integer: 0 + value = 0 + + name = integer: 123 + value = 123 + + name = integer: max + value = 9223372036854775807 + + name = integer: min + value = -9223372036854775808 + + name = null + value = \n\ + + name = text: ascii apostrophe + value = ['] + + name = text: ascii backslash + value = [\\] + + name = text: ascii double quote + value = ["] + + name = text: ascii line feed + value = [ + ] + + name = text: ascii long + value = Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi tristique tempor condimentum. Pellentesque pharetra lacus non ante sollicitudin auctor. Vestibulum sit amet mauris vitae urna non luctus. + + name = text: ascii short + value = Hello + + name = text: ascii slash + value = [/] + + name = text: ascii tab + value = [\t] + + name = text: ascii url + value = https://github.com/groue/GRDB.swift + + name = text: empty + value = \n\ + + name = text: utf8 short + value = 您好🙂 + + """) + } + } + + func test_line_empty_results() throws { + try makeDatabaseQueue().write { db in + do { + // Columns + let stream = TestStream() + try db.dumpSQL("SELECT NULL WHERE NULL", format: .line(), to: stream) + XCTAssertEqual(stream.output, "") + } + do { + // No columns + let stream = TestStream() + try db.dumpSQL("CREATE TABLE t(a)", format: .line(), to: stream) + XCTAssertEqual(stream.output, "") + } + } + } + + func test_line_duplicate_columns() throws { + try makeDatabaseQueue().read { db in + let stream = TestStream() + try db.dumpSQL("SELECT 1 AS name, 'foo' AS name", format: .line(), to: stream) + XCTAssertEqual(stream.output, """ + name = 1 + name = foo + + """) + } + } + + func test_line_multiple_statements() throws { + try makeDatabaseQueue().write { db in + let stream = TestStream() + try db.dumpSQL( + """ + CREATE TABLE t(a, b); + INSERT INTO t VALUES (1, 'foo'); + INSERT INTO t VALUES (2, 'bar'); + SELECT * FROM t ORDER BY a; + SELECT b FROM t ORDER BY b; + SELECT NULL WHERE NULL; + """, + format: .line(), + to: stream) + XCTAssertEqual(stream.output, """ + a = 1 + b = foo + + a = 2 + b = bar + + b = bar + + b = foo + + """) + } + } + + func test_line_nullValue() throws { + try makeRugbyDatabase().read { db in + do { + // Default null + let stream = TestStream() + try db.dumpSQL("SELECT * FROM player ORDER BY id", format: .line(), to: stream) + XCTAssertEqual(stream.output, """ + id = 1 + teamId = FRA + name = Antoine Dupond + + id = 2 + teamId = ENG + name = Owen Farrell + + id = 3 + teamId = \n\ + name = Gwendal Roué + + """) + } + do { + // Custom null + let stream = TestStream() + try db.dumpSQL("SELECT * FROM player ORDER BY id", format: .line(nullValue: "NULL"), to: stream) + XCTAssertEqual(stream.output, """ + id = 1 + teamId = FRA + name = Antoine Dupond + + id = 2 + teamId = ENG + name = Owen Farrell + + id = 3 + teamId = NULL + name = Gwendal Roué + + """) + } + } + } + + // MARK: - List + + func test_list_value_formatting() throws { + try makeValuesDatabase().read { db in + let stream = TestStream() + try db.dumpSQL("SELECT * FROM value ORDER BY name", format: .list(), to: stream) + XCTAssertEqual(stream.output, """ + blob: ascii apostrophe|['] + blob: ascii double quote|["] + blob: ascii line feed|[ + ] + blob: ascii long|Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi tristique tempor condimentum. Pellentesque pharetra lacus non ante sollicitudin auctor. Vestibulum sit amet mauris vitae urna non luctus. + blob: ascii short|Hello + blob: ascii tab|[\t] + blob: binary short|� + blob: empty| + blob: utf8 short|您好🙂 + blob: uuid|\("i\u{fffd}\u{fffd}\u{fffd}\u{fffd}\u{fffd}Gw\u{fffd}\u{11}\u{fffd}E\u{1d}\u{fffd}\u{fffd}\u{fffd}") + double: -1.0|-1.0 + double: -inf|-inf + double: 0.0|0.0 + double: 123.45|123.45 + double: inf|inf + double: nan| + integer: -1|-1 + integer: 0|0 + integer: 123|123 + integer: max|9223372036854775807 + integer: min|-9223372036854775808 + null| + text: ascii apostrophe|['] + text: ascii backslash|[\\] + text: ascii double quote|["] + text: ascii line feed|[ + ] + text: ascii long|Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi tristique tempor condimentum. Pellentesque pharetra lacus non ante sollicitudin auctor. Vestibulum sit amet mauris vitae urna non luctus. + text: ascii short|Hello + text: ascii slash|[/] + text: ascii tab|[\t] + text: ascii url|https://github.com/groue/GRDB.swift + text: empty| + text: utf8 short|您好🙂 + + """) + } + } + + func test_list_empty_results() throws { + try makeDatabaseQueue().write { db in + do { + // Columns + let stream = TestStream() + try db.dumpSQL("SELECT NULL WHERE NULL", format: .list(), to: stream) + XCTAssertEqual(stream.output, "") + } + do { + // No columns + let stream = TestStream() + try db.dumpSQL("CREATE TABLE t(a)", format: .list(), to: stream) + XCTAssertEqual(stream.output, "") + } + } + } + + func test_list_headers() throws { + try makeRugbyDatabase().read { db in + do { + // Headers on + let stream = TestStream() + try db.dumpSQL("SELECT * FROM player ORDER BY id", format: .list(header: true), to: stream) + XCTAssertEqual(stream.output, """ + id|teamId|name + 1|FRA|Antoine Dupond + 2|ENG|Owen Farrell + 3||Gwendal Roué + + """) + } + do { + // Headers on, no result + let stream = TestStream() + try db.dumpSQL("SELECT * FROM player WHERE 0", format: .list(header: true), to: stream) + XCTAssertEqual(stream.output, "") + } + do { + // Headers off + let stream = TestStream() + try db.dumpSQL("SELECT * FROM player ORDER BY id", format: .list(header: false), to: stream) + XCTAssertEqual(stream.output, """ + 1|FRA|Antoine Dupond + 2|ENG|Owen Farrell + 3||Gwendal Roué + + """) + } + do { + // Headers off, no result + let stream = TestStream() + try db.dumpSQL("SELECT * FROM player WHERE 0", format: .list(header: false), to: stream) + XCTAssertEqual(stream.output, "") + } + } + } + + func test_list_duplicate_columns() throws { + try makeDatabaseQueue().read { db in + let stream = TestStream() + try db.dumpSQL("SELECT 1 AS name, 'foo' AS name", format: .list(header: true), to: stream) + XCTAssertEqual(stream.output, """ + name|name + 1|foo + + """) + } + } + + func test_list_multiple_statements() throws { + try makeDatabaseQueue().write { db in + let stream = TestStream() + try db.dumpSQL( + """ + CREATE TABLE t(a, b); + INSERT INTO t VALUES (1, 'foo'); + INSERT INTO t VALUES (2, 'bar'); + SELECT * FROM t ORDER BY a; + SELECT b FROM t ORDER BY b; + SELECT NULL WHERE NULL; + """, + format: .list(), + to: stream) + XCTAssertEqual(stream.output, """ + 1|foo + 2|bar + bar + foo + + """) + } + } + + func test_list_separator() throws { + try makeRugbyDatabase().read { db in + do { + // Default separator + let stream = TestStream() + try db.dumpSQL("SELECT * FROM player ORDER BY id", format: .list(header: true), to: stream) + XCTAssertEqual(stream.output, """ + id|teamId|name + 1|FRA|Antoine Dupond + 2|ENG|Owen Farrell + 3||Gwendal Roué + + """) + } + do { + // Custom separator + let stream = TestStream() + try db.dumpSQL("SELECT * FROM player ORDER BY id", format: .list(header: true, separator: "---"), to: stream) + XCTAssertEqual(stream.output, """ + id---teamId---name + 1---FRA---Antoine Dupond + 2---ENG---Owen Farrell + 3------Gwendal Roué + + """) + } + } + } + + func test_list_nullValue() throws { + try makeRugbyDatabase().read { db in + do { + // Default null + let stream = TestStream() + try db.dumpSQL("SELECT * FROM player ORDER BY id", format: .list(), to: stream) + XCTAssertEqual(stream.output, """ + 1|FRA|Antoine Dupond + 2|ENG|Owen Farrell + 3||Gwendal Roué + + """) + } + do { + // Custom null + let stream = TestStream() + try db.dumpSQL("SELECT * FROM player ORDER BY id", format: .list(nullValue: "NULL"), to: stream) + XCTAssertEqual(stream.output, """ + 1|FRA|Antoine Dupond + 2|ENG|Owen Farrell + 3|NULL|Gwendal Roué + + """) + } + } + } + + // MARK: - Quote + + func test_quote_value_formatting() throws { + try makeValuesDatabase().read { db in + let stream = TestStream() + try db.dumpSQL("SELECT * FROM value ORDER BY name", format: .quote(), to: stream) + XCTAssertEqual(stream.output, """ + 'blob: ascii apostrophe',X'5B275D' + 'blob: ascii double quote',X'5B225D' + 'blob: ascii line feed',X'5B0A5D' + 'blob: ascii long',X'4C6F72656D20697073756D20646F6C6F722073697420616D65742C20636F6E73656374657475722061646970697363696E6720656C69742E204D6F726269207472697374697175652074656D706F7220636F6E64696D656E74756D2E2050656C6C656E746573717565207068617265747261206C61637573206E6F6E20616E746520736F6C6C696369747564696E20617563746F722E20566573746962756C756D2073697420616D6574206D61757269732076697461652075726E61206E6F6E206C75637475732E' + 'blob: ascii short',X'48656C6C6F' + 'blob: ascii tab',X'5B095D' + 'blob: binary short',X'80' + 'blob: empty',X'' + 'blob: utf8 short',X'E682A8E5A5BDF09F9982' + 'blob: uuid',X'69BF8A9CD9F04777BD1193451D84CBCF' + 'double: -1.0',-1.0 + 'double: -inf',-Inf + 'double: 0.0',0.0 + 'double: 123.45',123.45 + 'double: inf',Inf + 'double: nan',NULL + 'integer: -1',-1 + 'integer: 0',0 + 'integer: 123',123 + 'integer: max',9223372036854775807 + 'integer: min',-9223372036854775808 + 'null',NULL + 'text: ascii apostrophe','['']' + 'text: ascii backslash','[\\]' + 'text: ascii double quote','["]' + 'text: ascii line feed','[ + ]' + 'text: ascii long','Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi tristique tempor condimentum. Pellentesque pharetra lacus non ante sollicitudin auctor. Vestibulum sit amet mauris vitae urna non luctus.' + 'text: ascii short','Hello' + 'text: ascii slash','[/]' + 'text: ascii tab','[\t]' + 'text: ascii url','https://github.com/groue/GRDB.swift' + 'text: empty','' + 'text: utf8 short','您好🙂' + + """) + } + } + + func test_quote_empty_results() throws { + try makeDatabaseQueue().write { db in + do { + // Columns + let stream = TestStream() + try db.dumpSQL("SELECT NULL WHERE NULL", format: .quote(), to: stream) + XCTAssertEqual(stream.output, "") + } + do { + // No columns + let stream = TestStream() + try db.dumpSQL("CREATE TABLE t(a)", format: .quote(), to: stream) + XCTAssertEqual(stream.output, "") + } + } + } + + func test_quote_headers() throws { + try makeRugbyDatabase().read { db in + do { + // Headers on + let stream = TestStream() + try db.dumpSQL("SELECT * FROM player ORDER BY id", format: .quote(header: true), to: stream) + XCTAssertEqual(stream.output, """ + 'id','teamId','name' + 1,'FRA','Antoine Dupond' + 2,'ENG','Owen Farrell' + 3,NULL,'Gwendal Roué' + + """) + } + do { + // Headers on, no result + let stream = TestStream() + try db.dumpSQL("SELECT * FROM player WHERE 0", format: .quote(header: true), to: stream) + XCTAssertEqual(stream.output, "") + } + do { + // Headers off + let stream = TestStream() + try db.dumpSQL("SELECT * FROM player ORDER BY id", format: .quote(header: false), to: stream) + XCTAssertEqual(stream.output, """ + 1,'FRA','Antoine Dupond' + 2,'ENG','Owen Farrell' + 3,NULL,'Gwendal Roué' + + """) + } + do { + // Headers off, no result + let stream = TestStream() + try db.dumpSQL("SELECT * FROM player WHERE 0", format: .quote(header: false), to: stream) + XCTAssertEqual(stream.output, "") + } + } + } + + func test_quote_duplicate_columns() throws { + try makeDatabaseQueue().read { db in + let stream = TestStream() + try db.dumpSQL("SELECT 1 AS name, 'foo' AS name", format: .quote(header: true), to: stream) + XCTAssertEqual(stream.output, """ + 'name','name' + 1,'foo' + + """) + } + } + + func test_quote_multiple_statements() throws { + try makeDatabaseQueue().write { db in + let stream = TestStream() + try db.dumpSQL( + """ + CREATE TABLE t(a, b); + INSERT INTO t VALUES (1, 'foo'); + INSERT INTO t VALUES (2, 'bar'); + SELECT * FROM t ORDER BY a; + SELECT b FROM t ORDER BY b; + SELECT NULL WHERE NULL; + """, + format: .quote(), + to: stream) + XCTAssertEqual(stream.output, """ + 1,'foo' + 2,'bar' + 'bar' + 'foo' + + """) + } + } + + func test_quote_separator() throws { + try makeRugbyDatabase().read { db in + do { + // Default separator + let stream = TestStream() + try db.dumpSQL("SELECT * FROM player ORDER BY id", format: .quote(header: true), to: stream) + XCTAssertEqual(stream.output, """ + 'id','teamId','name' + 1,'FRA','Antoine Dupond' + 2,'ENG','Owen Farrell' + 3,NULL,'Gwendal Roué' + + """) + } + do { + // Custom separator + let stream = TestStream() + try db.dumpSQL("SELECT * FROM player ORDER BY id", format: .quote(header: true, separator: "---"), to: stream) + XCTAssertEqual(stream.output, """ + 'id'---'teamId'---'name' + 1---'FRA'---'Antoine Dupond' + 2---'ENG'---'Owen Farrell' + 3---NULL---'Gwendal Roué' + + """) + } + } + } + + // MARK: - Dump error + + func test_dumpError() throws { + try makeDatabaseQueue().read { db in + let stream = TestStream() + do { + try db.dumpSQL( + """ + SELECT 'Hello'; + Not sql; + """, + to: stream) + XCTFail("Expected error") + } catch { + XCTAssertEqual(stream.output, """ + Hello + + """) + } + } + } + + // MARK: - Request dump + + func test_dumpRequest() throws { + try makeRugbyDatabase().read { db in + do { + // Default format + let stream = TestStream() + try db.dumpRequest(Player.orderByPrimaryKey(), to: stream) + XCTAssertEqual(stream.output, """ + 1|FRA|Antoine Dupond + 2|ENG|Owen Farrell + 3||Gwendal Roué + + """) + } + do { + // Custom format + let stream = TestStream() + try db.dumpRequest(Player.orderByPrimaryKey(), format: .json(), to: stream) + XCTAssertEqual(stream.output, """ + [{"id":1,"teamId":"FRA","name":"Antoine Dupond"}, + {"id":2,"teamId":"ENG","name":"Owen Farrell"}, + {"id":3,"teamId":null,"name":"Gwendal Roué"}] + + """) + } + } + } + + func test_dumpRequest_association_to_one() throws { + try makeRugbyDatabase().read { db in + let request = Player.orderByPrimaryKey().including(required: Player.team) + + do { + // Default format + let stream = TestStream() + try db.dumpRequest(request, to: stream) + XCTAssertEqual(stream.output, """ + 1|FRA|Antoine Dupond|FRA|XV de France|blue + 2|ENG|Owen Farrell|ENG|England Rugby|white + + """) + } + do { + // Custom format + let stream = TestStream() + try db.dumpRequest(request, format: .json(), to: stream) + XCTAssertEqual(stream.output, """ + [{"id":1,"teamId":"FRA","name":"Antoine Dupond","id":"FRA","name":"XV de France","color":"blue"}, + {"id":2,"teamId":"ENG","name":"Owen Farrell","id":"ENG","name":"England Rugby","color":"white"}] + + """) + } + } + } + + func test_dumpRequest_association_to_many() throws { + try makeRugbyDatabase().read { db in + let request = Team.orderByPrimaryKey().including(all: Team.players.orderByPrimaryKey()) + + do { + // Default format + let stream = TestStream() + try db.dumpRequest(request, to: stream) + XCTAssertEqual(stream.output, """ + ENG|England Rugby|white + FRA|XV de France|blue + + players + 1|FRA|Antoine Dupond + 2|ENG|Owen Farrell + + """) + } + do { + // Custom format + let stream = TestStream() + try db.dumpRequest(request, format: .json(), to: stream) + XCTAssertEqual(stream.output, """ + [{"id":"ENG","name":"England Rugby","color":"white"}, + {"id":"FRA","name":"XV de France","color":"blue"}] + + players + [{"id":1,"teamId":"FRA","name":"Antoine Dupond"}, + {"id":2,"teamId":"ENG","name":"Owen Farrell"}] + + """) + } + } + } + + // MARK: - Table dump + + func test_dumpTables_zero() throws { + try makeRugbyDatabase().read { db in + let stream = TestStream() + try db.dumpTables([], to: stream) + XCTAssertEqual(stream.output, "") + } + } + + func test_dumpTables_single() throws { + try makeRugbyDatabase().read { db in + do { + // Default format + let stream = TestStream() + try db.dumpTables(["player"], to: stream) + XCTAssertEqual(stream.output, """ + 1|FRA|Antoine Dupond + 2|ENG|Owen Farrell + 3||Gwendal Roué + + """) + } + do { + // Custom format + let stream = TestStream() + try db.dumpTables(["player"], format: .json(), to: stream) + XCTAssertEqual(stream.output, """ + [{"id":1,"teamId":"FRA","name":"Antoine Dupond"}, + {"id":2,"teamId":"ENG","name":"Owen Farrell"}, + {"id":3,"teamId":null,"name":"Gwendal Roué"}] + + """) + } + } + } + + func test_dumpTables_multiple() throws { + try makeRugbyDatabase().read { db in + do { + // Default format + let stream = TestStream() + try db.dumpTables(["player", "team"], to: stream) + XCTAssertEqual(stream.output, """ + player + 1|FRA|Antoine Dupond + 2|ENG|Owen Farrell + 3||Gwendal Roué + + team + ENG|England Rugby|white + FRA|XV de France|blue + + """) + } + do { + // Custom format + let stream = TestStream() + try db.dumpTables(["team", "player"], format: .json(), to: stream) + XCTAssertEqual(stream.output, """ + team + [{"id":"ENG","name":"England Rugby","color":"white"}, + {"id":"FRA","name":"XV de France","color":"blue"}] + + player + [{"id":1,"teamId":"FRA","name":"Antoine Dupond"}, + {"id":2,"teamId":"ENG","name":"Owen Farrell"}, + {"id":3,"teamId":null,"name":"Gwendal Roué"}] + + """) + } + } + } + + // MARK: - Database content dump + + func test_dumpContent() throws { + try makeRugbyDatabase().read { db in + do { + // Default format + let stream = TestStream() + try db.dumpContent(to: stream) + XCTAssertEqual(stream.output, """ + sqlite_master + CREATE TABLE "player" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "teamId" TEXT REFERENCES "team"("id"), "name" TEXT NOT NULL); + CREATE INDEX "player_on_teamId" ON "player"("teamId"); + CREATE TABLE "team" ("id" TEXT PRIMARY KEY NOT NULL, "name" TEXT NOT NULL, "color" TEXT NOT NULL); + + player + 1|FRA|Antoine Dupond + 2|ENG|Owen Farrell + 3||Gwendal Roué + + team + ENG|England Rugby|white + FRA|XV de France|blue + + """) + } + do { + // Custom format + let stream = TestStream() + try db.dumpContent(format: .json(), to: stream) + XCTAssertEqual(stream.output, """ + sqlite_master + CREATE TABLE "player" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "teamId" TEXT REFERENCES "team"("id"), "name" TEXT NOT NULL); + CREATE INDEX "player_on_teamId" ON "player"("teamId"); + CREATE TABLE "team" ("id" TEXT PRIMARY KEY NOT NULL, "name" TEXT NOT NULL, "color" TEXT NOT NULL); + + player + [{"id":1,"teamId":"FRA","name":"Antoine Dupond"}, + {"id":2,"teamId":"ENG","name":"Owen Farrell"}, + {"id":3,"teamId":null,"name":"Gwendal Roué"}] + + team + [{"id":"ENG","name":"England Rugby","color":"white"}, + {"id":"FRA","name":"XV de France","color":"blue"}] + + """) + } + } + } + + func test_dumpContent_empty_database() throws { + try makeDatabaseQueue().read { db in + let stream = TestStream() + try db.dumpContent(to: stream) + XCTAssertEqual(stream.output, """ + sqlite_master + + """) + } + } + + func test_dumpContent_empty_tables() throws { + try makeDatabaseQueue().write { db in + try db.execute(literal: """ + CREATE TABLE blue(name); + CREATE TABLE red(name); + CREATE TABLE yellow(name); + INSERT INTO red VALUES ('vermillon') + """) + let stream = TestStream() + try db.dumpContent(to: stream) + XCTAssertEqual(stream.output, """ + sqlite_master + CREATE TABLE blue(name); + CREATE TABLE red(name); + CREATE TABLE yellow(name); + + blue + + red + vermillon + + yellow + + """) + } + } + + func test_dumpContent_sqlite_master_ordering() throws { + try makeDatabaseQueue().write { db in + try db.execute(literal: """ + CREATE TABLE blue(name); + CREATE TABLE RED(name); + CREATE TABLE yellow(name); + CREATE INDEX index_blue1 ON blue(name); + CREATE INDEX INDEX_blue2 ON blue(name); + CREATE INDEX indexRed1 ON RED(name); + CREATE INDEX INDEXRed2 ON RED(name); + CREATE VIEW colors1 AS SELECT name FROM blue; + CREATE VIEW COLORS2 AS SELECT name FROM blue UNION SELECT name FROM yellow; + CREATE TRIGGER update_blue UPDATE OF name ON blue + BEGIN + DELETE FROM RED; + END; + CREATE TRIGGER update_RED UPDATE OF name ON RED + BEGIN + DELETE FROM yellow; + END; + """) + let stream = TestStream() + try db.dumpContent(to: stream) + XCTAssertEqual(stream.output, """ + sqlite_master + CREATE TABLE blue(name); + CREATE INDEX index_blue1 ON blue(name); + CREATE INDEX INDEX_blue2 ON blue(name); + CREATE TRIGGER update_blue UPDATE OF name ON blue + BEGIN + DELETE FROM RED; + END; + CREATE VIEW colors1 AS SELECT name FROM blue; + CREATE VIEW COLORS2 AS SELECT name FROM blue UNION SELECT name FROM yellow; + CREATE TABLE RED(name); + CREATE INDEX indexRed1 ON RED(name); + CREATE INDEX INDEXRed2 ON RED(name); + CREATE TRIGGER update_RED UPDATE OF name ON RED + BEGIN + DELETE FROM yellow; + END; + CREATE TABLE yellow(name); + + blue + + RED + + yellow + + """) + } + } + + // MARK: - Support Databases + + private func makeValuesDatabase() throws -> DatabaseQueue { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.execute(literal: """ + CREATE TABLE value(name, value); + + INSERT INTO value VALUES ('blob: ascii long', CAST('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi tristique tempor condimentum. Pellentesque pharetra lacus non ante sollicitudin auctor. Vestibulum sit amet mauris vitae urna non luctus.' AS BLOB)); + INSERT INTO value VALUES ('blob: ascii short', CAST('Hello' AS BLOB)); + INSERT INTO value VALUES ('blob: ascii tab', CAST('['||char(9)||']' AS BLOB)); + INSERT INTO value VALUES ('blob: ascii line feed', CAST('['||char(10)||']' AS BLOB)); + INSERT INTO value VALUES ('blob: ascii apostrophe', CAST('['']' AS BLOB)); + INSERT INTO value VALUES ('blob: ascii double quote', CAST('["]' AS BLOB)); + INSERT INTO value VALUES ('blob: binary short', X'80'); + INSERT INTO value VALUES ('blob: empty', x''); + INSERT INTO value VALUES ('blob: utf8 short', CAST('您好🙂' AS BLOB)); + INSERT INTO value VALUES ('blob: uuid', x'69BF8A9CD9F04777BD1193451D84CBCF'); + + INSERT INTO value VALUES ('double: -1.0', -1.0); + INSERT INTO value VALUES ('double: -inf', \(-1.0 / 0)); + INSERT INTO value VALUES ('double: 0.0', 0.0); + INSERT INTO value VALUES ('double: 123.45', 123.45); + INSERT INTO value VALUES ('double: inf', \(1.0 / 0)); + INSERT INTO value VALUES ('double: nan', \(0.0 / 0)); + + INSERT INTO value VALUES ('integer: 0', 0); + INSERT INTO value VALUES ('integer: -1', -1); + INSERT INTO value VALUES ('integer: 123', 123); + INSERT INTO value VALUES ('integer: max', 9223372036854775807); + INSERT INTO value VALUES ('integer: min', -9223372036854775808); + + INSERT INTO value VALUES ('null', NULL); + + INSERT INTO value VALUES ('text: empty', ''); + INSERT INTO value VALUES ('text: ascii apostrophe', '['']'); + INSERT INTO value VALUES ('text: ascii backslash', '[\\]'); + INSERT INTO value VALUES ('text: ascii double quote', '["]'); + INSERT INTO value VALUES ('text: ascii long', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi tristique tempor condimentum. Pellentesque pharetra lacus non ante sollicitudin auctor. Vestibulum sit amet mauris vitae urna non luctus.'); + INSERT INTO value VALUES ('text: ascii line feed', '['||char(10)||']'); + INSERT INTO value VALUES ('text: ascii short', 'Hello'); + INSERT INTO value VALUES ('text: ascii slash', '[/]'); + INSERT INTO value VALUES ('text: ascii tab', '['||char(9)||']'); + INSERT INTO value VALUES ('text: ascii url', 'https://github.com/groue/GRDB.swift'); + INSERT INTO value VALUES ('text: utf8 short', '您好🙂'); + """) + } + return dbQueue + } + + private func makeRugbyDatabase() throws -> DatabaseQueue { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "team") { t in + t.primaryKey("id", .text) + t.column("name", .text).notNull() + t.column("color", .text).notNull() + } + + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.belongsTo("team") + t.column("name", .text).notNull() + } + + let england = Team(id: "ENG", name: "England Rugby", color: "white") + let france = Team(id: "FRA", name: "XV de France", color: "blue") + + try england.insert(db) + try france.insert(db) + + _ = try Player(name: "Antoine Dupond", teamId: france.id).inserted(db) + _ = try Player(name: "Owen Farrell", teamId: england.id).inserted(db) + _ = try Player(name: "Gwendal Roué", teamId: nil).inserted(db) + } + return dbQueue + } +} diff --git a/Tests/GRDBTests/DatabaseReaderDumpTests.swift b/Tests/GRDBTests/DatabaseReaderDumpTests.swift new file mode 100644 index 000000000..303bfb81d --- /dev/null +++ b/Tests/GRDBTests/DatabaseReaderDumpTests.swift @@ -0,0 +1,212 @@ +import XCTest +import GRDB + +private final class TestStream: TextOutputStream { + var output: String + + init() { + output = "" + } + + func write(_ string: String) { + output.append(string) + } +} + +private struct Player: Codable, MutablePersistableRecord { + var id: Int64? + var name: String + var teamId: String? + + mutating func didInsert(_ inserted: InsertionSuccess) { + id = inserted.rowID + } +} + +private struct Team: Codable, PersistableRecord { + var id: String + var name: String + var color: String +} + +final class DatabaseReaderDumpTests: GRDBTestCase { + func test_dumpSQL() throws { + do { + // Default format + let stream = TestStream() + try makeDatabaseQueue().dumpSQL( + """ + CREATE TABLE t(a, b); + INSERT INTO t VALUES (1, 'foo'); + INSERT INTO t VALUES (2, 'bar'); + SELECT * FROM t ORDER BY a; + SELECT b FROM t ORDER BY b; + SELECT NULL WHERE NULL; + """, + to: stream) + XCTAssertEqual(stream.output, """ + 1|foo + 2|bar + bar + foo + + """) + } + do { + // Custom format + let stream = TestStream() + try makeDatabaseQueue().dumpSQL( + """ + CREATE TABLE t(a, b); + INSERT INTO t VALUES (1, 'foo'); + INSERT INTO t VALUES (2, 'bar'); + SELECT * FROM t ORDER BY a; + SELECT b FROM t ORDER BY b; + SELECT NULL WHERE NULL; + """, + format: .json(), + to: stream) + XCTAssertEqual(stream.output, """ + [{"a":1,"b":"foo"}, + {"a":2,"b":"bar"}] + [{"b":"bar"}, + {"b":"foo"}] + [] + + """) + } + } + + func test_dumpRequest() throws { + do { + // Default format + let stream = TestStream() + try makeRugbyDatabase().dumpRequest(Player.orderByPrimaryKey(), to: stream) + XCTAssertEqual(stream.output, """ + 1|FRA|Antoine Dupond + 2|ENG|Owen Farrell + 3||Gwendal Roué + + """) + } + do { + // Custom format + let stream = TestStream() + try makeRugbyDatabase().dumpRequest(Player.orderByPrimaryKey(), format: .json(), to: stream) + XCTAssertEqual(stream.output, """ + [{"id":1,"teamId":"FRA","name":"Antoine Dupond"}, + {"id":2,"teamId":"ENG","name":"Owen Farrell"}, + {"id":3,"teamId":null,"name":"Gwendal Roué"}] + + """) + } + } + + func test_dumpTables() throws { + do { + // Default format + let stream = TestStream() + try makeRugbyDatabase().dumpTables(["player", "team"], to: stream) + XCTAssertEqual(stream.output, """ + player + 1|FRA|Antoine Dupond + 2|ENG|Owen Farrell + 3||Gwendal Roué + + team + ENG|England Rugby|white + FRA|XV de France|blue + + """) + } + do { + // Custom format + let stream = TestStream() + try makeRugbyDatabase().dumpTables(["team", "player"], format: .json(), to: stream) + XCTAssertEqual(stream.output, """ + team + [{"id":"ENG","name":"England Rugby","color":"white"}, + {"id":"FRA","name":"XV de France","color":"blue"}] + + player + [{"id":1,"teamId":"FRA","name":"Antoine Dupond"}, + {"id":2,"teamId":"ENG","name":"Owen Farrell"}, + {"id":3,"teamId":null,"name":"Gwendal Roué"}] + + """) + } + } + + func test_dumpContent() throws { + do { + // Default format + let stream = TestStream() + try makeRugbyDatabase().dumpContent(to: stream) + XCTAssertEqual(stream.output, """ + sqlite_master + CREATE TABLE "player" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "teamId" TEXT REFERENCES "team"("id"), "name" TEXT NOT NULL); + CREATE INDEX "player_on_teamId" ON "player"("teamId"); + CREATE TABLE "team" ("id" TEXT PRIMARY KEY NOT NULL, "name" TEXT NOT NULL, "color" TEXT NOT NULL); + + player + 1|FRA|Antoine Dupond + 2|ENG|Owen Farrell + 3||Gwendal Roué + + team + ENG|England Rugby|white + FRA|XV de France|blue + + """) + } + do { + // Custom format + let stream = TestStream() + try makeRugbyDatabase().dumpContent(format: .json(), to: stream) + XCTAssertEqual(stream.output, """ + sqlite_master + CREATE TABLE "player" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "teamId" TEXT REFERENCES "team"("id"), "name" TEXT NOT NULL); + CREATE INDEX "player_on_teamId" ON "player"("teamId"); + CREATE TABLE "team" ("id" TEXT PRIMARY KEY NOT NULL, "name" TEXT NOT NULL, "color" TEXT NOT NULL); + + player + [{"id":1,"teamId":"FRA","name":"Antoine Dupond"}, + {"id":2,"teamId":"ENG","name":"Owen Farrell"}, + {"id":3,"teamId":null,"name":"Gwendal Roué"}] + + team + [{"id":"ENG","name":"England Rugby","color":"white"}, + {"id":"FRA","name":"XV de France","color":"blue"}] + + """) + } + } + + private func makeRugbyDatabase() throws -> DatabaseQueue { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "team") { t in + t.primaryKey("id", .text) + t.column("name", .text).notNull() + t.column("color", .text).notNull() + } + + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.belongsTo("team") + t.column("name", .text).notNull() + } + + let england = Team(id: "ENG", name: "England Rugby", color: "white") + let france = Team(id: "FRA", name: "XV de France", color: "blue") + + try england.insert(db) + try france.insert(db) + + _ = try Player(name: "Antoine Dupond", teamId: france.id).inserted(db) + _ = try Player(name: "Owen Farrell", teamId: england.id).inserted(db) + _ = try Player(name: "Gwendal Roué", teamId: nil).inserted(db) + } + return dbQueue + } +}