Compare commits

...
17 Commits
Author SHA1 Message Date
Gwendal Roué 389b14ede0 Tests for super encoders WIP 2024-03-18 19:07:07 +01:00
Gwendal Roué 4e0ab25106 Fix flaky tests due to Recorder incorrect critical section 2024-03-17 22:40:38 +01:00
Gwendal Roué c52db6095a Stop testing test_CocoaPodsLint
Because it does no longer work due to https://github.com/CocoaPods/CocoaPods/issues/11839
2024-03-17 22:15:08 +01:00
Gwendal Roué 1464940eeb Merge pull request #1511 from groue/dev/schema-dump
Database schema dump
2024-03-17 22:11:55 +01:00
Gwendal Roué f274e464cd CHANGELOG 2024-03-17 20:45:48 +01:00
Gwendal Roué c3e7736534 Dump schema 2024-03-17 20:45:31 +01:00
Gwendal Roué 9b95dd5be1 Merge pull request #1510 from groue/dev/trivial-sendable-conformances
Add Sendable conformances and unavailabilities
2024-03-17 20:45:01 +01:00
Gwendal Roué 77da5f4a30 CHANGELOG 2024-03-17 19:18:30 +01:00
Gwendal Roué 43ced9b2f0 Trivial Sendable conformances
Either added, either made explicitly unavailable.
2024-03-17 18:25:04 +01:00
Gwendal Roué 4ffad63f1b Fix Swift 5.10 warning on WALSnapshot 2024-03-17 17:55:25 +01:00
Gwendal Roué 62e7ea1ef2 CHANGELOG 2024-03-17 17:55:15 +01:00
Gwendal Roué 91492b849d Merge pull request #1508 from groue/dev/issue-1500
Fix ValueObservation mishandling of database schema modification
2024-03-17 17:53:28 +01:00
Gwendal Roué d54d0abc07 Fix WALSnapshotTransaction so that it clears its schema cache if needed 2024-03-17 16:13:35 +01:00
Gwendal Roué 3b096b38e7 Failing test for #1500 2024-03-17 16:13:35 +01:00
Gwendal Roué 9593297cf0 CHANGELOG 2024-03-17 14:54:07 +01:00
Gwendal Roué 8ac5591189 Merge pull request #1503 from simba909/master
Conform Database.ColumnType to Sendable
2024-03-17 14:51:44 +01:00
Simon Jarbrant 4232fa687d Conform Database.ColumnType to Sendable 2024-03-08 14:28:36 +01:00
61 changed files with 708 additions and 164 deletions

No files matched your search

+7
View File
@@ -123,6 +123,13 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## Next Release
- **New**: [#1503](https://github.com/groue/GRDB.swift/pull/1503) by [@simba909](https://github.com/simba909): Conform Database.ColumnType to Sendable
- **New**: [#1510](https://github.com/groue/GRDB.swift/pull/1510) by [@groue](https://github.com/groue): Add Sendable conformances and unavailabilities
- **New**: [#1511](https://github.com/groue/GRDB.swift/pull/1511) by [@groue](https://github.com/groue): Database schema dump
- **Fixed**: [#1508](https://github.com/groue/GRDB.swift/pull/1508) by [@groue](https://github.com/groue): Fix ValueObservation mishandling of database schema modification
## 6.25.0
Released February 25, 2024
+1 -1
View File
@@ -294,7 +294,7 @@ public struct Configuration {
/// connection is opened.
///
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_journal_mode>
public enum JournalModeConfiguration {
public enum JournalModeConfiguration: Sendable {
/// The default setup has ``DatabaseQueue`` perform no specific
/// configuration of the journal mode, and ``DatabasePool``
/// configure the database for the WAL mode (just like the
+40
View File
@@ -733,6 +733,11 @@ public final class AnyCursor<Element>: Cursor {
}
}
// Explicit non-conformance to Sendable: a type-erased cursor can't be more
// sendable than non-sendable cursors (such as `DatabaseCursor`).
@available(*, unavailable)
extension AnyCursor: Sendable { }
/// A `Cursor` that consumes and drops n elements from an underlying `Base`
/// cursor before possibly returning the first available element.
public final class DropFirstCursor<Base: Cursor> {
@@ -747,6 +752,11 @@ public final class DropFirstCursor<Base: Cursor> {
}
}
// Explicit non-conformance to Sendable: `DropFirstCursor` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension DropFirstCursor: Sendable { }
extension DropFirstCursor: Cursor {
public func next() throws -> Base.Element? {
while dropped < limit {
@@ -773,6 +783,11 @@ public final class DropWhileCursor<Base: Cursor> {
}
}
// Explicit non-conformance to Sendable: `DropWhileCursor` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension DropWhileCursor: Sendable { }
extension DropWhileCursor: Cursor {
public func next() throws -> Base.Element? {
if predicateHasFailed {
@@ -818,6 +833,11 @@ public final class EnumeratedCursor<Base: Cursor> {
}
}
// Explicit non-conformance to Sendable: `EnumeratedCursor` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension EnumeratedCursor: Sendable { }
extension EnumeratedCursor: Cursor {
public func next() throws -> (Int, Base.Element)? {
guard let element = try base.next() else { return nil }
@@ -875,6 +895,11 @@ public final class FlattenCursor<Base: Cursor> where Base.Element: Cursor {
}
}
// Explicit non-conformance to Sendable: `EnumeratedCursor` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension FlattenCursor: Sendable { }
extension FlattenCursor: Cursor {
public func next() throws -> Base.Element.Element? {
while true {
@@ -901,6 +926,11 @@ public final class MapCursor<Base: Cursor, Element> {
}
}
// Explicit non-conformance to Sendable: There is no known reason for making
// it thread-safe (`transform` a Sendable closure).
@available(*, unavailable)
extension MapCursor: Sendable { }
extension MapCursor: Cursor {
public func next() throws -> Element? {
guard let element = try base.next() else { return nil }
@@ -927,6 +957,11 @@ public final class PrefixCursor<Base: Cursor> {
}
}
// Explicit non-conformance to Sendable: `PrefixCursor` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension PrefixCursor: Sendable { }
extension PrefixCursor: Cursor {
public func next() throws -> Base.Element? {
if taken >= maxLength { return nil }
@@ -954,6 +989,11 @@ public final class PrefixWhileCursor<Base: Cursor> {
}
}
// Explicit non-conformance to Sendable: `PrefixCursor` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension PrefixWhileCursor: Sendable { }
extension PrefixWhileCursor: Cursor {
public func next() throws -> Base.Element? {
if !predicateHasFailed, let nextElement = try base.next() {
+6 -6
View File
@@ -997,7 +997,7 @@ extension Database {
///
/// - [pragma `table_info`](https://www.sqlite.org/pragma.html#pragma_table_info)
/// - [pragma `table_xinfo`](https://www.sqlite.org/pragma.html#pragma_table_xinfo)
public struct ColumnInfo: FetchableRecord {
public struct ColumnInfo: FetchableRecord, Sendable {
let cid: Int
let hidden: Int?
@@ -1083,9 +1083,9 @@ public struct ColumnInfo: FetchableRecord {
///
/// - [pragma `index_list`](https://www.sqlite.org/pragma.html#pragma_index_list)
/// - [pragma `index_info`](https://www.sqlite.org/pragma.html#pragma_index_info)
public struct IndexInfo {
public struct IndexInfo: Sendable{
/// The origin of an index.
public struct Origin: RawRepresentable, Equatable, DatabaseValueConvertible {
public struct Origin: RawRepresentable, Equatable, DatabaseValueConvertible, Sendable {
public var rawValue: String
public init(rawValue: String) {
@@ -1158,7 +1158,7 @@ public struct IndexInfo {
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_foreign_key_check>
public struct ForeignKeyViolation {
public struct ForeignKeyViolation: Sendable {
/// The name of the table that contains the foreign key.
public var originTable: String
@@ -1307,7 +1307,7 @@ extension ForeignKeyViolation: CustomStringConvertible {
/// pk.rowIDColumn // nil
/// pk.isRowID // false
/// ```
public struct PrimaryKeyInfo {
public struct PrimaryKeyInfo: Sendable {
private enum Impl {
/// The hidden rowID.
case hiddenRowID
@@ -1433,7 +1433,7 @@ public struct PrimaryKeyInfo {
/// `Database` method.
///
/// Related SQLite documentation: [pragma `foreign_key_list`](https://www.sqlite.org/pragma.html#pragma_foreign_key_list).
public struct ForeignKeyInfo {
public struct ForeignKeyInfo: Sendable {
/// The first column in the output of the `foreign_key_list` pragma.
public var id: Int
+5
View File
@@ -361,6 +361,11 @@ public class SQLStatementCursor {
}
}
// Explicit non-conformance to Sendable: database cursors must be used from
// a serialized database access dispatch queue.
@available(*, unavailable)
extension SQLStatementCursor: Sendable { }
extension SQLStatementCursor: Cursor {
public func next() throws -> Statement? {
guard offset < cString.count - 1 /* trailing \0 */ else {
+24 -8
View File
@@ -70,6 +70,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
///
/// - ``dumpContent(format:to:)``
/// - ``dumpRequest(_:format:to:)``
/// - ``dumpSchema(to:)``
/// - ``dumpSQL(_:format:to:)``
/// - ``dumpTables(_:format:tableHeader:stableOrder:to:)``
/// - ``DumpFormat``
@@ -1729,6 +1730,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
}
// Explicit non-conformance to Sendable: `Database` must be used from a
// serialized database access dispatch queue (see `SerializedDatabase`).
@available(*, unavailable)
extension Database: Sendable { }
#if SQLITE_HAS_CODEC
extension Database {
@@ -1854,7 +1860,7 @@ extension Database {
/// The available checkpoint modes.
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/wal_checkpoint_v2.html>
public enum CheckpointMode: CInt {
public enum CheckpointMode: CInt, Sendable {
/// The `SQLITE_CHECKPOINT_PASSIVE` mode.
case passive = 0
@@ -1873,7 +1879,7 @@ extension Database {
/// Related SQLite documentation:
/// - <https://www.sqlite.org/datatype3.html#collating_sequences>
/// - <https://www.sqlite.org/datatype3.html#collation>
public struct CollationName: RawRepresentable, Hashable {
public struct CollationName: RawRepresentable, Hashable, Sendable {
public let rawValue: String
/// Creates a collation name.
@@ -1910,7 +1916,7 @@ extension Database {
///
/// For more information, see
/// [Datatypes In SQLite](https://www.sqlite.org/datatype3.html).
public struct ColumnType: RawRepresentable, Hashable {
public struct ColumnType: RawRepresentable, Hashable, Sendable {
/// The SQL for the column type (`"TEXT"`, `"BLOB"`, etc.)
public let rawValue: String
@@ -1962,7 +1968,7 @@ extension Database {
/// An SQLite conflict resolution.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_conflict.html>
public enum ConflictResolution: String {
public enum ConflictResolution: String, Sendable {
/// The `ROLLBACK` conflict resolution.
case rollback = "ROLLBACK"
@@ -1982,7 +1988,7 @@ extension Database {
/// A foreign key action.
///
/// Related SQLite documentation: <https://www.sqlite.org/foreignkeys.html>
public enum ForeignKeyAction: String {
public enum ForeignKeyAction: String, Sendable {
/// The `CASCADE` foreign key action.
case cascade = "CASCADE"
@@ -2005,7 +2011,7 @@ extension Database {
/// ``Database/trace(options:_:)`` method.
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/c_trace.html>
public struct TracingOptions: OptionSet {
public struct TracingOptions: OptionSet, Sendable {
/// The raw trace event code.
public let rawValue: CInt
@@ -2138,7 +2144,7 @@ extension Database {
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
@frozen
public enum TransactionCompletion {
public enum TransactionCompletion: Sendable {
case commit
case rollback
}
@@ -2146,7 +2152,7 @@ extension Database {
/// A transaction kind.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
public enum TransactionKind: String {
public enum TransactionKind: String, Sendable {
/// The `DEFERRED` transaction kind.
case deferred = "DEFERRED"
@@ -2179,3 +2185,13 @@ extension Database {
}
}
}
// Explicit non-conformance to Sendable: a trace event contains transient
// information.
@available(*, unavailable)
extension Database.TraceEvent: Sendable { }
// Explicit non-conformance to Sendable: a trace event contains transient
// information.
@available(*, unavailable)
extension Database.TraceEvent.Statement: Sendable { }
+1 -1
View File
@@ -1,7 +1,7 @@
/// Describe the progress of a database backup.
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/backup_finish.html>
public struct DatabaseBackupProgress {
public struct DatabaseBackupProgress: Sendable {
/// The number of pages still to be backed up.
///
/// It is the result of the `sqlite3_backup_remaining` function.
+1
View File
@@ -37,6 +37,7 @@ import Dispatch
///
/// - ``dumpContent(format:to:)``
/// - ``dumpRequest(_:format:to:)``
/// - ``dumpSchema(to:)``
/// - ``dumpSQL(_:format:to:)``
/// - ``dumpTables(_:format:tableHeader:stableOrder:to:)``
/// - ``DumpFormat``
+1 -1
View File
@@ -40,7 +40,7 @@
///
/// - ``isModified(byEventsOfKind:)``
/// - ``isModified(by:)``
public struct DatabaseRegion {
public struct DatabaseRegion: Sendable {
private let tableRegions: [CaseInsensitiveIdentifier: TableRegion]?
private init(tableRegions: [CaseInsensitiveIdentifier: TableRegion]?) {
+5
View File
@@ -222,6 +222,11 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
}
}
// Explicit non-conformance to Sendable: database cursors must be used from
// a serialized database access dispatch queue.
@available(*, unavailable)
extension DatabaseValueCursor: Sendable { }
/// DatabaseValueConvertible comes with built-in methods that allow to fetch
/// cursors, arrays, or single values:
///
+5
View File
@@ -152,6 +152,11 @@ public struct PreparedRequest {
}
}
// Explicit non-conformance to Sendable: `PreparedRequest` contains
// a statement.
@available(*, unavailable)
extension PreparedRequest: Sendable { }
extension PreparedRequest: Refinable { }
// MARK: - AdaptedFetchRequest
+12 -1
View File
@@ -245,6 +245,12 @@ public final class Row {
}
}
// Explicit non-conformance to Sendable: a row contains transient
// information. TODO GRDB7: split non sendable statement rows from sendable
// copied rows.
@available(*, unavailable)
extension Row: Sendable { }
extension Row {
// MARK: - Columns
@@ -1377,6 +1383,11 @@ public final class RowCursor: DatabaseCursor {
public func _element(sqliteStatement: SQLiteStatement) -> Row { _row }
}
// Explicit non-conformance to Sendable: database cursors must be used from
// a serialized database access dispatch queue.
@available(*, unavailable)
extension RowCursor: Sendable { }
extension Row {
// MARK: - Fetching From Prepared Statement
@@ -2059,7 +2070,7 @@ typealias RowIndex = Row.Index
extension Row {
/// An index to a (column, value) pair in a ``Row``.
public struct Index {
public struct Index: Sendable {
let index: Int
init(_ index: Int) { self.index = index }
}
+4 -4
View File
@@ -378,7 +378,7 @@ extension RowAdapter {
///
/// This limit adapter may turn out useful in some narrow use cases. You'll
/// be happy to find it when you need it.
public struct EmptyRowAdapter: RowAdapter {
public struct EmptyRowAdapter: RowAdapter, Sendable {
/// Creates an `EmptyRowAdapter`.
public init() { }
@@ -403,7 +403,7 @@ public struct EmptyRowAdapter: RowAdapter {
///
/// Note that columns that are not present in the dictionary are not present
/// in the resulting adapted row.
public struct ColumnMapping: RowAdapter {
public struct ColumnMapping: RowAdapter, Sendable {
/// A dictionary from mapped column names to column names in a base row.
let mapping: [String: String]
@@ -444,7 +444,7 @@ public struct ColumnMapping: RowAdapter {
/// // [c:2, d: 3]
/// try Row.fetchOne(db, sql: sql, adapter: adapter)!
/// ```
public struct SuffixRowAdapter: RowAdapter {
public struct SuffixRowAdapter: RowAdapter, Sendable {
/// The suffix index
let index: Int
@@ -473,7 +473,7 @@ public struct SuffixRowAdapter: RowAdapter {
/// // [b:1 c:2]
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
/// ```
public struct RangeRowAdapter: RowAdapter {
public struct RangeRowAdapter: RowAdapter, Sendable {
/// The range
let range: CountableRange<Int>
+5
View File
@@ -623,6 +623,11 @@ public final class Statement {
}
}
// Explicit non-conformance to Sendable: statements must be used from
// a serialized database access dispatch queue.
@available(*, unavailable)
extension Statement: Sendable { }
extension Statement: CustomStringConvertible {
public var description: String {
SchedulingWatchdog.allows(database) ? sql : "Statement"
@@ -241,6 +241,11 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
}
}
// Explicit non-conformance to Sendable: database cursors must be used from
// a serialized database access dispatch queue.
@available(*, unavailable)
extension FastDatabaseValueCursor: Sendable { }
/// Types that adopt both DatabaseValueConvertible and
/// StatementColumnConvertible can be efficiently initialized from
/// database values.
@@ -1,10 +1,10 @@
import Foundation
/// A database value that holds date components.
public struct DatabaseDateComponents {
public struct DatabaseDateComponents: Sendable {
/// The SQLite formats for date components.
public enum Format: String {
public enum Format: String, Sendable {
/// The format "yyyy-MM-dd".
case YMD = "yyyy-MM-dd"
+8 -3
View File
@@ -135,7 +135,7 @@ extension Database {
}
/// The extent of the observation performed by a ``TransactionObserver``.
public enum TransactionObservationExtent {
public enum TransactionObservationExtent: Sendable {
/// Observation lasts until observer is deallocated.
case observerLifetime
/// Observation lasts until the next transaction.
@@ -1056,7 +1056,7 @@ struct StatementObservation {
/// See the ``TransactionObserver/observes(eventsOfKind:)`` method in the
/// ``TransactionObserver`` protocol for more information.
@frozen
public enum DatabaseEventKind {
public enum DatabaseEventKind: Sendable {
/// The insertion of a row in a database table.
case insert(tableName: String)
@@ -1109,7 +1109,7 @@ protocol DatabaseEventProtocol {
/// ``TransactionObserver`` protocol for more information.
public struct DatabaseEvent {
/// An event kind.
public enum Kind: CInt {
public enum Kind: CInt, Sendable {
/// An insertion event
case insert = 18 // SQLITE_INSERT
@@ -1173,6 +1173,11 @@ public struct DatabaseEvent {
}
}
// Explicit non-conformance to Sendable: this type can't be made Sendable
// until GRDB7 where we can distinguish between a transient event and its copy.
@available(*, unavailable)
extension DatabaseEvent: Sendable { }
extension DatabaseEvent: DatabaseEventProtocol {
func send(to observer: TransactionObservation) {
observer.databaseDidChange(with: self)
+3 -1
View File
@@ -21,7 +21,9 @@
/// Yes, this is an awfully complex logic.
///
/// See <https://www.sqlite.org/c3ref/snapshot.html>.
final class WALSnapshot: Sendable {
final class WALSnapshot: @unchecked Sendable {
// @unchecked because sqlite3_snapshot has no threading requirements.
// <https://www.sqlite.org/c3ref/snapshot.html>
let sqliteSnapshot: UnsafeMutablePointer<sqlite3_snapshot>
init(_ db: Database) throws {
+3 -1
View File
@@ -46,7 +46,9 @@ class WALSnapshotTransaction {
// Open a long-lived transaction, and enter snapshot isolation
self.walSnapshot = try reader.sync(allowingLongLivedTransaction: true) { db in
try db.beginTransaction(.deferred)
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
// This also acquires snapshot isolation because checking
// database schema performs a read access.
try db.clearSchemaCacheIfNeeded()
return try WALSnapshot(db)
}
self.reader = reader
+59 -19
View File
@@ -12,7 +12,7 @@ extension Database {
/// // Prints
/// // 1|Arthur|500
/// // 2|Barbara|1000
/// db.dumpSQL("SELECT * FROM player ORDER BY id")
/// try db.dumpSQL("SELECT * FROM player ORDER BY id")
/// }
/// ```
///
@@ -40,7 +40,7 @@ extension Database {
/// // Prints
/// // 1|Arthur|500
/// // 2|Barbara|1000
/// db.dumpRequest(Player.orderByPrimaryKey())
/// try db.dumpRequest(Player.orderByPrimaryKey())
/// }
/// ```
///
@@ -72,7 +72,7 @@ extension Database {
/// // team
/// // 1|Red
/// // 2|Blue
/// db.dumpTables(["player", "team"])
/// try db.dumpTables(["player", "team"])
/// }
/// ```
///
@@ -111,7 +111,7 @@ extension Database {
///
/// ```swift
/// try dbQueue.read { db in
/// db.dumpContent()
/// try db.dumpContent()
/// }
/// ```
///
@@ -145,6 +145,40 @@ extension Database {
var dumpStream = DumpStream(stream)
try _dumpContent(format: format, to: &dumpStream)
}
/// Prints the schema of the database.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// try db.dumpSchema()
/// }
/// ```
///
/// This prints the database schema. For example:
///
/// ```
/// sqlite_master
/// CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)
/// ```
///
/// > Note: Internal SQLite and GRDB schema objects are not recorded
/// > (those with a name that starts with "sqlite_" or "grdb_").
/// >
/// > [Shadow tables](https://www.sqlite.org/vtab.html#xshadowname) are
/// > not recorded, starting SQLite 3.37+.
///
/// - Parameters:
/// - stream: A stream for text output, which directs output to the
/// console by default.
public func dumpSchema(
to stream: (any TextOutputStream)? = nil)
throws
{
var dumpStream = DumpStream(stream)
try _dumpSchema(to: &dumpStream)
}
}
// MARK: -
@@ -241,6 +275,26 @@ extension Database {
format: some DumpFormat,
to stream: inout DumpStream)
throws
{
try _dumpSchema(to: &stream)
stream.margin()
let tables = try String
.fetchAll(self, sql: """
SELECT name
FROM sqlite_master
WHERE type = 'table'
ORDER BY name COLLATE NOCASE
""")
.filter {
try !ignoresObject(named: $0)
}
try _dumpTables(tables, format: format, tableHeader: .always, stableOrder: true, to: &stream)
}
func _dumpSchema(
to stream: inout DumpStream)
throws
{
stream.writeln("sqlite_master")
let sqlRows = try Row.fetchAll(self, sql: """
@@ -260,20 +314,6 @@ extension Database {
}
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 {
try !ignoresObject(named: $0)
}
if tables.isEmpty { return }
stream.write("\n")
try _dumpTables(tables, format: format, tableHeader: .always, stableOrder: true, to: &stream)
}
private func ignoresObject(named name: String) throws -> Bool {
@@ -308,7 +348,7 @@ extension Database {
}
/// Options for printing table names.
public enum DumpTableHeaderOptions {
public enum DumpTableHeaderOptions: Sendable {
/// Table names are only printed when several tables are printed.
case automatic
+37 -4
View File
@@ -7,7 +7,7 @@ extension DatabaseReader {
/// // Prints
/// // 1|Arthur|500
/// // 2|Barbara|1000
/// dbQueue.dumpSQL("SELECT * FROM player ORDER BY id")
/// try dbQueue.dumpSQL("SELECT * FROM player ORDER BY id")
/// ```
///
/// - Parameters:
@@ -34,7 +34,7 @@ extension DatabaseReader {
/// // Prints
/// // 1|Arthur|500
/// // 2|Barbara|1000
/// dbQueue.dumpRequest(Player.orderByPrimaryKey())
/// try dbQueue.dumpRequest(Player.orderByPrimaryKey())
/// ```
///
/// - Parameters:
@@ -65,7 +65,7 @@ extension DatabaseReader {
/// // team
/// // 1|Red
/// // 2|Blue
/// dbQueue.dumpTables(["player", "team"])
/// try dbQueue.dumpTables(["player", "team"])
/// ```
///
/// - Parameters:
@@ -103,7 +103,7 @@ extension DatabaseReader {
/// For example:
///
/// ```swift
/// dbQueue.dumpContent()
/// try dbQueue.dumpContent()
/// ```
///
/// This prints the database schema as well as the content of all
@@ -137,4 +137,37 @@ extension DatabaseReader {
try db.dumpContent(format: format, to: stream)
}
}
/// Prints the schema of the database.
///
/// For example:
///
/// ```swift
/// try dbQueue.dumpSchema()
/// ```
///
/// This prints the database schema. For example:
///
/// ```
/// sqlite_master
/// CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)
/// ```
///
/// > Note: Internal SQLite and GRDB schema objects are not recorded
/// > (those with a name that starts with "sqlite_" or "grdb_").
/// >
/// > [Shadow tables](https://www.sqlite.org/vtab.html#xshadowname) are
/// > not recorded, starting SQLite 3.37+.
///
/// - Parameters:
/// - stream: A stream for text output, which directs output to the
/// console by default.
public func dumpSchema(
to stream: (any TextOutputStream)? = nil)
throws
{
try unsafeReentrantRead { db in
try db.dumpSchema(to: stream)
}
}
}
+1 -1
View File
@@ -17,7 +17,7 @@ import Foundation
/// // Craig|200
/// try db.dumpRequest(Player.all(), format: .debug())
/// ```
public struct DebugDumpFormat {
public struct DebugDumpFormat: Sendable {
/// A boolean value indicating if column labels are printed as the first
/// line of output.
public var header: Bool
+1 -1
View File
@@ -27,7 +27,7 @@ import Foundation
/// encoder.outputFormatting = .prettyPrinted
/// try db.dumpRequest(Player.all(), format: .json(encoder))
/// ```
public struct JSONDumpFormat {
public struct JSONDumpFormat: Sendable {
/// The default `JSONEncoder` for database values.
///
/// It is configured so that blob values (`Data`) are encoded in the
+1 -1
View File
@@ -13,7 +13,7 @@ import Foundation
/// // score = 1000
/// try db.dumpRequest(Player.all(), format: .line())
/// ```
public struct LineDumpFormat {
public struct LineDumpFormat: Sendable {
/// The string to print for NULL values.
public var nullValue: String
+1 -1
View File
@@ -14,7 +14,7 @@ import Foundation
/// // Craig|200
/// try db.dumpRequest(Player.all(), format: .list())
/// ```
public struct ListDumpFormat {
public struct ListDumpFormat: Sendable {
/// A boolean value indicating if column labels are printed as the first
/// line of output.
public var header: Bool
+1 -1
View File
@@ -9,7 +9,7 @@
/// // 'Craig',200
/// try db.dumpRequest(Player.all(), format: .quote())
/// ```
public struct QuoteDumpFormat {
public struct QuoteDumpFormat: Sendable {
/// A boolean value indicating if column labels are printed as the first
/// line of output.
public var header: Bool
+6 -1
View File
@@ -29,7 +29,7 @@
/// - ``tokenize(_:withTokenizer:)``
public struct FTS3 {
/// Options for Latin script characters.
public enum Diacritics {
public enum Diacritics: Sendable {
/// Do not remove diacritics from Latin script characters. This option
/// matches the `remove_diacritics=0` tokenizer argument.
///
@@ -183,3 +183,8 @@ public final class FTS3TableDefinition {
columns.append(name)
}
}
// Explicit non-conformance to Sendable: `FTS3TableDefinition` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension FTS3TableDefinition: Sendable { }
+1 -1
View File
@@ -16,7 +16,7 @@
/// - ``init(matchingAllTokensIn:)``
/// - ``init(matchingAnyTokenIn:)``
/// - ``init(matchingPhrase:)``
public struct FTS3Pattern {
public struct FTS3Pattern: Sendable {
/// The raw pattern string.
///
/// It is guaranteed to be a valid FTS3/4 pattern.
+1 -1
View File
@@ -20,7 +20,7 @@
/// - ``simple``
/// - ``unicode61(diacritics:separators:tokenCharacters:)``
/// - ``FTS3/Diacritics``
public struct FTS3TokenizerDescriptor {
public struct FTS3TokenizerDescriptor: Sendable {
let name: String
let arguments: [String]
+10
View File
@@ -313,6 +313,11 @@ public final class FTS4TableDefinition {
}
}
// Explicit non-conformance to Sendable: `FTS4TableDefinition` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension FTS4TableDefinition: Sendable { }
/// Describes a column in an ``FTS4`` virtual table.
///
/// You get instances of `FTS4ColumnDefinition` when you create an ``FTS4``
@@ -377,6 +382,11 @@ public final class FTS4ColumnDefinition {
}
}
// Explicit non-conformance to Sendable: `FTS4ColumnDefinition` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension FTS4ColumnDefinition: Sendable { }
extension Database {
/// Deletes the synchronization triggers for a synchronized FTS4 table.
///
+11 -1
View File
@@ -44,7 +44,7 @@ public struct FTS5 {
/// tokenizer argument.
///
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#unicode61_tokenizer>
public enum Diacritics {
public enum Diacritics: Sendable {
/// Do not remove diacritics from Latin script characters. This
/// option matches the raw "remove_diacritics=0" tokenizer argument.
case keep
@@ -492,6 +492,11 @@ public final class FTS5TableDefinition {
}
}
// Explicit non-conformance to Sendable: `FTS5TableDefinition` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension FTS5TableDefinition: Sendable { }
/// Describes a column in an ``FTS5`` virtual table.
///
/// You get instances of `FTS5ColumnDefinition` when you create an ``FTS5``
@@ -534,6 +539,11 @@ public final class FTS5ColumnDefinition {
}
}
// Explicit non-conformance to Sendable: `FTS5ColumnDefinition` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension FTS5ColumnDefinition: Sendable { }
extension Column {
/// The ``FTS5`` rank column.
public static let rank = Column("rank")
+1 -1
View File
@@ -16,7 +16,7 @@
/// - ``init(matchingAnyTokenIn:)``
/// - ``init(matchingPhrase:)``
/// - ``init(matchingPrefixPhrase:)``
public struct FTS5Pattern {
public struct FTS5Pattern: Sendable {
/// The raw pattern string.
///
+1 -1
View File
@@ -16,7 +16,7 @@ public typealias FTS5TokenCallback = @convention(c) (
/// The reason why FTS5 is requesting tokenization.
///
/// See the `FTS5_TOKENIZE_*` constants in <https://www.sqlite.org/fts5.html#custom_tokenizers>.
public struct FTS5Tokenization: OptionSet {
public struct FTS5Tokenization: OptionSet, Sendable {
public let rawValue: CInt
public init(rawValue: CInt) {
+1 -1
View File
@@ -24,7 +24,7 @@
/// ### Instantiating Tokenizers
///
/// - ``Database/makeTokenizer(_:)``
public struct FTS5TokenizerDescriptor {
public struct FTS5TokenizerDescriptor: Sendable {
/// The tokenizer components.
///
/// For example:
+1 -1
View File
@@ -4,7 +4,7 @@ import Foundation
/// Flags that tell SQLite how to register a token.
///
/// See the `FTS5_TOKEN_*` constants in <https://www.sqlite.org/fts5.html#custom_tokenizers>.
public struct FTS5TokenFlags: OptionSet {
public struct FTS5TokenFlags: OptionSet, Sendable {
public let rawValue: CInt
public init(rawValue: CInt) {
+1 -1
View File
@@ -73,7 +73,7 @@
/// > .fetchAll(db)
/// > }
/// > ```
public struct JSONColumn: ColumnExpression, SQLJSONExpressible {
public struct JSONColumn: ColumnExpression, SQLJSONExpressible, Sendable {
public var name: String
/// Creates a `JSONColumn` given its name.
+1 -1
View File
@@ -42,7 +42,7 @@ import Foundation
/// - ``hasCompletedMigrations(_:)``
public struct DatabaseMigrator {
/// Controls how a migration handle foreign keys constraints.
public enum ForeignKeyChecks {
public enum ForeignKeyChecks: Sendable {
/// The migration runs with disabled foreign keys.
///
/// Foreign keys are checked right before changes are committed on disk,
+1 -1
View File
@@ -80,7 +80,7 @@
/// using: Book.translatorForeignKey)
/// }
/// ```
public struct ForeignKey: Equatable {
public struct ForeignKey: Equatable, Sendable {
var originColumns: [String]
var destinationColumns: [String]?
+1 -1
View File
@@ -92,7 +92,7 @@ extension ColumnExpression where Self == Column {
///
/// - ``init(_:)-5grmu``
/// - ``init(_:)-7xc4z``
public struct Column {
public struct Column: Sendable {
/// The hidden rowID column.
public static let rowID = Column("rowid")
+1 -1
View File
@@ -315,7 +315,7 @@ public struct SQLExpression {
/// 1000.databaseValue]
/// let request = Player.select(values.joined(operator: .add))
/// ```
public struct AssociativeBinaryOperator: Hashable {
public struct AssociativeBinaryOperator: Hashable, Sendable {
/// The SQL operator
let sql: String
+1 -1
View File
@@ -408,7 +408,7 @@ extension SQLSpecificExpressible {
/// A date modifier for SQLite date functions.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_datefunc.html>
public enum SQLDateModifier: SQLSpecificExpressible {
public enum SQLDateModifier: SQLSpecificExpressible, Sendable {
/// Adds the specified amount of seconds
case second(Double)
+1 -1
View File
@@ -324,7 +324,7 @@ extension SQLSelection: SQLSelectable {
/// let players = try Player.select(AllColumns()).fetchAll(db)
/// }
/// ```
public struct AllColumns {
public struct AllColumns: Sendable {
/// The `*` selection.
public init() { }
}
+1 -1
View File
@@ -138,7 +138,7 @@
/// ### Database Observation Support
///
/// - ``databaseRegion(_:)``
public struct Table<RowDecoder> {
public struct Table<RowDecoder>: Sendable {
/// The table name.
public var tableName: String
@@ -76,7 +76,7 @@ public final class ColumnDefinition {
/// The kind of a generated column.
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html#virtual_versus_stored_columns>
public enum GeneratedColumnQualification {
public enum GeneratedColumnQualification: Sendable {
/// A `VIRTUAL` generated column.
case virtual
/// A `STORED` generated column.
@@ -565,3 +565,8 @@ public final class ColumnDefinition {
}
}
}
// Explicit non-conformance to Sendable: `ColumnDefinition` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension ColumnDefinition: Sendable { }
@@ -681,7 +681,7 @@ extension Database {
}
/// View creation options
public struct ViewOptions: OptionSet {
public struct ViewOptions: OptionSet, Sendable {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
@@ -104,3 +104,8 @@ public final class ForeignKeyDefinition {
throw DatabaseError.noSuchTable(name)
}
}
// Explicit non-conformance to Sendable: `ForeignKeyDefinition` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension ForeignKeyDefinition: Sendable { }
@@ -7,7 +7,7 @@ struct IndexDefinition {
}
/// Index creation options
public struct IndexOptions: OptionSet {
public struct IndexOptions: OptionSet, Sendable {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
@@ -161,3 +161,8 @@ public final class TableAlteration {
alterations.append(.drop(name))
}
}
// Explicit non-conformance to Sendable: `TableAlteration` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension TableAlteration: Sendable { }
@@ -1,5 +1,5 @@
/// Table creation options.
public struct TableOptions: OptionSet {
public struct TableOptions: OptionSet, Sendable {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
@@ -753,3 +753,8 @@ public final class TableDefinition {
literalConstraints.append(literal)
}
}
// Explicit non-conformance to Sendable: `TableDefinition` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension TableDefinition: Sendable { }
@@ -7,6 +7,7 @@ extension FetchableRecord where Self: Decodable {
}
}
// TODO GRDB7: make it a final class, and Sendable.
/// An object that decodes fetchable records from database rows.
///
/// The example below shows how to decode an instance of a simple `Player`
+5
View File
@@ -854,6 +854,11 @@ public final class RecordCursor<Record: FetchableRecord>: DatabaseCursor {
}
}
// Explicit non-conformance to Sendable: database cursors must be used from
// a serialized database access dispatch queue.
@available(*, unavailable)
extension RecordCursor: Sendable { }
// MARK: - DatabaseDataDecodingStrategy
/// `DatabaseDataDecodingStrategy` specifies how `FetchableRecord` types that
+1 -1
View File
@@ -348,7 +348,7 @@ extension MutablePersistableRecord {
/// See `MutablePersistableRecord.persistenceConflictPolicy`.
///
/// See <https://www.sqlite.org/lang_conflict.html>
public struct PersistenceConflictPolicy {
public struct PersistenceConflictPolicy: Sendable {
/// The conflict resolution algorithm for insertions
public let conflictResolutionForInsert: Database.ConflictResolution
+1 -1
View File
@@ -31,7 +31,7 @@ extension String {
/// A type that controls GRDB string inflections.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
public struct Inflections {
public struct Inflections: Sendable {
private var pluralizeRules: [(NSRegularExpression, String)] = []
private var singularizeRules: [(NSRegularExpression, String)] = []
private var uncountablesRegularExpressions: [String: NSRegularExpression] = [:]
@@ -1,7 +1,7 @@
import Foundation
/// The extent of the shared subscription to a ``SharedValueObservation``.
public enum SharedValueObservationExtent {
public enum SharedValueObservationExtent: Sendable {
/// The ``SharedValueObservation`` starts a single database observation,
/// which stops when the `SharedValueObservation` is deallocated and all
/// subscriptions terminated.
@@ -76,7 +76,7 @@ extension ValueObservationScheduler where Self == AsyncValueObservationScheduler
/// A scheduler that notifies all values on the main `DispatchQueue`. The
/// first value is immediately notified when the `ValueObservation`
/// is started.
public struct ImmediateValueObservationScheduler: ValueObservationScheduler {
public struct ImmediateValueObservationScheduler: ValueObservationScheduler, Sendable {
public init() { }
public func immediateInitialValue() -> Bool {
+1 -1
View File
@@ -76,7 +76,7 @@ test_framework_GRDB: test_framework_GRDBOSX test_framework_GRDBiOS test_framewor
test_framework_GRDBCustom: test_framework_GRDBCustomSQLiteOSX test_framework_GRDBCustomSQLiteiOS
test_framework_SQLCipher: test_framework_SQLCipher3 test_framework_SQLCipher3Encrypted test_framework_SQLCipher4 test_framework_SQLCipher4Encrypted
test_archive: test_universal_xcframework
test_install: test_install_manual test_install_SPM test_install_customSQLite test_install_GRDB_CocoaPods test_CocoaPodsLint
test_install: test_install_manual test_install_SPM test_install_customSQLite test_install_GRDB_CocoaPods
test_CocoaPodsLint: test_CocoaPodsLint_GRDB
test_demo_apps: test_GRDBDemoiOS test_GRDBCombineDemo test_GRDBAsyncDemo
+93 -81
View File
@@ -106,53 +106,59 @@ public class Recorder<Input, Failure: Error>: Subscriber {
/// the expectation. For example, the Prefix expectation uses true, but
/// the NextOne expectation uses false.
func fulfillOnInput(_ expectation: XCTestExpectation, includingConsumed: Bool) {
synchronized {
preconditionCanFulfillExpectation()
lock.lock()
preconditionCanFulfillExpectation()
let expectedFulfillmentCount = expectation.expectedFulfillmentCount
switch state {
case .waitingForSubscription:
let exp = RecorderExpectation.onInput(expectation, remainingCount: expectedFulfillmentCount)
state = .waitingForSubscription(exp)
lock.unlock()
let expectedFulfillmentCount = expectation.expectedFulfillmentCount
case let .subscribed(subscription, _, elements):
let maxFulfillmentCount = includingConsumed
? elements.count
: elements.count - consumedCount
let fulfillmentCount = min(expectedFulfillmentCount, maxFulfillmentCount)
switch state {
case .waitingForSubscription:
let exp = RecorderExpectation.onInput(expectation, remainingCount: expectedFulfillmentCount)
state = .waitingForSubscription(exp)
case let .subscribed(subscription, _, elements):
let maxFulfillmentCount = includingConsumed
? elements.count
: elements.count - consumedCount
let fulfillmentCount = min(expectedFulfillmentCount, maxFulfillmentCount)
expectation.fulfill(count: fulfillmentCount)
let remainingCount = expectedFulfillmentCount - fulfillmentCount
if remainingCount > 0 {
let exp = RecorderExpectation.onInput(expectation, remainingCount: remainingCount)
state = .subscribed(subscription, exp, elements)
}
case .completed:
expectation.fulfill(count: expectedFulfillmentCount)
let remainingCount = expectedFulfillmentCount - fulfillmentCount
if remainingCount > 0 {
let exp = RecorderExpectation.onInput(expectation, remainingCount: remainingCount)
state = .subscribed(subscription, exp, elements)
}
lock.unlock()
expectation.fulfill(count: fulfillmentCount)
case .completed:
lock.unlock()
expectation.fulfill(count: expectedFulfillmentCount)
}
}
/// Registers the expectation so that it gets fulfilled when
/// publisher completes.
func fulfillOnCompletion(_ expectation: XCTestExpectation) {
synchronized {
preconditionCanFulfillExpectation()
lock.lock()
preconditionCanFulfillExpectation()
switch state {
case .waitingForSubscription:
let exp = RecorderExpectation.onCompletion(expectation)
state = .waitingForSubscription(exp)
lock.unlock()
switch state {
case .waitingForSubscription:
let exp = RecorderExpectation.onCompletion(expectation)
state = .waitingForSubscription(exp)
case let .subscribed(subscription, _, elements):
let exp = RecorderExpectation.onCompletion(expectation)
state = .subscribed(subscription, exp, elements)
case .completed:
expectation.fulfill()
}
case let .subscribed(subscription, _, elements):
let exp = RecorderExpectation.onCompletion(expectation)
state = .subscribed(subscription, exp, elements)
lock.unlock()
case .completed:
lock.unlock()
expectation.fulfill()
}
}
@@ -171,7 +177,7 @@ public class Recorder<Input, Failure: Error>: Subscriber {
_ completion: Subscribers.Completion<Failure>?,
_ remainingElements: ArraySlice<Input>,
_ consume: (_ count: Int) -> ()) throws -> T)
rethrows -> T
rethrows -> T
{
try synchronized {
let (elements, completion) = state.elementsAndCompletion
@@ -217,58 +223,64 @@ public class Recorder<Input, Failure: Error>: Subscriber {
}
public func receive(_ input: Input) -> Subscribers.Demand {
return synchronized {
switch state {
case let .subscribed(subscription, exp, elements):
var elements = elements
elements.append(input)
if case let .onInput(expectation, remainingCount: remainingCount) = exp {
assert(remainingCount > 0)
expectation.fulfill()
if remainingCount > 1 {
let exp = RecorderExpectation.onInput(expectation, remainingCount: remainingCount - 1)
state = .subscribed(subscription, exp, elements)
} else {
state = .subscribed(subscription, nil, elements)
}
} else {
lock.lock()
switch state {
case let .subscribed(subscription, exp, elements):
var elements = elements
elements.append(input)
if case let .onInput(expectation, remainingCount: remainingCount) = exp {
assert(remainingCount > 0)
expectation.fulfill()
if remainingCount > 1 {
let exp = RecorderExpectation.onInput(expectation, remainingCount: remainingCount - 1)
state = .subscribed(subscription, exp, elements)
} else {
state = .subscribed(subscription, nil, elements)
}
return .unlimited
case .waitingForSubscription:
XCTFail("Publisher recorder got unexpected input before subscription: \(String(reflecting: input))")
return .none
case .completed:
XCTFail("Publisher recorder got unexpected input after completion: \(String(reflecting: input))")
return .none
} else {
state = .subscribed(subscription, exp, elements)
}
lock.unlock()
return .unlimited
case .waitingForSubscription:
lock.unlock()
XCTFail("Publisher recorder got unexpected input before subscription: \(String(reflecting: input))")
return .none
case .completed:
lock.unlock()
XCTFail("Publisher recorder got unexpected input after completion: \(String(reflecting: input))")
return .none
}
}
public func receive(completion: Subscribers.Completion<Failure>) {
synchronized {
switch state {
case let .subscribed(_, exp, elements):
if let exp {
switch exp {
case let .onCompletion(expectation):
expectation.fulfill()
case let .onInput(expectation, remainingCount: remainingCount):
expectation.fulfill(count: remainingCount)
}
lock.lock()
switch state {
case let .subscribed(_, exp, elements):
if let exp {
switch exp {
case let .onCompletion(expectation):
expectation.fulfill()
case let .onInput(expectation, remainingCount: remainingCount):
expectation.fulfill(count: remainingCount)
}
state = .completed(elements, completion)
case .waitingForSubscription:
XCTFail("Publisher recorder got unexpected completion before subscription: \(String(describing: completion))")
case .completed:
XCTFail("Publisher recorder got unexpected completion after completion: \(String(describing: completion))")
}
state = .completed(elements, completion)
lock.unlock()
case .waitingForSubscription:
lock.unlock()
XCTFail("Publisher recorder got unexpected completion before subscription: \(String(describing: completion))")
case .completed:
lock.unlock()
XCTFail("Publisher recorder got unexpected completion after completion: \(String(describing: completion))")
}
}
}
+158
View File
@@ -1196,6 +1196,164 @@ final class DatabaseDumpTests: GRDBTestCase {
}
}
// MARK: - Database schema dump
func test_dumpSchema() throws {
try makeRugbyDatabase().read { db in
let stream = TestStream()
try db.dumpSchema(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);
""")
}
}
func test_dumpSchema_empty_database() throws {
try makeDatabaseQueue().read { db in
let stream = TestStream()
try db.dumpSchema(to: stream)
XCTAssertEqual(stream.output, """
sqlite_master
""")
}
}
func test_dumpSchema_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.dumpSchema(to: stream)
XCTAssertEqual(stream.output, """
sqlite_master
CREATE TABLE blue(name);
CREATE TABLE red(name);
CREATE TABLE yellow(name);
""")
}
}
func test_dumpSchema_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.dumpSchema(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);
""")
}
}
func test_dumpSchema_ignores_shadow_tables() throws {
guard sqlite3_libversion_number() >= 3037000 else {
throw XCTSkip("Can't detect shadow tables")
}
try makeDatabaseQueue().write { db in
try db.create(table: "document") { t in
t.autoIncrementedPrimaryKey("id")
t.column("body")
}
try db.execute(sql: "INSERT INTO document VALUES (1, 'Hello world!')")
try db.create(virtualTable: "document_ft", using: FTS4()) { t in
t.synchronize(withTable: "document")
t.column("body")
}
let stream = TestStream()
try db.dumpSchema(to: stream)
print(stream.output)
XCTAssertEqual(stream.output, """
sqlite_master
CREATE TABLE "document" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "body");
CREATE TRIGGER "__document_ft_ai" AFTER INSERT ON "document" BEGIN
INSERT INTO "document_ft"("docid", "body") VALUES(new."id", new."body");
END;
CREATE TRIGGER "__document_ft_au" AFTER UPDATE ON "document" BEGIN
INSERT INTO "document_ft"("docid", "body") VALUES(new."id", new."body");
END;
CREATE TRIGGER "__document_ft_bd" BEFORE DELETE ON "document" BEGIN
DELETE FROM "document_ft" WHERE docid=old."id";
END;
CREATE TRIGGER "__document_ft_bu" BEFORE UPDATE ON "document" BEGIN
DELETE FROM "document_ft" WHERE docid=old."id";
END;
CREATE VIRTUAL TABLE "document_ft" USING fts4(body, content="document");
""")
}
}
func test_dumpSchema_ignores_GRDB_internal_tables() throws {
let dbQueue = try makeDatabaseQueue()
var migrator = DatabaseMigrator()
migrator.registerMigration("v1") { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
}
}
try migrator.migrate(dbQueue)
try dbQueue.read { db in
let stream = TestStream()
try db.dumpSchema(to: stream)
print(stream.output)
XCTAssertEqual(stream.output, """
sqlite_master
CREATE TABLE "player" ("id" INTEGER PRIMARY KEY AUTOINCREMENT);
""")
}
}
// MARK: - Database content dump
func test_dumpContent() throws {
@@ -340,3 +340,51 @@ extension DatabaseValueConvertibleEncodableTests {
}
}
}
// MARK: - Super Encoders
extension DatabaseValueConvertibleEncodableTests {
func testSuperEncoder() throws {
// Gets compiler-synthesized `Codable` impl
class CodableSup: Codable, DatabaseValueConvertible {
var x: Int
init(_ x: Int) { self.x = x }
}
// We have to override init(from:) and encode(to:) to avoid inheriting them
class CodableSub: CodableSup {
var y: Int
init(_ x: Int, _ y: Int) { self.y = y; super.init(x) }
private enum CodingKeys: String, CodingKey {
case y
}
required init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
y = try container.decode(Int.self, forKey: .y)
// This will effectively fetch a nested container for key "super", then return a `Decoder` wrapping it
let superDecoder = try container.superDecoder()
try super.init(from: superDecoder)
}
override func encode(to encoder: any Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(y, forKey: .y)
// This will effectively create a nested container for key "super", then return an `Encoder` wrapping it
let superEncoder = container.superEncoder()
try super.encode(to: superEncoder)
}
}
do {
let dbValue = CodableSup(42).databaseValue
XCTAssertEqual(dbValue.storage.value as! String, #"{"x":42}"#)
let dbValue2 = CodableSub(42, 500).databaseValue
XCTAssertEqual(dbValue2.storage.value as! String, #"{"super":{"x":42},"y":500}"#)
}
}
}
@@ -844,3 +844,68 @@ extension MutablePersistableRecordEncodableTests {
fileprivate extension CodingUserInfoKey {
static let testKey = CodingUserInfoKey(rawValue: "correct")!
}
// MARK: - Super Encoders
extension MutablePersistableRecordEncodableTests {
func testSuperEncoder() throws {
// Gets compiler-synthesized `Codable` impl
class CodableSup: Codable {
var x: Int
init(_ x: Int) { self.x = x }
}
// We have to override init(from:) and encode(to:) to avoid inheriting them
class CodableSub: CodableSup {
var y: Int
init(_ x: Int, _ y: Int) { self.y = y; super.init(x) }
private enum CodingKeys: String, CodingKey {
case y
}
required init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
y = try container.decode(Int.self, forKey: .y)
// This will effectively fetch a nested container for key "super", then return a `Decoder` wrapping it
let superDecoder = try container.superDecoder()
try super.init(from: superDecoder)
}
override func encode(to encoder: any Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(y, forKey: .y)
// This will effectively create a nested container for key "super", then return an `Encoder` wrapping it
let superEncoder = container.superEncoder()
try super.encode(to: superEncoder)
}
}
struct Record: PersistableRecord, Encodable {
var id: String
var value: CodableSup
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "record") { t in
t.primaryKey("id", .text)
t.column("value", .jsonText)
}
do {
try Record(id: "sup", value: CodableSup(42)).insert(db)
let value = try String.fetchOne(db, sql: "SELECT value FROM record WHERE id = 'sup'")
XCTAssertEqual(value, #"{"x":42}"#)
}
do {
try Record(id: "sub", value: CodableSub(42, 500)).insert(db)
let value = try String.fetchOne(db, sql: "SELECT value FROM record WHERE id = 'sub'")
XCTAssertEqual(value, #"{"super":{"x":42},"y":500}"#)
}
}
}
}
+29 -1
View File
@@ -1268,5 +1268,33 @@ class ValueObservationTests: GRDBTestCase {
onChange: { _ in
})
}
// Regression test for <https://github.com/groue/GRDB.swift/issues/1500>
func testIssue1500() throws {
let pool = try makeDatabasePool()
try pool.read { db in
_ = try db.tableExists("t")
}
try pool.write { db in
try db.create(table: "t") { t in
t.column("a")
}
}
_ = ValueObservation
.trackingConstantRegion { db in
try db.tableExists("t")
}
.start(
in: pool,
scheduling: .immediate,
onError: { error in
XCTFail("Unexpected error \(error)")
},
onChange: { value in
XCTAssertEqual(value, true)
})
}
}