diff --git a/CHANGELOG.md b/CHANGELOG.md index c11a06535..9d31c3a7e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: #### 6.x Releases +- `6.28.x` Releases - [6.28.0](#6280) - `6.27.x` Releases - [6.27.0](#6270) - `6.26.x` Releases - [6.26.0](#6260) - `6.25.x` Releases - [6.25.0](#6250) @@ -125,6 +126,15 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- +## 6.28.0 + +Released July 11, 2024 + +- **New**: [#1570](https://github.com/groue/GRDB.swift/pull/1570) by [@groue](https://github.com/groue): Support single-value encoding +- **New**: Added `QueryInterfaceRequest.deleteAndFetchIds(_:)` which returns the set of deleted ids. +- **New**: Added `Set` methods `union`, `formUnion`, `intersection` and `formIntersection` that accept a cursor. +- **New**: `DatabaseUUIDEncodingStrategy` is Sendable. + ## 6.27.0 Released April 21, 2024 diff --git a/Documentation/CommonTableExpressions.md b/Documentation/CommonTableExpressions.md index 16373db74..4f447ad2b 100644 --- a/Documentation/CommonTableExpressions.md +++ b/Documentation/CommonTableExpressions.md @@ -251,7 +251,7 @@ let rightCTE = ... let association = LeftRecord.association( to: rightCTE, on: { left, right in - left[Column("x")] = right[Column("y")] + left[Column("x")] == right[Column("y")] }) ``` diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 5ae61b42b..9c58025bc 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '6.27.0' + s.version = '6.28.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index b8ee02155..af874297c 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -195,6 +195,56 @@ extension Set { // database cursors. try cursor.forEach { insert($0) } } + + /// Returns a new set with the elements of both this set and the + /// given cursor. + /// + /// If the set already contains one or more elements that are also in + /// the cursor, the existing members are kept. If the cursor contains + /// multiple instances of equivalent elements, only the first instance + /// is kept. + /// + /// - parameter cursor: A cursor of elements. + /// - returns: A new set with the unique elements of this set + /// and `cursor`. + public func union(_ cursor: some Cursor) throws -> Set { + var result = self + try result.formUnion(cursor) + return result + } + + /// Inserts the elements of the given cursor into the set. + /// + /// If the set already contains one or more elements that are also in + /// the cursor, the existing members are kept. If the cursor contains + /// multiple instances of equivalent elements, only the first instance + /// is kept. + /// + /// - parameter cursor: A cursor of elements. + public mutating func formUnion(_ cursor: some Cursor) throws { + while let element = try cursor.next() { + insert(element) + } + } + + /// Returns a new set with the elements that are common to both this set + /// and the given cursor. + /// + /// - parameter cursor: A cursor of elements. + /// - returns: A new set. + public func intersection(_ cursor: some Cursor) throws -> Set { + var result = self + try result.formIntersection(cursor) + return result + } + + /// Removes the elements of the set that aren’t also in the + /// given cursor. + /// + /// - parameter cursor: A cursor of elements. + public mutating func formIntersection(_ cursor: some Cursor) throws { + try formIntersection(Set(cursor)) + } } extension Sequence { diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index 028cfcc42..944d5c0f8 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -366,6 +366,7 @@ extension AssociationToMany { /// ### Top-Level Functions /// /// - ``abs(_:)-43n8v`` +/// - ``cast(_:as:)-63ttx`` /// - ``length(_:)-9dr2v`` public struct AssociationAggregate { fileprivate let preparation: AssociationAggregatePreparation diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index c573a2f3c..1d0d7cdad 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -61,6 +61,7 @@ /// ### Batch Delete /// /// - ``deleteAll(_:)`` +/// - ``deleteAndFetchIds(_:)`` /// - ``deleteAndFetchCursor(_:)`` /// - ``deleteAndFetchAll(_:)`` /// - ``deleteAndFetchSet(_:)`` @@ -528,7 +529,7 @@ extension QueryInterfaceRequest { /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: - /// . + /// . /// /// - parameter db: A database connection. /// - parameter selection: The returned columns (must not be empty). @@ -561,7 +562,7 @@ extension QueryInterfaceRequest { /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: - /// . + /// . /// /// - parameter db: A database connection. /// - returns: A ``RecordCursor`` over the deleted records. @@ -588,7 +589,7 @@ extension QueryInterfaceRequest { /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: - /// . + /// . /// /// - parameter db: A database connection. /// - returns: An array of deleted records. @@ -614,7 +615,7 @@ extension QueryInterfaceRequest { /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: - /// . + /// . /// /// - parameter db: A database connection. /// - returns: A set of deleted records. @@ -625,6 +626,41 @@ extension QueryInterfaceRequest { { try Set(deleteAndFetchCursor(db)) } + + /// Executes a `DELETE RETURNING` statement and returns the set of + /// deleted ids. + /// + /// For example: + /// + /// ```swift + /// // Fetch the ids of deleted players + /// // DELETE FROM player RETURNING id + /// let request = Player.all() + /// let deletedPlayerIds = try request.deleteAndFetchIds(db) + /// ``` + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - returns: A set of deleted ids. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) // Identifiable + public func deleteAndFetchIds(_ db: Database) + throws -> Set + where RowDecoder: TableRecord & Identifiable, + RowDecoder.ID: Hashable & DatabaseValueConvertible & StatementColumnConvertible + { + let primaryKey = try db.primaryKey(RowDecoder.databaseTableName) + GRDBPrecondition( + primaryKey.columns.count == 1, + "Fetching id requires a single-column primary key in the table \(databaseTableName)") + + let statement = try deleteAndFetchStatement(db, selection: [Column(primaryKey.columns[0])]) + + return try RowDecoder.ID.fetchSet(statement) + } #else /// Returns a `DELETE RETURNING` prepared statement. /// @@ -640,7 +676,7 @@ extension QueryInterfaceRequest { /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: - /// . + /// . /// /// - parameter db: A database connection. /// - parameter selection: The returned columns (must not be empty). @@ -674,7 +710,7 @@ extension QueryInterfaceRequest { /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: - /// . + /// . /// /// - parameter db: A database connection. /// - returns: A ``RecordCursor`` over the deleted records. @@ -702,7 +738,7 @@ extension QueryInterfaceRequest { /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: - /// . + /// . /// /// - parameter db: A database connection. /// - returns: An array of deleted records. @@ -729,7 +765,7 @@ extension QueryInterfaceRequest { /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: - /// . + /// . /// /// - parameter db: A database connection. /// - returns: A set of deleted records. @@ -741,6 +777,41 @@ extension QueryInterfaceRequest { { try Set(deleteAndFetchCursor(db)) } + + /// Executes a `DELETE RETURNING` statement and returns the set of + /// deleted ids. + /// + /// For example: + /// + /// ```swift + /// // Fetch the ids of deleted players + /// // DELETE FROM player RETURNING id + /// let request = Player.all() + /// let deletedPlayerIds = try request.deleteAndFetchIds(db) + /// ``` + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - returns: A set of deleted ids. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ + public func deleteAndFetchIds(_ db: Database) + throws -> Set + where RowDecoder: TableRecord & Identifiable, + RowDecoder.ID: Hashable & DatabaseValueConvertible & StatementColumnConvertible + { + let primaryKey = try db.primaryKey(RowDecoder.databaseTableName) + GRDBPrecondition( + primaryKey.columns.count == 1, + "Fetching id requires a single-column primary key in the table \(databaseTableName)") + + let statement = try deleteAndFetchStatement(db, selection: [Column(primaryKey.columns[0])]) + + return try RowDecoder.ID.fetchSet(statement) + } #endif } @@ -844,7 +915,7 @@ extension QueryInterfaceRequest { /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: - /// . + /// . /// /// - parameter db: A database connection. /// - parameter conflictResolution: A policy for conflict resolution. @@ -893,7 +964,7 @@ extension QueryInterfaceRequest { /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: - /// . + /// . /// /// - parameter db: A database connection. /// - parameter conflictResolution: A policy for conflict resolution. @@ -930,7 +1001,7 @@ extension QueryInterfaceRequest { /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: - /// . + /// . /// /// - parameter db: A database connection. /// - parameter conflictResolution: A policy for conflict resolution. @@ -962,7 +1033,7 @@ extension QueryInterfaceRequest { /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: - /// . + /// . /// /// - parameter db: A database connection. /// - parameter conflictResolution: A policy for conflict resolution. @@ -996,7 +1067,7 @@ extension QueryInterfaceRequest { /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: - /// . + /// . /// /// - parameter db: A database connection. /// - parameter conflictResolution: A policy for conflict resolution. @@ -1046,7 +1117,7 @@ extension QueryInterfaceRequest { /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: - /// . + /// . /// /// - parameter db: A database connection. /// - parameter conflictResolution: A policy for conflict resolution. @@ -1084,7 +1155,7 @@ extension QueryInterfaceRequest { /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: - /// . + /// . /// /// - parameter db: A database connection. /// - parameter conflictResolution: A policy for conflict resolution. @@ -1117,7 +1188,7 @@ extension QueryInterfaceRequest { /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: - /// . + /// . /// /// - parameter db: A database connection. /// - parameter conflictResolution: A policy for conflict resolution. diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index ad772c8df..eb63e59c4 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -2167,6 +2167,7 @@ extension SQLExpressible where Self == Column { /// - ``average(_:)`` /// - ``average(_:filter:)`` /// - ``capitalized`` +/// - ``cast(_:as:)-1dmu3`` /// - ``count(_:)`` /// - ``count(distinct:)`` /// - ``dateTime(_:_:)`` diff --git a/GRDB/Record/EncodableRecord+Encodable.swift b/GRDB/Record/EncodableRecord+Encodable.swift index c7816c672..4ecbd5f80 100644 --- a/GRDB/Record/EncodableRecord+Encodable.swift +++ b/GRDB/Record/EncodableRecord+Encodable.swift @@ -34,18 +34,7 @@ private class RecordEncoder: Encoder { } func singleValueContainer() -> SingleValueEncodingContainer { - // @itaiferber on https://forums.swift.org/t/how-to-encode-objects-of-unknown-type/12253/11 - // - // > Encoding a value into a single-value container is equivalent to - // > encoding the value directly into the encoder, with the primary - // > difference being the above: encoding into the encoder writes the - // > contents of a type into the encoder, while encoding to a - // > single-value container gives the encoder a chance to intercept the - // > type as a whole. - // - // Wait for somebody hitting this fatal error so that we can write a - // meaningful regression test. - fatalError("single value encoding is not supported") + self } private struct KeyedContainer: KeyedEncodingContainerProtocol { @@ -169,6 +158,80 @@ private class RecordEncoder: Encoder { } } +extension RecordEncoder: SingleValueEncodingContainer { + private func unsupportedSingleValueEncoding() { + fatalError("Can't encode a single value in a database row.") + } + + func encodeNil() throws { + unsupportedSingleValueEncoding() + } + + func encode(_ value: Bool) throws { + unsupportedSingleValueEncoding() + } + + func encode(_ value: String) throws { + unsupportedSingleValueEncoding() + } + + func encode(_ value: Double) throws { + unsupportedSingleValueEncoding() + } + + func encode(_ value: Float) throws { + unsupportedSingleValueEncoding() + } + + func encode(_ value: Int) throws { + unsupportedSingleValueEncoding() + } + + func encode(_ value: Int8) throws { + unsupportedSingleValueEncoding() + } + + func encode(_ value: Int16) throws { + unsupportedSingleValueEncoding() + } + + func encode(_ value: Int32) throws { + unsupportedSingleValueEncoding() + } + + func encode(_ value: Int64) throws { + unsupportedSingleValueEncoding() + } + + func encode(_ value: UInt) throws { + unsupportedSingleValueEncoding() + } + + func encode(_ value: UInt8) throws { + unsupportedSingleValueEncoding() + } + + func encode(_ value: UInt16) throws { + unsupportedSingleValueEncoding() + } + + func encode(_ value: UInt32) throws { + unsupportedSingleValueEncoding() + } + + func encode(_ value: UInt64) throws { + unsupportedSingleValueEncoding() + } + + func encode(_ value: T) throws where T : Encodable { + if let record = value as? EncodableRecord { + try record.encode(to: &_persistenceContainer) + } else { + try value.encode(to: self) + } + } +} + // MARK: - ColumnEncoder /// The encoder that encodes into a database column diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index 30bf4bb48..b1015c751 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -585,7 +585,7 @@ public enum DatabaseDateEncodingStrategy { /// var uuid: UUID /// } /// ``` -public enum DatabaseUUIDEncodingStrategy { +public enum DatabaseUUIDEncodingStrategy: Sendable { /// The strategy that uses formatting from the UUID type. /// /// It encodes UUIDs as 16-bytes data blobs. diff --git a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift index 78cc9352c..a287a3767 100644 --- a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift +++ b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift @@ -865,6 +865,8 @@ extension ValueConcurrentObserver: DatabaseCancellable { // Notify cancellation let (events, dbPool): (ValueObservationEvents?, DatabasePool?) = lock.synchronized { let events = notificationCallbacks?.events + // Set callbacks to nil so that we can't notify anything after + // the cancellation. notificationCallbacks = nil return (events, databaseAccess?.dbPool) } diff --git a/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift b/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift index ea084cce8..e7dc67bda 100644 --- a/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift +++ b/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift @@ -448,6 +448,8 @@ extension ValueWriteOnlyObserver: DatabaseCancellable { // Notify cancellation let (events, writer) = lock.synchronized { let events = notificationCallbacks?.events + // Set callbacks to nil so that we can't notify anything after + // the cancellation. notificationCallbacks = nil return (events, databaseAccess?.writer) } diff --git a/README.md b/README.md index cfef0ead4..79838cbd2 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ CI Status

-**Latest release**: April 21, 2024 • [version 6.27.0](https://github.com/groue/GRDB.swift/tree/v6.27.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) +**Latest release**: July 11, 2024 • [version 6.28.0](https://github.com/groue/GRDB.swift/tree/v6.28.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) **Requirements**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ • SQLite 3.19.3+ • Swift 5.7+ / Xcode 14+ @@ -2343,7 +2343,7 @@ See [Persistence Methods], [Upsert](#upsert), and [`updateChanges` methods](#the **Batch operations** can return updated or deleted values: -> **Warning**: Make sure you check the [documentation of the `RETURNING` clause](https://www.sqlite.org/lang_returning.html), which describes important limitations and caveats for batch operations. +> **Warning**: Make sure you check the [documentation of the `RETURNING` clause](https://www.sqlite.org/lang_returning.html#limitations_and_caveats), which describes important limitations and caveats for batch operations. ```swift let request = Player.filter(...)... diff --git a/Support/Info.plist b/Support/Info.plist index 43d72a701..a9a6ba2d3 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 6.27.0 + 6.28.0 CFBundleSignature ???? CFBundleVersion diff --git a/TODO.md b/TODO.md index b8fbe3ff3..096a98127 100644 --- a/TODO.md +++ b/TODO.md @@ -17,6 +17,7 @@ ## Features +- [ ] Detect when `ColumnExpression.noOverwrite` excludes a non-existing column. Code is in DOA.upsertStatement()`. We should not silently ignore non-existing columns, as demonstrated by . - [ ] Can Swift 5.5 help us with `select(.all)` (request of RowDecoder), `select(.id)` (request of RowDecoder.ID), `select(.rowid)` (request of Int64)? - [ ] Direct access to statement for bindings - [ ] Property wrapper that decodes dictionaries (but how to tell the key column?) diff --git a/Tests/GRDBTests/BackupTestCase.swift b/Tests/GRDBTests/BackupTestCase.swift index 1d969c6cb..33b2f1ac6 100644 --- a/Tests/GRDBTests/BackupTestCase.swift +++ b/Tests/GRDBTests/BackupTestCase.swift @@ -139,4 +139,13 @@ class BackupTestCase: GRDBTestCase { XCTAssertFalse(try db.tableExists("items")) } } + + // Test passes if it compiles. + // See + func testBackupToAnyDatabaseWriter( + _ reader: some DatabaseReader, + destination: any DatabaseWriter + ) throws { + try reader.backup(to: destination) + } } diff --git a/Tests/GRDBTests/CursorTests.swift b/Tests/GRDBTests/CursorTests.swift index 29930f223..01c104d8c 100644 --- a/Tests/GRDBTests/CursorTests.swift +++ b/Tests/GRDBTests/CursorTests.swift @@ -223,6 +223,32 @@ class CursorTests: GRDBTestCase { let set = try Set(cursor, minimumCapacity: 100) XCTAssertEqual(set, [1, 2, 3]) } + + do { + let cursor = AnyCursor([1, 2, 1, 3]) + let set: Set = [1, 4] + try XCTAssertEqual(set.union(cursor), [1, 2, 3, 4]) + } + + do { + let cursor = AnyCursor([1, 2, 1, 3]) + var set: Set = [1, 4] + try set.formUnion(cursor) + XCTAssertEqual(set, [1, 2, 3, 4]) + } + + do { + let cursor = AnyCursor([1, 2, 1, 3]) + let set: Set = [1, 3, 4] + try XCTAssertEqual(set.intersection(cursor), [1, 3]) + } + + do { + let cursor = AnyCursor([1, 2, 1, 3]) + var set: Set = [1, 3, 4] + try set.formIntersection(cursor) + XCTAssertEqual(set, [1, 3]) + } } func testDictionaryGrouping() throws { diff --git a/Tests/GRDBTests/DatabaseDumpTests.swift b/Tests/GRDBTests/DatabaseDumpTests.swift index c0551a0e8..06d86ccb2 100644 --- a/Tests/GRDBTests/DatabaseDumpTests.swift +++ b/Tests/GRDBTests/DatabaseDumpTests.swift @@ -51,10 +51,8 @@ final class DatabaseDumpTests: GRDBTestCase { 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 @@ -250,10 +248,8 @@ final class DatabaseDumpTests: GRDBTestCase { {"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}, @@ -413,18 +409,12 @@ final class DatabaseDumpTests: GRDBTestCase { 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\ @@ -604,10 +594,8 @@ final class DatabaseDumpTests: GRDBTestCase { 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 @@ -799,10 +787,8 @@ final class DatabaseDumpTests: GRDBTestCase { '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 @@ -1586,10 +1572,8 @@ final class DatabaseDumpTests: GRDBTestCase { 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); diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index e9a65cba4..9f9815824 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -2,6 +2,12 @@ import XCTest import GRDB class DatabaseMigratorTests : GRDBTestCase { + // Test passes if it compiles. + // See + func testMigrateAnyDatabaseWriter(writer: any DatabaseWriter) throws { + let migrator = DatabaseMigrator() + try migrator.migrate(writer) + } func testEmptyMigratorSync() throws { func test(writer: some DatabaseWriter) throws { diff --git a/Tests/GRDBTests/DatabaseReaderTests.swift b/Tests/GRDBTests/DatabaseReaderTests.swift index df99cf9cc..bf2d51c3f 100644 --- a/Tests/GRDBTests/DatabaseReaderTests.swift +++ b/Tests/GRDBTests/DatabaseReaderTests.swift @@ -2,13 +2,29 @@ import XCTest import GRDB class DatabaseReaderTests : GRDBTestCase { - func testAnyDatabaseReader() throws { // This test passes if this code compiles. let dbQueue = try DatabaseQueue() let _: any DatabaseReader = AnyDatabaseReader(dbQueue) } + // Test passes if it compiles. + func testInitFromGeneric(_ reader: some DatabaseReader) { + _ = AnyDatabaseReader(reader) + } + + // Test passes if it compiles. + // See + func testInitFromExistentialReader(_ reader: any DatabaseReader) { + _ = AnyDatabaseReader(reader) + } + + // Test passes if it compiles. + // See + func testInitFromExistentialWriter(_ writer: any DatabaseWriter) { + _ = AnyDatabaseReader(writer) + } + // MARK: - Read func testReadCanRead() throws { diff --git a/Tests/GRDBTests/DatabaseRegionObservationTests.swift b/Tests/GRDBTests/DatabaseRegionObservationTests.swift index dd4218a00..0625d91c6 100644 --- a/Tests/GRDBTests/DatabaseRegionObservationTests.swift +++ b/Tests/GRDBTests/DatabaseRegionObservationTests.swift @@ -2,6 +2,18 @@ import XCTest import GRDB class DatabaseRegionObservationTests: GRDBTestCase { + // Test passes if it compiles. + // See + func testAnyDatabaseWriter(writer: any DatabaseWriter) throws { + let observation = DatabaseRegionObservation(tracking: .fullDatabase) + + _ = observation.start(in: writer, onError: { _ in }, onChange: { _ in }) + + if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { + _ = observation.publisher(in: writer) + } + } + func testDatabaseRegionObservation_FullDatabase() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { diff --git a/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift b/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift index b6aa66fa8..339a4a497 100644 --- a/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift @@ -83,6 +83,97 @@ extension MutablePersistableRecordEncodableTests { XCTAssertEqual(string, "foo (MutablePersistableRecord)") } } + + // Regression test for + func testSingleValueContainer() throws { + struct Struct: Encodable { + let value: String + } + + struct Wrapper: MutablePersistableRecord, Encodable { + static var databaseTableName: String { "t1" } + var model: Model + var otherValue: String + + enum CodingKeys: String, CodingKey { + case otherValue + } + + func encode(to encoder: any Encoder) throws { + var modelContainer = encoder.singleValueContainer() + try modelContainer.encode(model) + + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(otherValue, forKey: .otherValue) + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "t1") { t in + t.column("value", .text) + t.column("otherValue", .text) + } + + var value = Wrapper(model: Struct(value: "foo"), otherValue: "bar") + try assert(value, isEncodedIn: ["value": "foo", "otherValue": "bar"]) + + try value.insert(db) + let row = try Row.fetchOne(db, sql: "SELECT value, otherValue FROM t1")! + XCTAssertEqual(row[0], "foo") + XCTAssertEqual(row[1], "bar") + } + } + + // Regression test for + // Here we test that `EncodableRecord` takes precedence over `Encodable` + // when a record is encoded with a `SingleValueEncodingContainer`. + func testSingleValueContainerWithEncodableRecord() throws { + struct Struct: Encodable, EncodableRecord { + let value: String + + func encode(to container: inout PersistenceContainer) throws { + container["column1"] = "test" + container["column2"] = 12 + } + } + + struct Wrapper: MutablePersistableRecord, Encodable { + static var databaseTableName: String { "t1" } + var model: Model + var otherValue: String + + enum CodingKeys: String, CodingKey { + case otherValue + } + + func encode(to encoder: any Encoder) throws { + var modelContainer = encoder.singleValueContainer() + try modelContainer.encode(model) + + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(otherValue, forKey: .otherValue) + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "t1") { t in + t.column("column1", .text) + t.column("column2", .integer) + t.column("otherValue", .text) + } + + var value = Wrapper(model: Struct(value: "foo"), otherValue: "bar") + try assert(value, isEncodedIn: ["column1": "test", "column2": 12, "otherValue": "bar"]) + + try value.insert(db) + let row = try Row.fetchOne(db, sql: "SELECT column1, column2, otherValue FROM t1")! + XCTAssertEqual(row[0], "test") + XCTAssertEqual(row[1], 12) + XCTAssertEqual(row[2], "bar") + } + } } // MARK: - Different kinds of single-value properties diff --git a/Tests/GRDBTests/SharedValueObservationTests.swift b/Tests/GRDBTests/SharedValueObservationTests.swift index ca53c61d9..156960805 100644 --- a/Tests/GRDBTests/SharedValueObservationTests.swift +++ b/Tests/GRDBTests/SharedValueObservationTests.swift @@ -2,6 +2,22 @@ import XCTest import GRDB class SharedValueObservationTests: GRDBTestCase { + // Test passes if it compiles. + // See + func testInitFromAnyDatabaseReader(reader: any DatabaseReader) { + _ = ValueObservation + .trackingConstantRegion { _ in } + .shared(in: reader) + } + + // Test passes if it compiles. + // See + func testInitFromAnyDatabaseWriter(writer: any DatabaseWriter) { + _ = ValueObservation + .trackingConstantRegion { _ in } + .shared(in: writer) + } + func test_immediate_observationLifetime() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in diff --git a/Tests/GRDBTests/TableRecordDeleteTests.swift b/Tests/GRDBTests/TableRecordDeleteTests.swift index 88e9c8174..e45252a55 100644 --- a/Tests/GRDBTests/TableRecordDeleteTests.swift +++ b/Tests/GRDBTests/TableRecordDeleteTests.swift @@ -364,6 +364,30 @@ class TableRecordDeleteTests: GRDBTestCase { } } + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) // Identifiable + func testRequestDeleteAndFetchIds() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3035000 else { + throw XCTSkip("RETURNING clause is not available") + } +#else + guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else { + throw XCTSkip("RETURNING clause is not available") + } +#endif + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try Person(id: 1, name: "Arthur", email: "arthur@example.com").insert(db) + try Person(id: 2, name: "Barbara", email: "barbara@example.com").insert(db) + try Person(id: 3, name: "Craig", email: "craig@example.com").insert(db) + + let request = Person.filter(Column("id") != 2) + let deletedIds = try request.deleteAndFetchIds(db) + XCTAssertEqual(deletedIds, [1, 3]) + } + } + func testJoinedRequestDeleteAll() throws { try makeDatabaseQueue().inDatabase { db in struct Player: MutablePersistableRecord { diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index f5c1e4908..7beeb4d6f 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -3,6 +3,33 @@ import Dispatch @testable import GRDB class ValueObservationTests: GRDBTestCase { + // Test passes if it compiles. + // See + func testStartFromAnyDatabaseReader(reader: any DatabaseReader) { + _ = ValueObservation + .trackingConstantRegion { _ in } + .start(in: reader, onError: { _ in }, onChange: { }) + } + + // Test passes if it compiles. + // See + func testStartFromAnyDatabaseWriter(writer: any DatabaseWriter) { + _ = ValueObservation + .trackingConstantRegion { _ in } + .start(in: writer, onError: { _ in }, onChange: { }) + } + + // Test passes if it compiles. + // See + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) + func testValuesFromAnyDatabaseWriter(writer: any DatabaseWriter) { + func observe( + fetch: @Sendable @escaping (Database) throws -> T + ) throws -> AsyncValueObservation { + ValueObservation.tracking(fetch).values(in: writer) + } + } + func testImmediateError() throws { struct TestError: Error { } @@ -748,6 +775,53 @@ class ValueObservationTests: GRDBTestCase { try test(makeDatabasePool()) } + func testIssue1550() throws { + func test(_ writer: some DatabaseWriter) throws { + try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + // Start observing + var counts: [Int] = [] + let cancellable = ValueObservation + .trackingConstantRegion { try Table("t").fetchCount($0) } + .start(in: writer) { error in + XCTFail("Unexpected error: \(error)") + } onChange: { count in + counts.append(count) + } + + // Perform a write after cancellation, but before the + // observation could schedule the removal of its transaction + // observer from the writer dispatch queue. + let semaphore = DispatchSemaphore(value: 0) + writer.asyncWriteWithoutTransaction { db in + semaphore.wait() + do { + try db.execute(sql: "INSERT INTO t(id) VALUES (NULL)") + } catch { + XCTFail("Unexpected error: \(error)") + } + } + cancellable.cancel() + semaphore.signal() + + // Wait until a second write could run, after the observation + // has removed its transaction observer from the writer + // dispatch queue. + let secondWriteExpectation = expectation(description: "cancelled") + writer.asyncWriteWithoutTransaction { _ in + secondWriteExpectation.fulfill() + } + wait(for: [secondWriteExpectation], timeout: 5) + + // We should not have been notified of the first write, because + // it was performed after cancellation. + XCTAssertFalse(counts.contains(1)) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + func testIssue1209() throws { func test(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write {