Merge branch 'development'

This commit is contained in:
Gwendal Roué committed 2024-07-11 07:49:09 +02:00
commit 78448cf8f4
24 files changed
+510 -51

No files matched your search

+10
View File
@@ -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
+1 -1
View File
@@ -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")]
})
```
+1 -1
View File
@@ -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.'
+50
View File
@@ -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<Element>) throws -> Set<Element> {
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<Element>) 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<Element>) throws -> Set<Element> {
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<Element>) throws {
try formIntersection(Set(cursor))
}
}
extension Sequence {
@@ -366,6 +366,7 @@ extension AssociationToMany {
/// ### Top-Level Functions
///
/// - ``abs(_:)-43n8v``
/// - ``cast(_:as:)-63ttx``
/// - ``length(_:)-9dr2v``
public struct AssociationAggregate<RowDecoder> {
fileprivate let preparation: AssociationAggregatePreparation<RowDecoder>
@@ -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:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#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:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#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:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#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:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#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:
/// <https://www.sqlite.org/lang_returning.html#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<RowDecoder.ID>
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:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#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:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#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:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#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:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#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:
/// <https://www.sqlite.org/lang_returning.html#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<RowDecoder.ID>
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:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#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:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#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:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#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:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#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:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#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:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#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:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#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:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
@@ -2167,6 +2167,7 @@ extension SQLExpressible where Self == Column {
/// - ``average(_:)``
/// - ``average(_:filter:)``
/// - ``capitalized``
/// - ``cast(_:as:)-1dmu3``
/// - ``count(_:)``
/// - ``count(distinct:)``
/// - ``dateTime(_:_:)``
+75 -12
View File
@@ -34,18 +34,7 @@ private class RecordEncoder<Record: EncodableRecord>: 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<Key: CodingKey>: KeyedEncodingContainerProtocol {
@@ -169,6 +158,80 @@ private class RecordEncoder<Record: EncodableRecord>: 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<T>(_ 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
+1 -1
View File
@@ -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.
@@ -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)
}
@@ -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)
}
+2 -2
View File
@@ -15,7 +15,7 @@
<a href="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml"><img alt="CI Status" src="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml/badge.svg?branch=master"></a>
</p>
**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+ &bull; SQLite 3.19.3+ &bull; 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(...)...
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>6.27.0</string>
<string>6.28.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+1
View File
@@ -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 <https://github.com/groue/GRDB.swift/issues/1539>.
- [ ] 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?)
+9
View File
@@ -139,4 +139,13 @@ class BackupTestCase: GRDBTestCase {
XCTAssertFalse(try db.tableExists("items"))
}
}
// Test passes if it compiles.
// See <https://github.com/groue/GRDB.swift/issues/1541>
func testBackupToAnyDatabaseWriter(
_ reader: some DatabaseReader,
destination: any DatabaseWriter
) throws {
try reader.backup(to: destination)
}
}
+26
View File
@@ -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<Int> = [1, 4]
try XCTAssertEqual(set.union(cursor), [1, 2, 3, 4])
}
do {
let cursor = AnyCursor([1, 2, 1, 3])
var set: Set<Int> = [1, 4]
try set.formUnion(cursor)
XCTAssertEqual(set, [1, 2, 3, 4])
}
do {
let cursor = AnyCursor([1, 2, 1, 3])
let set: Set<Int> = [1, 3, 4]
try XCTAssertEqual(set.intersection(cursor), [1, 3])
}
do {
let cursor = AnyCursor([1, 2, 1, 3])
var set: Set<Int> = [1, 3, 4]
try set.formIntersection(cursor)
XCTAssertEqual(set, [1, 3])
}
}
func testDictionaryGrouping() throws {
-16
View File
@@ -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);
@@ -2,6 +2,12 @@ import XCTest
import GRDB
class DatabaseMigratorTests : GRDBTestCase {
// Test passes if it compiles.
// See <https://github.com/groue/GRDB.swift/issues/1541>
func testMigrateAnyDatabaseWriter(writer: any DatabaseWriter) throws {
let migrator = DatabaseMigrator()
try migrator.migrate(writer)
}
func testEmptyMigratorSync() throws {
func test(writer: some DatabaseWriter) throws {
+17 -1
View File
@@ -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 <https://github.com/groue/GRDB.swift/issues/1541>
func testInitFromExistentialReader(_ reader: any DatabaseReader) {
_ = AnyDatabaseReader(reader)
}
// Test passes if it compiles.
// See <https://github.com/groue/GRDB.swift/issues/1541>
func testInitFromExistentialWriter(_ writer: any DatabaseWriter) {
_ = AnyDatabaseReader(writer)
}
// MARK: - Read
func testReadCanRead() throws {
@@ -2,6 +2,18 @@ import XCTest
import GRDB
class DatabaseRegionObservationTests: GRDBTestCase {
// Test passes if it compiles.
// See <https://github.com/groue/GRDB.swift/issues/1541>
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 {
@@ -83,6 +83,97 @@ extension MutablePersistableRecordEncodableTests {
XCTAssertEqual(string, "foo (MutablePersistableRecord)")
}
}
// Regression test for <https://github.com/groue/GRDB.swift/issues/1565>
func testSingleValueContainer() throws {
struct Struct: Encodable {
let value: String
}
struct Wrapper<Model: Encodable>: 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 <https://github.com/groue/GRDB.swift/issues/1565>
// 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<Model: Encodable>: 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
@@ -2,6 +2,22 @@ import XCTest
import GRDB
class SharedValueObservationTests: GRDBTestCase {
// Test passes if it compiles.
// See <https://github.com/groue/GRDB.swift/issues/1541>
func testInitFromAnyDatabaseReader(reader: any DatabaseReader) {
_ = ValueObservation
.trackingConstantRegion { _ in }
.shared(in: reader)
}
// Test passes if it compiles.
// See <https://github.com/groue/GRDB.swift/issues/1541>
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
@@ -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 {
@@ -3,6 +3,33 @@ import Dispatch
@testable import GRDB
class ValueObservationTests: GRDBTestCase {
// Test passes if it compiles.
// See <https://github.com/groue/GRDB.swift/issues/1541>
func testStartFromAnyDatabaseReader(reader: any DatabaseReader) {
_ = ValueObservation
.trackingConstantRegion { _ in }
.start(in: reader, onError: { _ in }, onChange: { })
}
// Test passes if it compiles.
// See <https://github.com/groue/GRDB.swift/issues/1541>
func testStartFromAnyDatabaseWriter(writer: any DatabaseWriter) {
_ = ValueObservation
.trackingConstantRegion { _ in }
.start(in: writer, onError: { _ in }, onChange: { })
}
// Test passes if it compiles.
// See <https://github.com/groue/GRDB.swift/issues/1541>
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
func testValuesFromAnyDatabaseWriter(writer: any DatabaseWriter) {
func observe<T>(
fetch: @Sendable @escaping (Database) throws -> T
) throws -> AsyncValueObservation<T> {
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 {