diff --git a/.spi.yml b/.spi.yml index be9b518d8..9e3cf0267 100644 --- a/.spi.yml +++ b/.spi.yml @@ -1,3 +1,4 @@ version: 1 -external_links: - documentation: "https://github.com/groue/GRDB.swift/blob/master/README.md" +builder: + configs: + - documentation_targets: [GRDB] diff --git a/CHANGELOG.md b/CHANGELOG.md index 1400a420c..a1dcbb650 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.3.x` Releases - [6.3.0](#630) - `6.2.x` Releases - [6.2.0](#620) - `6.1.x` Releases - [6.1.0](#610) - `6.0.x` Releases - [6.0.0](#600) @@ -100,6 +101,13 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- +## 6.3.0 + +Released November 6, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.2.0...v6.3.0) + +- **New**: [#1291](https://github.com/groue/GRDB.swift/pull/1291) by [@groue](https://github.com/groue): DocC inline documentation +- **New**: The `Row.dataNoCopy` methods are deprecated. Use `Row.withUnsafeData` instead. + ## 6.2.0 Released October 28, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.1.0...v6.2.0) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c34c9b466..64d7ba60e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -69,7 +69,9 @@ How you can Contribute 7. **Please provide documentation for your changes** - GRDB documentation is provided as reference (inline doc comments starting with `///`, see [Documentation Comment Syntax](https://github.com/apple/swift/blob/main/docs/DocumentationComments.md)), and guides ([README.md](README.md) and the [Documentation](Documentation) folder). + GRDB documentation is provided as a DocC reference, and guides ([README.md](README.md) and the [Documentation](Documentation) folder). + + Please keep the reference and the guides up-to-date. Use Xcode > Product > Build Documentation in order to control the quality of your reference documentation. GRDB is "documentation-driven", which means that nothing ships until it is supported by documentation that makes sense. Documentation makes sense when someone who is not you is able to figure out what is the purpose of your contribution, how to use it, and what are its eventual caveats and corner cases. When the documentation is hard to write, or reveals too many caveats, it is the sign that the api needs to be fixed. diff --git a/Documentation/Concurrency.md b/Documentation/Concurrency.md index 1b48b2c89..e1a739da2 100644 --- a/Documentation/Concurrency.md +++ b/Documentation/Concurrency.md @@ -118,7 +118,7 @@ let playerCount = try dbQueue.read { db in } let newPlayerCount = try dbQueue.write { db -> Int in - try Player(id: 12, name: "Arthur").insert(db) + try Player(name: "Arthur").insert(db) return try Player.fetchCount(db) } ``` @@ -145,7 +145,7 @@ let playerCount = try await dbQueue.read { db in } let newPlayerCount = try await dbQueue.write { db -> Int in - try Player(id: 12, name: "Arthur").insert(db) + try Player(name: "Arthur").insert(db) return try Player.fetchCount(db) } ``` @@ -163,7 +163,7 @@ let playerCountPublisher = dbQueue.readPublisher { db in } let newPlayerCountPublisher = dbQueue.writePublisher { db -> Int in - try Player(id: 12, name: "Arthur").insert(db) + try Player(name: "Arthur").insert(db) return try Player.fetchCount(db) } ``` @@ -181,7 +181,7 @@ let playerCountObservable = dbQueue.rx.read { db in } let newPlayerCountObservable = dbQueue.rx.write { db -> Int in - try Player(id: 12, name: "Arthur").insert(db) + try Player(name: "Arthur").insert(db) return try Player.fetchCount(db) } ``` @@ -196,27 +196,24 @@ Those observables do not access the database until they are subscribed. They com ```swift dbQueue.asyncRead { (dbResult: Result) in do { - // Maybe read access could not be established let db = try dbResult.get() let playerCount = try Player.fetchCount(db) - ... // Handle playerCount } catch { - ... // Handle error + // Handle error } } -dbQueue.asyncWrite({ (db: Database) -> Int in - try Player(id: 12, name: "Arthur").insert(db) +dbQueue.asyncWrite { (db: Database) -> Int in + try Player(name: "Arthur").insert(db) return try Player.fetchCount(db) -}, completion: { (db: Database, result: Result) in - // Handle write transaction result: +} completion: { (db: Database, result: Result) in switch result { case let .success(newPlayerCount): - ... // Handle newPlayerCount + // Handle success case let .failure(error): - ... // Handle error + // Handle error } -}) +} ``` diff --git a/Documentation/FullTextSearch.md b/Documentation/FullTextSearch.md index 15a75d0ef..d831d00ee 100644 --- a/Documentation/FullTextSearch.md +++ b/Documentation/FullTextSearch.md @@ -304,7 +304,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/6.2/Structs/StatementArguments.html): +FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/grdb/documentation/grdb/statementarguments): ```swift let documents = try Document.fetchAll(db, @@ -587,7 +587,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/6.2/Structs/StatementArguments.html): +FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/grdb/documentation/grdb/statementarguments): ```swift let documents = try Document.fetchAll(db, diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index cceb8bfdd..86b01f80a 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -77,7 +77,7 @@ try dbQueue.read { db in } ``` -See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/6.2/Structs/DatabaseMigrator.html) for more migrator methods. +See the [DatabaseMigrator reference](https://swiftpackageindex.com/groue/grdb/documentation/grdb/databasemigrator) for more migrator methods. ## The `eraseDatabaseOnSchemaChange` Option diff --git a/Documentation/ReleaseProcess.md b/Documentation/ReleaseProcess.md index 18a4bcda4..0ae106b56 100644 --- a/Documentation/ReleaseProcess.md +++ b/Documentation/ReleaseProcess.md @@ -13,18 +13,14 @@ To release a new GRDB version: - On https://github.com/groue/sqlcipher.git upgrade, update SQLCipher version in README.md - On https://github.com/swiftlyfalling/SQLiteLib upgrade, update SQLite version in Documentation/CustomSQLiteBuilds.md - Update GRDB version number and release date in: - - Makefile - CHANGELOG.md - GRDB.swift.podspec - README.md - - Documentation/FullTextSearch.md - - Documentation/Migrations.md - Support/Info.plist - Commit and tag - Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags` - Push to the master & development branch - `pod trunk push --allow-warnings GRDB.swift.podspec` -- `make doc`, and update index.html in the `gh-pages` branch - Update http://github.com/groue/WWDCCompanion - Update [performance comparison](https://github.com/groue/GRDB.swift/wiki/Performance): diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index aedf28403..091b00d19 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.2.0' + s.version = '6.3.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/Configuration.swift b/GRDB/Core/Configuration.swift index 093c29257..197bba618 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -1,37 +1,54 @@ import Dispatch import Foundation -/// Configuration for a DatabaseQueue or DatabasePool. +/// The configuration of a ``Database``, ``DatabaseQueue``, or ``DatabasePool``. +/// +/// Usage: +/// +/// ```swift +/// var config = Configuration() +/// config.readonly = true +/// config.foreignKeysEnabled = true // Default is already true +/// config.label = "MyDatabase" // Useful when your app opens multiple databases +/// config.maximumReaderCount = 10 // (DatabasePool only) The default is 5 +/// +/// let dbQueue = try DatabaseQueue( // or DatabasePool +/// path: "/path/to/database.sqlite", +/// configuration: config) +/// ``` public struct Configuration { // MARK: - Misc options - /// If true (the default), support for foreign keys is enabled. - /// See for more information. + /// A boolean value indicating whether foreign key support is enabled. /// - /// Default: true + /// The default is true. + /// + /// Related SQLite documentation: . public var foreignKeysEnabled = true - /// If true, database modifications are disallowed. + /// A boolean value indicating whether an SQLite connection is read-only. /// - /// Default: false + /// The default is false. public var readonly = false - /// The configuration label. + /// A label that describes a database connection. /// /// You can query this label at runtime: /// - /// var configuration = Configuration() - /// configuration.label = "MyDatabase" - /// let dbQueue = try DatabaseQueue(path: ..., configuration: configuration) + /// ```swift + /// var configuration = Configuration() + /// configuration.label = "MyDatabase" + /// let dbQueue = try DatabaseQueue(path: ..., configuration: configuration) /// - /// try dbQueue.read { db in - /// print(db.configuration.label) // Prints "MyDatabase" - /// } + /// try dbQueue.read { db in + /// print(db.configuration.label) // Prints "MyDatabase" + /// } + /// ``` /// - /// The configuration label is also used to name Database connections (the - /// `Database.description` property), and the various dispatch queues - /// created by GRDB, visible in debugging sessions and crash logs. + /// The configuration label is also used to name ``Database`` connections + /// (their ``Database/description`` property), and the various dispatch + /// queues created by GRDB, visible in debugging sessions and crash logs. /// /// Those connection names and dispatch queue labels are intended for /// debugging only. Their format may change between GRDB releases. @@ -66,62 +83,73 @@ public struct Configuration { /// The default configuration label is nil. public var label: String? = nil - /// If false, SQLite from version 3.29.0 will not interpret a double-quoted - /// string as a string literal if it does not match any valid identifier. + /// A boolean value indicating whether SQLite 3.29+ interprets + /// double-quoted strings as string literals when they does not match any + /// valid identifier. + /// + /// The default and recommended value is false. /// /// For example: /// - /// // Error: no such column: foo - /// let name = try String.fetchOne(db, sql: """ - /// SELECT "foo" FROM "player" - /// """) + /// ```swift + /// // Error: no such column: foo + /// let name = try String.fetchOne(db, sql: """ + /// SELECT "foo" FROM "player" + /// """) + /// ``` /// - /// When true, or before version 3.29.0, such strings are interpreted as - /// string literals, as in the example below. This is a well known SQLite - /// [misfeature](https://sqlite.org/quirks.html#dblquote). + /// When true, or before SQLite version 3.29.0, such strings are interpreted + /// as string literals, as in the example below. This is a well known SQLite + /// [misfeature](https://sqlite.org/quirks.html#dblquote): /// - /// // Success: "foo" - /// let name = try String.fetchOne(db, sql: """ - /// SELECT "foo" FROM "player" - /// """) - /// - /// - Recommended value: false - /// - Default value: false + /// ```swift + /// // Success: "foo" + /// let name = try String.fetchOne(db, sql: """ + /// SELECT "foo" FROM "player" + /// """) + /// ``` public var acceptsDoubleQuotedStringLiterals = false - /// When true, the `Database.suspendNotification` and - /// `Database.resumeNotification` suspend and resume the database. Database - /// suspension helps avoiding the [`0xdead10cc` - /// exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report). + /// A boolean value indicating whether the database connection listens to + /// the ``Database/suspendNotification`` and ``Database/resumeNotification`` + /// notifications. + /// + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// Database suspension helps avoiding the + /// [`0xdead10cc` exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report). /// /// During suspension, all database accesses but reads in WAL mode may throw - /// a DatabaseError of code `SQLITE_INTERRUPT`, or `SQLITE_ABORT`. You can - /// check for those error codes with the - /// `DatabaseError.isInterruptionError` property. - /// - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// a ``DatabaseError`` of code `SQLITE_INTERRUPT` or `SQLITE_ABORT`. You + /// can check for those error codes with the + /// ``DatabaseError/isInterruptionError`` property. public var observesSuspensionNotifications = false - /// If false (the default), statement arguments are not visible in the - /// description of database errors and trace events, preventing sensitive + /// A boolean value indicating whether statement arguments are visible in + /// the description of database errors and trace events. + /// + /// The default and recommended value is false: statement arguments are not + /// visible in database errors and trace events, preventing sensitive /// information from leaking in unexpected places. /// /// For example: /// - /// // Error: sensitive information is not printed when an error occurs: - /// do { - /// let email = "..." // sensitive information - /// let player = try Player.filter(Column("email") == email).fetchOne(db) - /// } catch { - /// print(error) - /// } - /// - /// // Trace: sensitive information is not printed when a statement is traced: - /// db.trace { event in - /// print(event) - /// } + /// ```swift + /// // Error: sensitive information is not printed when an error occurs: + /// do { /// let email = "..." // sensitive information /// let player = try Player.filter(Column("email") == email).fetchOne(db) + /// } catch { + /// print(error) + /// } + /// + /// // Trace: sensitive information is not printed when a statement is traced: + /// db.trace { event in + /// print(event) + /// } + /// let email = "..." // sensitive information + /// let player = try Player.filter(Column("email") == email).fetchOne(db) + /// ``` /// /// For debugging purpose, you can set this flag to true, and get more /// precise database reports. It is your responsibility to prevent sensitive @@ -129,57 +157,65 @@ public struct Configuration { /// this flag in release builds (think about GDPR and other /// privacy-related rules): /// - /// var config = Configuration() - /// #if DEBUG - /// // Protect sensitive information by enabling verbose debugging in DEBUG builds only - /// config.publicStatementArguments = true - /// #endif + /// ```swift + /// var config = Configuration() + /// #if DEBUG + /// // Protect sensitive information by enabling verbose debugging in DEBUG builds only + /// config.publicStatementArguments = true + /// #endif /// - /// // The descriptions of trace events and errors now contain the - /// // sensitive information: - /// db.trace { event in - /// print(event) - /// } - /// do { - /// let email = "..." - /// let player = try Player.filter(Column("email") == email).fetchOne(db) - /// } catch { - /// print(error) - /// } + /// // The descriptions of trace events and errors now contain the + /// // sensitive information: + /// db.trace { event in + /// print(event) + /// } + /// do { + /// let email = "..." + /// let player = try Player.filter(Column("email") == email).fetchOne(db) + /// } catch { + /// print(error) + /// } + /// ``` public var publicStatementArguments = false // MARK: - Managing SQLite Connections private var setups: [(Database) throws -> Void] = [] - /// The function argument is run when an SQLite connection is opened, - /// before the connection is made available for database access methods. + /// Defines a function to run whenever an SQLite connection is opened. + /// + /// The preparation function is run before the connection is made available + /// for database access methods. /// /// This method can be called several times. The preparation functions are /// run in the same order. /// /// For example: /// - /// var config = Configuration() - /// config.prepareDatabase { db in - /// try db.execute(sql: "PRAGMA kdf_iter = 10000") - /// } + /// ```swift + /// var config = Configuration() + /// config.prepareDatabase { db in + /// try db.execute(sql: "PRAGMA kdf_iter = 10000") + /// } + /// ``` /// - /// When you use a `DatabasePool`, preparation functions are called for + /// When you use a ``DatabasePool``, preparation functions are called for /// the writer connection and all reader connections. You can distinguish /// them by querying `db.configuration.readonly`: /// - /// var config = Configuration() - /// config.prepareDatabase { db in - /// if db.configuration.readonly { - /// // reader connection - /// } else { - /// // writer connection - /// } + /// ```swift + /// var config = Configuration() + /// config.prepareDatabase { db in + /// if db.configuration.readonly { + /// // reader connection + /// } else { + /// // writer connection /// } + /// } + /// ``` /// - /// On newly created databases, `DatabasePool` the WAL mode is activated - /// after the preparation functions have run. + /// On newly created databases files, ``DatabasePool`` activates the WAL + /// mode after the preparation functions have run. public mutating func prepareDatabase(_ setup: @escaping (Database) throws -> Void) { setups.append(setup) } @@ -188,64 +224,72 @@ public struct Configuration { /// The default kind of transaction. /// - /// Default: deferred + /// The default is ``Database/TransactionKind/deferred``. + /// + /// Related SQLite documentation: public var defaultTransactionKind: Database.TransactionKind = .deferred - /// If false, it is a programmer error to leave a transaction opened at the - /// end of a database access block. + /// A boolean value indicating whether it is valid to leave a transaction + /// opened at the end of a database access method. /// - /// For example: + /// The default value is false: not completing a transaction is a + /// programmer error: /// - /// let dbQueue = try DatabaseQueue() + /// ```swift + /// let dbQueue = try DatabaseQueue() /// - /// // fatal error: A transaction has been left opened at the end of a database access - /// try dbQueue.inDatabase { db in - /// try db.beginTransaction() - /// } + /// // fatal error: A transaction has been left opened at the end of a database access + /// try dbQueue.inDatabase { db in + /// try db.beginTransaction() + /// } + /// ``` /// - /// If true, one can leave opened transaction at the end of database access - /// blocks: + /// When true, one can leave opened transaction at the end of database + /// access method: /// - /// var config = Configuration() - /// config.allowsUnsafeTransactions = true - /// let dbQueue = try DatabaseQueue(configuration: config) + /// ```swift + /// var config = Configuration() + /// config.allowsUnsafeTransactions = true + /// let dbQueue = try DatabaseQueue(configuration: config) /// - /// try dbQueue.inDatabase { db in - /// try db.beginTransaction() - /// } + /// try dbQueue.inDatabase { db in + /// try db.beginTransaction() + /// } /// - /// try dbQueue.inDatabase { db in - /// try db.commit() - /// } + /// try dbQueue.inDatabase { db in + /// try db.commit() + /// } + /// ``` /// - /// This configuration flag has no effect on DatabasePool readers: those - /// never allow leaving a transaction opened at the end of a read access. - /// - /// Default: false + /// This configuration flag has no effect on ``DatabasePool`` reader + /// connections: those never allow leaving a transaction opened at the end + /// of a read access. public var allowsUnsafeTransactions = false // MARK: - Concurrency - /// The behavior in case of SQLITE_BUSY error. See + /// Defines the how `SQLITE_BUSY` errors are handled. /// - /// Default: immediateError + /// The default is ``Database/BusyMode/immediateError``. + /// + /// Related SQLite documentation: public var busyMode: Database.BusyMode = .immediateError /// The behavior in case of SQLITE_BUSY error, for read-only connections. /// If nil, GRDB picks a default one. var readonlyBusyMode: Database.BusyMode? = nil - /// The maximum number of concurrent readers (applies to database - /// pools only). + /// The maximum number of concurrent readers. /// - /// Default: 5 + /// This configuration applies to ``DatabasePool`` only. The default value + /// is 5. public var maximumReaderCount: Int = 5 - /// The quality of service class for the work performed by the database. + /// The quality of service, or the execution priority, or database accesses. /// - /// The quality of service is ignored if you supply a target queue. + /// The quality of service is ignored if you supply a ``targetQueue``. /// - /// Default: .userInitiated + /// The default is `userInitiated`. public var qos: DispatchQoS = .userInitiated /// The quality of service of read accesses @@ -253,40 +297,42 @@ public struct Configuration { targetQueue?.qos ?? self.qos } - /// A target queue for database accesses. + /// The target dispatch queue for database accesses. /// /// Database connections which are not read-only will prefer - /// `writeTargetQueue` instead, if it is not nil. + /// ``writeTargetQueue`` instead, if it is not nil. /// - /// When you use a database pool, make sure this queue is concurrent. This + /// When you use ``DatabasePool``, make sure this queue is concurrent. This /// is because in a serial dispatch queue, no concurrent database access can /// happen, and you may experience deadlocks. /// /// If the queue is nil, all database accesses happen in unspecified /// dispatch queues whose quality of service is determined by the - /// `qos` property. + /// ``qos`` property. /// - /// Default: nil + /// The default is nil. public var targetQueue: DispatchQueue? = nil - /// The target queue for database connections which are not read-only. + /// The target dispatch queue for database accesses which are not read-only. /// - /// If this queue is nil, writer connections are controlled by `targetQueue`. + /// If this queue is nil, writer connections are controlled + /// by ``targetQueue``. /// - /// Default: nil + /// The default is nil. public var writeTargetQueue: DispatchQueue? = nil #if os(iOS) - /// Sets whether GRDB will release memory when entering the background or - /// upon receiving a memory warning in iOS. + /// A boolean value indicating whether the database connection releases + /// memory when entering the background or upon receiving a memory warning + /// in iOS. /// - /// Default: true + /// The default is true. public var automaticMemoryManagement = true #endif // MARK: - Factory Configuration - /// Creates a factory configuration + /// Creates a factory configuration. public init() { } // MARK: - Not Public diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index fe89ed16a..58834bb85 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -214,13 +214,13 @@ extension Sequence { /// /// ## Overview /// -/// The most common way to iterate over the elements of a cursor is to use a -/// `while` loop: +/// To iterate over the elements of a cursor, use a `while` loop: /// -/// let cursor = ... -/// while let element = try cursor.next() { -/// ... -/// } +/// ```swift +/// while let element = try cursor.next() { +/// print(element) +/// } +/// ``` /// /// ## Relationship with standard Sequence and IteratorProtocol /// @@ -237,12 +237,28 @@ extension Sequence { /// `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, /// `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, /// `suffix`. +/// +/// ## Topics +/// +/// ### Supporting Types +/// +/// - ``AnyCursor`` +/// - ``DropFirstCursor`` +/// - ``DropWhileCursor`` +/// - ``EnumeratedCursor`` +/// - ``FilterCursor`` +/// - ``FlattenCursor`` +/// - ``MapCursor`` +/// - ``PrefixCursor`` +/// - ``PrefixWhileCursor`` public protocol Cursor: AnyObject { /// The type of element traversed by the cursor. associatedtype Element /// Advances to the next element and returns it, or nil if no next element - /// exists. Once nil has been returned, all subsequent calls return nil. + /// exists. + /// + /// Once nil has been returned, all subsequent calls return nil. func next() throws -> Element? /// Calls the given closure on each element in the cursor. @@ -672,24 +688,22 @@ extension Cursor where Element: StringProtocol { // MARK: Specialized Cursors -/// A type-erased cursor of Element. +/// A type-erased cursor. /// -/// This cursor forwards its next() method to an arbitrary underlying cursor -/// having the same Element type, hiding the specifics of the underlying -/// cursor. +/// An instance of `AnyCursor` forwards its operations to an underlying base +/// cursor having the same `Element` type, hiding the specifics of the +/// underlying cursor. public final class AnyCursor: Cursor { private let _next: () throws -> Element? private let _forEach: ((Element) throws -> Void) throws -> Void - /// Creates a cursor that wraps a base cursor but whose type depends only on - /// the base cursor’s element type + /// Creates a new cursor that wraps and forwards operations to `base`. public init(_ base: C) where C.Element == Element { _next = base.next _forEach = base.forEach } - /// Creates a cursor that wraps a base iterator but whose type depends only - /// on the base iterator’s element type + /// Creates a new cursor whose elements are elements of `iterator`. public convenience init(iterator: I) where I: IteratorProtocol, I.Element == Element { @@ -697,15 +711,14 @@ public final class AnyCursor: Cursor { self.init { iterator.next() } } - /// Creates a cursor that wraps a base sequence but whose type depends only - /// on the base sequence’s element type - public convenience init(_ s: S) + /// Creates a new cursor whose elements are elements of `sequence`. + public convenience init(_ sequence: S) where S: Sequence, S.Element == Element { - self.init(iterator: s.makeIterator()) + self.init(iterator: sequence.makeIterator()) } - /// Creates a cursor that wraps the given closure in its next() method + /// Creates a cursor that wraps the given closure in its ``next()`` method. public init(_ next: @escaping () throws -> Element?) { _next = next _forEach = { @@ -720,8 +733,9 @@ public final class AnyCursor: Cursor { } } -/// :nodoc: -public final class DropFirstCursor: Cursor { +/// A `Cursor` that consumes and drops n elements from an underlying `Base` +/// cursor before possibly returning the first available element. +public final class DropFirstCursor { private let base: Base private let limit: Int private var dropped: Int = 0 @@ -731,7 +745,9 @@ public final class DropFirstCursor: Cursor { self.base = base self.limit = limit } - +} + +extension DropFirstCursor: Cursor { public func next() throws -> Base.Element? { while dropped < limit { if try base.next() == nil { @@ -744,11 +760,9 @@ public final class DropFirstCursor: Cursor { } } -/// A cursor whose elements consist of the elements that follow the initial -/// consecutive elements of some base cursor that satisfy a given predicate. -/// -/// :nodoc: -public final class DropWhileCursor: Cursor { +/// A `Cursor` whose elements consist of the elements that follow the initial +/// consecutive elements of some `Base` cursor that satisfy a given predicate. +public final class DropWhileCursor { private let base: Base private let predicate: (Base.Element) throws -> Bool private var predicateHasFailed = false @@ -757,7 +771,9 @@ public final class DropWhileCursor: Cursor { self.base = base self.predicate = predicate } - +} + +extension DropWhileCursor: Cursor { public func next() throws -> Base.Element? { if predicateHasFailed { return try base.next() @@ -775,19 +791,24 @@ public final class DropWhileCursor: Cursor { /// An enumeration of the elements of a cursor. /// -/// To create an instance of `EnumeratedCursor`, call the `enumerated()` method -/// on a cursor: +/// `EnumeratedCursor` is a cursor of pairs _(n, x)_, where _ns_ are consecutive +/// `Int` values starting at zero, and _xs_ are the elements of a `Base` cursor. /// -/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'") -/// let c = cursor.enumerated() -/// while let (n, x) = c.next() { -/// print("\(n): \(x)") -/// } -/// // Prints: "0: foo" -/// // Prints: "1: bar" +/// To create an instance of `EnumeratedCursor`, call `enumerated()` on a +/// cursor. For example: /// -/// :nodoc: -public final class EnumeratedCursor: Cursor { +/// ```swift +/// let base = try String.fetchCursor(db, sql: """ +/// SELECT 'foo' UNION ALL SELECT 'bar' +/// """) +/// let cursor = base.enumerated() +/// while let (n, x) = cursor.next() { +/// print("\(n): \(x)") +/// } +/// // Prints: "0: foo" +/// // Prints: "1: bar" +/// ``` +public final class EnumeratedCursor { private let base: Base private var index: Int @@ -795,7 +816,9 @@ public final class EnumeratedCursor: Cursor { self.base = base self.index = 0 } - +} + +extension EnumeratedCursor: Cursor { public func next() throws -> (Int, Base.Element)? { guard let element = try base.next() else { return nil } defer { index += 1 } @@ -810,11 +833,9 @@ public final class EnumeratedCursor: Cursor { } } -/// A cursor whose elements consist of the elements of some base cursor that +/// A `Cursor` whose elements consist of the elements of some `Base` cursor that /// also satisfy a given predicate. -/// -/// :nodoc: -public final class FilterCursor: Cursor { +public final class FilterCursor { private let base: Base private let isIncluded: (Base.Element) throws -> Bool @@ -822,7 +843,9 @@ public final class FilterCursor: Cursor { self.base = base self.isIncluded = isIncluded } - +} + +extension FilterCursor: Cursor { public func next() throws -> Base.Element? { while let element = try base.next() { if try isIncluded(element) { @@ -841,20 +864,18 @@ public final class FilterCursor: Cursor { } } -/// A cursor consisting of all the elements contained in each segment contained -/// in some Base cursor. -/// -/// See Cursor.joined(), Cursor.flatMap(_:), Sequence.flatMap(_:) -/// -/// :nodoc: -public final class FlattenCursor: Cursor where Base.Element: Cursor { +/// A `Cursor` consisting of all the elements contained in each segment +/// contained in some `Base` cursor. +public final class FlattenCursor where Base.Element: Cursor { private let base: Base private var inner: Base.Element? init(_ base: Base) { self.base = base } - +} + +extension FlattenCursor: Cursor { public func next() throws -> Base.Element.Element? { while true { if let element = try inner?.next() { @@ -868,13 +889,9 @@ public final class FlattenCursor: Cursor where Base.Element: Curso } } -/// A Cursor whose elements consist of those in a Base Cursor passed through a -/// transform function returning Element. -/// -/// See Cursor.map(_:) -/// -/// :nodoc: -public final class MapCursor: Cursor { +/// A `Cursor` whose elements consist of those in a `Base` cursor passed through +/// a transform function returning Element. +public final class MapCursor { private let base: Base private let transform: (Base.Element) throws -> Element @@ -882,7 +899,9 @@ public final class MapCursor: Cursor { self.base = base self.transform = transform } - +} + +extension MapCursor: Cursor { public func next() throws -> Element? { guard let element = try base.next() else { return nil } return try transform(element) @@ -895,11 +914,9 @@ public final class MapCursor: Cursor { } } -/// A cursor that only consumes up to `n` elements from an underlying +/// A `Cursor` that only consumes up to `n` elements from an underlying /// `Base` cursor. -/// -/// :nodoc: -public final class PrefixCursor: Cursor { +public final class PrefixCursor { private let base: Base private let maxLength: Int private var taken = 0 @@ -908,7 +925,9 @@ public final class PrefixCursor: Cursor { self.base = base self.maxLength = maxLength } - +} + +extension PrefixCursor: Cursor { public func next() throws -> Base.Element? { if taken >= maxLength { return nil } taken += 1 @@ -922,11 +941,9 @@ public final class PrefixCursor: Cursor { } } -/// A cursor whose elements consist of the initial consecutive elements of -/// some base cursor that satisfy a given predicate. -/// -/// :nodoc: -public final class PrefixWhileCursor: Cursor { +/// A `Cursor` whose elements consist of the initial consecutive elements of +/// some `Base` cursor that satisfy a given predicate. +public final class PrefixWhileCursor { private let base: Base private let predicate: (Base.Element) throws -> Bool private var predicateHasFailed = false @@ -935,7 +952,9 @@ public final class PrefixWhileCursor: Cursor { self.base = base self.predicate = predicate } - +} + +extension PrefixWhileCursor: Cursor { public func next() throws -> Base.Element? { if !predicateHasFailed, let nextElement = try base.next() { if try predicate(nextElement) { diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 8bdd3c6fa..02ac56a37 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -81,8 +81,9 @@ extension Database { /// Clears the database schema cache. /// - /// You may need to clear the cache manually if the database schema is - /// modified by another connection. + /// If the database schema is modified by another SQLite connection to the + /// same database file, your application may need to call this method in + /// order to avoid undesired consequences. public func clearSchemaCache() { SchedulingWatchdog.preconditionValidQueue(self) schemaCache.clear() @@ -220,7 +221,7 @@ extension Database { /// Returns whether a table is an internal GRDB table. /// - /// Those are tables whose name begins with "grdb_". + /// Those are tables whose name begins with `grdb_`. public static func isGRDBInternalTable(_ tableName: String) -> Bool { tableName.starts(with: "grdb_") } @@ -253,7 +254,9 @@ extension Database { /// table has no explicit primary key, the result is the hidden /// "rowid" column. /// - /// - throws: A DatabaseError if table does not exist. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no + /// such table exists in the main or temp schema, or in an + /// attached database. public func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo { for schemaIdentifier in try schemaIdentifiers() { if let result = try primaryKey(TableIdentifier(schemaID: schemaIdentifier, name: tableName)) { @@ -413,7 +416,9 @@ extension Database { /// the columns contain the primary key or a unique index, use /// ``table(_:hasUniqueKey:)``. /// - /// - throws: A DatabaseError if table does not exist. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no + /// such table exists in the main or temp schema, or in an + /// attached database. public func indexes(on tableName: String) throws -> [IndexInfo] { for schemaIdentifier in try schemaIdentifiers() { if let result = try indexes(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) { @@ -473,18 +478,25 @@ extension Database { return indexes } - /// True if a sequence of columns uniquely identifies a row, that is to say - /// if the columns contain the primary key, or a unique index. + /// Returns whether a sequence of columns uniquely identifies a row. + /// + /// The result is true if and only if the primary key, or a unique index, is + /// included in the sequence. /// /// For example: /// - /// // CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c); - /// // CREATE UNIQUE INDEX i ON t(a, b); - /// try db.table("t", hasUniqueKey: ["id"]) // true - /// try db.table("t", hasUniqueKey: ["a", "b"]) // true - /// try db.table("t", hasUniqueKey: ["c"]) // false - /// try db.table("t", hasUniqueKey: ["id", "a"]) // true - /// try db.table("t", hasUniqueKey: ["id", "a", "b", "c"]) // true + /// ```swift + /// // One table with one primary key (id), and a unique index (a, b): + /// // + /// // > CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c); + /// // > CREATE UNIQUE INDEX i ON t(a, b); + /// try db.table("t", hasUniqueKey: ["id"]) // true + /// try db.table("t", hasUniqueKey: ["a", "b"]) // true + /// try db.table("t", hasUniqueKey: ["b", "a"]) // true + /// try db.table("t", hasUniqueKey: ["c"]) // false + /// try db.table("t", hasUniqueKey: ["id", "a"]) // true + /// try db.table("t", hasUniqueKey: ["id", "a", "b", "c"]) // true + /// ``` public func table( _ tableName: String, hasUniqueKey columns: Columns) @@ -494,9 +506,11 @@ extension Database { try columnsForUniqueKey(Array(columns), in: tableName) != nil } - /// The foreign keys defined on table named `tableName`. + /// Returns the foreign keys defined on table named `tableName`. /// - /// - throws: A DatabaseError if table does not exist. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no + /// such table exists in the main or temp schema, or in an + /// attached database. public func foreignKeys(on tableName: String) throws -> [ForeignKeyInfo] { for schemaIdentifier in try schemaIdentifiers() { if let result = try foreignKeys(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) { @@ -577,6 +591,10 @@ extension Database { } /// Returns a cursor over foreign key violations in the table. + /// + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no + /// such table exists in the main or temp schema, or in an + /// attached database. public func foreignKeyViolations(in tableName: String) throws -> RecordCursor { for schemaIdentifier in try schemaIdentifiers() { if try exists(type: .table, name: tableName, in: schemaIdentifier) { @@ -592,14 +610,26 @@ extension Database { """) } - /// Throws a DatabaseError of extended code `SQLITE_CONSTRAINT_FOREIGNKEY` - /// if there exists a foreign key violation in the database. + /// Throws an error if there exists a foreign key violation in the database. + /// + /// On the first foreign key violation found in the database, this method + /// throws a ``DatabaseError`` with extended code + /// `SQLITE_CONSTRAINT_FOREIGNKEY`. + /// + /// If you are looking for the list of foreign key violations, prefer + /// ``foreignKeyViolations()`` instead. public func checkForeignKeys() throws { try checkForeignKeys(from: foreignKeyViolations()) } - /// Throws a DatabaseError of extended code `SQLITE_CONSTRAINT_FOREIGNKEY` - /// if there exists a foreign key violation in the table. + /// Throws an error if there exists a foreign key violation in the table. + /// + /// On the first foreign key violation found in the table, this method + /// throws a ``DatabaseError`` with extended code + /// `SQLITE_CONSTRAINT_FOREIGNKEY`. + /// + /// If you are looking for the list of foreign key violations, prefer + /// ``foreignKeyViolations(in:)`` instead. public func checkForeignKeys(in tableName: String) throws { try checkForeignKeys(from: foreignKeyViolations(in: tableName)) } @@ -613,7 +643,9 @@ extension Database { /// Returns the actual name of the database table, or nil if the table does /// not exist. /// - /// - throws: A DatabaseError if table does not exist. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no + /// such table exists in the main or temp schema, or in an + /// attached database. func canonicalTableName(_ tableName: String) throws -> String? { for schemaIdentifier in try schemaIdentifiers() { if let result = try schema(schemaIdentifier).canonicalName(tableName, ofType: .table) { @@ -635,9 +667,11 @@ extension Database { extension Database { - /// The columns in the table, or view, named `tableName`. + /// Returns the columns in a table or a view. /// - /// - throws: A DatabaseError if table does not exist. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no + /// such table or view with this name exists in the main or temp schema, or + /// in an attached database. public func columns(in tableName: String) throws -> [ColumnInfo] { for schemaIdentifier in try schemaIdentifiers() { if let result = try columns(in: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) { @@ -794,43 +828,29 @@ extension Database { } } -/// A column of a database table. +/// Information about a column of a database table. /// -/// This type closely matches the information returned by the -/// `table_info` and `table_xinfo` pragmas. +/// You get `ColumnInfo` instances with the ``Database/columns(in:)`` +/// `Database` method. /// -/// sqlite> CREATE TABLE player ( -/// ...> id INTEGER PRIMARY KEY, -/// ...> firstName TEXT, -/// ...> lastName TEXT); -/// sqlite> PRAGMA table_info(player); -/// cid name type notnull dflt_value pk -/// ------ ---------- ---------- ---------- ---------- ----- -/// 0 id INTEGER 0 1 -/// 1 firstName TEXT 0 0 -/// 2 lastName TEXT 0 0 -/// sqlite> PRAGMA table_xinfo(player); -/// cid name type notnull dflt_value pk hidden -/// ------ ---------- ---------- ---------- ---------- ----- ---------- -/// 0 id INTEGER 0 1 0 -/// 1 firstName TEXT 0 0 0 -/// 2 lastName TEXT 0 0 0 +/// Related SQLite documentation: /// -/// See `Database.columns(in:)` and +/// - [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 { let cid: Int let hidden: Int? - /// The column name + /// The column name. public let name: String - /// The column data type + /// The column data type. /// /// The casing of this string depends on the SQLite version: make sure you /// process this string in a case-insensitive way. public let type: String - /// True if and only if the column is constrained to be not null. + /// A boolean value indicating if the column is constrained to be not null. public let isNotNull: Bool /// The SQL snippet that defines the default value, if any. @@ -841,31 +861,34 @@ public struct ColumnInfo: FetchableRecord { /// expression may be a literal, as `1`, or `'foo'`. It may also contain a /// non-constant expression such as `CURRENT_TIMESTAMP`. /// - /// For more information, see - /// . + /// Related SQLite documentation: . /// /// For example: /// - /// try db.execute(sql: """ - /// CREATE TABLE player( - /// id INTEGER PRIMARY KEY, - /// name TEXT DEFAULT 'Anonymous', - /// score INT DEFAULT 0, - /// creationDate DATE DEFAULT CURRENT_TIMESTAMP - /// ) - /// """) - /// let columnInfos = try db.columns(in: "player") - /// columnInfos[0].defaultValueSQL // nil - /// columnInfos[1].defaultValueSQL // "'Anonymous'" - /// columnInfos[2].defaultValueSQL // "0" - /// columnInfos[3].defaultValueSQL // "CURRENT_TIMESTAMP" + /// ```swift + /// try db.execute(sql: """ + /// CREATE TABLE player( + /// id INTEGER PRIMARY KEY, + /// name TEXT DEFAULT 'Anonymous', + /// score INT DEFAULT 0, + /// creationDate DATE DEFAULT CURRENT_TIMESTAMP + /// ) + /// """) + /// let columnInfos = try db.columns(in: "player") + /// columnInfos[0].defaultValueSQL // nil + /// columnInfos[1].defaultValueSQL // "'Anonymous'" + /// columnInfos[2].defaultValueSQL // "0" + /// columnInfos[3].defaultValueSQL // "CURRENT_TIMESTAMP" + /// ``` + /// + /// Related SQLite documentation: . public let defaultValueSQL: String? - /// For columns that are part of the primary key, this is the one-based - /// index of the column in the primary key. For other columns, it is zero. + /// The one-based index of the column in the primary key. + /// + /// For columns that are not part of the primary key, it is zero. public let primaryKeyIndex: Int - /// :nodoc: public init(row: Row) { cid = row["cid"] name = row["name"] @@ -877,13 +900,17 @@ public struct ColumnInfo: FetchableRecord { } } -/// An index on a database table. +/// Information about an index. /// -/// See `Database.indexes(on:)` +/// You get `ForeignKeyInfo` instances with the ``Database/indexes(on:)`` +/// `Database` method. +/// +/// Related SQLite documentation: +/// +/// - [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 { /// The origin of an index. - /// - /// See ``Database/indexes(on:)``. public struct Origin: RawRepresentable, Equatable, DatabaseValueConvertible { public var rawValue: String @@ -891,46 +918,52 @@ public struct IndexInfo { self.rawValue = rawValue } - /// An index created from a CREATE INDEX statement. + /// An index created from a `CREATE INDEX` statement. public static let createIndex = Origin(rawValue: "c") - /// An index created by a UNIQUE constraint. + /// An index created by a `UNIQUE` constraint. public static let uniqueConstraint = Origin(rawValue: "u") - /// An index created by a PRIMARY KEY constraint. + /// An index created by a `PRIMARY KEY` constraint. public static let primaryKeyConstraint = Origin(rawValue: "pk") } - /// The name of the index + /// The name of the index. public let name: String - /// The indexed columns + /// The indexed columns. public let columns: [String] - /// True if the index is unique + /// A boolean value indicating if the index is unique. public let isUnique: Bool - /// The origin of the index + /// The origin of the index. public let origin: Origin } -/// A foreign key violation produced by PRAGMA foreign_key_check +/// A foreign key violation. /// -/// See +/// You get instances of `ForeignKeyViolation` from the `Database` methods +/// ``Database/foreignKeyViolations()`` and +/// ``Database/foreignKeyViolations(in:)`` methods. +/// +/// Related SQLite documentation: public struct ForeignKeyViolation: FetchableRecord, CustomStringConvertible { - /// The name of the table that contains the `REFERENCES` clause + /// The name of the table that contains the foreign key. public var originTable: String - /// The rowid of the row that contains the invalid `REFERENCES` clause, or - /// nil if the origin table is a `WITHOUT ROWID` table. + /// The rowid of the row that contains the foreign key violation. + /// + /// If it nil if the origin table is a `WITHOUT ROWID` table. public var originRowID: Int64? /// The name of the table that is referred to. public var destinationTable: String - /// The id of the specific foreign key constraint that failed. This id - /// matches `ForeignKeyInfo.id`. See `Database.foreignKeys(on:)` for more - /// information. + /// The id of the foreign key constraint that failed. + /// + /// This id matches the ``ForeignKeyInfo/id`` property in + /// ``ForeignKeyInfo``. See ``Database/foreignKeys(on:)``. public var foreignKeyId: Int public init(row: Row) { @@ -940,6 +973,15 @@ public struct ForeignKeyViolation: FetchableRecord, CustomStringConvertible { foreignKeyId = row[3] } + /// A description of the foreign key violation. + /// + /// For example: + /// + /// ``` + /// FOREIGN KEY constraint violation - from player to team, in rowid 1 + /// ``` + /// + /// See also ``failureDescription(_:)``. public var description: String { if let originRowID = originRowID { return """ @@ -953,10 +995,16 @@ public struct ForeignKeyViolation: FetchableRecord, CustomStringConvertible { } } - /// Returns a precise description of the foreign key violation. + /// A precise description of the foreign key violation. /// - /// For example: 'FOREIGN KEY constraint violation - from player(teamId) to team(id), - /// in [id:1 teamId:2 name:"O'Brien" score: 1000]' + /// For example: + /// + /// ``` + /// FOREIGN KEY constraint violation - from player(teamId) to team(id), + /// in [id:1 teamId:2 name:"O'Brien" score: 1000] + /// ``` + /// + /// See also ``description``. public func failureDescription(_ db: Database) throws -> String { // Grab detailed information, if possible, for better error message let originRow = try originRowID.flatMap { rowid in @@ -986,7 +1034,9 @@ public struct ForeignKeyViolation: FetchableRecord, CustomStringConvertible { return description } - /// Returns a DatabaseError of extended code `SQLITE_CONSTRAINT_FOREIGNKEY` + /// Converts the violation into a ``DatabaseError``. + /// + /// The returned error has the extended code `SQLITE_CONSTRAINT_FOREIGNKEY`. public func databaseError(_ db: Database) -> DatabaseError { // Grab detailed information, if possible, for better error message. // If detailed information is not available, fallback to plain description. @@ -997,45 +1047,52 @@ public struct ForeignKeyViolation: FetchableRecord, CustomStringConvertible { } } -/// Primary keys are returned from the Database.primaryKey(_:) method. +/// Information about a primary key. +/// +/// You get `PrimaryKeyInfo` instances with the ``Database/primaryKey(_:)`` +/// `Database` method. /// /// When the table's primary key is the rowid: /// -/// // CREATE TABLE item (name TEXT) -/// let pk = try db.primaryKey("item") -/// pk.columns // ["rowid"] -/// pk.rowIDColumn // nil -/// pk.isRowID // true +/// ```swift +/// // CREATE TABLE item (name TEXT) +/// let pk = try db.primaryKey("item") +/// pk.columns // ["rowid"] +/// pk.rowIDColumn // nil +/// pk.isRowID // true /// -/// // CREATE TABLE citizen ( -/// // id INTEGER PRIMARY KEY, -/// // name TEXT -/// // ) -/// let pk = try db.primaryKey("citizen")! -/// pk.columns // ["id"] -/// pk.rowIDColumn // "id" -/// pk.isRowID // true +/// // CREATE TABLE citizen ( +/// // id INTEGER PRIMARY KEY, +/// // name TEXT +/// // ) +/// let pk = try db.primaryKey("citizen")! +/// pk.columns // ["id"] +/// pk.rowIDColumn // "id" +/// pk.isRowID // true +/// ``` /// /// When the table's primary key is not the rowid: /// -/// // CREATE TABLE country ( -/// // isoCode TEXT NOT NULL PRIMARY KEY -/// // name TEXT -/// // ) -/// let pk = db.primaryKey("country")! -/// pk.columns // ["isoCode"] -/// pk.rowIDColumn // nil -/// pk.isRowID // false +/// ```swift +/// // CREATE TABLE country ( +/// // isoCode TEXT NOT NULL PRIMARY KEY +/// // name TEXT +/// // ) +/// let pk = try db.primaryKey("country")! +/// pk.columns // ["isoCode"] +/// pk.rowIDColumn // nil +/// pk.isRowID // false /// -/// // CREATE TABLE citizenship ( -/// // citizenID INTEGER NOT NULL REFERENCES citizen(id) -/// // countryIsoCode TEXT NOT NULL REFERENCES country(isoCode) -/// // PRIMARY KEY (citizenID, countryIsoCode) -/// // ) -/// let pk = db.primaryKey("citizenship")! -/// pk.columns // ["citizenID", "countryIsoCode"] -/// pk.rowIDColumn // nil -/// pk.isRowID // false +/// // CREATE TABLE citizenship ( +/// // citizenID INTEGER NOT NULL REFERENCES citizen(id) +/// // countryIsoCode TEXT NOT NULL REFERENCES country(isoCode) +/// // PRIMARY KEY (citizenID, countryIsoCode) +/// // ) +/// let pk = try db.primaryKey("citizenship")! +/// pk.columns // ["citizenID", "countryIsoCode"] +/// pk.rowIDColumn // nil +/// pk.isRowID // false +/// ``` public struct PrimaryKeyInfo { private enum Impl { /// The hidden rowID. @@ -1063,7 +1120,7 @@ public struct PrimaryKeyInfo { static let hiddenRowID = PrimaryKeyInfo(impl: .hiddenRowID) - /// The columns in the primary key; this array is never empty. + /// The columns in the primary key. This array is never empty. public var columns: [String] { switch impl { case .hiddenRowID: @@ -1075,7 +1132,8 @@ public struct PrimaryKeyInfo { } } - /// When not nil, the name of the column that contains the INTEGER PRIMARY KEY. + /// When not nil, the name of the column that contains the + /// `INTEGER PRIMARY KEY`. public var rowIDColumn: String? { switch impl { case .hiddenRowID: @@ -1087,7 +1145,7 @@ public struct PrimaryKeyInfo { } } - /// When true, the primary key is the rowid: + /// A boolean value indicating if the primary key is the rowid. public var isRowID: Bool { switch impl { case .hiddenRowID: @@ -1099,7 +1157,9 @@ public struct PrimaryKeyInfo { } } - /// When false, the table is a WITHOUT ROWID table + /// A boolean value indicating if the table has a rowid. + /// + /// Related SQLite documentation: var tableHasRowID: Bool { switch impl { case .hiddenRowID: @@ -1111,7 +1171,7 @@ public struct PrimaryKeyInfo { } } - /// The name of the fastest primary key column + /// The name of the fastest primary key column. /// /// Returns nil for WITHOUT ROWID tables with a multi-columns primary key var fastPrimaryKeyColumn: String? { @@ -1140,30 +1200,34 @@ public struct PrimaryKeyInfo { } } -/// You get foreign keys from table names, with the -/// `foreignKeys(on:)` method. +/// Information about a foreign key. +/// +/// You get `ForeignKeyInfo` instances with the ``Database/foreignKeys(on:)`` +/// `Database` method. +/// +/// Related SQLite documentation: [pragma `foreign_key_list`](https://www.sqlite.org/pragma.html#pragma_foreign_key_list). public struct ForeignKeyInfo { - /// The first column in the output of the `foreign_key_list` pragma + /// The first column in the output of the `foreign_key_list` pragma. public var id: Int - /// The name of the destination table + /// The name of the destination table. public let destinationTable: String - /// The column to column mapping + /// The column to column mapping. public let mapping: [(origin: String, destination: String)] - /// The origin columns + /// The origin columns. public var originColumns: [String] { mapping.map(\.origin) } - /// The destination columns + /// The destination columns. public var destinationColumns: [String] { mapping.map(\.destination) } } -/// See +/// Related SQLite documentation: struct TableInfo: FetchableRecord { struct Kind: RawRepresentable { var rawValue: String diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index e6b4d17cd..25993284b 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -8,17 +8,19 @@ extension Database { /// /// For example: /// - /// let statement = try db.makeStatement(sql: "SELECT * FROM player WHERE id = ?") - /// let player1 = try Player.fetchOne(statement, arguments: [1])! - /// let player2 = try Player.fetchOne(statement, arguments: [2])! + /// ```swift + /// let statement = try db.makeStatement(sql: "SELECT * FROM player WHERE id = ?") + /// let player1 = try Player.fetchOne(statement, arguments: [1])! + /// let player2 = try Player.fetchOne(statement, arguments: [2])! /// - /// let statement = try db.makeStatement(sql: "INSERT INTO player (name) VALUES (?)") - /// try statement.execute(arguments: ["Arthur"]) - /// try statement.execute(arguments: ["Barbara"]) + /// let statement = try db.makeStatement(sql: "INSERT INTO player (name) VALUES (?)") + /// try statement.execute(arguments: ["Arthur"]) + /// try statement.execute(arguments: ["Barbara"]) + /// ``` /// - /// - parameter sql: An SQL query. - /// - returns: A Statement. - /// - throws: A DatabaseError whenever SQLite could not parse the sql query. + /// - parameter sql: An SQL string. + /// - returns: A prepared statement. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func makeStatement(sql: String) throws -> Statement { try makeStatement(sql: sql, prepFlags: 0) } @@ -27,33 +29,38 @@ extension Database { /// /// For example: /// - /// let statement = try db.makeStatement(literal: "SELECT * FROM player WHERE id = ?") - /// let player1 = try Player.fetchOne(statement, arguments: [1])! - /// let player2 = try Player.fetchOne(statement, arguments: [2])! + /// ```swift + /// let statement = try db.makeStatement(literal: "SELECT * FROM player WHERE id = ?") + /// let player1 = try Player.fetchOne(statement, arguments: [1])! + /// let player2 = try Player.fetchOne(statement, arguments: [2])! /// - /// let statement = try db.makeStatement(literal: "INSERT INTO player (name) VALUES (?)") - /// try statement.execute(arguments: ["Arthur"]) - /// try statement.execute(arguments: ["Barbara"]) + /// let statement = try db.makeStatement(literal: "INSERT INTO player (name) VALUES (?)") + /// try statement.execute(arguments: ["Arthur"]) + /// try statement.execute(arguments: ["Barbara"]) + /// ``` /// - /// - parameter sqlLiteral: An `SQL` literal. - /// - returns: A Statement. - /// - throws: A DatabaseError whenever SQLite could not parse the sql query. - /// - precondition: No argument must be set, or all arguments must be set. - /// An error is raised otherwise. + /// In the provided literal, no argument must be set, or all arguments must + /// be set. An error is raised otherwise. For example: /// - /// // OK - /// try makeStatement(literal: """ - /// SELECT COUNT(*) FROM player WHERE score > ? - /// """) - /// try makeStatement(literal: """ - /// SELECT COUNT(*) FROM player WHERE score > \(1000) - /// """) + /// ```swift + /// // OK + /// try makeStatement(literal: """ + /// SELECT COUNT(*) FROM player WHERE score > ? + /// """) + /// try makeStatement(literal: """ + /// SELECT COUNT(*) FROM player WHERE score > \(1000) + /// """) /// - /// // NOT OK - /// try makeStatement(literal: """ - /// SELECT COUNT(*) FROM player - /// WHERE color = ? AND score > \(1000) - /// """) + /// // NOT OK (first argument is not set, but second is) + /// try makeStatement(literal: """ + /// SELECT COUNT(*) FROM player + /// WHERE color = ? AND score > \(1000) + /// """) + /// ``` + /// + /// - parameter sqlLiteral: An ``SQL`` literal. + /// - returns: A prepared statement. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func makeStatement(literal sqlLiteral: SQL) throws -> Statement { let (sql, arguments) = try sqlLiteral.build(self) let statement = try makeStatement(sql: sql) @@ -72,11 +79,11 @@ extension Database { /// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])! /// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])! /// - /// - parameter sql: An SQL query. + /// - parameter sql: An SQL string. /// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from /// SQLite 3.20.0, see ) - /// - returns: A Statement. - /// - throws: A DatabaseError whenever SQLite could not parse the sql query. + /// - returns: A prepared statement. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. func makeStatement(sql: String, prepFlags: CUnsignedInt) throws -> Statement { let statements = SQLStatementCursor(database: self, sql: sql, arguments: nil, prepFlags: prepFlags) guard let statement = try statements.next() else { @@ -113,20 +120,22 @@ extension Database { /// /// For example: /// - /// let statement = try db.cachedStatement(sql: "SELECT * FROM player WHERE id = ?") - /// let player1 = try Player.fetchOne(statement, arguments: [1])! - /// let player2 = try Player.fetchOne(statement, arguments: [2])! + /// ```swift + /// let statement = try db.cachedStatement(sql: "SELECT * FROM player WHERE id = ?") + /// let player1 = try Player.fetchOne(statement, arguments: [1])! + /// let player2 = try Player.fetchOne(statement, arguments: [2])! /// - /// let statement = try db.cachedStatement(sql: "INSERT INTO player (name) VALUES (?)") - /// try statement.execute(arguments: ["Arthur"]) - /// try statement.execute(arguments: ["Barbara"]) + /// let statement = try db.cachedStatement(sql: "INSERT INTO player (name) VALUES (?)") + /// try statement.execute(arguments: ["Arthur"]) + /// try statement.execute(arguments: ["Barbara"]) + /// ``` /// /// The returned statement may have already been used: it may or may not /// contain values for its eventual arguments. /// - /// - parameter sql: An SQL query. - /// - returns: A Statement. - /// - throws: A DatabaseError whenever SQLite could not parse the sql query. + /// - parameter sql: An SQL string. + /// - returns: A prepared statement. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func cachedStatement(sql: String) throws -> Statement { try publicStatementCache.statement(sql) } @@ -135,33 +144,38 @@ extension Database { /// /// For example: /// - /// let statement = try db.cachedStatement(literal: "SELECT * FROM player WHERE id = ?") - /// let player1 = try Player.fetchOne(statement, arguments: [1])! - /// let player2 = try Player.fetchOne(statement, arguments: [2])! + /// ```swift + /// let statement = try db.cachedStatement(literal: "SELECT * FROM player WHERE id = ?") + /// let player1 = try Player.fetchOne(statement, arguments: [1])! + /// let player2 = try Player.fetchOne(statement, arguments: [2])! /// - /// let statement = try db.cachedStatement(literal: "INSERT INTO player (name) VALUES (?)") - /// try statement.execute(arguments: ["Arthur"]) - /// try statement.execute(arguments: ["Barbara"]) + /// let statement = try db.cachedStatement(literal: "INSERT INTO player (name) VALUES (?)") + /// try statement.execute(arguments: ["Arthur"]) + /// try statement.execute(arguments: ["Barbara"]) + /// ``` /// - /// - parameter sqlLiteral: An `SQL` literal. - /// - returns: A Statement. - /// - throws: A DatabaseError whenever SQLite could not parse the sql query. - /// - precondition: No argument must be set, or all arguments must be set. - /// An error is raised otherwise. + /// In the provided literal, no argument must be set, or all arguments must + /// be set. An error is raised otherwise. For example: /// - /// // OK - /// try cachedStatement(literal: """ - /// SELECT COUNT(*) FROM player WHERE score > ? - /// """) - /// try cachedStatement(literal: """ - /// SELECT COUNT(*) FROM player WHERE score > \(1000) - /// """) + /// ```swift + /// // OK + /// try cachedStatement(literal: """ + /// SELECT COUNT(*) FROM player WHERE score > ? + /// """) + /// try cachedStatement(literal: """ + /// SELECT COUNT(*) FROM player WHERE score > \(1000) + /// """) /// - /// // NOT OK - /// try cachedStatement(literal: """ - /// SELECT COUNT(*) FROM player - /// WHERE color = ? AND score > \(1000) - /// """) + /// // NOT OK (first argument is not set, but second is) + /// try cachedStatement(literal: """ + /// SELECT COUNT(*) FROM player + /// WHERE color = ? AND score > \(1000) + /// """) + /// ``` + /// + /// - parameter sqlLiteral: An ``SQL`` literal. + /// - returns: A prepared statement. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func cachedStatement(literal sqlLiteral: SQL) throws -> Statement { let (sql, arguments) = try sqlLiteral.build(self) let statement = try cachedStatement(sql: sql) @@ -177,83 +191,95 @@ extension Database { try internalStatementCache.statement(sql) } - /// Returns a cursor of all SQL statements separated by semi-colons. + /// Returns a cursor of prepared statements. /// /// For example: /// - /// let statements = try db.allStatements(sql: """ - /// INSERT INTO player (name) VALUES (?); - /// INSERT INTO player (name) VALUES (?); - /// INSERT INTO player (name) VALUES (?); - /// """, arguments: ["Arthur", "Barbara", "O'Brien"]) - /// while let statement = try statements.next() { - /// try statement.execute() - /// } + /// ```swift + /// let statements = try db.allStatements(sql: """ + /// INSERT INTO player (name) VALUES (?); + /// INSERT INTO player (name) VALUES (?); + /// INSERT INTO player (name) VALUES (?); + /// """, arguments: ["Arthur", "Barbara", "O'Brien"]) + /// while let statement = try statements.next() { + /// try statement.execute() + /// } + /// ``` + /// + /// The `arguments` parameter must be nil, or all arguments must be set. The + /// returned cursor will throw an error otherwise. For example: + /// + /// ```swift + /// // OK + /// try allStatements(sql: """ + /// SELECT COUNT(*) FROM player WHERE score < ?; + /// SELECT COUNT(*) FROM player WHERE score > ?; + /// """) + /// + /// try allStatements(sql: """ + /// SELECT COUNT(*) FROM player WHERE score < ?; + /// SELECT COUNT(*) FROM player WHERE score > ?; + /// """, arguments: [1000, 1000]) + /// + /// // NOT OK (first argument is set, but second is not) + /// try allStatements(sql: """ + /// SELECT COUNT(*) FROM player WHERE score < ?; + /// SELECT COUNT(*) FROM player WHERE score > ?; + /// """, arguments: [1000]) + /// ``` /// /// - parameters: - /// - sql: An SQL query. + /// - sql: An SQL string. /// - arguments: Statement arguments. - /// - returns: A cursor of `Statement` - /// - throws: A DatabaseError whenever an SQLite error occurs. - /// - precondition: Arguments must be nil, or all arguments must be set. - /// The returned cursor will throw an error otherwise. - /// - /// // OK - /// try allStatements(sql: """ - /// SELECT COUNT(*) FROM player WHERE score < ?; - /// SELECT COUNT(*) FROM player WHERE score > ?; - /// """) - /// try allStatements(sql: """ - /// SELECT COUNT(*) FROM player WHERE score < ?; - /// SELECT COUNT(*) FROM player WHERE score > ?; - /// """, arguments: [1000, 1000]) - /// - /// // NOT OK - /// try allStatements(sql: """ - /// SELECT COUNT(*) FROM player WHERE score < ?; - /// SELECT COUNT(*) FROM player WHERE score > ?; - /// """, arguments: [1000]) + /// - returns: A cursor of prepared ``Statement``. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func allStatements(sql: String, arguments: StatementArguments? = nil) throws -> SQLStatementCursor { SQLStatementCursor(database: self, sql: sql, arguments: arguments) } - /// Returns a cursor of all SQL statements separated by semi-colons. + /// Returns a cursor of prepared statements. /// - /// Literals allow you to safely embed raw values in your SQL, without any - /// risk of syntax errors or SQL injection: + /// ``SQL`` literals allow you to safely embed raw values in your SQL, + /// without any risk of syntax errors or SQL injection: /// - /// let statements = try db.allStatements(literal: """ - /// INSERT INTO player (name) VALUES (\("Arthur")); - /// INSERT INTO player (name) VALUES (\("Barbara")); - /// INSERT INTO player (name) VALUES (\("O'Brien")); - /// """) - /// while let statement = try statements.next() { - /// try statement.execute() - /// } + /// ```swift + /// let statements = try db.allStatements(literal: """ + /// INSERT INTO player (name) VALUES (\("Arthur")); + /// INSERT INTO player (name) VALUES (\("Barbara")); + /// INSERT INTO player (name) VALUES (\("O'Brien")); + /// """) + /// while let statement = try statements.next() { + /// try statement.execute() + /// } + /// ``` /// - /// - parameter sqlLiteral: An `SQL` literal. - /// - returns: A cursor of `Statement` - /// - throws: A DatabaseError whenever an SQLite error occurs. - /// - precondition: No argument must be set, or all arguments must be set. - /// The returned cursor will throw an error otherwise. + /// In the provided literal, no argument must be set, or all arguments must + /// be set. The returned cursor will throw an error otherwise. For example: /// - /// // OK - /// try allStatements(literal: """ - /// SELECT COUNT(*) FROM player WHERE score < ?; - /// SELECT COUNT(*) FROM player WHERE score > ?; - /// """) - /// try allStatements(literal: """ - /// SELECT COUNT(*) FROM player WHERE score < \(1000); - /// SELECT COUNT(*) FROM player WHERE score > \(1000); - /// """) + /// ```swift + /// // OK + /// try allStatements(literal: """ + /// SELECT COUNT(*) FROM player WHERE score < ?; + /// SELECT COUNT(*) FROM player WHERE score > ?; + /// """) /// - /// // NOT OK - /// try allStatements(literal: """ - /// SELECT COUNT(*) FROM player WHERE score < \(1000); - /// SELECT COUNT(*) FROM player WHERE score > ?; - /// """) + /// try allStatements(literal: """ + /// SELECT COUNT(*) FROM player WHERE score < \(1000); + /// SELECT COUNT(*) FROM player WHERE score > \(1000); + /// """) + /// + /// // NOT OK (first argument is set, but second is not) + /// try allStatements(literal: """ + /// SELECT COUNT(*) FROM player WHERE score < \(1000); + /// SELECT COUNT(*) FROM player WHERE score > ?; + /// """) + /// ``` + /// + /// - parameter sqlLiteral: An ``SQL`` literal. + /// - returns: A cursor of prepared ``Statement``. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func allStatements(literal sqlLiteral: SQL) throws -> SQLStatementCursor { let context = SQLGenerationContext(self) let sql = try sqlLiteral.sql(context) @@ -263,45 +289,49 @@ extension Database { return SQLStatementCursor(database: self, sql: sql, arguments: arguments) } - /// Executes one or several SQL statements, separated by semi-colons. + /// Executes one or several SQL statements. /// /// For example: /// - /// try db.execute( - /// sql: "INSERT INTO player (name) VALUES (:name)", - /// arguments: ["name": "Arthur"]) + /// ```swift + /// try db.execute( + /// sql: "INSERT INTO player (name) VALUES (:name)", + /// arguments: ["name": "Arthur"]) /// - /// try db.execute(sql: """ - /// INSERT INTO player (name) VALUES (?); - /// INSERT INTO player (name) VALUES (?); - /// INSERT INTO player (name) VALUES (?); - /// """, arguments: ["Arthur", "Barbara", "O'Brien"]) + /// try db.execute(sql: """ + /// INSERT INTO player (name) VALUES (?); + /// INSERT INTO player (name) VALUES (?); + /// INSERT INTO player (name) VALUES (?); + /// """, arguments: ["Arthur", "Barbara", "O'Brien"]) + /// ``` /// /// - parameters: - /// - sql: An SQL query. + /// - sql: An SQL string. /// - arguments: Statement arguments. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func execute(sql: String, arguments: StatementArguments = StatementArguments()) throws { try execute(literal: SQL(sql: sql, arguments: arguments)) } - /// Executes one or several SQL statements, separated by semi-colons. + /// Executes one or several SQL statements. /// - /// Literals allow you to safely embed raw values in your SQL, without any - /// risk of syntax errors or SQL injection: + /// ``SQL`` literals allow you to safely embed raw values in your SQL, + /// without any risk of syntax errors or SQL injection: /// - /// try db.execute(literal: """ - /// INSERT INTO player (name) VALUES (\("Arthur")) - /// """) + /// ```swift + /// try db.execute(literal: """ + /// INSERT INTO player (name) VALUES (\("Arthur")) + /// """) /// - /// try db.execute(literal: """ - /// INSERT INTO player (name) VALUES (\("Arthur")); - /// INSERT INTO player (name) VALUES (\("Barbara")); - /// INSERT INTO player (name) VALUES (\("O'Brien")); - /// """) + /// try db.execute(literal: """ + /// INSERT INTO player (name) VALUES (\("Arthur")); + /// INSERT INTO player (name) VALUES (\("Barbara")); + /// INSERT INTO player (name) VALUES (\("O'Brien")); + /// """) + /// ``` /// - /// - parameter sqlLiteral: An `SQL` literal. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - parameter sqlLiteral: An ``SQL`` literal. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func execute(literal sqlLiteral: SQL) throws { let statements = try allStatements(literal: sqlLiteral) while let statement = try statements.next() { @@ -310,8 +340,8 @@ extension Database { } } -/// A cursor over all statements in a SQL string. -public class SQLStatementCursor: Cursor { +/// A cursor over all statements in an SQL string. +public class SQLStatementCursor { private let database: Database private let cString: ContiguousArray private let prepFlags: CUnsignedInt @@ -329,7 +359,9 @@ public class SQLStatementCursor: Cursor { self.offset = 0 self.arguments = arguments } - +} + +extension SQLStatementCursor: Cursor { public func next() throws -> Statement? { guard offset < cString.count - 1 /* trailing \0 */ else { // End of C string -> end of cursor. diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 876306e1e..89ef2c4c8 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -8,26 +8,162 @@ typealias SQLiteValue = OpaquePointer let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_destructor_type.self) -/// A Database connection. +/// An SQLite connection. /// -/// You don't create a database directly. Instead, you use a DatabaseQueue, or -/// a DatabasePool: +/// You don't create `Database` instances directly. Instead, you use a database +/// access method from ``DatabaseQueue``, ``DatabasePool``. +/// ``DatabaseSnapshot``, ``DatabaseMigrator`` or ``ValueObservation``. +/// For example: /// -/// let dbQueue = try DatabaseQueue(...) +/// ```swift +/// let dbQueue = try DatabaseQueue() /// -/// // The Database is the `db` in the closure: -/// try dbQueue.write { db in -/// try Player(...).insert(db) -/// } +/// // The Database is the `db` in the closure: +/// try dbQueue.write { db in +/// try Player(name: "Arthur").insert(db) +/// } +/// ``` +/// +/// ## Topics +/// +/// ### Database Information +/// +/// - ``changesCount`` +/// - ``configuration`` +/// - ``debugDescription`` +/// - ``description`` +/// - ``lastErrorCode`` +/// - ``lastErrorMessage`` +/// - ``lastInsertedRowID`` +/// - ``maximumStatementArgumentCount`` +/// - ``sqliteConnection`` +/// - ``totalChangesCount`` +/// - ``SQLiteConnection`` +/// +/// ### Database Statements +/// +/// - ``allStatements(literal:)`` +/// - ``allStatements(sql:arguments:)`` +/// - ``cachedStatement(literal:)`` +/// - ``cachedStatement(sql:)`` +/// - ``execute(literal:)`` +/// - ``execute(sql:arguments:)`` +/// - ``makeStatement(literal:)`` +/// - ``makeStatement(sql:)`` +/// - ``SQLStatementCursor`` +/// +/// ### Database Transactions +/// +/// - ``beginTransaction(_:)`` +/// - ``commit()`` +/// - ``inSavepoint(_:)`` +/// - ``inTransaction(_:_:)`` +/// - ``isInsideTransaction`` +/// - ``rollback()`` +/// - ``TransactionCompletion`` +/// - ``TransactionKind`` +/// +/// ### Observing Database Transactions +/// +/// - ``add(transactionObserver:extent:)`` +/// - ``afterNextTransaction(onCommit:onRollback:)`` +/// - ``remove(transactionObserver:)`` +/// - ``TransactionObserver`` +/// - ``TransactionObservationExtent`` +/// +/// ### Defining the Database Schema +/// +/// - ``alter(table:body:)`` +/// - ``clearSchemaCache()`` +/// - ``create(index:on:columns:options:condition:)`` +/// - ``create(table:options:body:)`` +/// - ``create(virtualTable:ifNotExists:using:)`` +/// - ``create(virtualTable:ifNotExists:using:_:)`` +/// - ``drop(index:)`` +/// - ``drop(table:)`` +/// - ``dropFTS4SynchronizationTriggers(forTable:)`` +/// - ``rename(table:to:)`` +/// - ``ColumnType`` +/// - ``ConflictResolution`` +/// - ``ForeignKeyAction`` +/// - ``IndexOptions`` +/// - ``TableAlteration`` +/// - ``TableDefinition`` +/// - ``TableOptions`` +/// - ``VirtualTableModule`` +/// +/// ### Querying the Database Schema +/// +/// - ``columns(in:)`` +/// - ``foreignKeys(on:)`` +/// - ``indexes(on:)`` +/// - ``isGRDBInternalTable(_:)`` +/// - ``isSQLiteInternalTable(_:)`` +/// - ``primaryKey(_:)`` +/// - ``table(_:hasUniqueKey:)`` +/// - ``tableExists(_:)`` +/// - ``triggerExists(_:)`` +/// - ``viewExists(_:)`` +/// - ``ColumnInfo`` +/// - ``ForeignKeyInfo`` +/// - ``IndexInfo`` +/// - ``PrimaryKeyInfo`` +/// +/// ### Collations +/// +/// - ``add(collation:)`` +/// - ``reindex(collation:)-171fj`` +/// - ``reindex(collation:)-2hxil`` +/// - ``remove(collation:)`` +/// - ``CollationName`` +/// - ``DatabaseCollation`` +/// +/// ### SQL Functions +/// +/// - ``add(function:)`` +/// - ``remove(function:)`` +/// - ``DatabaseFunction`` +/// +/// ### Integrity Checks +/// +/// - ``checkForeignKeys()`` +/// - ``checkForeignKeys(in:)`` +/// - ``foreignKeyViolations()`` +/// - ``foreignKeyViolations(in:)`` +/// - ``ForeignKeyViolation`` +/// +/// ### Notifications +/// +/// - ``resumeNotification`` +/// - ``suspendNotification`` +/// +/// ### Other Operations +/// +/// - ``backup(to:pagesPerStep:progress:)`` +/// - ``checkpoint(_:on:)`` +/// - ``logError`` +/// - ``releaseMemory()`` +/// - ``trace(options:_:)`` +/// - ``CheckpointMode`` +/// - ``DatabaseBackupProgress`` +/// - ``TraceEvent`` +/// - ``TracingOptions`` +/// +/// ### Sunsetted Methods +/// +/// - ``create(index:on:columns:unique:ifNotExists:condition:)`` +/// - ``create(table:temporary:ifNotExists:withoutRowID:body:)`` public final class Database: CustomStringConvertible, CustomDebugStringConvertible { // The Database class is not thread-safe. An instance should always be // used through a SerializedDatabase. // MARK: - SQLite C API + // TODO: make it non optional, since one can't get a `Database` instance + // after `close()`. /// The raw SQLite connection, suitable for the SQLite C API. /// - /// It is nil after the database has been successfully closed with + /// The result is nil after the database has been successfully closed with /// ``DatabaseReader/close()``. public private(set) var sqliteConnection: SQLiteConnection? @@ -35,34 +171,29 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// The error logging function. /// - /// Quoting : - /// - /// > SQLite can be configured to invoke a callback function containing an - /// > error code and a terse error message whenever anomalies occur. This - /// > mechanism is very helpful in tracking obscure problems that occur - /// > rarely and in the field. Application developers are encouraged to take - /// > advantage of the error logging facility of SQLite in their products, - /// > as it is very low CPU and memory cost but can be a huge aid - /// > for debugging. + /// Related SQLite documentation: public static var logError: LogErrorFunction? = nil { didSet { if logError != nil { - registerErrorLogCallback { (_, code, message) in + _registerErrorLogCallback { (_, code, message) in guard let logError = Database.logError else { return } guard let message = message.map(String.init) else { return } let resultCode = ResultCode(rawValue: code) logError(resultCode, message) } } else { - registerErrorLogCallback(nil) + _registerErrorLogCallback(nil) } } } - /// The database configuration + /// The database configuration. public let configuration: Configuration - /// See `Configuration.label` + /// A description of this database connection. + /// + /// The returned string is based on the ``Configuration/label`` + /// of ``configuration``. public let description: String public var debugDescription: String { "" } @@ -72,9 +203,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// The rowID of the most recently inserted row. /// /// If no row has ever been inserted using this database connection, - /// returns zero. + /// the last inserted rowID is zero. /// - /// For more detailed information, see + /// Related SQLite documentation: public var lastInsertedRowID: Int64 { SchedulingWatchdog.preconditionValidQueue(self) return sqlite3_last_insert_rowid(sqliteConnection) @@ -83,7 +214,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// The number of rows modified, inserted or deleted by the most recent /// successful INSERT, UPDATE or DELETE statement. /// - /// For more detailed information, see + /// Related SQLite documentation: public var changesCount: Int { SchedulingWatchdog.preconditionValidQueue(self) return Int(sqlite3_changes(sqliteConnection)) @@ -93,13 +224,17 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// INSERT, UPDATE or DELETE statements since the database connection was /// opened. /// - /// For more detailed information, see + /// Related SQLite documentation: public var totalChangesCount: Int { SchedulingWatchdog.preconditionValidQueue(self) return Int(sqlite3_total_changes(sqliteConnection)) } - /// True if the database connection is currently in a transaction. + /// A Boolean value indicating whether the database connection is currently + /// inside a transaction. + /// + /// A database is inside a transaction if and only if it is not in the + /// autocommit mode. See . public var isInsideTransaction: Bool { // https://sqlite.org/c3ref/get_autocommit.html // @@ -119,10 +254,10 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib return sqlite3_get_autocommit(sqliteConnection) == 0 } - /// The last error code + /// The last error code. public var lastErrorCode: ResultCode { ResultCode(rawValue: sqlite3_errcode(sqliteConnection)) } - /// The last error message + /// The last error message. public var lastErrorMessage: String? { String(cString: sqlite3_errmsg(sqliteConnection)) } // MARK: - Internal properties @@ -279,9 +414,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib private func setupDoubleQuotedStringLiterals() { if configuration.acceptsDoubleQuotedStringLiterals { - enableDoubleQuotedStringLiterals(sqliteConnection) + _enableDoubleQuotedStringLiterals(sqliteConnection) } else { - disableDoubleQuotedStringLiterals(sqliteConnection) + _disableDoubleQuotedStringLiterals(sqliteConnection) } } @@ -477,35 +612,42 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// array does not contain more than `maximumStatementArgumentCount` /// elements: /// - /// let ids: [Int] = ... - /// try dbQueue.write { db in - /// try Player.deleteAll(db, keys: ids) - /// } + /// ```swift + /// // DELETE FROM player WHERE id IN (?, ?, ...) + /// let ids: [Int] = ... + /// try dbQueue.write { db in + /// try Player.deleteAll(db, keys: ids) + /// } + /// ``` /// - /// See - /// and `SQLITE_LIMIT_VARIABLE_NUMBER`. + /// Related SQLite documentation: see `SQLITE_LIMIT_VARIABLE_NUMBER` in + /// . public var maximumStatementArgumentCount: Int { Int(sqlite3_limit(sqliteConnection, SQLITE_LIMIT_VARIABLE_NUMBER, -1)) } // MARK: - Functions - /// Add or redefine an SQL function. + /// Adds or redefines a custom SQL function. /// - /// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in - /// guard let int = Int.fromDatabaseValue(dbValues[0]) else { - /// return nil - /// } - /// return int + 1 - /// } - /// db.add(function: fn) - /// try Int.fetchOne(db, sql: "SELECT succ(1)")! // 2 + /// When you want to add a function to all connections created by a + /// ``DatabasePool``, add the function in + /// ``Configuration/prepareDatabase(_:)``: + /// + /// ```swift + /// var config = Configuration() + /// config.prepareDatabase { db in + /// // Add the function to both writer and readers connections. + /// db.add(function: ...) + /// } + /// let dbPool = try DatabasePool(path: ..., configuration: config) + /// ``` public func add(function: DatabaseFunction) { functions.update(with: function) function.install(in: self) } - /// Remove an SQL function. + /// Removes a custom SQL function. public func remove(function: DatabaseFunction) { functions.remove(function) function.uninstall(in: self) @@ -513,13 +655,20 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // MARK: - Collations - /// Add or redefine a collation. + /// Adds or redefines a collation. /// - /// let collation = DatabaseCollation("localized_standard") { (string1, string2) in - /// return (string1 as NSString).localizedStandardCompare(string2) - /// } - /// db.add(collation: collation) - /// try db.execute(sql: "CREATE TABLE files (name TEXT COLLATE localized_standard") + /// When you want to add a collation to all connections created by a + /// ``DatabasePool``, add the collation in + /// ``Configuration/prepareDatabase(_:)``: + /// + /// ```swift + /// var config = Configuration() + /// config.prepareDatabase { db in + /// // Add the collation to both writer and readers connections. + /// db.add(collation: ...) + /// } + /// let dbPool = try DatabasePool(path: ..., configuration: config) + /// ``` public func add(collation: DatabaseCollation) { collations.update(with: collation) let collationPointer = Unmanaged.passUnretained(collation).toOpaque() @@ -538,7 +687,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib } } - /// Remove a collation. + /// Removes a collation. public func remove(collation: DatabaseCollation) { collations.remove(collation) sqlite3_create_collation_v2( @@ -631,21 +780,29 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// /// For example: /// - /// // Trace all SQL statements executed by the database - /// var configuration = Configuration() - /// configuration.prepareDatabase { db in - /// db.trace(options: .statement) { event in - /// print("SQL: \(event)") - /// } + /// ```swift + /// // Trace all SQL statements executed by the database + /// var config = Configuration() + /// config.prepareDatabase { db in + /// db.trace(options: .statement) { event in + /// print("SQL: \(event)") /// } - /// let dbQueue = try DatabaseQueue(path: "...", configuration: configuration) + /// } + /// let dbQueue = try DatabaseQueue(path: ..., configuration: config) + /// ``` /// /// Pass an empty options set in order to stop database tracing: /// - /// // Stop tracing - /// db.trace(options: []) + /// ```swift + /// // Stop tracing + /// db.trace(options: []) + /// ``` /// - /// See for more information. + /// If you want to see statement arguments in the traced events, you will + /// need to set the ``Configuration/publicStatementArguments`` flag in the + /// database ``configuration``. + /// + /// Related SQLite documentation: /// /// - parameter options: The set of desired event kinds. Defaults to /// `.statement`, which notifies all executed database statements. @@ -725,16 +882,15 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// Runs a WAL checkpoint. /// - /// See and - /// for - /// more information. + /// Related SQLite documentation: + /// - + /// - /// /// - parameter kind: The checkpoint mode (default passive) /// - parameter dbName: The database name (default "main") - /// - returns: A tuple: - /// - `walFrameCount`: the total number of frames in the log file - /// - `checkpointedFrameCount`: the total number of checkpointed frames - /// in the log file + /// - returns: A tuple where `walFrameCount` is the total number of frames + /// in the log file and `checkpointedFrameCount` is the total number of + /// checkpointed frames in the log file @discardableResult public func checkpoint(_ kind: Database.CheckpointMode = .passive, on dbName: String? = "main") throws -> (walFrameCount: Int, checkpointedFrameCount: Int) @@ -766,13 +922,13 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// When this notification is posted, databases which were opened with the /// `Configuration.observesSuspensionNotifications` flag are suspended. /// - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) public static let suspendNotification = Notification.Name("GRDB.Database.Suspend") /// When this notification is posted, databases which were opened with the /// `Configuration.observesSuspensionNotifications` flag are resumed. /// - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) public static let resumeNotification = Notification.Name("GRDB.Database.Resume") /// Suspends the database. A suspended database prevents database locks in @@ -922,21 +1078,26 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib } } - /// Executes a block inside a database transaction. + /// Wraps database operations inside a database transaction. /// /// For example: /// - /// try dbQueue.inDatabase do { - /// try db.inTransaction { - /// try db.execute(sql: "INSERT ...") - /// return .commit - /// } + /// ```swift + /// try dbQueue.writeWithoutTransaction do { + /// try db.inTransaction { + /// try db.execute(sql: "INSERT ...") + /// return .commit /// } + /// } + /// ``` /// - /// If the block throws an error, the transaction is rollbacked and the - /// error is rethrown. + /// If `operations` throws an error, the transaction is rollbacked and the + /// error is rethrown. If it returns ``TransactionCompletion/rollback``, the + /// transaction is also rollbacked, but no error is thrown. /// - /// - warning: This method is not reentrant: you can't nest transactions. + /// Related SQLite documentation: + /// + /// - warning: This method is not reentrant: you can not nest transactions. /// Use ``inSavepoint(_:)`` instead. /// /// - parameters: @@ -946,15 +1107,13 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// kind is ``TransactionKind/deferred``. /// /// If nil, and the database connection is not read-only, the - /// transaction kind is ``Configuration/defaultTransactionKind``. - /// - /// See for - /// more information. - /// - block: A block that executes SQL statements and return either - /// ``TransactionCompletion/commit`` or - /// ``TransactionCompletion/rollback``. - /// - throws: The error thrown by the block. - public func inTransaction(_ kind: TransactionKind? = nil, _ block: () throws -> TransactionCompletion) throws { + /// transaction kind is the ``Configuration/defaultTransactionKind`` + /// of the ``configuration``. + /// - operations: A function that executes SQL statements and returns + /// either ``TransactionCompletion/commit`` or ``TransactionCompletion/rollback``. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or the + /// error thrown by `operations`. + public func inTransaction(_ kind: TransactionKind? = nil, _ operations: () throws -> TransactionCompletion) throws { // Begin transaction try beginTransaction(kind) @@ -971,7 +1130,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib var firstError: Error? = nil let needsRollback: Bool do { - let completion = try block() + let completion = try operations() switch completion { case .commit: // In case of aborted transaction, throw SQLITE_ABORT instead @@ -1042,27 +1201,33 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib } } - /// Executes a block inside a savepoint. + /// Wraps database operations inside a savepoint. /// /// For example: /// - /// try dbQueue.inDatabase do { - /// try db.inSavepoint { - /// try db.execute(sql: "INSERT ...") - /// return .commit - /// } + /// ```swift + /// try dbQueue.write do { + /// try db.inSavepoint { + /// try db.execute(sql: "INSERT ...") + /// return .commit /// } + /// } + /// ``` /// - /// If the block throws an error, the savepoint is rollbacked and the - /// error is rethrown. + /// If `operations` throws an error, the savepoint is rollbacked and the + /// error is rethrown. If it returns ``TransactionCompletion/rollback``, the + /// savepoint is also rollbacked, but no error is thrown. /// /// This method is reentrant: you can nest savepoints. /// - /// - parameter block: A block that executes SQL statements and return - /// either ``TransactionCompletion/commit`` or + /// Related SQLite documentation: + /// + /// - parameter operations: A function that executes SQL statements and + /// returns either ``TransactionCompletion/commit`` or /// ``TransactionCompletion/rollback``. - /// - throws: The error thrown by the block. - public func inSavepoint(_ block: () throws -> TransactionCompletion) throws { + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or the + /// error thrown by `operations`. + public func inSavepoint(_ operations: () throws -> TransactionCompletion) throws { if !isInsideTransaction { // By default, top level SQLite savepoints open a // deferred transaction. @@ -1084,7 +1249,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // // For those two reasons, we open a transaction instead of a // top-level savepoint. - try inTransaction { try block() } + try inTransaction { try operations() } return } @@ -1109,7 +1274,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib var firstError: Error? = nil let needsRollback: Bool do { - let completion = try block() + let completion = try operations() switch completion { case .commit: // In case of aborted transaction, throw SQLITE_ABORT instead @@ -1153,6 +1318,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// Begins a database transaction. /// + /// Related SQLite documentation: + /// /// - parameters: /// - kind: The transaction type (default nil). /// @@ -1160,11 +1327,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// kind is ``TransactionKind/deferred``. /// /// If nil, and the database connection is not read-only, the - /// transaction kind is ``Configuration/defaultTransactionKind``. - /// - /// See for - /// more information. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// transaction kind is the ``Configuration/defaultTransactionKind`` + /// of the ``configuration``. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func beginTransaction(_ kind: TransactionKind? = nil) throws { // SQLite throws an error for non-deferred transactions when read-only. let kind = kind ?? (isReadOnly ? .deferred : configuration.defaultTransactionKind) @@ -1173,6 +1338,10 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib } /// Rollbacks a database transaction. + /// + /// Related SQLite documentation: + /// + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func rollback() throws { // The SQLite documentation contains two related but distinct techniques // to handle rollbacks and errors: @@ -1220,6 +1389,10 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib } /// Commits a database transaction. + /// + /// Related SQLite documentation: + /// + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func commit() throws { try execute(sql: "COMMIT TRANSACTION") assert(sqlite3_get_autocommit(sqliteConnection) != 0) @@ -1227,7 +1400,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // MARK: - Memory Management - /// Free as much memory as possible. + /// Frees as much memory as possible. public func releaseMemory() { SchedulingWatchdog.preconditionValidQueue(self) sqlite3_db_release_memory(sqliteConnection) @@ -1283,36 +1456,36 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// /// Usage: /// - /// let source: DatabaseQueue = ... - /// let destination: DatabaseQueue = ... - /// try source.write { sourceDb in - /// try destination.barrierWriteWithoutTransaction { destDb in - /// try sourceDb.backup(to: destDb) - /// } + /// ```swift + /// let source: DatabaseQueue = ... + /// let destination: DatabaseQueue = ... + /// try source.write { sourceDb in + /// try destination.barrierWriteWithoutTransaction { destDb in + /// try sourceDb.backup(to: destDb) /// } - /// + /// } + /// ``` /// /// When you're after progress reporting during backup, you'll want to /// perform the backup in several steps. Each step copies the number of /// _database pages_ you specify. See /// for more information: /// - /// // Backup with progress reporting - /// try sourceDb.backup( - /// to: destDb, - /// pagesPerStep: ...) - /// { backupProgress in - /// print("Database backup progress:", backupProgress) - /// } + /// ```swift + /// // Backup with progress reporting + /// try sourceDb.backup(to: destDb, pagesPerStep: ...) { progress in + /// print("Database backup progress:", progress) + /// } + /// ``` /// /// The `progress` callback will be called at least once—when /// `backupProgress.isCompleted == true`. If the callback throws /// when `backupProgress.isCompleted == false`, the backup is aborted - /// and the error is rethrown. If the callback throws when + /// and the error is rethrown. If the callback throws when /// `backupProgress.isCompleted == true`, backup completion is /// unaffected and the error is silently ignored. /// - /// See also `DatabaseReader.backup()`. + /// See also ``DatabaseReader/backup(to:pagesPerStep:progress:)``. /// /// - parameters: /// - destDb: The destination database. @@ -1320,8 +1493,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// step. By default, all pages are copied in one single step. /// - progress: An optional function that is notified of the backup /// progress. - /// - throws: The error thrown by `progress` if the backup is abandoned, or - /// any `DatabaseError` that would happen while performing the backup. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or the + /// error thrown by `progress`. public func backup( to destDb: Database, pagesPerStep: CInt = -1, @@ -1485,7 +1658,7 @@ extension Database { /// /// // Wait 1 second before failing with SQLITE_BUSY /// let configuration = Configuration(busyMode: .timeout(1)) - /// let dbQueue = try DatabaseQueue(path: "...", configuration: configuration) + /// let dbQueue = try DatabaseQueue(path: ..., configuration: configuration) /// /// Relevant SQLite documentation: /// @@ -1494,66 +1667,84 @@ extension Database { /// - /// - public enum BusyMode { - /// The SQLITE_BUSY error is immediately returned to the connection that - /// tries to access the locked database. + /// The `SQLITE_BUSY` error is immediately returned to the connection + /// that tries to access the locked database. case immediateError - /// The SQLITE_BUSY error will be returned only if the database remains - /// locked for more than the specified duration (in seconds). + /// The `SQLITE_BUSY` error will be returned only if the database + /// remains locked for more than the specified duration (in seconds). case timeout(TimeInterval) /// A custom callback that is called when a database is locked. - /// See + /// + /// Related SQLite documentation: case callback(BusyCallback) } - /// The available [checkpoint modes](https://www.sqlite.org/c3ref/wal_checkpoint_v2.html). + /// The available checkpoint modes. + /// + /// Related SQLite documentation: public enum CheckpointMode: CInt { - /// The `SQLITE_CHECKPOINT_PASSIVE` mode + /// The `SQLITE_CHECKPOINT_PASSIVE` mode. case passive = 0 - /// The `SQLITE_CHECKPOINT_FULL` mode + /// The `SQLITE_CHECKPOINT_FULL` mode. case full = 1 - /// The `SQLITE_CHECKPOINT_RESTART` mode + /// The `SQLITE_CHECKPOINT_RESTART` mode. case restart = 2 - /// The `SQLITE_CHECKPOINT_TRUNCATE` mode + /// The `SQLITE_CHECKPOINT_TRUNCATE` mode. case truncate = 3 } - /// A built-in SQLite collation. + /// The name of a string comparison function used by SQLite. /// - /// See + /// Related SQLite documentation: + /// - + /// - public struct CollationName: RawRepresentable, Hashable { - /// :nodoc: public let rawValue: String - /// Creates a built-in collation name. + /// Creates a collation name. public init(rawValue: String) { self.rawValue = rawValue } - /// The `BINARY` built-in SQL collation + /// The `BINARY` built-in SQL collation. public static let binary = CollationName(rawValue: "BINARY") - /// The `NOCASE` built-in SQL collation + /// The `NOCASE` built-in SQL collation. public static let nocase = CollationName(rawValue: "NOCASE") - /// The `RTRIM` built-in SQL collation + /// The `RTRIM` built-in SQL collation. public static let rtrim = CollationName(rawValue: "RTRIM") } /// An SQL column type. /// - /// try db.create(table: "player") { t in - /// t.autoIncrementedPrimaryKey("id") - /// t.column("title", .text) - /// } + /// You use column types when you modify the database schema. For example, + /// the code below create a `player` table with a `name` column whose type + /// is ``text`` (`TEXT` in SQL): /// - /// See + /// ```swift + /// // CREATE TABLE player( + /// // id INTEGER PRIMARY KEY AUTOINCREMENT, + /// // name TEXT + /// // ) + /// try db.create(table: "player") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("name", .text) + /// } + /// ``` + /// + /// A `ColumnType` is an element of the SQL language, as is `TEXT` in the + /// example above. The type comes with many built-in constants for + /// frequently used types: ``text``, ``integer``, etc. + /// + /// Related SQLite documentation: public struct ColumnType: RawRepresentable, Hashable { - /// :nodoc: + /// The SQL for the column type (`"TEXT"`, `"BLOB"`, etc.) public let rawValue: String /// Creates an SQL column type. @@ -1561,111 +1752,113 @@ extension Database { self.rawValue = rawValue } - /// The `TEXT` SQL column type + /// The `TEXT` SQL column type. public static let text = ColumnType(rawValue: "TEXT") - /// The `INTEGER` SQL column type + /// The `INTEGER` SQL column type. public static let integer = ColumnType(rawValue: "INTEGER") - /// The `DOUBLE` SQL column type + /// The `DOUBLE` SQL column type. public static let double = ColumnType(rawValue: "DOUBLE") - /// The `REAL` SQL column type + /// The `REAL` SQL column type. public static let real = ColumnType(rawValue: "REAL") - /// The `NUMERIC` SQL column type + /// The `NUMERIC` SQL column type. public static let numeric = ColumnType(rawValue: "NUMERIC") - /// The `BOOLEAN` SQL column type + /// The `BOOLEAN` SQL column type. public static let boolean = ColumnType(rawValue: "BOOLEAN") - /// The `BLOB` SQL column type + /// The `BLOB` SQL column type. public static let blob = ColumnType(rawValue: "BLOB") - /// The `DATE` SQL column type + /// The `DATE` SQL column type. public static let date = ColumnType(rawValue: "DATE") - /// The `DATETIME` SQL column type + /// The `DATETIME` SQL column type. public static let datetime = ColumnType(rawValue: "DATETIME") - /// The `ANY` SQL column type + /// The `ANY` SQL column type. public static let any = ColumnType(rawValue: "ANY") } /// An SQLite conflict resolution. /// - /// See + /// Related SQLite documentation: public enum ConflictResolution: String { - /// The `ROLLBACK` conflict resolution + /// The `ROLLBACK` conflict resolution. case rollback = "ROLLBACK" - /// The `ABORT` conflict resolution + /// The `ABORT` conflict resolution. case abort = "ABORT" - /// The `FAIL` conflict resolution + /// The `FAIL` conflict resolution. case fail = "FAIL" - /// The `IGNORE` conflict resolution + /// The `IGNORE` conflict resolution. case ignore = "IGNORE" - /// The `REPLACE` conflict resolution + /// The `REPLACE` conflict resolution. case replace = "REPLACE" } /// A foreign key action. /// - /// See + /// Related SQLite documentation: public enum ForeignKeyAction: String { - /// The `CASCADE` foreign key action + /// The `CASCADE` foreign key action. case cascade = "CASCADE" - /// The `RESTRICT` foreign key action + /// The `RESTRICT` foreign key action. case restrict = "RESTRICT" - /// The `SET NULL` foreign key action + /// The `SET NULL` foreign key action. case setNull = "SET NULL" - /// The `SET DEFAULT` foreign key action + /// The `SET DEFAULT` foreign key action. case setDefault = "SET DEFAULT" } /// An error log function that takes an error code and message. public typealias LogErrorFunction = (_ resultCode: ResultCode, _ message: String) -> Void - /// An option for `Database.trace(options:_:)` + /// An option for the SQLite tracing feature. + /// + /// You use `TracingOptions` with the `Database` + /// ``Database/trace(options:_:)`` method. + /// + /// Related SQLite documentation: public struct TracingOptions: OptionSet { - /// The raw "Trace Event Code". - /// - /// See + /// The raw trace event code. public let rawValue: CInt - /// Creates a `TracingOptions` from a raw "Trace Event Code". - /// - /// See: - /// - - /// - `Database.trace(options:_:)` + /// Creates a `TracingOptions` from a raw trace event code. public init(rawValue: CInt) { self.rawValue = rawValue } - /// Reports executed statements. + /// The option that reports executed statements. /// - /// See `Database.trace(options:_:)` + /// Trace event code: `SQLITE_TRACE_STMT`. public static let statement = TracingOptions(rawValue: SQLITE_TRACE_STMT) #if !os(Linux) - /// Reports executed statements and the estimated duration that the - /// statement took to run. + /// The option that reports executed statements and the estimated + /// duration that the statement took to run. /// - /// See `Database.trace(options:_:)` + /// Trace event code: `SQLITE_TRACE_PROFILE`. public static let profile = TracingOptions(rawValue: SQLITE_TRACE_PROFILE) #endif } - /// An event reported by `Database.trace(options:_:)` + /// A trace event. + /// + /// You get instances of `TraceEvent` from the `Database` + /// ``Database/trace(options:_:)`` method. public enum TraceEvent: CustomStringConvertible { - /// Information about a statement reported by `Database.trace(options:_:)` + /// Information about an executed statement. public struct Statement: CustomStringConvertible { enum Impl { case trace_v1(String) @@ -1682,7 +1875,9 @@ extension Database { /// /// For example: /// - /// SELECT * FROM player WHERE email = ? + /// ```sql + /// SELECT * FROM player WHERE email = ? + /// ``` public var sql: String { _sql } #endif @@ -1705,7 +1900,9 @@ extension Database { /// /// For example: /// - /// SELECT * FROM player WHERE email = 'arthur@example.com' + /// ```sql + /// SELECT * FROM player WHERE email = 'arthur@example.com' + /// ``` /// /// - warning: It is your responsibility to prevent sensitive /// information from leaking in unexpected locations, so use this @@ -1739,13 +1936,15 @@ extension Database { } } - /// An event reported by `TracingOptions.statement`. + /// An event reported by the + /// ``Database/TracingOptions/statement`` option. case statement(Statement) - /// An event reported by `TracingOptions.profile`. + /// An event reported by the + /// ``Database/TracingOptions/profile`` option. case profile(statement: Statement, duration: TimeInterval) - /// The trace event description. + /// A description of the trace event. /// /// For example: /// @@ -1764,7 +1963,8 @@ extension Database { } } - /// The trace event description, where bound parameters are expanded. + /// A description of the trace event, where bound parameters + /// are expanded. /// /// For example: /// @@ -1788,25 +1988,26 @@ extension Database { } } - /// Confirms or cancels the changes performed by a transaction or savepoint. + /// A transaction commit, or rollback. + /// + /// Related SQLite documentation: . @frozen public enum TransactionCompletion { - /// Confirms changes case commit - - /// Cancel changes case rollback } - /// An SQLite transaction kind. See + /// A transaction kind. + /// + /// Related SQLite documentation: . public enum TransactionKind: String { - /// The `DEFERRED` transaction kind + /// The `DEFERRED` transaction kind. case deferred = "DEFERRED" - /// The `IMMEDIATE` transaction kind + /// The `IMMEDIATE` transaction kind. case immediate = "IMMEDIATE" - /// The `EXCLUSIVE` transaction kind + /// The `EXCLUSIVE` transaction kind. case exclusive = "EXCLUSIVE" } diff --git a/GRDB/Core/DatabaseBackupProgress.swift b/GRDB/Core/DatabaseBackupProgress.swift index cf38f98d2..3119dfa5b 100644 --- a/GRDB/Core/DatabaseBackupProgress.swift +++ b/GRDB/Core/DatabaseBackupProgress.swift @@ -1,22 +1,27 @@ -/// An instance of `DatabaseBackupProgress` is passed to a callback of the -/// `DatabaseReader.backup` or `Database.backup` methods to report -/// database backup progress to the caller. +/// Describe the progress of a database backup. /// -/// This is an advanced API for expert users. It is based directly on the SQLite -/// [online backup API](https://www.sqlite.org/c3ref/backup_finish.html). +/// Related SQLite documentation: public struct DatabaseBackupProgress { - /// Total page count is defined by the `sqlite3_backup_remaining` function + /// The number of pages still to be backed up. + /// + /// It is the result of the `sqlite3_backup_remaining` function. public let remainingPageCount: Int - - /// Total page count is defined by the `sqlite3_backup_pagecount` function + + /// The number of pages in the source database. + /// + /// It is the result of the `sqlite3_backup_pagecount` function. public let totalPageCount: Int - - /// Completed page count is defined as `sqlite3_backup_pagecount() - sqlite3_backup_remaining()` + + /// The number of of backed up pages. + /// + /// It is equal to `totalPageCount - remainingPageCount`. public var completedPageCount: Int { totalPageCount - remainingPageCount } - - /// This property is true if and only if `sqlite3_backup_step()` returns - /// `SQLITE_DONE` + + /// A boolean value indicating whether the backup is complete. + /// + /// It is true if and only if the last call the `sqlite3_backup_step` has + /// returned `SQLITE_DONE`. public let isCompleted: Bool } diff --git a/GRDB/Core/DatabaseCollation.swift b/GRDB/Core/DatabaseCollation.swift index d94322dbb..2f76223c5 100644 --- a/GRDB/Core/DatabaseCollation.swift +++ b/GRDB/Core/DatabaseCollation.swift @@ -1,21 +1,44 @@ import Foundation -/// A Collation is a string comparison function used by SQLite. +/// `DatabaseCollation` is a custom string comparison function used by SQLite. +/// +/// See also ``Database/CollationName``. +/// +/// Related SQLite documentation: +/// +/// ## Topics +/// +/// ### Creating a Custom Collation +/// +/// - ``init(_:function:)`` +/// - ``name`` +/// +/// ### Built-in Collations +/// +/// - ``caseInsensitiveCompare`` +/// - ``localizedCaseInsensitiveCompare`` +/// - ``localizedCompare`` +/// - ``localizedStandardCompare`` +/// - ``unicodeCompare`` public final class DatabaseCollation { - /// The name of the collation + /// The name of the collation. public let name: String let function: (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult /// Creates a collation. /// - /// let collation = DatabaseCollation("localized_standard") { (string1, string2) in - /// return (string1 as NSString).localizedStandardCompare(string2) - /// } - /// db.add(collation: collation) - /// try db.execute(sql: "CREATE TABLE file (name TEXT COLLATE localized_standard") + /// For example: + /// + /// ```swift + /// let collation = DatabaseCollation("localized_standard") { (string1, string2) in + /// return (string1 as NSString).localizedStandardCompare(string2) + /// } + /// db.add(collation: collation) + /// try db.execute(sql: "CREATE TABLE file (name TEXT COLLATE localized_standard") + /// ``` /// /// - parameters: - /// - name: The function name. + /// - name: The collation name. /// - function: A function that compares two strings. public init(_ name: String, function: @escaping (String, String) -> ComparisonResult) { self.name = name @@ -43,13 +66,11 @@ extension DatabaseCollation: Hashable { // implies hash equality) is thus non trivial. But it's not that // important, since this hashValue is only used when one adds // or removes a collation from a database connection. - /// :nodoc: public func hash(into hasher: inout Hasher) { hasher.combine(0) } /// Two collations are equal if they share the same name (case insensitive) - /// :nodoc: public static func == (lhs: DatabaseCollation, rhs: DatabaseCollation) -> Bool { // See return sqlite3_stricmp(lhs.name, rhs.name) == 0 diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index 6530f58fa..7fdc9d1ab 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -2,9 +2,9 @@ import Foundation /// An SQLite result code. /// -/// See -public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible { - /// The raw SQLite result code +/// Related SQLite documentation: +public struct ResultCode: RawRepresentable, Equatable { + /// The raw SQLite result code. public let rawValue: CInt /// Creates a `ResultCode` from a raw SQLite result code. @@ -12,11 +12,14 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible { self.rawValue = rawValue } - /// A result code limited to the least significant 8 bits of the receiver. - /// See for more information. + /// A primary result code limited to the least significant 8 bits. /// - /// let resultCode = .SQLITE_CONSTRAINT_FOREIGNKEY - /// resultCode.primaryResultCode == .SQLITE_CONSTRAINT // true + /// For example: + /// + /// ```swift + /// let resultCode = .SQLITE_CONSTRAINT_FOREIGNKEY + /// resultCode.primaryResultCode == .SQLITE_CONSTRAINT // true + /// ``` public var primaryResultCode: ResultCode { ResultCode(rawValue: rawValue & 0xFF) } @@ -28,11 +31,15 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible { /// Primary result codes match themselves and their extended result codes, /// while extended result codes match only themselves: /// - /// switch error.extendedResultCode { - /// case .SQLITE_CONSTRAINT_FOREIGNKEY: // foreign key constraint error - /// case .SQLITE_CONSTRAINT: // any other constraint error - /// default: // any other database error - /// } + /// For example: + /// + /// ```swift + /// switch error.extendedResultCode { + /// case .SQLITE_CONSTRAINT_FOREIGNKEY: // foreign key constraint error + /// case .SQLITE_CONSTRAINT: // any other constraint error + /// default: // any other database error + /// } + /// ``` public static func ~= (pattern: ResultCode, code: ResultCode) -> Bool { if pattern.isPrimary { return pattern == code.primaryResultCode @@ -166,28 +173,30 @@ extension ResultCode { /// Primary result codes match themselves and their extended result codes, /// while extended result codes match only themselves. /// - /// do { - /// try ... - /// } catch ResultCode.SQLITE_CONSTRAINT_FOREIGNKEY { - /// // foreign key constraint error - /// } catch ResultCode.SQLITE_CONSTRAINT { - /// // any other constraint error - /// } catch { - /// // any other database error - /// } + /// For example: + /// + /// ```swift + /// do { + /// try ... + /// } catch ResultCode.SQLITE_CONSTRAINT_FOREIGNKEY { + /// // foreign key constraint error + /// } catch ResultCode.SQLITE_CONSTRAINT { + /// // any other constraint error + /// } catch { + /// // any other database error + /// } + /// ``` public static func ~= (lhs: Self, rhs: Error) -> Bool { guard let error = rhs as? DatabaseError else { return false } return lhs ~= error.extendedResultCode } } -// CustomStringConvertible -extension ResultCode { +extension ResultCode: CustomStringConvertible { var errorString: String? { String(cString: sqlite3_errstr(rawValue)) } - /// :nodoc: public var description: String { if let errorString = errorString { return "\(rawValue) (\(errorString))" @@ -199,61 +208,143 @@ extension ResultCode { extension ResultCode: Sendable { } -/// DatabaseError wraps an SQLite error. -public struct DatabaseError: Error, CustomStringConvertible, CustomNSError { - - /// The SQLite error code (see - /// ). - /// - /// do { - /// ... - /// } catch let error as DatabaseError where error.resultCode == .SQL_CONSTRAINT { - /// // A constraint error - /// } +/// A `DatabaseError` describes an SQLite error. +/// +/// For example: +/// +/// ```swift +/// do { +/// try player.insert(db) +/// } catch let error as DatabaseError { +/// switch error.resultCode { +/// case ResultCode.SQLITE_CONSTRAINT_FOREIGNKEY: +/// // foreign key constraint error +/// case ResultCode.SQLITE_CONSTRAINT: +/// // any other constraint error +/// default: +/// // any other database error +/// } +/// } +/// ``` +/// +/// The above example can also be written in a shorter way: +/// +/// ```swift +/// do { +/// try player.insert(db) +/// } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { +/// // foreign key constraint error +/// } catch DatabaseError.SQLITE_CONSTRAINT { +/// // any other constraint error +/// } catch { +/// // any other database error +/// } +/// ``` +/// +/// Related SQLite documentation: +/// +/// ## Topics +/// +/// ### Creating DatabaseError +/// +/// - ``init(resultCode:message:sql:arguments:publicStatementArguments:)`` +/// - ``ResultCode`` +/// +/// ### Error Information +/// +/// - ``arguments`` +/// - ``extendedResultCode`` +/// - ``isInterruptionError`` +/// - ``message`` +/// - ``resultCode`` +/// - ``sql`` +/// +/// ### Converting DatabaseError to String +/// +/// - ``description`` +/// - ``expandedDescription`` +public struct DatabaseError: Error { + /// The SQLite primary result code. /// /// This property returns a "primary result code", that is to say the least - /// significant 8 bits of any SQLite result code. See - /// for more information. + /// significant 8 bits of any SQLite result code. /// - /// See also `extendedResultCode`. + /// For example: + /// + /// ```swift + /// do { + /// ... + /// } catch let error as DatabaseError where error.resultCode == .SQL_CONSTRAINT { + /// // A constraint error + /// } + /// ``` + /// + /// The above example can also be written in a shorter way: + /// + /// ```swift + /// do { + /// ... + /// } catch DatabaseError.SQL_CONSTRAINT { + /// // A constraint error + /// } + /// ``` + /// + /// See also ``extendedResultCode``. + /// + /// Related SQLite documentation: public var resultCode: ResultCode { extendedResultCode.primaryResultCode } - /// The SQLite extended error code (see - /// ). + /// The SQLite extended error code. /// - /// do { - /// ... - /// } catch let error as DatabaseError where error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY { - /// // A foreign key constraint error - /// } + /// For example: /// - /// See also `resultCode`. + /// ```swift + /// do { + /// ... + /// } catch let error as DatabaseError where error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY { + /// // A foreign key constraint error + /// } + /// ``` + /// + /// The above example can also be written in a shorter way: + /// + /// ```swift + /// do { + /// ... + /// } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { + /// // A foreign key constraint error + /// } + /// ``` + /// + /// See also ``resultCode``. + /// + /// Related SQLite documentation: public let extendedResultCode: ResultCode /// The SQLite error message. public let message: String? - /// The SQL query that yielded the error (if relevant). + /// The SQL query that yielded the error. public let sql: String? - /// The query arguments that yielded the error (if relevant). + /// The query arguments that yielded the error. public let arguments: StatementArguments? /// See Configuration.publicStatementArguments var publicStatementArguments: Bool - /// Creates a DatabaseError. + /// Creates a `DatabaseError`. /// /// - parameters: /// - resultCode: A ResultCode (defaults to .SQLITE_ERROR). /// - message: An eventual error message. If nil, the error message is /// derived from the result code. /// - sql: An eventual SQL string. - /// - arguments: Eventual Statement arguments. + /// - arguments: Eventual statement arguments. /// - publicStatementArguments: If false (the default), statement - /// arguments are not visible in the error's `description` property. + /// arguments are not visible in the error's ``description`` property. public init( resultCode: ResultCode = .SQLITE_ERROR, message: String? = nil, @@ -422,13 +513,14 @@ extension DatabaseError { } extension DatabaseError { - /// Returns true if the error has code `SQLITE_ABORT` or `SQLITE_INTERRUPT`. + /// A boolean value indicating if the error has code + /// `SQLITE_ABORT` or `SQLITE_INTERRUPT`. /// /// Such an error can be thrown when a database has been interrupted, or /// when the database is suspended. /// - /// See `DatabaseReader.interrupt()` and `DatabaseReader.suspend()` for - /// more information. + /// See ``DatabaseReader/interrupt()`` and ``Database/suspendNotification`` + /// for more information. public var isInterruptionError: Bool { switch resultCode { case .SQLITE_ABORT, .SQLITE_INTERRUPT: @@ -439,8 +531,7 @@ extension DatabaseError { } } -// CustomStringConvertible -extension DatabaseError { +extension DatabaseError: CustomStringConvertible { /// The error description. /// /// For example: @@ -493,19 +584,18 @@ extension DatabaseError { } } -// CustomNSError -extension DatabaseError { - - /// NSError bridging: the domain of the error. - /// :nodoc: +extension DatabaseError: CustomNSError { + /// Part of the `CustomNSError` conformance. + /// + /// Returns `GRDB.DatabaseError`. public static var errorDomain: String { "GRDB.DatabaseError" } - /// NSError bridging: the error code within the given domain. - /// :nodoc: + /// Part of the `CustomNSError` conformance. + /// + /// Returns the ``extendedResultCode``. public var errorCode: Int { Int(extendedResultCode.rawValue) } - /// NSError bridging: the user-info dictionary. - /// :nodoc: + /// Part of the `CustomNSError` conformance. public var errorUserInfo: [String: Any] { var userInfo = [NSLocalizedDescriptionKey: description] if let message = message { diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index b7c23f7fe..db3af3ef8 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -1,4 +1,25 @@ -/// An SQL function or aggregate. +/// A custom SQL function or aggregate. +/// +/// ## Topics +/// +/// ### Creating a Custom SQL Function or Aggregate +/// +/// - ``init(_:argumentCount:pure:function:)`` +/// - ``init(_:argumentCount:pure:aggregate:)`` +/// - ``DatabaseAggregate`` +/// +/// ### Calling an SQL Function or Aggregate +/// +/// - ``callAsFunction(_:)`` +/// +/// ### Built-in Functions +/// +/// - ``capitalize`` +/// - ``localizedCapitalize`` +/// - ``localizedLowercase`` +/// - ``localizedUppercase`` +/// - ``lowercase`` +/// - ``uppercase`` public final class DatabaseFunction: Hashable { // SQLite identifies functions by (name + argument count) private struct Identity: Hashable { @@ -17,14 +38,23 @@ public final class DatabaseFunction: Hashable { /// /// For example: /// - /// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in - /// guard let int = Int.fromDatabaseValue(dbValues[0]) else { - /// return nil - /// } - /// return int + 1 + /// ```swift + /// let succ = DatabaseFunction("succ", argumentCount: 1) { dbValues in + /// guard let int = Int.fromDatabaseValue(dbValues[0]) else { + /// return nil /// } - /// db.add(function: fn) + /// return int + 1 + /// } + /// let dbQueue = try DatabaseQueue() + /// try dbQueue.read { db in + /// db.add(function: succ) /// try Int.fetchOne(db, sql: "SELECT succ(1)")! // 2 + /// } + /// ``` + /// + /// ### Related APIs + /// + /// - ``Database/add(function:)`` /// /// - parameters: /// - name: The function name. @@ -34,10 +64,10 @@ public final class DatabaseFunction: Hashable { /// only depends on its inputs. When a function is pure, SQLite has /// the opportunity to perform additional optimizations. Default value /// is false. - /// - function: A function that takes an array of DatabaseValue - /// arguments, and returns an optional DatabaseValueConvertible such - /// as Int, String, NSDate, etc. The array is guaranteed to have - /// exactly *argumentCount* elements, provided *argumentCount* is + /// - function: A function that takes an array of ``DatabaseValue`` + /// arguments, and returns an optional ``DatabaseValueConvertible`` + /// such as `Int`, `String`, `Date`, etc. The array is guaranteed to + /// have exactly `argumentCount` elements, provided `argumentCount` is /// not nil. public init( _ name: String, @@ -59,29 +89,35 @@ public final class DatabaseFunction: Hashable { /// /// For example: /// - /// struct MySum: DatabaseAggregate { - /// var sum: Int = 0 + /// ```swift + /// struct MySum: DatabaseAggregate { + /// var sum: Int = 0 /// - /// mutating func step(_ dbValues: [DatabaseValue]) { - /// if let int = Int.fromDatabaseValue(dbValues[0]) { - /// sum += int - /// } - /// } - /// - /// func finalize() -> (any DatabaseValueConvertible)? { - /// return sum + /// mutating func step(_ dbValues: [DatabaseValue]) { + /// if let int = Int.fromDatabaseValue(dbValues[0]) { + /// sum += int /// } /// } /// - /// let dbQueue = try DatabaseQueue() - /// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self) - /// try dbQueue.write { db in - /// db.add(function: fn) - /// try db.execute(sql: "CREATE TABLE test(i)") - /// try db.execute(sql: "INSERT INTO test(i) VALUES (1)") - /// try db.execute(sql: "INSERT INTO test(i) VALUES (2)") - /// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3 + /// func finalize() -> (any DatabaseValueConvertible)? { + /// return sum /// } + /// } + /// + /// let dbQueue = try DatabaseQueue() + /// let mySum = DatabaseFunction("mySum", argumentCount: 1, aggregate: MySum.self) + /// try dbQueue.write { db in + /// db.add(function: mySum) + /// try db.execute(sql: "CREATE TABLE test(i)") + /// try db.execute(sql: "INSERT INTO test(i) VALUES (1)") + /// try db.execute(sql: "INSERT INTO test(i) VALUES (2)") + /// try Int.fetchOne(db, sql: "SELECT mySum(i) FROM test")! // 3 + /// } + /// ``` + /// + /// ### Related APIs + /// + /// - ``Database/add(function:)`` /// /// - parameters: /// - name: The function name. @@ -91,10 +127,11 @@ public final class DatabaseFunction: Hashable { /// results only depends on its inputs. When an aggregate is pure, /// SQLite has the opportunity to perform additional optimizations. /// Default value is false. - /// - aggregate: A type that implements the DatabaseAggregate protocol. - /// For each step of the aggregation, its `step` method is called with - /// an array of DatabaseValue arguments. The array is guaranteed to - /// have exactly *argumentCount* elements, provided *argumentCount* is + /// - aggregate: A type that implements the ``DatabaseAggregate`` + /// protocol. For each step of the aggregation, its + /// ``DatabaseAggregate/step(_:)`` method is called with an array of + /// ``DatabaseValue`` arguments. The array is guaranteed to have + /// exactly `argumentCount` elements, provided `argumentCount` is /// not nil. public init( _ name: String, @@ -109,7 +146,29 @@ public final class DatabaseFunction: Hashable { /// Returns an SQL expression that applies the function. /// - /// See + /// You can use a `DatabaseFunction` as a regular Swift function. It returns + /// an SQL expression that you can use in the query interface. + /// + /// In the example below, `square(Column("score"))` generates the + /// `square(score)` SQL expression: + /// + /// ```swift + /// let square = DatabaseFunction("square", argumentCount: 1) { dbValues in + /// guard let int = Int.fromDatabaseValue(dbValues[0]) else { + /// return nil + /// } + /// return int * int + /// } + /// let dbQueue = try DatabaseQueue() + /// try dbQueue.read { db in + /// db.add(function: square) + /// + /// // SELECT square(score) FROM player + /// let squaredScores = let Player + /// .select(square(Column("score")), as: Int.self) + /// .fetchAll(db) + /// } + /// ``` public func callAsFunction(_ arguments: any SQLExpressible...) -> SQLExpression { switch kind { case .aggregate: @@ -346,13 +405,11 @@ public final class DatabaseFunction: Hashable { } extension DatabaseFunction { - /// :nodoc: public func hash(into hasher: inout Hasher) { hasher.combine(identity) } /// Two functions are equal if they share the same name and arity. - /// :nodoc: public static func == (lhs: DatabaseFunction, rhs: DatabaseFunction) -> Bool { lhs.identity == rhs.identity } @@ -362,47 +419,53 @@ extension DatabaseFunction { /// /// For example: /// -/// struct MySum : DatabaseAggregate { -/// var sum: Int = 0 +/// ```swift +/// struct MySum : DatabaseAggregate { +/// var sum: Int = 0 /// -/// mutating func step(_ dbValues: [DatabaseValue]) { -/// if let int = Int.fromDatabaseValue(dbValues[0]) { -/// sum += int -/// } -/// } -/// -/// func finalize() -> (any DatabaseValueConvertible)? { -/// return sum +/// mutating func step(_ dbValues: [DatabaseValue]) { +/// if let int = Int.fromDatabaseValue(dbValues[0]) { +/// sum += int /// } /// } /// -/// let dbQueue = try DatabaseQueue() -/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self) -/// try dbQueue.write { db in -/// db.add(function: fn) -/// try db.execute(sql: "CREATE TABLE test(i)") -/// try db.execute(sql: "INSERT INTO test(i) VALUES (1)") -/// try db.execute(sql: "INSERT INTO test(i) VALUES (2)") -/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3 +/// func finalize() -> (any DatabaseValueConvertible)? { +/// return sum /// } +/// } +/// +/// let dbQueue = try DatabaseQueue() +/// let mySum = DatabaseFunction("mySum", argumentCount: 1, aggregate: MySum.self) +/// try dbQueue.write { db in +/// db.add(function: mySum) +/// try db.execute(sql: "CREATE TABLE test(i)") +/// try db.execute(sql: "INSERT INTO test(i) VALUES (1)") +/// try db.execute(sql: "INSERT INTO test(i) VALUES (2)") +/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3 +/// } +/// ``` public protocol DatabaseAggregate { /// Creates an aggregate. + /// + /// A new instance is created for each aggregation. init() - /// This method is called at each step of the aggregation. + /// Updates the aggregated value for one step of the aggregation. /// - /// The dbValues argument contains as many values as given to the SQL - /// aggregate function. + /// This method is called once for each step of the aggregation. /// - /// -- One value - /// SELECT maxLength(name) FROM player + /// The `dbValues` argument contains as many values as given to the SQL + /// aggregate function: /// - /// -- Two values - /// SELECT maxFullNameLength(firstName, lastName) FROM player + /// ```sql + /// -- One value + /// SELECT maxLength(name) FROM player /// - /// This method is never called after the finalize() method has been called. + /// -- Two values + /// SELECT maxFullNameLength(firstName, lastName) FROM player + /// ``` mutating func step(_ dbValues: [DatabaseValue]) throws - /// Returns the final result + /// Returns the aggregated value. func finalize() throws -> (any DatabaseValueConvertible)? } diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index bf4b986fe..7d1e3b2d6 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -4,8 +4,42 @@ import Foundation import UIKit #endif -/// A DatabasePool grants concurrent accesses to an SQLite database. -public final class DatabasePool: DatabaseWriter { +/// A database connection that allows concurrent accesses to an SQLite database. +/// +/// Unless ``Configuration/readonly``, a database pool opens an SQLite database +/// in the [WAL mode](https://sqlite.org/wal.html). +/// +/// It creates one writer SQLite connection, and a pool of up to +/// ``Configuration/maximumReaderCount`` read-only SQLite connections. All +/// write accesses are executed in a serial **writer dispatch queue**. All +/// read accesses are executed in **reader dispatch queues** (one per read-only +/// SQLite connection). +/// +/// A database pool inherits most of its database access methods from the +/// ``DatabaseReader`` and ``DatabaseWriter`` protocols. It defines a few +/// specific database access methods as well. +/// +/// ## Topics +/// +/// ### Creating a DatabasePool +/// +/// - ``init(path:configuration:)`` +/// +/// ### Creating a DatabaseSnapshot +/// +/// - ``makeSnapshot()`` +/// +/// ### Accessing the Database +/// +/// - ``asyncConcurrentRead(_:)`` +/// - ``writeInTransaction(_:_:)`` +/// +/// ### Managing SQLite Connections +/// +/// - ``invalidateReadOnlyConnections()`` +/// - ``releaseMemory()`` +/// - ``releaseMemoryEventually()`` +public final class DatabasePool { private let writer: SerializedDatabase /// The pool of reader connections. @@ -16,7 +50,6 @@ public final class DatabasePool: DatabaseWriter { // MARK: - Database Information - /// The database configuration public var configuration: Configuration { writer.configuration } @@ -28,16 +61,21 @@ public final class DatabasePool: DatabaseWriter { // MARK: - Initializer - /// Opens the SQLite database at path *path*. + /// Opens or creates an SQLite database. /// - /// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") + /// For example: /// - /// Database connections get closed when the database pool gets deallocated. + /// ```swift + /// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") + /// ``` + /// + /// The SQLite connections are closed when the database pool + /// gets deallocated. /// /// - parameters: /// - path: The path to the database file. /// - configuration: A configuration. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public init(path: String, configuration: Configuration = Configuration()) throws { GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1") @@ -462,48 +500,46 @@ extension DatabasePool: DatabaseReader { } } - /// Performs the same job as asyncConcurrentRead. - /// - /// :nodoc: public func spawnConcurrentRead(_ value: @escaping (Result) -> Void) { asyncConcurrentRead(value) } - /// Asynchronously executes a read-only function in a protected - /// dispatch queue. + /// Performs an asynchronous read access. /// - /// This method must be called from a writing dispatch queue, outside of any - /// transaction. You'll get a fatal error otherwise. + /// This method must be called from the writer dispatch queue, outside of + /// any transaction. You'll get a fatal error otherwise. /// /// The `value` function is guaranteed to see the database in the last /// committed state at the moment this method is called. Eventual /// concurrent database updates are not visible from the function. /// - /// This method returns as soon as the isolation guarantees described above - /// are established. + /// This method returns as soon as the isolation guarantee described above + /// has been established. /// /// In the example below, the number of players is fetched concurrently with - /// the player insertion. Yet the future is guaranteed to return zero: + /// the player insertion. Yet it is guaranteed to be zero: /// - /// try writer.asyncWriteWithoutTransaction { db in - /// // Delete all players - /// try Player.deleteAll() + /// ```swift + /// try writer.asyncWriteWithoutTransaction { db in + /// // Delete all players + /// try Player.deleteAll() /// - /// // Count players concurrently - /// writer.asyncConcurrentRead { dbResult in - /// do { - /// let db = try dbResult.get() - /// // Guaranteed to be zero - /// let count = try Player.fetchCount(db) - /// } catch { - /// // Handle error - /// } + /// // Count players concurrently + /// writer.asyncConcurrentRead { dbResult in + /// do { + /// let db = try dbResult.get() + /// // Guaranteed to be zero + /// let count = try Player.fetchCount(db) + /// } catch { + /// // Handle error /// } - /// - /// // Insert a player - /// try Player(...).insert(db) /// } /// + /// // Insert a player + /// try Player(...).insert(db) + /// } + /// ``` + /// /// - parameter value: A function that accesses the database. public func asyncConcurrentRead(_ value: @escaping (Result) -> Void) { // Check that we're on the writer queue... @@ -638,89 +674,8 @@ extension DatabasePool: DatabaseReader { return readers.first { $0.onValidQueue } } - // MARK: - Writing in Database - - @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func writeWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { - try writer.sync(updates) - } - - @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T { - guard let readerPool else { - throw DatabaseError.connectionIsClosed() - } - return try readerPool.barrier { - try writer.sync(updates) - } - } - - public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) { - guard let readerPool else { - updates(.failure(DatabaseError.connectionIsClosed())) - return - } - readerPool.asyncBarrier { - self.writer.sync { updates(.success($0)) } - } - } - - /// Synchronously executes database updates in a protected dispatch queue, - /// wrapped inside a transaction, and returns the result. - /// - /// If the updates throws an error, the transaction is rollbacked and the - /// error is rethrown. If the updates return .rollback, the transaction is - /// also rollbacked, but no error is thrown. - /// - /// Eventual concurrent database updates are postponed until the transaction - /// has completed. - /// - /// Eventual concurrent reads are guaranteed to not see any partial updates - /// of the database until the transaction has completed. - /// - /// This method is *not* reentrant. - /// - /// try dbPool.writeInTransaction { db in - /// db.execute(...) - /// return .commit - /// } - /// - /// - parameters: - /// - kind: The transaction type (default nil). If nil, the transaction - /// type is configuration.defaultTransactionKind, which itself - /// defaults to .deferred. See - /// for more information. - /// - updates: The updates to the database. - /// - throws: The error thrown by the updates, or by the - /// wrapping transaction. - public func writeInTransaction( - _ kind: Database.TransactionKind? = nil, - _ updates: (Database) throws -> Database.TransactionCompletion) - throws - { - try writer.sync { db in - try db.inTransaction(kind) { - try updates(db) - } - } - } - - public func unsafeReentrantWrite(_ updates: (Database) throws -> T) rethrows -> T { - try writer.reentrantSync(updates) - } - - /// Asynchronously executes database updates in a protected dispatch queue, - /// outside of any transaction. - /// - /// Eventual concurrent reads may see partial updates unless you wrap them - /// in a transaction. - public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { - writer.async(updates) - } - // MARK: - Database Observation - /// :nodoc: public func _add( observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, @@ -771,68 +726,147 @@ extension DatabasePool: DatabaseReader { } } +extension DatabasePool: DatabaseWriter { + // MARK: - Writing in Database + + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails + public func writeWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { + try writer.sync(updates) + } + + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails + public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T { + guard let readerPool else { + throw DatabaseError.connectionIsClosed() + } + return try readerPool.barrier { + try writer.sync(updates) + } + } + + public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) { + guard let readerPool else { + updates(.failure(DatabaseError.connectionIsClosed())) + return + } + readerPool.asyncBarrier { + self.writer.sync { updates(.success($0)) } + } + } + + /// Wraps database operations inside a database transaction. + /// + /// The `updates` function runs in the writer dispatch queue, serialized + /// with all database updates. + /// + /// If `updates` throws an error, the transaction is rollbacked and the + /// error is rethrown. If it returns + /// ``Database/TransactionCompletion/rollback``, the transaction is also + /// rollbacked, but no error is thrown. + /// + /// For example: + /// + /// ```swift + /// try dbPool.writeInTransaction { db in + /// try Player(name: "Arthur").insert(db) + /// try Player(name: "Barbara").insert(db) + /// return .commit + /// } + /// ``` + /// + /// - precondition: This method is not reentrant. + /// - parameters: + /// - kind: The transaction type (default nil). If nil, the transaction + /// type is the ``Configuration/defaultTransactionKind`` of the + /// the ``configuration``. + /// - updates: A function that updates the database. + /// - throws: The error thrown by `updates`, or by the wrapping transaction. + public func writeInTransaction( + _ kind: Database.TransactionKind? = nil, + _ updates: (Database) throws -> Database.TransactionCompletion) + throws + { + try writer.sync { db in + try db.inTransaction(kind) { + try updates(db) + } + } + } + + public func unsafeReentrantWrite(_ updates: (Database) throws -> T) rethrows -> T { + try writer.reentrantSync(updates) + } + + public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { + writer.async(updates) + } +} + extension DatabasePool { // MARK: - Snapshots /// Creates a database snapshot. /// - /// The snapshot sees an unchanging database content, as it existed at the - /// moment it was created. + /// The returned snapshot sees an unchanging database content, as it existed + /// at the moment it was created. /// /// When you want to control the latest committed changes seen by a - /// snapshot, create it from the pool's writer protected dispatch queue: + /// snapshot, create it from the pool's writer dispatch queue. Compare: /// - /// let snapshot1 = try dbPool.write { db -> DatabaseSnapshot in + /// ```swift + /// let snapshot1 = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshot in + /// try Player.deleteAll() + /// return try dbPool.makeSnapshot() + /// } + /// // <- Other threads may modify the database here + /// let snapshot2 = try dbPool.makeSnapshot() + /// + /// try snapshot1.read { db in + /// // Guaranteed to be zero + /// try Player.fetchCount(db) + /// } + /// + /// try snapshot2.read { db in + /// // Could be anything + /// try Player.fetchCount(db) + /// } + /// ``` + /// + /// It is forbidden to create a snapshot from the writer dispatch queue when + /// a transaction is opened, because it is likely a programmer error: + /// + /// ```swift + /// try dbPool.writeInTransaction { db in + /// try Player.deleteAll() + /// // fatal error: makeSnapshot() must not be called from inside a transaction + /// let snapshot = try dbPool.makeSnapshot() + /// return .commit + /// } + /// ``` + /// + /// To avoid this fatal error, create the snapshot *before* or *after* + /// the transaction: + /// + /// ```swift + /// try dbPool.writeWithoutTransaction { db in + /// // OK + /// let snapshot = try dbPool.makeSnapshot() + /// + /// try db.inTransaction { /// try Player.deleteAll() - /// return try dbPool.makeSnapshot() - /// } - /// // <- Other threads may modify the database here - /// let snapshot2 = try dbPool.makeSnapshot() - /// - /// try snapshot1.read { db in - /// // Guaranteed to be zero - /// try Player.fetchCount(db) + /// return .commit /// } /// - /// try snapshot2.read { db in - /// // Could be anything - /// try Player.fetchCount(db) - /// } - /// - /// It is forbidden to create a snapshot from the writer protected dispatch - /// queue when a transaction is opened, though, because it is likely a - /// programmer error: - /// - /// try dbPool.write { db in - /// try db.inTransaction { - /// try Player.deleteAll() - /// // fatal error: makeSnapshot() must not be called from inside a transaction - /// let snapshot = try dbPool.makeSnapshot() - /// return .commit - /// } - /// } - /// - /// To avoid this fatal error, create the snapshot *before* or *after* the - /// transaction: - /// - /// try dbPool.writeWithoutTransaction { db in - /// // OK - /// let snapshot = try dbPool.makeSnapshot() - /// - /// try db.inTransaction { - /// try Player.deleteAll() - /// return .commit - /// } - /// - /// // OK - /// let snapshot = try dbPool.makeSnapshot() - /// } + /// // OK + /// let snapshot = try dbPool.makeSnapshot() + /// } + /// ``` /// /// You can create as many snapshots as you need, regardless of the maximum /// number of reader connections in the pool. /// - /// For more information, read about "snapshot isolation" at + /// Related SQLite documentation: public func makeSnapshot() throws -> DatabaseSnapshot { // Sanity check if writer.onValidQueue { diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index dbcf000f7..89a119452 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -4,34 +4,63 @@ import Foundation import UIKit #endif -/// A DatabaseQueue serializes access to an SQLite database. -public final class DatabaseQueue: DatabaseWriter { +/// A database connection that serializes accesses to an SQLite database. +/// +/// A database queue creates one single SQLite connection. All database accesses +/// are executed in a serial **writer dispatch queue**. +/// +/// A database queue inherits most of its database access methods from the +/// ``DatabaseReader`` and ``DatabaseWriter`` protocols. It defines a few +/// specific database access methods as well. +/// +/// ## Topics +/// +/// ### Creating a DatabaseQueue +/// +/// - ``init(configuration:)`` +/// - ``init(path:configuration:)`` +/// +/// ### Accessing the Database +/// +/// - ``inDatabase(_:)`` +/// - ``inTransaction(_:_:)`` +/// +/// ### Managing the SQLite Connection +/// +/// - ``releaseMemory()`` +public final class DatabaseQueue { private let writer: SerializedDatabase // MARK: - Configuration - /// The database configuration public var configuration: Configuration { writer.configuration } - /// The path to the database file; it is ":memory:" for in-memory databases. + /// The path to the database file. + /// + /// The path is `:memory:` for in-memory databases. public var path: String { writer.path } // MARK: - Initializers - /// Opens the SQLite database at path *path*. + /// Opens or creates an SQLite database. /// - /// let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite") + /// For example: /// - /// Database connections get closed when the database queue gets deallocated. + /// ```swift + /// let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite") + /// ``` + /// + /// The SQLite connection is closed when the database queue + /// gets deallocated. /// /// - parameters: /// - path: The path to the database file. /// - configuration: A configuration. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public init(path: String, configuration: Configuration = Configuration()) throws { writer = try SerializedDatabase( path: path, @@ -51,9 +80,8 @@ public final class DatabaseQueue: DatabaseWriter { /// Opens an in-memory SQLite database. /// - /// let dbQueue = try DatabaseQueue() - /// - /// Database memory is released when the database queue gets deallocated. + /// The database memory is released when the database queue + /// gets deallocated. /// /// - parameter configuration: A configuration. public init(configuration: Configuration = Configuration()) throws { @@ -70,10 +98,6 @@ public final class DatabaseQueue: DatabaseWriter { // Explicit unregistration is required before OS X 10.11. NotificationCenter.default.removeObserver(self) } - - public func close() throws { - try writer.sync { try $0.close() } - } } extension DatabaseQueue { @@ -133,7 +157,10 @@ extension DatabaseQueue { #endif } -extension DatabaseQueue { +extension DatabaseQueue: DatabaseReader { + public func close() throws { + try writer.sync { try $0.close() } + } // MARK: - Interrupting Database Operations @@ -233,9 +260,6 @@ extension DatabaseQueue { }) } - /// Performs the same job as asyncConcurrentRead. - /// - /// :nodoc: public func spawnConcurrentRead(_ value: @escaping (Result) -> Void) { // Check that we're on the writer queue... writer.execute { db in @@ -258,33 +282,59 @@ extension DatabaseQueue { } } + // MARK: - Database Observation + + public func _add( + observation: ValueObservation, + scheduling scheduler: ValueObservationScheduler, + onChange: @escaping (Reducer.Value) -> Void) + -> AnyDatabaseCancellable + { + if configuration.readonly { + // The easy case: the database does not change + return _addReadOnly( + observation: observation, + scheduling: scheduler, + onChange: onChange) + } else { + // Observe from the writer database connection. + return _addWriteOnly( + observation: observation, + scheduling: scheduler, + onChange: onChange) + } + } +} + +extension DatabaseQueue: DatabaseWriter { // MARK: - Writing in Database - /// Synchronously executes database updates in a protected dispatch queue, - /// wrapped inside a transaction, and returns the result. + /// Wraps database operations inside a database transaction. /// - /// If the updates throws an error, the transaction is rollbacked and the - /// error is rethrown. If the updates return .rollback, the transaction is - /// also rollbacked, but no error is thrown. + /// The `updates` function runs in the writer dispatch queue, serialized + /// with all database updates. + /// + /// If `updates` throws an error, the transaction is rollbacked and the + /// error is rethrown. If it returns + /// ``Database/TransactionCompletion/rollback``, the transaction is also + /// rollbacked, but no error is thrown. /// - /// Eventual concurrent database accesses are postponed until the - /// transaction has completed. + /// For example: /// - /// This method is *not* reentrant. - /// - /// try dbQueue.writeInTransaction { db in - /// db.execute(...) - /// return .commit - /// } + /// ```swift + /// try dbQueue.inTransaction { db in + /// try Player(name: "Arthur").insert(db) + /// try Player(name: "Barbara").insert(db) + /// return .commit + /// } + /// ``` /// /// - parameters: /// - kind: The transaction type (default nil). If nil, the transaction - /// type is configuration.defaultTransactionKind, which itself - /// defaults to .deferred. See - /// for more information. - /// - updates: The updates to the database. - /// - throws: The error thrown by the updates, or by the - /// wrapping transaction. + /// type is the ``Configuration/defaultTransactionKind`` of the + /// the ``configuration``. + /// - updates: A function that updates the database. + /// - throws: The error thrown by `updates`, or by the wrapping transaction. public func inTransaction( _ kind: Database.TransactionKind? = nil, _ updates: (Database) throws -> Database.TransactionCompletion) @@ -311,19 +361,40 @@ extension DatabaseQueue { writer.async { updates(.success($0)) } } - /// Synchronously executes database updates in a protected dispatch queue, - /// outside of any transaction, and returns the result. + /// Executes database operations, and returns their result after they have + /// finished executing. /// - /// Eventual concurrent database updates are postponed until the updates - /// are completed. + /// This method is identical to + /// ``DatabaseWriter/writeWithoutTransaction(_:)-4qh1w`` /// - /// Eventual concurrent reads may see partial updates unless you wrap them - /// in a transaction. + /// For example: /// - /// This method is *not* reentrant. + /// ```swift + /// let newPlayerCount = try dbQueue.inDatabase { db in + /// try Player(name: "Arthur").insert(db) + /// return try Player.fetchCount(db) + /// } + /// ``` /// - /// - parameter updates: The updates to the database. - /// - throws: The error thrown by the updates. + /// Database operations run in the writer dispatch queue, serialized + /// with all database updates performed by this `DatabaseWriter`. + /// + /// The ``Database`` argument to `updates` is valid only during the + /// execution of the closure. Do not store or return the database connection + /// for later use. + /// + /// It is a programmer error to call this method from another database + /// access method. Doing so raises a "Database methods are not reentrant" + /// fatal error at runtime. + /// + /// - warning: Database operations are not wrapped in a transaction. They + /// can see changes performed by concurrent writes or writes performed by + /// other processes: two identical requests performed by the `updates` + /// closure may not return the same value. Concurrent database accesses + /// can see partial updates performed by the `updates` closure. + /// + /// - parameter updates: A closure which accesses the database. + /// - throws: The error thrown by `updates`. public func inDatabase(_ updates: (Database) throws -> T) rethrows -> T { try writer.sync(updates) } @@ -335,28 +406,4 @@ extension DatabaseQueue { public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { writer.async(updates) } - - // MARK: - Database Observation - - /// :nodoc: - public func _add( - observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) - -> AnyDatabaseCancellable - { - if configuration.readonly { - // The easy case: the database does not change - return _addReadOnly( - observation: observation, - scheduling: scheduler, - onChange: onChange) - } else { - // Observe from the writer database connection. - return _addWriteOnly( - observation: observation, - scheduling: scheduler, - onChange: onChange) - } - } } diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 431b6c048..e1a555f1d 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -3,273 +3,302 @@ import Combine #endif import Dispatch -/// `DatabaseReader` is the protocol for all types that can fetch values from -/// an SQLite database. +/// The protocol for types that read from an SQLite database. /// -/// It is adopted by `DatabaseQueue`, `DatabasePool`, and `DatabaseSnapshot`. +/// Do not declare new conformances to `DatabaseReader`. Only the +/// ``DatabaseQueue``, ``DatabasePool``, and ``DatabaseSnapshot`` types are +/// valid conforming types. /// /// The protocol comes with isolation guarantees that describe the behavior of /// adopting types in a multithreaded application. /// -/// Types that adopt the protocol can provide in practice stronger guarantees. -/// For example, `DatabaseQueue` provides a stronger isolation level -/// than `DatabasePool`. +/// ## Topics /// -/// **Warning**: Isolation guarantees stand as long as there is no external -/// connection to the database. Should you have to cope with external -/// connections, protect yourself with transactions, and be ready to setup a -/// [busy handler](https://www.sqlite.org/c3ref/busy_handler.html). +/// ### Database Information +/// +/// - ``configuration`` +/// +/// ### Reading from the Database +/// +/// - ``asyncRead(_:)`` +/// - ``read(_:)-3806d`` +/// - ``read(_:)-4w6gy`` +/// - ``readPublisher(receiveOn:value:)`` +/// +/// ### Unsafe Methods +/// +/// - ``asyncUnsafeRead(_:)`` +/// - ``unsafeRead(_:)-5i7tf`` +/// - ``unsafeRead(_:)-11mk0`` +/// - ``unsafeReentrantRead(_:)`` +/// +/// ### Other Database Operations +/// +/// - ``backup(to:pagesPerStep:progress:)`` +/// - ``close()`` +/// - ``interrupt()`` +/// +/// ### Supporting Types +/// +/// - ``AnyDatabaseReader`` public protocol DatabaseReader: AnyObject, Sendable { - /// The database configuration + /// The database configuration. var configuration: Configuration { get } - /// Closes the database connection with the `sqlite3_close()` function. + /// Closes the database connection. /// - /// **Note**: You DO NOT HAVE to call this method, and you SHOULD NOT call - /// it unless the correct execution of your program depends on precise - /// database closing. Database connections are automatically closed when - /// they are deinitialized, and this is sufficient for most applications. + /// - note: You do not have to call this method, and you should not call + /// it unless the correct execution of your program depends on precise + /// database closing. Database connections are automatically closed when + /// they are deinitialized, and this is sufficient for most applications. /// /// If this method does not throw, then the database is properly closed, and - /// every future database access will throw a `DatabaseError` of + /// every future database access will throw a ``DatabaseError`` of /// code `SQLITE_MISUSE`. /// /// Otherwise, there exists concurrent database accesses or living prepared /// statements that prevent the database from closing, and this method - /// throws a `DatabaseError` of code `SQLITE_BUSY`. + /// throws a ``DatabaseError`` of code `SQLITE_BUSY`. /// See for more information. /// /// After an error has been thrown, the database may still be opened, and /// you can keep on accessing it. It may also remain in a "zombie" state, /// in which case it will throw `SQLITE_MISUSE` for all future /// database accesses. + /// + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. func close() throws // MARK: - Interrupting Database Operations - /// This method causes any pending database operation to abort and return at - /// its earliest opportunity. + /// Causes any pending database operation to abort and return at its + /// earliest opportunity. /// - /// It can be called from any thread. + /// This method can be called from any thread. /// /// A call to `interrupt()` that occurs when there are no running SQL /// statements is a no-op and has no effect on SQL statements that are /// started after `interrupt()` returns. /// - /// A database operation that is interrupted will throw a DatabaseError with - /// code SQLITE_INTERRUPT. If the interrupted SQL operation is an INSERT, - /// UPDATE, or DELETE that is inside an explicit transaction, then the - /// entire transaction will be rolled back automatically. If the rolled back - /// transaction was started by a transaction-wrapping method such as - /// `DatabaseWriter.write` or `Database.inTransaction`, then all database - /// accesses will throw a DatabaseError with code SQLITE_ABORT until the - /// wrapping method returns. + /// A database operation that is interrupted will throw a ``DatabaseError`` + /// with code `SQLITE_INTERRUPT`. If the interrupted SQL operation is an + /// `INSERT`, `UPDATE`, or `DELETE` that is inside an explicit transaction, + /// then the entire transaction will be rolled back automatically. If the + /// rolled back transaction was started by a transaction-wrapping method + /// such as ``DatabaseWriter/write(_:)-76inz`` or + /// ``Database/inTransaction(_:_:)``, then all database accesses will throw + /// a ``DatabaseError`` with code `SQLITE_ABORT` until the wrapping + /// method returns. /// /// For example: /// - /// try dbQueue.write { db in + /// ```swift + /// try dbQueue.write { db in + /// // interrupted: + /// try Player(...).insert(db) // throws SQLITE_INTERRUPT + /// // not executed: + /// try Player(...).insert(db) + /// } // throws SQLITE_INTERRUPT + /// + /// try dbQueue.write { db in + /// do { /// // interrupted: - /// try Player(...).insert(db) // throws SQLITE_INTERRUPT - /// // not executed: - /// try Player(...).insert(db) - /// } // throws SQLITE_INTERRUPT + /// try Player(...).insert(db) // throws SQLITE_INTERRUPT + /// } catch { } + /// try Player(...).insert(db) // throws SQLITE_ABORT + /// } // throws SQLITE_ABORT /// - /// try dbQueue.write { db in - /// do { - /// // interrupted: - /// try Player(...).insert(db) // throws SQLITE_INTERRUPT - /// } catch { } - /// try Player(...).insert(db) // throws SQLITE_ABORT - /// } // throws SQLITE_ABORT + /// try dbQueue.write { db in + /// do { + /// // interrupted: + /// try Player(...).insert(db) // throws SQLITE_INTERRUPT + /// } catch { } + /// } // throws SQLITE_ABORT + /// ``` /// - /// try dbQueue.write { db in - /// do { - /// // interrupted: - /// try Player(...).insert(db) // throws SQLITE_INTERRUPT - /// } catch { } - /// } // throws SQLITE_ABORT + /// Beware: when an application opens a transaction without a + /// transaction-wrapping method, no `SQLITE_ABORT` error warns of + /// aborted transactions: /// - /// When an application creates transaction without a transaction-wrapping - /// method, no SQLITE_ABORT error warns of aborted transactions: + /// ```swift + /// try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction + /// try db.beginTransaction() + /// do { + /// // interrupted: + /// try Player(...).insert(db) // throws SQLITE_INTERRUPT + /// } catch { } + /// try Player(...).insert(db) // success + /// try db.commit() // throws SQLITE_ERROR "cannot commit - no transaction is active" + /// } + /// ``` /// - /// try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction - /// try db.beginTransaction() - /// do { - /// // interrupted: - /// try Player(...).insert(db) // throws SQLITE_INTERRUPT - /// } catch { } - /// try Player(...).insert(db) // success - /// try db.commit() // throws SQLITE_ERROR "cannot commit - no transaction is active" - /// } - /// - /// Both SQLITE_ABORT and SQLITE_INTERRUPT errors can be checked with the - /// `DatabaseError.isInterruptionError` property. + /// Both `SQLITE_ABORT` and `SQLITE_INTERRUPT` errors can be checked with the + /// ``DatabaseError/isInterruptionError`` property. func interrupt() // MARK: - Read From Database - /// Synchronously executes a read-only function that accepts a database - /// connection, and returns its result. + /// Executes read-only database operations, and returns their result after + /// they have finished executing. /// /// For example: /// - /// let count = try reader.read { db in - /// try Player.fetchCount(db) - /// } + /// ```swift + /// let count = try reader.read { db in + /// try Player.fetchCount(db) + /// } + /// ``` /// - /// The `value` function runs in an isolated fashion: eventual concurrent - /// database updates are not visible from the function: + /// Database operations are isolated in a transaction: they do not see + /// changes performed by eventual concurrent writes (even writes performed + /// by other processes). /// - /// try reader.read { db in - /// // Those two values are guaranteed to be equal, even if the - /// // `player` table is modified, between the two requests, by - /// // some other database connection or some other thread. - /// let count1 = try Player.fetchCount(db) - /// let count2 = try Player.fetchCount(db) - /// } + /// The database connection is read-only: attempts to write throw a + /// ``DatabaseError`` with resultCode `SQLITE_READONLY`. /// - /// try reader.read { db in - /// // Now this value may be different: - /// let count = try Player.fetchCount(db) - /// } - /// - /// Attempts to write in the database throw a DatabaseError with - /// resultCode `SQLITE_READONLY`. + /// The ``Database`` argument to `value` is valid only during the execution + /// of the closure. Do not store or return the database connection for + /// later use. /// /// It is a programmer error to call this method from another database - /// access method: + /// access method. Doing so raises a "Database methods are not reentrant" + /// fatal error at runtime. /// - /// try reader.read { db in - /// // Raises a fatal error - /// try reader.read { ... ) - /// } - /// - /// - parameter value: A function that accesses the database. - /// - throws: The error thrown by `value`, or any `DatabaseError` that would - /// happen while establishing the read access to the database. + /// - parameter value: A closure which accesses the database. + /// - throws: The error thrown by `value`, or any ``DatabaseError`` that + /// would happen while establishing the database access. @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails func read(_ value: (Database) throws -> T) throws -> T - /// Asynchronously executes a read-only function that accepts a - /// database connection. + /// Schedules read-only database operations for execution, and + /// returns immediately. /// - /// The `value` function runs in an isolated fashion: eventual concurrent - /// database updates are not visible from the function: + /// For example: /// - /// reader.asyncRead { dbResult in - /// do { - /// let db = try dbResult.get() - /// // Those two values are guaranteed to be equal, even if the - /// // `player` table is modified, between the two requests, by - /// // some other database connection or some other thread. - /// let count1 = try Player.fetchCount(db) - /// let count2 = try Player.fetchCount(db) - /// } catch { - /// // handle error - /// } + /// ```swift + /// try reader.asyncRead { dbResult in + /// do { + /// let db = try dbResult.get() + /// let count = try Player.fetchCount(db) + /// } catch { + /// // Handle error /// } + /// } + /// ``` /// - /// Attempts to write in the database throw a DatabaseError with - /// resultCode `SQLITE_READONLY`. + /// Database operations are isolated in a transaction: they do not see + /// changes performed by eventual concurrent writes (even writes performed + /// by other processes). /// - /// - parameter value: A function that accesses the database. Its argument + /// The database connection is read-only: attempts to write throw a + /// ``DatabaseError`` with resultCode `SQLITE_READONLY`. + /// + /// - parameter value: A closure which accesses the database. Its argument /// is a `Result` that provides the database connection, or the failure /// that would prevent establishing the read access to the database. func asyncRead(_ value: @escaping (Result) -> Void) - /// Synchronously executes a function that accepts a database - /// connection, and returns its result. + /// Executes database operations, and returns their result after they have + /// finished executing. + /// + /// This method is "unsafe" because the database reader does nothing more + /// than providing a database connection. When you use this method, you + /// become responsible for the thread-safety of your application, and + /// responsible for database accesses performed by other processes. /// /// For example: /// - /// let count = try reader.unsafeRead { db in - /// try Player.fetchCount(db) - /// } + /// ```swift + /// let count = try reader.unsafeRead { db in + /// try Player.fetchCount(db) + /// } + /// ``` /// - /// The guarantees of the `read` method are lifted: - /// - /// the `value` function is not isolated: eventual concurrent database - /// updates are visible from the function: - /// - /// try reader.unsafeRead { db in - /// // Those two values can be different, because some other - /// // database connection or some other thread may modify the - /// // database between the two requests. - /// let count1 = try Player.fetchCount(db) - /// let count2 = try Player.fetchCount(db) - /// } - /// - /// The `value` function is not prevented from writing (DatabaseQueue, in - /// particular, will accept database modifications in `unsafeRead`). + /// The ``Database`` argument to `value` is valid only during the execution + /// of the closure. Do not store or return the database connection for + /// later use. /// /// It is a programmer error to call this method from another database - /// access method: + /// access method. Doing so raises a "Database methods are not reentrant" + /// fatal error at runtime. /// - /// try reader.read { db in - /// // Raises a fatal error - /// try reader.unsafeRead { ... ) - /// } + /// - warning: Database operations are not wrapped in a transaction. They + /// can see changes performed by concurrent writes or writes performed by + /// other processes: two identical requests performed by the `value` + /// closure may not return the same value. + /// - warning: Attempts to write in the database may succeed. /// - /// - parameter value: A function that accesses the database. - /// - throws: The error thrown by `value`, or any `DatabaseError` that would - /// happen while establishing the read access to the database. + /// - parameter value: A closure which accesses the database. + /// - throws: The error thrown by `value`, or any ``DatabaseError`` that + /// would happen while establishing the database access. @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails func unsafeRead(_ value: (Database) throws -> T) throws -> T - /// Asynchronously executes a function that accepts a database connection. + /// Schedules database operations for execution, and returns immediately. /// - /// The guarantees of the `asyncRead` method are lifted: + /// This method is "unsafe" because the database reader does nothing more + /// than providing a database connection. When you use this method, you + /// become responsible for the thread-safety of your application, and + /// responsible for database accesses performed by other processes. /// - /// the `value` function is not isolated: eventual concurrent database - /// updates are visible from the function: + /// For example: /// - /// reader.asyncUnsafeRead { dbResult in - /// do { - /// let db = try dbResult.get() - /// // Those two values can be different, because some other - /// // database connection or some other thread may modify the - /// // database between the two requests. - /// let count1 = try Player.fetchCount(db) - /// let count2 = try Player.fetchCount(db) - /// } catch { - /// // handle error - /// } + /// ```swift + /// reader.asyncUnsafeRead { dbResult in + /// do { + /// let db = try dbResult.get() + /// let count = try Player.fetchCount(db) + /// } catch { + /// // handle error /// } + /// } + /// ``` /// - /// The `value` function is not prevented from writing (DatabaseQueue, in - /// particular, will accept database modifications in `asyncUnsafeRead`). + /// - warning: Database operations are not wrapped in a transaction. They + /// can see changes performed by concurrent writes or writes performed by + /// other processes: two identical requests performed by the `value` + /// closure may not return the same value. + /// - warning: Attempts to write in the database may succeed. /// - /// - parameter value: A function that accesses the database. Its argument + /// - parameter value: A closure which accesses the database. Its argument /// is a `Result` that provides the database connection, or the failure /// that would prevent establishing the read access to the database. func asyncUnsafeRead(_ value: @escaping (Result) -> Void) - /// Synchronously executes a function that accepts a database - /// connection, and returns its result. + /// Executes database operations, and returns their result after they have + /// finished executing. /// - /// The guarantees of the safe `read` method are lifted: + /// This method is "unsafe" because the database reader does nothing more + /// than providing a database connection. When you use this method, you + /// become responsible for the thread-safety of your application, and + /// responsible for database accesses performed by other processes. /// - /// the `value` function is not isolated: eventual concurrent database - /// updates are visible from the function: + /// This method can be called from other database access methods. Reentrant + /// database accesses are discouraged, though, because they muddle + /// transaction boundaries. /// - /// try reader.unsafeReentrantRead { db in - /// // Those two values can be different, because some other - /// // database connection or some other thread may modify the - /// // database between the two requests. - /// let count1 = try Player.fetchCount(db) - /// let count2 = try Player.fetchCount(db) - /// } + /// For example: /// - /// The `value` function is not prevented from writing (DatabaseQueue, in - /// particular, will accept database modifications in `unsafeRead`). + /// ```swift + /// let count = try reader.unsafeReentrantRead { db in + /// try Player.fetchCount(db) + /// } + /// ``` /// - /// This method is reentrant. It should be avoided because it fosters - /// dangerous concurrency practices. + /// The ``Database`` argument to `value` is valid only during the execution + /// of the closure. Do not store or return the database connection for + /// later use. /// - /// - parameter value: A function that accesses the database. - /// - throws: The error thrown by `value`, or any `DatabaseError` that would - /// happen while establishing the read access to the database. + /// - warning: Database operations are not wrapped in a transaction. They + /// can see changes performed by concurrent writes or writes performed by + /// other processes: two identical requests performed by the `value` + /// closure may not return the same value. + /// - warning: Attempts to write in the database may succeed. + /// + /// - parameter value: A closure which accesses the database. + /// - throws: The error thrown by `value`, or any ``DatabaseError`` that + /// would happen while establishing the database access. func unsafeReentrantRead(_ value: (Database) throws -> T) throws -> T @@ -277,13 +306,11 @@ public protocol DatabaseReader: AnyObject, Sendable { /// Starts a value observation. /// - /// You should use the `ValueObservation.start(in:onError:onChange:)` + /// Use the ``ValueObservation/start(in:scheduling:onError:onChange:)`` /// method instead. /// - /// - parameter observation: the stared observation - /// - returns: a cancellable - /// - /// :nodoc: + /// - parameter observation: a ValueObservation. + /// - returns: A DatabaseCancellable that can stop the observation. func _add( observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, @@ -306,31 +333,32 @@ extension DatabaseReader { /// /// Usage: /// - /// let source: DatabaseQueue = ... - /// let destination: DatabaseQueue = ... - /// try source.backup(to: destination) + /// ```swift + /// let source: DatabaseQueue = ... + /// let destination: DatabaseQueue = ... + /// try source.backup(to: destination) + /// ``` /// /// When you're after progress reporting during backup, you'll want to /// perform the backup in several steps. Each step copies the number of /// _database pages_ you specify. See /// for more information: /// - /// // Backup with progress reporting - /// try source.backup( - /// to: destination, - /// pagesPerStep: ...) - /// { backupProgress in - /// print("Database backup progress:", backupProgress) - /// } + /// ```swift + /// // Backup with progress reporting + /// try source.backup(to: destination, pagesPerStep: ...) { progress in + /// print("Database backup progress:", progress) + /// } + /// ``` /// /// The `progress` callback will be called at least once—when /// `backupProgress.isCompleted == true`. If the callback throws /// when `backupProgress.isCompleted == false`, the backup is aborted - /// and the error is rethrown. If the callback throws when + /// and the error is rethrown. If the callback throws when /// `backupProgress.isCompleted == true`, backup completion is /// unaffected and the error is silently ignored. /// - /// See also `Database.backup()`. + /// See also ``Database/backup(to:pagesPerStep:progress:)`` /// /// - parameters: /// - writer: The destination database. @@ -338,8 +366,8 @@ extension DatabaseReader { /// step. By default, all pages are copied in one single step. /// - progress: An optional function that is notified of the backup /// progress. - /// - throws: The error thrown by `progress` if the backup is abandoned, or - /// any `DatabaseError` that would happen while performing the backup. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or the + /// error thrown by `progress`. public func backup( to writer: some DatabaseWriter, pagesPerStep: CInt = -1, @@ -374,39 +402,33 @@ extension DatabaseReader { extension DatabaseReader { // MARK: - Asynchronous Database Access - /// Asynchronously executes a read-only function that accepts a database - /// connection, and returns its result. + /// Executes read-only database operations, and returns their result after + /// they have finished executing. /// - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) /// /// For example: /// - /// let count = try await reader.read { db in - /// try Player.fetchCount(db) - /// } + /// ```swift + /// let count = try await reader.read { db in + /// try Player.fetchCount(db) + /// } + /// ``` /// - /// The `value` function runs in an isolated fashion: eventual concurrent - /// database updates are not visible from the function: + /// Database operations are isolated in a transaction: they do not see + /// changes performed by eventual concurrent writes (even writes performed + /// by other processes). /// - /// try await reader.read { db in - /// // Those two values are guaranteed to be equal, even if the - /// // `player` table is modified, between the two requests, by - /// // some other database connection or some other thread. - /// let count1 = try Player.fetchCount(db) - /// let count2 = try Player.fetchCount(db) - /// } + /// The database connection is read-only: attempts to write throw a + /// ``DatabaseError`` with resultCode `SQLITE_READONLY`. /// - /// try await reader.read { db in - /// // Now this value may be different: - /// let count = try Player.fetchCount(db) - /// } + /// The ``Database`` argument to `value` is valid only during the execution + /// of the closure. Do not store or return the database connection for + /// later use. /// - /// Attempts to write in the database throw a DatabaseError with - /// resultCode `SQLITE_READONLY`. - /// - /// - parameter value: A function that accesses the database. - /// - throws: The error thrown by `value`, or any `DatabaseError` that would - /// happen while establishing the read access to the database. + /// - parameter value: A closure which accesses the database. + /// - throws: The error thrown by `value`, or any ``DatabaseError`` that + /// would happen while establishing the database access. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public func read(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T { try await withUnsafeThrowingContinuation { continuation in @@ -420,35 +442,37 @@ extension DatabaseReader { } } - /// Asynchronously executes a function that accepts a database connection. + /// Executes database operations, and returns their result after they have + /// finished executing. /// - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// This method is "unsafe" because the database reader does nothing more + /// than providing a database connection. When you use this method, you + /// become responsible for the thread-safety of your application, and + /// responsible for database accesses performed by other processes. /// /// For example: /// - /// let count = try await reader.unsafeRead { db in - /// try Player.fetchCount(db) - /// } + /// ```swift + /// let count = try await reader.unsafeRead { db in + /// try Player.fetchCount(db) + /// } + /// ``` /// - /// The guarantees of the `read` method are lifted: + /// The ``Database`` argument to `value` is valid only during the execution + /// of the closure. Do not store or return the database connection for + /// later use. /// - /// the `value` function is not isolated: eventual concurrent database - /// updates are visible from the function: + /// - warning: Database operations are not wrapped in a transaction. They + /// can see changes performed by concurrent writes or writes performed by + /// other processes: two identical requests performed by the `value` + /// closure may not return the same value. + /// - warning: Attempts to write in the database may succeed. /// - /// try await reader.asyncRead { db in - /// // Those two values can be different, because some other - /// // database connection or some other thread may modify the - /// // database between the two requests. - /// let count1 = try Player.fetchCount(db) - /// let count2 = try Player.fetchCount(db) - /// } - /// - /// The `value` function is not prevented from writing (DatabaseQueue, in - /// particular, will accept database modifications in `asyncUnsafeRead`). - /// - /// - parameter value: A function that accesses the database. - /// - throws: The error thrown by `value`, or any `DatabaseError` that would - /// happen while establishing the read access to the database. + /// - parameter value: A closure which accesses the database. + /// - throws: The error thrown by `value`, or any ``DatabaseError`` that + /// would happen while establishing the database access. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public func unsafeRead(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T { try await withUnsafeThrowingContinuation { continuation in @@ -467,41 +491,38 @@ extension DatabaseReader { extension DatabaseReader { // MARK: - Publishing Database Values - /// Returns a Publisher that asynchronously completes with a fetched value. + /// Returns a publisher that publishes one value and completes. /// - /// // DatabasePublishers.Read<[Player]> - /// let players = dbQueue.readPublisher { db in - /// try Player.fetchAll(db) - /// } + /// The database is not accessed until subscription. Value and completion + /// are published on `scheduler` (the main dispatch queue by default). /// - /// Its value and completion are emitted on the main dispatch queue. + /// For example: /// - /// - parameter value: A closure which accesses the database. - @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) - public func readPublisher( - value: @escaping (Database) throws -> Output) - -> DatabasePublishers.Read - { - readPublisher(receiveOn: DispatchQueue.main, value: value) - } - - /// Returns a Publisher that asynchronously completes with a fetched value. + /// ```swift + /// // DatabasePublishers.Read + /// let countPublisher = reader.readPublisher { db in + /// try Player.fetchCount(db) + /// } + /// ``` /// - /// // DatabasePublishers.Read<[Player]> - /// let players = dbQueue.readPublisher( - /// receiveOn: DispatchQueue.global(), - /// value: { db in try Player.fetchAll(db) }) + /// Database operations are isolated in a transaction: they do not see + /// changes performed by eventual concurrent writes (even writes performed + /// by other processes). /// - /// Its value and completion are emitted on `scheduler`. + /// The database connection is read-only: attempts to write throw a + /// ``DatabaseError`` with resultCode `SQLITE_READONLY`. + /// + /// The ``Database`` argument to `value` is valid only during the execution + /// of the closure. Do not store or return the database connection for + /// later use. /// /// - parameter scheduler: A Combine Scheduler. /// - parameter value: A closure which accesses the database. @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) - public func readPublisher( - receiveOn scheduler: S, + public func readPublisher( + receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main, value: @escaping (Database) throws -> Output) -> DatabasePublishers.Read - where S: Scheduler { Deferred { Future { fulfill in @@ -517,13 +538,11 @@ extension DatabaseReader { @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) extension DatabasePublishers { - /// A publisher that reads a value from the database. It publishes exactly - /// one element, or an error. + /// A publisher that reads from the database. /// - /// See: + /// `Read` publishes exactly one element, or an error. /// - /// - `DatabaseReader.readPublisher(receiveOn:value:)`. - /// - `DatabaseReader.readPublisher(value:)`. + /// You build such a publisher from ``DatabaseReader``. public struct Read: Publisher { public typealias Output = Output public typealias Failure = Error @@ -592,18 +611,21 @@ extension DatabaseReader { } } -/// A type-erased DatabaseReader +/// A type-erased database reader. /// -/// Instances of AnyDatabaseReader forward their methods to an arbitrary -/// underlying database reader. -public final class AnyDatabaseReader: DatabaseReader { +/// An instance of `AnyDatabaseReader` forwards its operations to an underlying +/// base database reader. +public final class AnyDatabaseReader { private let base: any DatabaseReader - /// Creates a database reader that wraps a base database reader. + /// Creates a new database reader that wraps and forwards operations + /// to `base`. public init(_ base: some DatabaseReader) { self.base = base } - +} + +extension AnyDatabaseReader: DatabaseReader { public var configuration: Configuration { base.configuration } @@ -612,14 +634,10 @@ public final class AnyDatabaseReader: DatabaseReader { try base.close() } - // MARK: - Interrupting Database Operations - public func interrupt() { base.interrupt() } - // MARK: - Reading from Database - @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func read(_ value: (Database) throws -> T) throws -> T { try base.read(value) @@ -642,9 +660,6 @@ public final class AnyDatabaseReader: DatabaseReader { try base.unsafeReentrantRead(value) } - // MARK: - Value Observation - - /// :nodoc: public func _add( observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 9f47083b6..a293aea6f 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -1,9 +1,8 @@ -/// DatabaseRegion defines a region in the database. DatabaseRegion is dedicated -/// to help transaction observers recognize impactful database changes in their -/// `observes(eventsOfKind:)` and `databaseDidChange(with:)` methods. +/// An observable region of the database. /// -/// A database region is the union of any number of "table regions", which can -/// cover a full table, or the combination of columns and rows: +/// A `DatabaseRegion` is the union of any number of "table regions", which can +/// cover a full table, or the combination of columns and rows identified by +/// their rowids: /// /// |Table1 | |Table2 | |Table3 | |Table4 | |Table5 | /// |-------| |-------| |-------| |-------| |-------| @@ -12,24 +11,36 @@ /// |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | | /// |x|x|x|x| |x| | | | | | | | | | | | | | | | | | | /// -/// To create a database region, you use one of those methods: +/// It is dedicated to help ``TransactionObserver`` types detect impactful +/// database changes. /// -/// - `DatabaseRegion.fullDatabase`: the region that covers all database tables. +/// You get `DatabaseRegion` instances from a ``DatabaseRegionConvertible`` +/// value, a prepared ``Statement``, or from the initializers described below. /// -/// - `DatabaseRegion()`: the empty region. +/// ## Topics /// -/// - `DatabaseRegion(table:)`: the region that covers one database table. +/// ### Creating Regions /// -/// - `Statement.databaseRegion`: +/// - ``fullDatabase-3ir3p`` +/// - ``init()`` /// -/// let statement = try db.makeStatement(sql: "SELECT name, score FROM player") -/// let region = statement.databaseRegion +/// ### Instance Properties /// -/// - `FetchRequest.databaseRegion(_:)` +/// - ``isEmpty`` +/// - ``isFullDatabase`` /// -/// let request = Player.filter(key: 1) -/// let region = try request.databaseRegion(db) -public struct DatabaseRegion: CustomStringConvertible, Equatable { +/// ### Combining Regions +/// +/// - ``formUnion(_:)`` +/// - ``union(_:)`` +/// +/// ### Detecting Database Changes +/// +/// Use those methods from ``TransactionObserver`` methods. +/// +/// - ``isModified(byEventsOfKind:)`` +/// - ``isModified(by:)`` +public struct DatabaseRegion { private let tableRegions: [CaseInsensitiveIdentifier: TableRegion]? private init(tableRegions: [CaseInsensitiveIdentifier: TableRegion]?) { @@ -45,17 +56,15 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable { return tableRegions.isEmpty } - /// Returns whether the region covers the full database: all columns and all - /// rows from all tables. + /// Returns whether the region covers the full database. public var isFullDatabase: Bool { tableRegions == nil } - /// The region that covers the full database: all columns and all rows - /// from all tables. + /// The region that covers the full database. public static let fullDatabase = DatabaseRegion(tableRegions: nil) - /// Creates an empty database region. + /// The empty database region. public init() { self.init(tableRegions: [:]) } @@ -226,9 +235,7 @@ extension DatabaseRegion { } } -// Equatable -extension DatabaseRegion { - /// :nodoc: +extension DatabaseRegion: Equatable { public static func == (lhs: DatabaseRegion, rhs: DatabaseRegion) -> Bool { switch (lhs.tableRegions, rhs.tableRegions) { case (nil, nil): @@ -249,9 +256,7 @@ extension DatabaseRegion { } } -// CustomStringConvertible -extension DatabaseRegion { - /// :nodoc: +extension DatabaseRegion: CustomStringConvertible { public var description: String { guard let tableRegions else { return "full database" @@ -337,10 +342,13 @@ private struct TableRegion: Equatable { // MARK: - DatabaseRegionConvertible -/// `DatabaseRegionConvertible` is the protocol for values that can be turned -/// into a `DatabaseRegion`. +/// A type that operates on a specific ``DatabaseRegion``. /// -/// Such values specify the region observed by `DatabaseRegionObservation`. +/// ## Topics +/// +/// ### Supporting Types +/// +/// - ``AnyDatabaseRegionConvertible`` public protocol DatabaseRegionConvertible { /// Returns a database region. /// @@ -355,7 +363,6 @@ extension DatabaseRegionConvertible where Self == DatabaseRegion { } extension DatabaseRegion: DatabaseRegionConvertible { - /// :nodoc: public func databaseRegion(_ db: Database) throws -> DatabaseRegion { self } @@ -373,7 +380,6 @@ public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible { _region = region.databaseRegion } - /// :nodoc: public func databaseRegion(_ db: Database) throws -> DatabaseRegion { try _region(db) } diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index 371a4e161..9e87d403f 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -3,19 +3,33 @@ import Combine #endif import Foundation -/// DatabaseRegionObservation tracks changes in the results of database -/// requests, and notifies each database transaction whenever the -/// database changes. +/// `DatabaseRegionObservation` tracks transactions that modify a +/// database region. /// /// For example: /// -/// let observation = DatabaseRegionObservation(tracking: Player.all) -/// let cancellable = try observation.start( -/// in: dbQueue, -/// onError: { error in ... }, -/// onChange: { (db: Database) in -/// print("A modification of the player table has just been committed.") -/// }) +/// ```swift +/// // Track the player table +/// let observation = DatabaseRegionObservation(tracking: Player.all()) +/// +/// let cancellable = try observation.start(in: dbQueue) { error in +/// // handle error +/// } onChange: { (db: Database) in +/// print("A modification of the player table has just been committed.") +/// } +/// ``` +/// +/// ## Topics +/// +/// ### Creating DatabaseRegionObservation +/// +/// - ``init(tracking:)-5ldbe`` +/// - ``init(tracking:)-2nqjd`` +/// +/// ### Observing Database Transactions +/// +/// - ``publisher(in:)`` +/// - ``start(in:onError:onChange:)`` public struct DatabaseRegionObservation { /// A closure that is evaluated when the observation starts, and returns /// the observed database region. @@ -23,51 +37,32 @@ public struct DatabaseRegionObservation { } extension DatabaseRegionObservation { - /// Creates a DatabaseRegionObservation which observes *regions*, and - /// notifies whenever one of the observed regions is modified by a - /// database transaction. + /// Creates a `DatabaseRegionObservation` that notifies all transactions + /// that modify one of the provided regions. /// - /// For example, this sample code counts the number of a times the player - /// table is modified: + /// For example: /// - /// let observation = DatabaseRegionObservation(tracking: Player.all()) - /// - /// var count = 0 - /// let cancellable = observation.start( - /// in: dbQueue, - /// onError: { error in ... }, - /// onChange: { _ in - /// count += 1 - /// print("Players have been modified \(count) times.") - /// }à - /// - /// The observation lasts until the cancellable returned by `start` is - /// cancelled or deallocated. + /// ```swift + /// // An observation that tracks the 'player' table + /// let observation = DatabaseRegionObservation(tracking: Player.all()) + /// ``` /// /// - parameter regions: A list of observed regions. public init(tracking regions: any DatabaseRegionConvertible...) { self.init(tracking: regions) } - /// Creates a DatabaseRegionObservation which observes *regions*, and - /// notifies whenever one of the observed regions is modified by a - /// database transaction. + /// Creates a `DatabaseRegionObservation` that notifies all transactions + /// that modify one of the provided regions. /// - /// For example, this sample code counts the number of a times the player - /// table is modified: + /// For example: /// - /// let observation = DatabaseRegionObservation(tracking: [Player.all()]) + /// ```swift + /// // An observation that tracks the 'player' table + /// let observation = DatabaseRegionObservation(tracking: [Player.all()]) + /// ``` /// - /// var count = 0 - /// let cancellable = observation.start(in: dbQueue) { _ in - /// count += 1 - /// print("Players have been modified \(count) times.") - /// } - /// - /// The observation lasts until the cancellable returned by `start` is - /// cancelled or deallocated. - /// - /// - parameter regions: A list of observed regions. + /// - parameter regions: An array of observed regions. public init(tracking regions: [any DatabaseRegionConvertible]) { self.init(observedRegion: DatabaseRegion.union(regions)) } @@ -81,29 +76,40 @@ extension DatabaseRegionObservation { case started(DatabaseRegionObserver) } - /// Starts the observation in the provided database writer (such as - /// a database queue or database pool), and returns a transaction observer. + /// Starts observing the database. + /// + /// The observation lasts until the returned cancellable is cancelled + /// or deallocated. /// /// For example: /// - /// let observation = DatabaseRegionObservation.tracking(Player.all()) - /// let cancellable = observation.start( - /// in: dbQueue, - /// onError: { error in ... }, - /// onChange: { (db: Database) in - /// print("A modification of the player table has just been committed.") - /// }) + /// ```swift + /// let observation = DatabaseRegionObservation(tracking: Player.all()) /// - /// If the `start` method is called from a writing database access method, - /// the observation of impactful transactions starts immediately. Otherwise, - /// it blocks the current thread until a write access can be established. + /// let cancellable = try observation.start(in: dbQueue) { error in + /// // handle error + /// } onChange: { (db: Database) in + /// print("A modification of the player table has just been committed.") + /// } + /// ``` + /// + /// If this method is called from the writer dispatch queue of `writer` (see + /// ``DatabaseWriter``), the observation starts immediately. Otherwise, it + /// blocks the current thread until a write access can be established. + /// + /// Both `onError` and `onChange` closures are executed in the writer + /// dispatch queue, serialized with all database updates performed + /// by `writer`. + /// + /// The ``Database`` argument to `onChange` is valid only during the + /// execution of the closure. Do not store or return the database connection + /// for later use. /// /// - parameter writer: A DatabaseWriter. - /// - parameter onError: A closure that is provided eventual errors that - /// happen during observation - /// - parameter onChange: A closure that is provided a database connection - /// with write access each time the observed region has been modified. - /// - returns: a cancellable. + /// - parameter onError: The closure to execute when the observation fails. + /// - parameter onChange: The closure to execute when a transaction has + /// modified the observed region. + /// - returns: A DatabaseCancellable that can stop the observation. public func start( in writer: some DatabaseWriter, onError: @escaping (Error) -> Void, @@ -153,12 +159,14 @@ extension DatabaseRegionObservation { extension DatabaseRegionObservation { // MARK: - Publishing Impactful Transactions - /// Returns a publisher that tracks changes in a database region. + /// Returns a publisher that observes the database. /// - /// It emits database connections on a protected dispatch queue. + /// The publisher publishes ``Database`` connections on the writer dispatch + /// queue of `writer` (see ``DatabaseWriter``). Those connections are valid + /// only when published. Do not store or return them for later use. /// - /// Error completion, if any, is only emitted, synchronously, - /// on subscription. + /// Do not reschedule the publisher with `receive(on:options:)` or any + /// `Publisher` method that schedules publisher elements. @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) public func publisher(in writer: some DatabaseWriter) -> DatabasePublishers.DatabaseRegion { DatabasePublishers.DatabaseRegion(self, in: writer) @@ -202,9 +210,9 @@ private class DatabaseRegionObserver: TransactionObserver { #if canImport(Combine) @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) extension DatabasePublishers { - /// A publisher that tracks changes in a database region. + /// A publisher that tracks transactions that modify a database region. /// - /// See `DatabaseRegionObservation.publisher(in:)`. + /// You build such a publisher from ``DatabaseRegionObservation``. public struct DatabaseRegion: Publisher { public typealias Output = Database public typealias Failure = Error @@ -217,7 +225,6 @@ extension DatabasePublishers { self.observation = observation } - /// :nodoc: public func receive(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input { let subscription = DatabaseRegionSubscription( writer: writer, diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index c3ff65c43..01e5986a0 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -1,12 +1,19 @@ import Dispatch -/// A DatabaseSnapshot sees an unchanging database content, as it existed at the -/// moment it was created. +/// A database connection that sees an unchanging database content, as it +/// existed at the moment it was created. /// -/// See DatabasePool.makeSnapshot() +/// You create instances of `DatabaseSnapshot` from a ``DatabasePool``, with +/// ``DatabasePool/makeSnapshot()``. /// -/// For more information, read about "snapshot isolation" at -public final class DatabaseSnapshot: DatabaseReader { +/// A database snapshot creates one single SQLite connection. All database +/// accesses are executed in a serial dispatch queue. +/// +/// A database snapshot inherits all of its database access methods from the +/// ``DatabaseReader`` protocol. +/// +/// Related SQLite documentation: +public final class DatabaseSnapshot { private let serializedDatabase: SerializedDatabase /// The database configuration @@ -16,7 +23,7 @@ public final class DatabaseSnapshot: DatabaseReader { init(path: String, configuration: Configuration = Configuration(), defaultLabel: String, purpose: String) throws { var configuration = DatabasePool.readerConfiguration(configuration) - configuration.allowsUnsafeTransactions = true // Snaphost keeps a long-lived transaction + configuration.allowsUnsafeTransactions = true // Snapshot keeps a long-lived transaction serializedDatabase = try SerializedDatabase( path: path, @@ -45,14 +52,12 @@ public final class DatabaseSnapshot: DatabaseReader { try? db.commit() } } - +} + +extension DatabaseSnapshot: DatabaseReader { public func close() throws { try serializedDatabase.sync { try $0.close() } } -} - -// DatabaseReader -extension DatabaseSnapshot { // MARK: - Interrupting Database Operations @@ -84,7 +89,6 @@ extension DatabaseSnapshot { // MARK: - Database Observation - /// :nodoc: public func _add( observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index f3d9d8c5f..2ab122672 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -1,21 +1,69 @@ -// TODO: remove @preconcurrency when Data conformance to Sendable is exposed. -@preconcurrency import Foundation +import Foundation -// MARK: - DatabaseValue - -/// DatabaseValue is the intermediate type between SQLite and your values. +/// A value stored in a database table. /// -/// See -public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLSpecificExpressible { - /// The SQLite storage +/// To get `DatabaseValue` instances, you can: +/// +/// - Fetch `DatabaseValue` from a ``Database`` instace: +/// +/// ```swift +/// try dbQueue.read { db in +/// let dbValue = try DatabaseValue.fetchOne(db, sql: """ +/// SELECT name FROM player +/// """) +/// } +/// ``` +/// +/// - Extract `DatabaseValue` from a database ``Row``: +/// +/// ```swift +/// try dbQueue.read { db in +/// if let row = try Row.fetchOne(db, sql: """ +/// SELECT name FROM player +/// """) +/// { +/// let dbValue = row[0] as DatabaseValue +/// } +/// } +/// ``` +/// +/// - Use the ``DatabaseValueConvertible/databaseValue-1ob9k`` property on a +/// ``DatabaseValueConvertible`` value: +/// +/// ```swift +/// let dbValue = DatabaseValue.null +/// let dbValue = 1.databaseValue +/// let dbValue = "Arthur".databaseValue +/// let dbValue = Date().databaseValue +/// ``` +/// +/// Related SQLite documentation: +/// +/// ## Topics +/// +/// ### Creating a DatabaseValue +/// +/// - ``init(value:)`` +/// - ``null`` +/// +/// ### Accessing the SQLite storage +/// +/// - ``isNull`` +/// - ``storage-swift.property`` +/// - ``Storage-swift.enum`` +public struct DatabaseValue: Hashable { + /// The SQLite storage. public let storage: Storage /// The NULL DatabaseValue. public static let null = DatabaseValue(storage: .null) - /// An SQLite storage (NULL, INTEGER, REAL, TEXT, BLOB). + /// A value stored in a database table, with its exact SQLite storage + /// (NULL, INTEGER, REAL, TEXT, BLOB). + /// + /// Related SQLite documentation: @frozen - public enum Storage: Equatable { + public enum Storage { /// The NULL storage class. case null @@ -31,7 +79,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon /// The BLOB storage class, wrapping Data. case blob(Data) - /// Returns Int64, Double, String, Data or nil. + /// Returns `Int64`, `Double`, `String`, `Data` or nil. public var value: (any DatabaseValueConvertible)? { switch self { case .null: @@ -46,27 +94,11 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon return data } } - - /// Return true if the storages are identical. - /// - /// Unlike DatabaseValue equality that considers the integer 1 to be - /// equal to the 1.0 double (as SQLite does), int64 and double storages - /// are never equal. - public static func == (_ lhs: Storage, _ rhs: Storage) -> Bool { - switch (lhs, rhs) { - case (.null, .null): return true - case let (.int64(lhs), .int64(rhs)): return lhs == rhs - case let (.double(lhs), .double(rhs)): return lhs == rhs - case let (.string(lhs), .string(rhs)): return lhs == rhs - case let (.blob(lhs), .blob(rhs)): return lhs == rhs - default: return false - } - } } - /// Creates a DatabaseValue from Any. + /// Creates a `DatabaseValue` from any value. /// - /// The result is nil unless object adopts DatabaseValueConvertible. + /// The result is nil unless `value` adopts ``DatabaseValueConvertible``. public init?(value: Any) { guard let convertible = value as? any DatabaseValueConvertible else { return nil @@ -76,7 +108,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon // MARK: - Extracting Value - /// Returns true if databaseValue is NULL. + /// A boolean value indicating is the database value is `NULL`. public var isNull: Bool { switch storage { case .null: @@ -116,7 +148,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon } } - /// Returns a DatabaseValue initialized from a raw SQLite statement pointer. + /// Creates a `DatabaseValue` initialized from a raw SQLite statement pointer. init(sqliteStatement: SQLiteStatement, index: CInt) { switch sqlite3_column_type(sqliteStatement, index) { case SQLITE_NULL: @@ -159,45 +191,54 @@ extension DatabaseValue: StatementBinding { } extension DatabaseValue: Sendable { } -extension DatabaseValue.Storage: Sendable { } + +// @unchecked Sendable because Data is not Sendable in all target OS +extension DatabaseValue.Storage: @unchecked Sendable { } // MARK: - Hashable & Equatable -// Hashable -extension DatabaseValue { - - /// :nodoc: - public func hash(into hasher: inout Hasher) { - switch storage { - case .null: - hasher.combine(0) - case .int64(let int64): - // 1 == 1.0, hence 1 and 1.0 must have the same hash: - hasher.combine(Double(int64)) - case .double(let double): - hasher.combine(double) - case .string(let string): - hasher.combine(string) - case .blob(let data): - hasher.combine(data) +extension DatabaseValue.Storage: Equatable { + /// Return true if the storages are identical. + /// + /// Unlike ``DatabaseValue`` equality that considers the integer 1 as + /// equal to the 1.0 double (as SQLite does), int64 and double storages + /// are never equal. + public static func == (_ lhs: Self, _ rhs: Self) -> Bool { + switch (lhs, rhs) { + case (.null, .null): return true + case let (.int64(lhs), .int64(rhs)): return lhs == rhs + case let (.double(lhs), .double(rhs)): return lhs == rhs + case let (.string(lhs), .string(rhs)): return lhs == rhs + case let (.blob(lhs), .blob(rhs)): return lhs == rhs + default: return false } } - - /// Returns whether two DatabaseValues are equal. +} + +extension DatabaseValue: Equatable { + /// Returns whether two ``DatabaseValue`` are equal. /// - /// 1.databaseValue == "foo".databaseValue // false - /// 1.databaseValue == 1.databaseValue // true + /// For example: + /// + /// ```swift + /// 1.databaseValue == "foo".databaseValue // false + /// 1.databaseValue == 1.databaseValue // true + /// ``` /// /// When comparing integers and doubles, the result is true if and only /// values are equal, and if converting one type to the other does /// not lose information: /// - /// 1.databaseValue == 1.0.databaseValue // true + /// ```swift + /// 1.databaseValue == 1.0.databaseValue // true + /// ``` /// /// For a comparison that distinguishes integer and doubles, compare /// storages instead: /// - /// 1.databaseValue.storage == 1.0.databaseValue.storage // false + /// ```swift + /// 1.databaseValue.storage == 1.0.databaseValue.storage // false + /// ``` public static func == (lhs: DatabaseValue, rhs: DatabaseValue) -> Bool { switch (lhs.storage, rhs.storage) { case (.null, .null): @@ -220,8 +261,25 @@ extension DatabaseValue { } } -// DatabaseValueConvertible extension DatabaseValue { + public func hash(into hasher: inout Hasher) { + switch storage { + case .null: + hasher.combine(0) + case .int64(let int64): + // 1 == 1.0, hence 1 and 1.0 must have the same hash: + hasher.combine(Double(int64)) + case .double(let double): + hasher.combine(double) + case .string(let string): + hasher.combine(string) + case .blob(let data): + hasher.combine(data) + } + } +} + +extension DatabaseValue: DatabaseValueConvertible { /// Returns self public var databaseValue: DatabaseValue { self @@ -233,16 +291,13 @@ extension DatabaseValue { } } -// SQLExpressible -extension DatabaseValue { +extension DatabaseValue: SQLSpecificExpressible { public var sqlExpression: SQLExpression { .databaseValue(self) } } -// CustomStringConvertible -extension DatabaseValue { - /// :nodoc: +extension DatabaseValue: CustomStringConvertible { public var description: String { switch storage { case .null: diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 0e59f9b53..44afac439 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -1,30 +1,70 @@ -/// Types that adopt DatabaseValueConvertible can be initialized from -/// database values. +/// A type that can convert itself into and out of a database value. /// -/// The protocol comes with built-in methods that allow to fetch cursors, -/// arrays, or single values: +/// `DatabaseValueConvertible` is adopted by `Bool`, `Int`, `String`, +/// `Date`, etc. /// -/// try String.fetchCursor(db, sql: "SELECT name FROM ...", arguments:...) // Cursor of String -/// try String.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String] -/// try String.fetchOne(db, sql: "SELECT name FROM ...", arguments:...) // String? +/// To conform to `DatabaseValueConvertible`, provide custom implementations +/// for ``fromDatabaseValue(_:)-21zzv`` and ``databaseValue-1ob9k``. These +/// implementations are ready-made for `RawRepresentable` types whose +/// `RawValue` is `StatementColumnConvertible`, and for `Codable` types. /// -/// let statement = try db.makeStatement(sql: "SELECT name FROM ...") -/// try String.fetchCursor(statement, arguments:...) // Cursor of String -/// try String.fetchAll(statement, arguments:...) // [String] -/// try String.fetchOne(statement, arguments:...) // String? +/// ## Topics /// -/// DatabaseValueConvertible is adopted by Bool, Int, String, etc. +/// ### Creating a Value +/// +/// - ``fromDatabaseValue(_:)-21zzv`` +/// - ``fromMissingColumn()-7iamp`` +/// +/// ### Accessing the DatabaseValue +/// +/// - ``databaseValue-1ob9k`` +/// +/// ### Fetching Values from Raw SQL +/// +/// - ``fetchCursor(_:sql:arguments:adapter:)-6elcz`` +/// - ``fetchAll(_:sql:arguments:adapter:)-1cqyb`` +/// - ``fetchSet(_:sql:arguments:adapter:)-5jene`` +/// - ``fetchOne(_:sql:arguments:adapter:)-qvqp`` +/// +/// ### Fetching Values from a Prepared Statement +/// +/// - ``fetchCursor(_:arguments:adapter:)-4l6af`` +/// - ``fetchAll(_:arguments:adapter:)-3abuc`` +/// - ``fetchSet(_:arguments:adapter:)-6y54n`` +/// - ``fetchOne(_:arguments:adapter:)-3d7ax`` +/// +/// ### Fetching Values from a Request +/// +/// - ``fetchCursor(_:_:)-8q4r6`` +/// - ``fetchAll(_:_:)-9hkqs`` +/// - ``fetchSet(_:_:)-1foke`` +/// - ``fetchOne(_:_:)-o6yj`` +/// +/// ### Supporting Types +/// +/// - ``DatabaseValueCursor`` +/// - ``StatementBinding`` public protocol DatabaseValueConvertible: SQLExpressible, StatementBinding { - /// Returns a value that can be stored in the database. + /// A database value. var databaseValue: DatabaseValue { get } - /// Returns a value initialized from `dbValue`, if possible. + /// Creates an instance with the specified database value. + /// + /// If there is no value of the type that corresponds with the specified + /// database value, this method returns nil. For example: + /// + /// ```swift + /// let dbValue = "Arthur".databaseValue + /// + /// String.fromDatabaseValue(dbValue) // "Arthur" + /// Int.fromDatabaseValue(dbValue) // nil + /// ``` /// /// - parameter dbValue: A DatabaseValue. /// - returns: A decoded value, or, if decoding is impossible, nil. static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? - /// Creates a value from a missing column, if possible. + /// Creates an instance from a missing column, if possible. /// /// - warning: Do not customize the default implementation. /// @@ -94,20 +134,26 @@ extension DatabaseValueConvertible { // MARK: - Cursors -/// A cursor of database values extracted from a single column. +/// A cursor of database values. +/// +/// A `DatabaseValueCursor` iterates all rows from a database request. Its +/// elements are the database values decoded from the leftmost column. +/// /// For example: /// -/// try dbQueue.read { db in -/// let urls: DatabaseValueCursor = try URL.fetchCursor(db, sql: "SELECT url FROM link") -/// while let url = urls.next() { // URL -/// print(url) -/// } +/// ```swift +/// try dbQueue.read { db in +/// let names: DatabaseValueCursor = try String.fetchCursor(db, sql: """ +/// SELECT name FROM player +/// """) +/// while let name = names.next() { // String +/// print(name) /// } +/// } +/// ``` public final class DatabaseValueCursor: DatabaseCursor { public typealias Element = Value - /// :nodoc: public let _statement: Statement - /// :nodoc: public var _isDone = false private let columnIndex: CInt @@ -130,7 +176,6 @@ public final class DatabaseValueCursor: Databas try? _statement.reset() } - /// :nodoc: public func _element(sqliteStatement: SQLiteStatement) throws -> Value { try Value.decode( fromStatement: sqliteStatement, @@ -158,23 +203,35 @@ extension DatabaseValueConvertible { /// Returns a cursor over values fetched from a prepared statement. /// - /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") - /// let names = try String.fetchCursor(statement) // Cursor of String - /// while let name = try names.next() { // String - /// ... + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT score FROM player WHERE lastName = ?" + /// let statement = try db.makeStatement(sql: sql) + /// let scores = try Int.fetchCursor(statement, arguments: [lastName]) + /// while let score = try scores.next() { + /// print(score) /// } + /// } + /// ``` + /// + /// Values are decoded from the leftmost column if the `adapter` argument + /// is nil. + /// + /// The returned cursor is valid only during the remaining execution of the + /// database access. Do not store or return the cursor for later use. /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// - /// The cursor must be iterated in a protected dispatch queue. - /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter - /// - returns: A cursor over fetched values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: A ``DatabaseValueCursor`` over fetched values. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor( _ statement: Statement, arguments: StatementArguments? = nil, @@ -186,15 +243,26 @@ extension DatabaseValueConvertible { /// Returns an array of values fetched from a prepared statement. /// - /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") - /// let names = try String.fetchAll(statement) // [String] + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT score FROM player WHERE lastName = ?" + /// let statement = try db.makeStatement(sql: sql) + /// let scores = try Int.fetchAll(statement, arguments: [lastName]) + /// } + /// ``` + /// + /// Values are decoded from the leftmost column if the `adapter` argument + /// is nil. /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: An array. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll( _ statement: Statement, arguments: StatementArguments? = nil, @@ -206,18 +274,29 @@ extension DatabaseValueConvertible { /// Returns a single value fetched from a prepared statement. /// - /// The result is nil if the query returns no row, or if no value can be - /// extracted from the first row. + /// The value is decoded from the leftmost column if the `adapter` argument + /// is nil. /// - /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") - /// let name = try String.fetchOne(statement) // String? + /// The result is nil if the request returns no row, or one row with a + /// `NULL` value. + /// + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT score FROM player WHERE lastName = ? LIMIT 1" + /// let statement = try db.makeStatement(sql: sql) + /// let score = try Int.fetchOne(statement, arguments: [lastName]) + /// } + /// ``` /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: An optional value. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne( _ statement: Statement, arguments: StatementArguments? = nil, @@ -233,15 +312,26 @@ extension DatabaseValueConvertible { extension DatabaseValueConvertible where Self: Hashable { /// Returns a set of values fetched from a prepared statement. /// - /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") - /// let names = try String.fetchSet(statement) // Set + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT score FROM player WHERE lastName = ?" + /// let statement = try db.makeStatement(sql: sql) + /// let scores = try Int.fetchSet(statement, arguments: [lastName]) + /// } + /// ``` + /// + /// Values are decoded from the leftmost column if the `adapter` argument + /// is nil. /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: A set. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet( _ statement: Statement, arguments: StatementArguments? = nil, @@ -258,23 +348,35 @@ extension DatabaseValueConvertible { /// Returns a cursor over values fetched from an SQL query. /// - /// let names = try String.fetchCursor(db, sql: "SELECT name FROM ...") // Cursor of String - /// while let name = try name.next() { // String - /// ... + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT score FROM player WHERE lastName = ?" + /// let scores = try Int.fetchCursor(db, sql: sql, arguments: [lastName]) + /// while let score = try scores.next() { + /// print(score) /// } + /// } + /// ``` + /// + /// Values are decoded from the leftmost column if the `adapter` argument + /// is nil. + /// + /// The returned cursor is valid only during the remaining execution of the + /// database access. Do not store or return the cursor for later use. /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// - /// The cursor must be iterated in a protected dispatch queue. - /// /// - parameters: /// - db: A database connection. - /// - sql: An SQL query. + /// - sql: An SQL string. /// - arguments: Statement arguments. /// - adapter: Optional RowAdapter - /// - returns: A cursor over fetched values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: A ``DatabaseValueCursor`` over fetched values. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor( _ db: Database, sql: String, @@ -287,15 +389,26 @@ extension DatabaseValueConvertible { /// Returns an array of values fetched from an SQL query. /// - /// let names = try String.fetchAll(db, sql: "SELECT name FROM ...") // [String] + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT score FROM player WHERE lastName = ?" + /// let scores = try Int.fetchAll(db, sql: sql, arguments: [lastName]) + /// } + /// ``` + /// + /// Values are decoded from the leftmost column if the `adapter` argument + /// is nil. /// /// - parameters: /// - db: A database connection. - /// - sql: An SQL query. + /// - sql: An SQL string. /// - arguments: Statement arguments. /// - adapter: Optional RowAdapter /// - returns: An array. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll( _ db: Database, sql: String, @@ -308,18 +421,29 @@ extension DatabaseValueConvertible { /// Returns a single value fetched from an SQL query. /// - /// The result is nil if the query returns no row, or if no value can be - /// extracted from the first row. + /// The value is decoded from the leftmost column if the `adapter` argument + /// is nil. /// - /// let name = try String.fetchOne(db, sql: "SELECT name FROM ...") // String? + /// The result is nil if the request returns no row, or one row with a + /// `NULL` value. + /// + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT score FROM player WHERE lastName = ?" + /// let score = try Int.fetchOne(db, sql: sql, arguments: [lastName]) + /// } + /// ``` /// /// - parameters: /// - db: A database connection. - /// - sql: An SQL query. + /// - sql: An SQL string. /// - arguments: Statement arguments. /// - adapter: Optional RowAdapter /// - returns: An optional value. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne( _ db: Database, sql: String, @@ -334,15 +458,26 @@ extension DatabaseValueConvertible { extension DatabaseValueConvertible where Self: Hashable { /// Returns a set of values fetched from an SQL query. /// - /// let names = try String.fetchSet(db, sql: "SELECT name FROM ...") // Set + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT score FROM player WHERE lastName = ?" + /// let scores = try Int.fetchSet(db, sql: sql, arguments: [lastName]) + /// } + /// ``` + /// + /// Values are decoded from the leftmost column if the `adapter` argument + /// is nil. /// /// - parameters: /// - db: A database connection. - /// - sql: An SQL query. + /// - sql: An SQL string. /// - arguments: Statement arguments. /// - adapter: Optional RowAdapter /// - returns: A set. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet( _ db: Database, sql: String, @@ -360,56 +495,114 @@ extension DatabaseValueConvertible { /// Returns a cursor over values fetched from a fetch request. /// - /// let request = Player.select(Column("name")) - /// let names = try String.fetchCursor(db, request) // Cursor of String - /// while let name = try name.next() { // String - /// ... + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player + /// .select(Column("score")) + /// .filter(Column("lastName") == lastName) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT score FROM player WHERE lastName = \(lastName) + /// """ + /// + /// let scores = try Int.fetchCursor(db, request) + /// while let score = try scores.next() { + /// print(score) /// } + /// } + /// ``` + /// + /// Values are decoded from the leftmost column. + /// + /// The returned cursor is valid only during the remaining execution of the + /// database access. Do not store or return the cursor for later use. /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// - /// The cursor must be iterated in a protected dispatch queue. - /// /// - parameters: /// - db: A database connection. /// - request: A FetchRequest. - /// - returns: A cursor over fetched values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: R) throws -> DatabaseValueCursor { + /// - returns: A ``DatabaseValueCursor`` over fetched values. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public static func fetchCursor(_ db: Database, _ request: some FetchRequest) throws -> DatabaseValueCursor { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchCursor(request.statement, adapter: request.adapter) } /// Returns an array of values fetched from a fetch request. /// - /// let request = Player.select(Column("name")) - /// let names = try String.fetchAll(db, request) // [String] + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player + /// .select(Column("score")) + /// .filter(Column("lastName") == lastName) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT score FROM player WHERE lastName = \(lastName) + /// """ + /// + /// let scores = try Int.fetchAll(db, request) + /// } + /// ``` + /// + /// Values are decoded from the leftmost column. /// /// - parameters: /// - db: A database connection. /// - request: A FetchRequest. /// - returns: An array. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: R) throws -> [Self] { + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchAll(request.statement, adapter: request.adapter) } /// Returns a single value fetched from a fetch request. /// - /// The result is nil if the query returns no row, or if no value can be - /// extracted from the first row. + /// The value is decoded from the leftmost column. /// - /// let request = Player.filter(key: 1).select(Column("name")) - /// let name = try String.fetchOne(db, request) // String? + /// The result is nil if the request returns no row, or one row with a + /// `NULL` value. + /// + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player + /// .select(Column("score")) + /// .filter(Column("lastName") == lastName) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT score FROM player WHERE lastName = \(lastName) LIMIT 1 + /// """ + /// + /// let scores = try Int.fetchOne(db, request) + /// } + /// ``` /// /// - parameters: /// - db: A database connection. /// - request: A FetchRequest. /// - returns: An optional value. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, _ request: R) throws -> Self? { + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? { let request = try request.makePreparedRequest(db, forSingleResult: true) return try fetchOne(request.statement, adapter: request.adapter) } @@ -418,15 +611,34 @@ extension DatabaseValueConvertible { extension DatabaseValueConvertible where Self: Hashable { /// Returns a set of values fetched from a fetch request. /// - /// let request = Player.select(Column("name")) - /// let names = try String.fetchSet(db, request) // Set + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player + /// .select(Column("score")) + /// .filter(Column("lastName") == lastName) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT score FROM player WHERE lastName = \(lastName) + /// """ + /// + /// let scores = try Int.fetchAll(db, request) + /// } + /// ``` + /// + /// Values are decoded from the leftmost column. /// /// - parameters: /// - db: A database connection. /// - request: A FetchRequest. /// - returns: A set. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, _ request: R) throws -> Set { + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchSet(request.statement, adapter: request.adapter) } @@ -436,63 +648,140 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { // MARK: Fetching Values - /// A cursor over fetched values. + /// Returns a cursor over fetched values. /// - /// let request: some FetchRequest = ... - /// let strings = try request.fetchCursor(db) // Cursor of String - /// while let string = try strings.next() { // String - /// ... + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player + /// .filter(Column("lastName") == lastName) + /// .select(Column("score"), as: Int.self) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT score FROM player WHERE lastName = \(lastName) + /// """ + /// + /// let scores = try request.fetchCursor(db) + /// while let score = try scores.next() { + /// print(score) /// } + /// } + /// ``` + /// + /// Values are decoded from the leftmost column. + /// + /// The returned cursor is valid only during the remaining execution of the + /// database access. Do not store or return the cursor for later use. /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// - /// The cursor must be iterated in a protected dispatch queue. - /// /// - parameter db: A database connection. - /// - returns: A cursor over fetched values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: A ``DatabaseValueCursor`` over fetched values. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor { try RowDecoder.fetchCursor(db, self) } - /// An array of fetched values. + /// Returns an array of fetched values. /// - /// let request: some FetchRequest = ... - /// let strings = try request.fetchAll(db) // [String] + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player + /// .filter(Column("lastName") == lastName) + /// .select(Column("score"), as: Int.self) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT score FROM player WHERE lastName = \(lastName) + /// """ + /// + /// let scores = try request.fetchAll(db) + /// } + /// ``` + /// + /// Values are decoded from the leftmost column. /// /// - parameter db: A database connection. /// - returns: An array of values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchAll(_ db: Database) throws -> [RowDecoder] { try RowDecoder.fetchAll(db, self) } - /// The first fetched value. + /// Returns a single fetched value. /// - /// The result is nil if the request returns no row, or if no value can be - /// extracted from the first row. + /// The value is decoded from the leftmost column. /// - /// let request: some FetchRequest = ... - /// let string = try request.fetchOne(db) // String? + /// The result is nil if the request returns no row, or one row with a + /// `NULL` value. + /// + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player + /// .filter(Column("lastName") == lastName) + /// .select(Column("score"), as: Int.self) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT score FROM player WHERE lastName = \(lastName) LIMIT 1 + /// """ + /// + /// let score = try request.fetchOne(db) + /// } + /// ``` /// /// - parameter db: A database connection. /// - returns: An optional value. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchOne(_ db: Database) throws -> RowDecoder? { try RowDecoder.fetchOne(db, self) } } extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable { - /// A set of fetched values. + /// Returns a set of fetched values. /// - /// let request: some FetchRequest = ... - /// let strings = try request.fetchSet(db) // Set + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player + /// .filter(Column("lastName") == lastName) + /// .select(Column("score"), as: Int.self) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT score FROM player WHERE lastName = \(lastName) + /// """ + /// + /// let scores = try request.fetchSet(db) + /// } + /// ``` + /// + /// Values are decoded from the leftmost column. /// /// - parameter db: A database connection. /// - returns: A set of values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchSet(_ db: Database) throws -> Set { try RowDecoder.fetchSet(db, self) } diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 8084a8b36..df30d4bc9 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -3,227 +3,370 @@ import Combine #endif import Dispatch -/// `DatabaseWriter` is the protocol for all types that can write into an -/// SQLite database. +/// The protocol for types that write into an SQLite database. /// -/// It is adopted by `DatabaseQueue` and `DatabasePool`. +/// Do not declare new conformances to `DatabaseWriter`. Only the +/// ``DatabaseQueue`` and ``DatabasePool`` types are valid conforming types. /// -/// The protocol comes with isolation guarantees that describe the behavior of -/// adopting types in a multithreaded application. +/// A database writer creates one single SQLite connection dedicated to database +/// updates. All updates are executed in a serial **writer dispatch queue**. /// -/// Types that adopt the protocol can in practice provide stronger guarantees. -/// For example, `DatabaseQueue` provides a stronger isolation level -/// than `DatabasePool`. +/// Read accesses are defined by ``DatabaseReader``, the protocol all database +/// writers conform to. /// -/// **Warning**: Isolation guarantees stand as long as there is no external -/// connection to the database. Should you have to cope with external -/// connections, protect yourself with transactions, and be ready to setup a -/// [busy handler](https://www.sqlite.org/c3ref/busy_handler.html). +/// ## Topics +/// +/// ### Writing into the Database +/// +/// - ``asyncWrite(_:completion:)`` +/// - ``asyncWriteWithoutTransaction(_:)`` +/// - ``write(_:)-76inz`` +/// - ``write(_:)-88g7e`` +/// - ``writePublisher(receiveOn:updates:)`` +/// - ``writePublisher(receiveOn:updates:thenRead:)`` +/// - ``writeWithoutTransaction(_:)-4qh1w`` +/// - ``writeWithoutTransaction(_:)-tckw`` +/// +/// ### Reading from the Database +/// +/// - ``concurrentRead(_:)`` +/// - ``spawnConcurrentRead(_:)`` +/// - ``DatabaseFuture`` +/// +/// ### Exclusive Access to the Database +/// +/// - ``asyncBarrierWriteWithoutTransaction(_:)`` +/// - ``barrierWriteWithoutTransaction(_:)-280j1`` +/// - ``barrierWriteWithoutTransaction(_:)-7u4xw`` +/// +/// ### Observing Database Transactions +/// +/// - ``add(transactionObserver:extent:)`` +/// - ``remove(transactionObserver:)`` +/// +/// ### Unsafe Methods +/// +/// - ``unsafeReentrantWrite(_:)`` +/// +/// ### Other Database Operations +/// +/// - ``erase()-w5n7`` +/// - ``erase()-7jv3d`` +/// - ``vacuum()-310uw`` +/// - ``vacuum()-9inj0`` +/// - ``vacuum(into:)-5lo41`` +/// - ``vacuum(into:)-9c5mb`` +/// +/// ### Supporting Types +/// +/// - ``AnyDatabaseWriter`` public protocol DatabaseWriter: DatabaseReader { // MARK: - Writing in Database - /// Synchronously executes database updates in a protected dispatch queue, - /// wrapped inside a transaction, and returns the result. + /// Executes database operations, and returns their result after they have + /// finished executing. /// - /// If the updates throw an error, the transaction is rollbacked and the - /// error is rethrown. + /// For example: /// - /// Eventual concurrent database updates are postponed until the transaction - /// has completed. + /// ```swift + /// let newPlayerCount = try writer.writeWithoutTransaction { db in + /// try Player(name: "Arthur").insert(db) + /// return try Player.fetchCount(db) + /// } + /// ``` /// - /// Eventual concurrent reads are guaranteed to not see any partial updates - /// of the database until the transaction has completed. + /// Database operations run in the writer dispatch queue, serialized + /// with all database updates performed by this `DatabaseWriter`. + /// + /// The ``Database`` argument to `updates` is valid only during the + /// execution of the closure. Do not store or return the database connection + /// for later use. /// /// It is a programmer error to call this method from another database - /// access method: + /// access method. Doing so raises a "Database methods are not reentrant" + /// fatal error at runtime. /// - /// try writer.write { db in - /// // Raises a fatal error - /// try writer.write { ... ) - /// } + /// - warning: Database operations are not wrapped in a transaction. They + /// can see changes performed by concurrent writes or writes performed by + /// other processes: two identical requests performed by the `updates` + /// closure may not return the same value. Concurrent database accesses + /// can see partial updates performed by the `updates` closure. /// - /// - parameter updates: The updates to the database. - /// - throws: The error thrown by the updates, or by the - /// wrapping transaction. - @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - func write(_ updates: (Database) throws -> T) throws -> T - - /// Synchronously executes database updates in a protected dispatch queue, - /// outside of any transaction, and returns the result. - /// - /// Eventual concurrent database updates are postponed until the updates - /// are completed. - /// - /// Eventual concurrent reads may see partial updates unless you wrap them - /// in a transaction. - /// - /// It is a programmer error to call this method from another database - /// access method: - /// - /// try writer.write { db in - /// // Raises a fatal error - /// try writer.writeWithoutTransaction { ... ) - /// } - /// - /// - parameter updates: The updates to the database. - /// - throws: The error thrown by the updates. + /// - parameter updates: A closure which accesses the database. + /// - throws: The error thrown by `updates`. @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails func writeWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T - /// Synchronously executes database updates in a protected dispatch queue, - /// outside of any transaction, and returns the result. + /// Executes database operations, and returns their result after they have + /// finished executing. /// - /// Updates are guaranteed an exclusive access to the database. They wait - /// until all pending writes and reads are completed. They postpone all - /// other writes and reads until they are completed. + /// This method waits until all currently executing database accesses + /// performed by the database writer finish executing (reads and writes). + /// At that point, database operations are executed. Once they finish, the + /// database writer can proceed with other database accesses. + /// + /// For example: + /// + /// ```swift + /// let newPlayerCount = try writer.barrierWriteWithoutTransaction { db in + /// try Player(name: "Arthur").insert(db) + /// return try Player.fetchCount(db) + /// } + /// ``` + /// + /// Database operations run in the writer dispatch queue, serialized + /// with all database updates performed by this `DatabaseWriter`. + /// + /// The ``Database`` argument to `updates` is valid only during the + /// execution of the closure. Do not store or return the database connection + /// for later use. /// /// It is a programmer error to call this method from another database - /// access method: + /// access method. Doing so raises a "Database methods are not reentrant" + /// fatal error at runtime. /// - /// try writer.write { db in - /// // Raises a fatal error - /// try writer.barrierWriteWithoutTransaction { ... ) - /// } + /// - warning: Database operations are not wrapped in a transaction. They + /// can see changes performed by concurrent writes or writes performed by + /// other processes: two identical requests performed by the `updates` + /// closure may not return the same value. Concurrent database accesses + /// can see partial updates performed by the `updates` closure. /// - /// - parameter updates: The updates to the database. - /// - throws: The error thrown by the updates. + /// - parameter updates: A closure which accesses the database. + /// - throws: The error thrown by `updates`. @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T - /// Asynchronously executes database updates in a protected dispatch queue, - /// outside of any transaction, and returns the result. + /// Schedules database operations for execution, and returns immediately. /// - /// Updates are guaranteed an exclusive access to the database. They wait - /// until all pending writes and reads are completed. They postpone all - /// other writes and reads until they are completed. + /// Database operations are not executed until all currently executing + /// database accesses performed by the database writer finish executing + /// (reads and writes). At that point, database operations are executed. + /// Once they finish, the database writer can proceed with other + /// database accesses. /// - /// - parameter updates: A function that accesses the database. Its argument + /// For example: + /// + /// ```swift + /// writer.asyncBarrierWriteWithoutTransaction { dbResult in + /// do { + /// let db = try dbResult.get() + /// try Player(name: "Arthur").insert(db) + /// let newPlayerCount = try Player.fetchCount(db) + /// } catch { + /// // Handle error + /// } + /// } + /// ``` + /// + /// Database operations run in the writer dispatch queue, serialized + /// with all database updates performed by this `DatabaseWriter`. + /// + /// The ``Database`` argument to `updates` is valid only during the + /// execution of the closure. Do not store or return the database connection + /// for later use. + /// + /// - warning: Database operations are not wrapped in a transaction. They + /// can see changes performed by concurrent writes or writes performed by + /// other processes: two identical requests performed by the `updates` + /// closure may not return the same value. Concurrent database accesses + /// can see partial updates performed by the `updates` closure. + /// + /// - parameter updates: A closure which accesses the database. Its argument /// is a `Result` that provides the database connection, or the failure /// that would prevent establishing the barrier access to the database. func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) - /// Asynchronously executes database updates in a protected dispatch queue, - /// wrapped inside a transaction. + /// Schedules database operations for execution, and returns immediately. /// - /// If the updates throw an error, the transaction is rollbacked. + /// For example: /// - /// The *completion* closure is always called with the result of the - /// database updates. Its arguments are a database connection and the - /// result of the transaction. This result is a failure if the transaction - /// could not be committed. + /// ```swift + /// writer.asyncWriteWithoutTransaction { db in + /// do { + /// try Player(name: "Arthur").insert(db) + /// let newPlayerCount = try Player.fetchCount(db) + /// } catch { + /// // Handle error + /// } + /// } + /// ``` /// - /// Eventual concurrent database updates are postponed until the transaction - /// and the *completion* closure have completed. + /// Database operations run in the writer dispatch queue, serialized + /// with all database updates performed by this `DatabaseWriter`. /// - /// Eventual concurrent reads are guaranteed to not see any partial updates - /// of the database until the transaction has completed. + /// The ``Database`` argument to `updates` is valid only during the + /// execution of the closure. Do not store or return the database connection + /// for later use. /// - /// This method is *not* reentrant. + /// - warning: Database operations are not wrapped in a transaction. They + /// can see changes performed by concurrent writes or writes performed by + /// other processes: two identical requests performed by the `updates` + /// closure may not return the same value. Concurrent database accesses + /// can see partial updates performed by the `updates` closure. /// - /// - parameter updates: The updates to the database. - /// - parameter completion: A closure that is called with the eventual - /// transaction error. - /// - throws: The error thrown by the updates, or by the wrapping transaction. - func asyncWrite( - _ updates: @escaping (Database) throws -> T, - completion: @escaping (Database, Result) -> Void) - - /// Asynchronously executes database updates in a protected dispatch queue, - /// outside of any transaction. - /// - /// Eventual concurrent reads may see partial updates unless you wrap them - /// in a transaction. + /// - parameter updates: A closure which accesses the database. func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) - /// Synchronously executes database updates in a protected dispatch queue, - /// outside of any transaction, and returns the result. + /// Executes database operations, and returns their result after they have + /// finished executing. /// - /// Eventual concurrent database updates are postponed until the updates - /// are completed. + /// This method can be called from other database access methods. Reentrant + /// database accesses are discouraged, though, because they muddle + /// transaction boundaries. /// - /// Eventual concurrent reads may see partial updates unless you wrap them - /// in a transaction. + /// For example: /// - /// This method is reentrant. It should be avoided because it fosters - /// dangerous concurrency practices. + /// ```swift + /// let newPlayerCount = try writer.unsafeReentrantWrite { db in + /// try Player(name: "Arthur").insert(db) + /// return try Player.fetchCount(db) + /// } + /// ``` + /// + /// Database operations run in the writer dispatch queue, serialized + /// with all database updates performed by this `DatabaseWriter`. + /// + /// The ``Database`` argument to `updates` is valid only during the + /// execution of the closure. Do not store or return the database connection + /// for later use. + /// + /// - warning: Database operations are not wrapped in a transaction. They + /// can see changes performed by concurrent writes or writes performed by + /// other processes: two identical requests performed by the `updates` + /// closure may not return the same value. Concurrent database accesses + /// can see partial updates performed by the `updates` closure. + /// + /// - parameter updates: A closure which accesses the database. + /// - throws: The error thrown by `updates`. func unsafeReentrantWrite(_ updates: (Database) throws -> T) rethrows -> T // MARK: - Reading from Database - /// Concurrently executes a read-only block in a protected dispatch queue. + /// Schedules read-only database operations for execution, and returns a + /// future value. /// - /// This method must be called from a writing dispatch queue, outside of any - /// transaction. You'll get a fatal error otherwise. + /// This method must be called from the writer dispatch queue, outside of + /// any transaction. You'll get a fatal error otherwise. /// - /// The *block* argument is guaranteed to see the database in the last - /// committed state at the moment this method is called. Eventual concurrent - /// database updates are *not visible* inside the block. + /// Database operations performed by the `value` closure are isolated in a + /// transaction: they do not see changes performed by eventual concurrent + /// writes (even writes performed by other processes). /// - /// To access the fetched results, you call the wait() method of the - /// returned future, on any dispatch queue. + /// They see the database in the state left by the last updates performed + /// by the database writer. + /// + /// To access the fetched results, you call the ``DatabaseFuture/wait()`` + /// method of the returned future, on any dispatch queue. /// /// In the example below, the number of players is fetched concurrently with /// the player insertion. Yet the future is guaranteed to return zero: /// - /// try writer.writeWithoutTransaction { db in - /// // Delete all players - /// try Player.deleteAll() + /// ```swift + /// try writer.writeWithoutTransaction { db in + /// // Delete all players + /// try Player.deleteAll() /// - /// // Count players concurrently - /// let future = writer.concurrentRead { db in - /// return try Player.fetchCount() - /// } - /// - /// // Insert a player - /// try Player(...).insert(db) - /// - /// // Guaranteed to be zero - /// let count = try future.wait() + /// // Count players concurrently + /// let future = writer.concurrentRead { db in + /// return try Player.fetchCount() /// } + /// + /// // Insert a player + /// try Player(...).insert(db) + /// + /// // Guaranteed to be zero + /// let count = try future.wait() + /// } + /// ``` + /// + /// - note: Usage of this method is discouraged, because waiting on the + /// returned ``DatabaseFuture`` blocks a thread. You may prefer the + /// asynchronous version of this method: ``spawnConcurrentRead(_:)``. + /// - parameter value: A closure which accesses the database. func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture // Exposed for RxGRDB and GRBCombine. Naming is not stabilized. - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// Schedules read-only database operations for execution, and + /// returns immediately. /// - /// Concurrently executes a read-only block in a protected dispatch queue. + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) /// - /// This method must be called from a writing dispatch queue, outside of any - /// transaction. You'll get a fatal error otherwise. + /// This method must be called from the writer dispatch queue, outside of + /// any transaction. You'll get a fatal error otherwise. /// - /// The *block* argument is guaranteed to see the database in the last - /// committed state at the moment this method is called. Eventual concurrent - /// database updates are *not visible* inside the block. + /// Database operations performed by the `value` closure are isolated in a + /// transaction: they do not see changes performed by eventual concurrent + /// writes (even writes performed by other processes). + /// + /// They see the database in the state left by the last updates performed + /// by the database writer. /// /// In the example below, the number of players is fetched concurrently with /// the player insertion. Yet the future is guaranteed to return zero: /// - /// try writer.asyncWriteWithoutTransaction { db in - /// // Delete all players - /// try Player.deleteAll() + /// ```swift + /// try writer.writeWithoutTransaction { db in + /// // Delete all players + /// try Player.deleteAll() /// - /// // Count players concurrently - /// writer.asyncConcurrentRead { dbResult in - /// do { - /// let db = try dbResult.get() - /// // Guaranteed to be zero - /// let count = try Player.fetchCount(db) - /// } catch { - /// // Handle error - /// } + /// // Count players concurrently + /// writer.spawnConcurrentRead { db in + /// do { + /// let db = try dbResult.get() + /// // Guaranteed to be zero + /// let count = try Player.fetchCount(db) + /// } catch { + /// // Handle error /// } - /// - /// // Insert a player - /// try Player(...).insert(db) /// } /// - /// - parameter block: A block that accesses the database. - /// :nodoc: + /// // Insert a player + /// try Player(...).insert(db) + /// } + /// ``` + /// + /// - parameter value: A closure which accesses the database. Its argument + /// is a `Result` that provides the database connection, or the failure + /// that would prevent establishing the read access to the database. func spawnConcurrentRead(_ value: @escaping (Result) -> Void) } extension DatabaseWriter { - + /// Executes database operations, and returns their result after they have + /// finished executing. + /// + /// For example: + /// + /// ```swift + /// let newPlayerCount = try writer.write { db in + /// try Player(name: "Arthur").insert(db) + /// return try Player.fetchCount(db) + /// } + /// ``` + /// + /// Database operations are wrapped in a transaction. If they throw an + /// error, the transaction is rollbacked and the error is rethrown. + /// + /// Concurrent database accesses can not see partial database updates (even + /// when performed by other processes). + /// + /// Database operations run in the writer dispatch queue, serialized + /// with all database updates performed by this `DatabaseWriter`. + /// + /// The ``Database`` argument to `updates` is valid only during the + /// execution of the closure. Do not store or return the database connection + /// for later use. + /// + /// It is a programmer error to call this method from another database + /// access method. Doing so raises a "Database methods are not reentrant" + /// fatal error at runtime. + /// + /// - parameter updates: A closure which accesses the database. + /// - throws: The error thrown by `updates`, or any ``DatabaseError`` that + /// would happen while establishing the database access or committing + /// the transaction. + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func write(_ updates: (Database) throws -> T) throws -> T { try writeWithoutTransaction { db in var result: T? @@ -235,29 +378,42 @@ extension DatabaseWriter { } } - /// Asynchronously executes database updates in a protected dispatch queue, - /// wrapped inside a transaction. + /// Schedules database operations for execution, and returns immediately. /// - /// If the updates throw an error, the transaction is rollbacked. + /// For example: /// - /// The *completion* closure is always called with the result of the - /// database updates. Its arguments are a database connection and the - /// result of the transaction. This result is a failure if the transaction - /// could not be committed. The completion closure is executed in a - /// protected dispatch queue, outside of any transaction. + /// ```swift + /// writer.asyncWrite { db -> Int in + /// try Player(name: "Arthur").insert(db) + /// return try Player.fetchCount(db) + /// } completion: { db, result in + /// switch result { + /// case let .success(newPlayerCount): + /// // Handle success + /// case let .failure(error): + /// // Handle error + /// } + /// ``` /// - /// Eventual concurrent database updates are postponed until the transaction - /// and the *completion* closure have completed. + /// Database operations run by the `updates` closure are wrapped in + /// a transaction. If they throw an error, the transaction is rollbacked. /// - /// Eventual concurrent reads are guaranteed to not see any partial updates - /// of the database until the transaction has completed. + /// The `completion` closure has two arguments: a database connection, and + /// the result of the transaction. This result is a failure if the + /// transaction could not be committed or if `updates` has thrown an error. /// - /// This method is *not* reentrant. + /// Concurrent database accesses can not see partial database updates + /// performed by `updates` (even when performed by other processes). /// - /// - parameter updates: The updates to the database. - /// - parameter completion: A closure that is called with the eventual - /// transaction error. - /// - throws: The error thrown by the updates, or by the wrapping transaction. + /// Database operations run in the writer dispatch queue, serialized + /// with all database updates performed by this `DatabaseWriter`. + /// + /// The ``Database`` argument to `updates` and `completion` is valid only + /// during the execution of those closures. Do not store or return the + /// database connection for later use. + /// + /// - parameter updates: A closure which accesses the database. + /// - parameter completion: A closure called with the transaction result. public func asyncWrite( _ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result) -> Void) @@ -278,10 +434,10 @@ extension DatabaseWriter { // MARK: - Transaction Observers - /// Add a transaction observer, so that it gets notified of - /// database changes. + /// Adds a transaction observer, so that it gets notified of + /// database changes and transactions. /// - /// To remove the observer, use `DatabaseReader.remove(transactionObserver:)`. + /// This method has no effect on read-only database connections. /// /// - parameter transactionObserver: A transaction observer. /// - parameter extent: The duration of the observation. The default is @@ -294,6 +450,7 @@ extension DatabaseWriter { writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) } } + /// Removes a transaction observer. public func remove(transactionObserver: some TransactionObserver) { writeWithoutTransaction { $0.remove(transactionObserver: transactionObserver) } } @@ -311,7 +468,7 @@ extension DatabaseWriter { /// Rebuilds the database file, repacking it into a minimal amount of /// disk space. /// - /// See for more information. + /// Related SQLite documentation: @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func vacuum() throws { try writeWithoutTransaction { try $0.execute(sql: "VACUUM") } @@ -327,14 +484,14 @@ extension DatabaseWriter { // This method is declared on DatabaseWriter instead of DatabaseReader, // so that it is not available on DatabaseSnaphot. VACUUM INTO is not // available inside the transaction that is kept open by DatabaseSnaphot. - #if GRDBCUSTOMSQLITE || GRDBCIPHER +#if GRDBCUSTOMSQLITE || GRDBCIPHER /// Creates a new database file at the specified path with a minimum /// amount of disk space. /// /// Databases encrypted with SQLCipher are copied with the same password /// and configuration as the original database. /// - /// See for more information. + /// Related SQLite documentation: /// /// - Parameter filePath: file path for new database @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails @@ -343,10 +500,11 @@ extension DatabaseWriter { try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath]) } } - #else +#else /// Creates a new database file at the specified path with a minimum /// amount of disk space. - /// See for more information. + /// + /// Related SQLite documentation: /// /// - Parameter filePath: file path for new database @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails @@ -356,7 +514,7 @@ extension DatabaseWriter { try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath]) } } - #endif +#endif // MARK: - Database Observation @@ -385,20 +543,41 @@ extension DatabaseWriter { extension DatabaseWriter { // MARK: - Asynchronous Database Access - /// Asynchronously executes database updates, wrapped inside a transaction, - /// and returns the result. + /// Executes database operations, and returns their result after they have + /// finished executing. /// - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) /// - /// If the updates throw an error, the transaction is rollbacked and the - /// error is rethrown. + /// For example: /// - /// Eventual concurrent reads are guaranteed to not see any partial updates - /// of the database until the transaction has completed. + /// ```swift + /// let newPlayerCount = try await writer.write { db in + /// try Player(name: "Arthur").insert(db) + /// return try Player.fetchCount(db) + /// } + /// ``` /// - /// - parameter updates: The updates to the database. - /// - throws: The error thrown by the updates, or by the - /// wrapping transaction. + /// Database operations are wrapped in a transaction. If they throw an + /// error, the transaction is rollbacked and the error is rethrown. + /// + /// Concurrent database accesses can not see partial database updates (even + /// when performed by other processes). + /// + /// Database operations run in the writer dispatch queue, serialized + /// with all database updates performed by this `DatabaseWriter`. + /// + /// The ``Database`` argument to `updates` is valid only during the + /// execution of the closure. Do not store or return the database connection + /// for later use. + /// + /// It is a programmer error to call this method from another database + /// access method. Doing so raises a "Database methods are not reentrant" + /// fatal error at runtime. + /// + /// - parameter updates: A closure which accesses the database. + /// - throws: The error thrown by `updates`, or any ``DatabaseError`` that + /// would happen while establishing the database access or committing + /// the transaction. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public func write(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T { try await withUnsafeThrowingContinuation { continuation in @@ -408,16 +587,39 @@ extension DatabaseWriter { } } - /// Asynchronously executes database updates, outside of any transaction, - /// and returns the result. + /// Executes database operations, and returns their result after they have + /// finished executing. /// - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) /// - /// Eventual concurrent reads may see partial updates unless you wrap them - /// in a transaction. + /// For example: /// - /// - parameter updates: The updates to the database. - /// - throws: The error thrown by the updates. + /// ```swift + /// let newPlayerCount = try await writer.writeWithoutTransaction { db in + /// try Player(name: "Arthur").insert(db) + /// return try Player.fetchCount(db) + /// } + /// ``` + /// + /// Database operations run in the writer dispatch queue, serialized + /// with all database updates performed by this `DatabaseWriter`. + /// + /// The ``Database`` argument to `updates` is valid only during the + /// execution of the closure. Do not store or return the database connection + /// for later use. + /// + /// It is a programmer error to call this method from another database + /// access method. Doing so raises a "Database methods are not reentrant" + /// fatal error at runtime. + /// + /// - warning: Database operations are not wrapped in a transaction. They + /// can see changes performed by concurrent writes or writes performed by + /// other processes: two identical requests performed by the `updates` + /// closure may not return the same value. Concurrent database accesses + /// can see partial updates performed by the `updates` closure. + /// + /// - parameter updates: A closure which accesses the database. + /// - throws: The error thrown by `updates`. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public func writeWithoutTransaction(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T { try await withUnsafeThrowingContinuation { continuation in @@ -431,17 +633,45 @@ extension DatabaseWriter { } } - /// Asynchronously executes database updates, outside of any transaction, - /// and returns the result. + /// Executes database operations, and returns their result after they have + /// finished executing. /// - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) /// - /// Updates are guaranteed an exclusive access to the database. They wait - /// until all pending writes and reads are completed. They postpone all - /// other writes and reads until they are completed. + /// Database operations are not executed until all currently executing + /// database accesses performed by the database writer finish executing + /// (both reads and writes). At that point, database operations are + /// executed. Once they finish, the database writer can proceed with other + /// database accesses. /// - /// - parameter updates: The updates to the database. - /// - throws: The error thrown by the updates. + /// For example: + /// + /// ```swift + /// let newPlayerCount = try await writer.barrierWriteWithoutTransaction { db in + /// try Player(name: "Arthur").insert(db) + /// return try Player.fetchCount(db) + /// } + /// ``` + /// + /// Database operations run in the writer dispatch queue, serialized + /// with all database updates performed by this `DatabaseWriter`. + /// + /// The ``Database`` argument to `updates` is valid only during the + /// execution of the closure. Do not store or return the database connection + /// for later use. + /// + /// It is a programmer error to call this method from another database + /// access method. Doing so raises a "Database methods are not reentrant" + /// fatal error at runtime. + /// + /// - warning: Database operations are not wrapped in a transaction. They + /// can see changes performed by concurrent writes or writes performed by + /// other processes: two identical requests performed by the `updates` + /// closure may not return the same value. Concurrent database accesses + /// can see partial updates performed by the `updates` closure. + /// + /// - parameter updates: A closure which accesses the database. + /// - throws: The error thrown by `updates`. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public func barrierWriteWithoutTransaction( _ updates: @Sendable @escaping (Database) throws -> T) @@ -456,7 +686,7 @@ extension DatabaseWriter { /// Erases the content of the database. /// - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public func erase() async throws { try await writeWithoutTransaction { try $0.erase() } @@ -465,20 +695,24 @@ extension DatabaseWriter { /// Rebuilds the database file, repacking it into a minimal amount of /// disk space. /// - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) /// - /// See for more information. + /// Related SQLite documentation: @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public func vacuum() async throws { try await writeWithoutTransaction { try $0.execute(sql: "VACUUM") } } +#if GRDBCUSTOMSQLITE || GRDBCIPHER /// Creates a new database file at the specified path with a minimum /// amount of disk space. /// - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) /// - /// See for more information. + /// Databases encrypted with SQLCipher are copied with the same password + /// and configuration as the original database. + /// + /// Related SQLite documentation: /// /// - Parameter filePath: file path for new database @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) @@ -487,51 +721,65 @@ extension DatabaseWriter { try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath]) } } +#else + /// Creates a new database file at the specified path with a minimum + /// amount of disk space. + /// + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// Related SQLite documentation: + /// + /// - Parameter filePath: file path for new database + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + public func vacuum(into filePath: String) async throws { + try await writeWithoutTransaction { + try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath]) + } + } +#endif } #if canImport(Combine) extension DatabaseWriter { // MARK: - Publishing Database Updates - /// Returns a Publisher that asynchronously writes into the database. + /// Returns a publisher that publishes one value and completes. /// - /// // DatabasePublishers.Write - /// let newPlayerCount = dbQueue.writePublisher { db -> Int in - /// try Player(...).insert(db) - /// return try Player.fetchCount(db) - /// } + /// The database is not accessed until subscription. Value and completion + /// are published on `scheduler` (the main dispatch queue by default). /// - /// Its value and completion are emitted on the main dispatch queue. + /// For example: /// - /// - parameter updates: A closure which writes in the database. - @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) - public func writePublisher( - updates: @escaping (Database) throws -> Output) - -> DatabasePublishers.Write - { - writePublisher(receiveOn: DispatchQueue.main, updates: updates) - } - - /// Returns a Publisher that asynchronously writes into the database. + /// ```swift + /// // DatabasePublishers.Write + /// let newPlayerCountPublisher = writer.writePublisher { db in + /// try Player(name: "Arthur").insert(db) + /// return try Player.fetchCount(db) + /// } + /// ``` /// - /// // DatabasePublishers.Write - /// let newPlayerCount = dbQueue.writePublisher( - /// receiveOn: DispatchQueue.global(), - /// updates: { db -> Int in - /// try Player(...).insert(db) - /// return try Player.fetchCount(db) - /// }) + /// Database operations are wrapped in a transaction. If they throw an + /// error, the transaction is rollbacked and the error completes + /// the publisher. /// - /// Its value and completion are emitted on `scheduler`. + /// Concurrent database accesses can not see partial database updates (even + /// when performed by other processes). + /// + /// Database operations are asynchronously dispatched in the writer dispatch + /// queue, serialized with all database updates performed by + /// this `DatabaseWriter`. + /// + /// The ``Database`` argument to `updates` is valid only during the + /// execution of the closure. Do not store or return the database connection + /// for later use. /// /// - parameter scheduler: A Combine Scheduler. - /// - parameter updates: A closure which writes in the database. + /// - parameter updates: A closure which accesses the database. @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) - public func writePublisher( - receiveOn scheduler: S, + public func writePublisher( + receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main, updates: @escaping (Database) throws -> Output) -> DatabasePublishers.Write - where S: Scheduler { OnDemandFuture { fulfill in self.asyncWrite(updates, completion: { _, result in @@ -544,43 +792,57 @@ extension DatabaseWriter { .eraseToWritePublisher() } - /// Returns a Publisher that asynchronously writes into the database. + /// Returns a publisher that publishes one value and completes. /// - /// // DatabasePublishers.Write - /// let newPlayerCount = dbQueue.writePublisher( - /// updates: { db in try Player(...).insert(db) } - /// thenRead: { db, _ in try Player.fetchCount(db) }) + /// The database is not accessed until subscription. Value and completion + /// are published on `scheduler` (the main dispatch queue by default). /// - /// Its value and completion are emitted on the main dispatch queue. + /// For example: /// - /// - parameter updates: A closure which writes in the database. - /// - parameter value: A closure which reads from the database. - @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) - public func writePublisher( - updates: @escaping (Database) throws -> T, - thenRead value: @escaping (Database, T) throws -> Output) - -> DatabasePublishers.Write - { - writePublisher(receiveOn: DispatchQueue.main, updates: updates, thenRead: value) - } - - - /// Returns a Publisher that asynchronously writes into the database. + /// ```swift + /// // DatabasePublishers.Write + /// let newPlayerCountPublisher = writer.writePublisher { db in + /// try Player(name: "Arthur").insert(db) + /// } thenRead: { db, _ in + /// try Player.fetchCount(db) + /// } + /// ``` /// - /// // DatabasePublishers.Write - /// let newPlayerCount = dbQueue.writePublisher( - /// receiveOn: DispatchQueue.global(), - /// updates: { db in try Player(...).insert(db) } - /// thenRead: { db, _ in try Player.fetchCount(db) }) + /// The returned publisher publishes exactly the same value as + /// ``writePublisher(receiveOn:updates:)``: /// - /// Its value and completion are emitted on `scheduler`. + /// ```swift + /// // DatabasePublishers.Write + /// let newPlayerCountPublisher = writer.writePublisher { db in + /// try Player(name: "Arthur").insert(db) + /// return try Player.fetchCount(db) + /// } + /// ``` + /// + /// The difference is that the last fetches are performed in the `thenRead` + /// closure. This closure accepts two arguments: a read-only database + /// connection, and the result of the `updates` function. This allows you to + /// pass information from a function to the other (it is ignored in the + /// sample code above). + /// + /// When you use a ``DatabasePool``, this method applies a scheduling + /// optimization: the `thenRead` closure sees the database in the state left + /// by the `updates` closure, but it does not block any concurrent writes. + /// This can reduce database write contention. + /// + /// When you use a ``DatabaseQueue``, the results are guaranteed to be + /// identical, but no scheduling optimization is applied. + /// + /// The ``Database`` argument to `updates` and `value` is valid only during + /// the execution of those closures. Do not store or return the database + /// connection for later use. /// /// - parameter scheduler: A Combine Scheduler. /// - parameter updates: A closure which writes in the database. /// - parameter value: A closure which reads from the database. @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) public func writePublisher( - receiveOn scheduler: S, + receiveOn scheduler: S = DispatchQueue.main, updates: @escaping (Database) throws -> T, thenRead value: @escaping (Database, T) throws -> Output) -> DatabasePublishers.Write @@ -612,15 +874,11 @@ extension DatabaseWriter { @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) extension DatabasePublishers { - /// A publisher that writes into the database. It publishes exactly - /// one element, or an error. + /// A publisher that writes into the database. /// - /// See: + /// `Write` publishes exactly one element, or an error. /// - /// - `DatabaseWriter.writePublisher(updates:)`. - /// - `DatabaseWriter.writePublisher(updates:thenRead:)`. - /// - `DatabaseWriter.writePublisher(receiveOn:updates:)`. - /// - `DatabaseWriter.writePublisher(receiveOn:updates:thenRead:)`. + /// You build such a publisher from ``DatabaseWriter``. public struct Write: Publisher { public typealias Output = Output public typealias Failure = Error @@ -641,19 +899,23 @@ extension Publisher where Failure == Error { } #endif -/// A future database value, returned by the DatabaseWriter.concurrentRead(_:) -/// method. +/// A future database value. /// -/// let futureCount: Future = try writer.writeWithoutTransaction { db in -/// try Player(...).insert() +/// You get instances of `DatabaseFuture` from the `DatabaseWriter` +/// ``DatabaseWriter/concurrentRead(_:)`` method. For example: /// -/// // Count players concurrently -/// return writer.concurrentRead { db in -/// return try Player.fetchCount() -/// } +/// ```swift +/// let futureCount: Future = try writer.writeWithoutTransaction { db in +/// try Player(...).insert() +/// +/// // Count players concurrently +/// return writer.concurrentRead { db in +/// return try Player.fetchCount() /// } +/// } /// -/// let count: Int = try futureCount.wait() +/// let count: Int = try futureCount.wait() +/// ``` public class DatabaseFuture { private var consumed = false private let _wait: () throws -> Value @@ -680,18 +942,21 @@ public class DatabaseFuture { } } -/// A type-erased DatabaseWriter +/// A type-erased database writer. /// -/// Instances of AnyDatabaseWriter forward their methods to an arbitrary -/// underlying database writer. -public final class AnyDatabaseWriter: DatabaseWriter { +/// An instance of `AnyDatabaseWriter` forwards its operations to an underlying +/// base database writer. +public final class AnyDatabaseWriter { private let base: any DatabaseWriter - /// Creates a database writer that wraps a base database writer. + /// Creates a new database reader that wraps and forwards operations + /// to `base`. public init(_ base: some DatabaseWriter) { self.base = base } - +} + +extension AnyDatabaseWriter: DatabaseReader { public var configuration: Configuration { base.configuration } @@ -700,14 +965,10 @@ public final class AnyDatabaseWriter: DatabaseWriter { try base.close() } - // MARK: - Interrupting Database Operations - public func interrupt() { base.interrupt() } - // MARK: - Reading from Database - @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func read(_ value: (Database) throws -> T) throws -> T { try base.read(value) @@ -730,22 +991,20 @@ public final class AnyDatabaseWriter: DatabaseWriter { try base.unsafeReentrantRead(value) } - public func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture { - base.concurrentRead(value) + public func _add( + observation: ValueObservation, + scheduling scheduler: ValueObservationScheduler, + onChange: @escaping (Reducer.Value) -> Void) + -> AnyDatabaseCancellable + { + base._add( + observation: observation, + scheduling: scheduler, + onChange: onChange) } - - /// :nodoc: - public func spawnConcurrentRead(_ value: @escaping (Result) -> Void) { - base.spawnConcurrentRead(value) - } - - // MARK: - Writing in Database - - @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func write(_ updates: (Database) throws -> T) throws -> T { - try base.write(updates) - } - +} + +extension AnyDatabaseWriter: DatabaseWriter { @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func writeWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { try base.writeWithoutTransaction(updates) @@ -760,13 +1019,6 @@ public final class AnyDatabaseWriter: DatabaseWriter { base.asyncBarrierWriteWithoutTransaction(updates) } - public func asyncWrite( - _ updates: @escaping (Database) throws -> T, - completion: @escaping (Database, Result) -> Void) - { - base.asyncWrite(updates, completion: completion) - } - public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { base.asyncWriteWithoutTransaction(updates) } @@ -775,18 +1027,11 @@ public final class AnyDatabaseWriter: DatabaseWriter { try base.unsafeReentrantWrite(updates) } - // MARK: - Database Observation + public func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture { + base.concurrentRead(value) + } - /// :nodoc: - public func _add( - observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) - -> AnyDatabaseCancellable - { - base._add( - observation: observation, - scheduling: scheduler, - onChange: onChange) + public func spawnConcurrentRead(_ value: @escaping (Result) -> Void) { + base.spawnConcurrentRead(value) } } diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index 56804c8e8..8c7d24711 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -1,38 +1,82 @@ // MARK: - FetchRequest -/// The protocol for all requests that fetch database rows, and tell how those -/// rows should be interpreted. +/// A type that fetches and decodes database rows. /// -/// struct Player: FetchableRecord { ... } -/// let request: some FetchRequest = ... +/// ## Topics /// -/// try request.fetchCursor(db) // Cursor of Player -/// try request.fetchAll(db) // [Player] -/// try request.fetchSet(db) // Set -/// try request.fetchOne(db) // Player? -/// try request.fetchCount(db) // Int +/// ### Counting the Results +/// +/// - ``fetchCount(_:)`` +/// +/// ### Fetching Database Rows +/// +/// - ``fetchCursor(_:)-9283d`` +/// - ``fetchAll(_:)-7p809`` +/// - ``fetchOne(_:)-9fafl`` +/// - ``fetchSet(_:)-6bdrd`` +/// +/// ### Fetching Database Values +/// +/// - ``fetchCursor(_:)-19f5g`` +/// - ``fetchCursor(_:)-66xoi`` +/// - ``fetchAll(_:)-1loau`` +/// - ``fetchAll(_:)-28pne`` +/// - ``fetchOne(_:)-44mvv`` +/// - ``fetchOne(_:)-5hlkf`` +/// - ``fetchSet(_:)-4hhtm`` +/// - ``fetchSet(_:)-9wshm`` +/// +/// ### Fetching Records +/// +/// - ``fetchCursor(_:)-2ah3q`` +/// - ``fetchAll(_:)-vdos`` +/// - ``fetchOne(_:)-2bq0k`` +/// - ``fetchSet(_:)-4jdrq`` +/// +/// ### Preparing Database Requests +/// +/// - ``makePreparedRequest(_:forSingleResult:)`` +/// - ``PreparedRequest`` +/// +/// ### Database Observation Support +/// +/// - ``databaseRegion(_:)`` +/// +/// ### Adapting the Fetched Rows +/// +/// - ``adapted(_:)`` +/// - ``AdaptedFetchRequest`` +/// +/// ### Supporting Types +/// +/// - ``AnyFetchRequest`` public protocol FetchRequest: SQLSubqueryable, DatabaseRegionConvertible { /// The type that tells how fetched database rows should be interpreted. associatedtype RowDecoder - /// Returns a PreparedRequest that is ready to be executed. + /// Returns a ``PreparedRequest``. + /// + /// The `singleResult` argument is a hint that a single result row will be + /// consumed. Implementations can optionally use it to optimize the + /// prepared statement, for example by adding a `LIMIT 1` SQL clause: + /// + /// ```swift + /// // Calls makePreparedRequest(db, forSingleResult: true) + /// try request.fetchOne(db) + /// + /// // Calls makePreparedRequest(db, forSingleResult: false) + /// try request.fetchAll(db) + /// ``` /// /// - parameter db: A database connection. /// - parameter singleResult: A hint that a single result row will be - /// consumed. Implementations can optionally use it to optimize the - /// prepared statement, for example by adding a `LIMIT 1` SQL clause. - /// - /// // Calls makePreparedRequest(db, forSingleResult: true) - /// try request.fetchOne(db) - /// - /// // Calls makePreparedRequest(db, forSingleResult: false) - /// try request.fetchAll(db) - /// - returns: A prepared request. + /// consumed. func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest /// Returns the number of rows fetched by the request. /// /// - parameter db: A database connection. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. func fetchCount(_ db: Database) throws -> Int } @@ -47,12 +91,12 @@ extension FetchRequest { // MARK: - PreparedRequest -/// A PreparedRequest is a request that is ready to be executed. +/// A `PreparedRequest` is a request that is ready to be executed. public struct PreparedRequest { - /// A prepared statement + /// A prepared statement with bound parameters. public var statement: Statement - /// An eventual adapter for rows fetched by the select statement + /// An eventual adapter for rows fetched by the select statement. public var adapter: (any RowAdapter)? /// Support for eager loading of hasMany associations. @@ -75,15 +119,21 @@ extension PreparedRequest: Refinable { } extension FetchRequest { /// Returns an adapted request. + /// + /// The returned request performs an identical database query, but adapts + /// the fetched rows. See ``RowAdapter``. + /// + /// - parameter adapter: A closure that accepts a database connection and + /// returns a row adapter. public func adapted(_ adapter: @escaping (Database) throws -> any RowAdapter) -> AdaptedFetchRequest { AdaptedFetchRequest(self, adapter) } } /// An adapted request. -public struct AdaptedFetchRequest: FetchRequest { - public typealias RowDecoder = Base.RowDecoder - +/// +/// See ``FetchRequest/adapted(_:)``. +public struct AdaptedFetchRequest { let base: Base let adapter: (Database) throws -> any RowAdapter @@ -93,10 +143,16 @@ public struct AdaptedFetchRequest: FetchRequest { self.base = base self.adapter = adapter } - +} + +extension AdaptedFetchRequest: SQLSubqueryable { public var sqlSubquery: SQLSubquery { base.sqlSubquery } +} + +extension AdaptedFetchRequest: FetchRequest { + public typealias RowDecoder = Base.RowDecoder public func fetchCount(_ db: Database) throws -> Int { try base.fetchCount(db) @@ -125,21 +181,39 @@ public struct AdaptedFetchRequest: FetchRequest { /// /// An `AnyFetchRequest` forwards its operations to an underlying request, /// hiding its specifics. -public struct AnyFetchRequest: FetchRequest { +public struct AnyFetchRequest { private let request: FetchRequestEraser - /// Creates a request bound to type RowDecoder. + /// Returns a request that performs an identical database query, but decodes + /// database rows with `type`. /// - /// - parameter type: The fetched type RowDecoder - /// - returns: A request bound to type RowDecoder. + /// For example: + /// + /// ```swift + /// // AnyFetchRequest + /// let playerRequest = AnyFetchRequest(Player.all()) + /// + /// // AnyFetchRequest + /// let rowRequest = playerRequest.asRequest(of: Row.self) public func asRequest(of type: RowDecoder.Type) -> AnyFetchRequest { AnyFetchRequest(request: request) } - +} + +extension AnyFetchRequest { + /// Creates a request that wraps and forwards operations to `request`. + public init(_ request: some FetchRequest) { + self.init(request: ConcreteFetchRequestEraser(request: request)) + } +} + +extension AnyFetchRequest: SQLSubqueryable { public var sqlSubquery: SQLSubquery { request.sqlSubquery } - +} + +extension AnyFetchRequest: FetchRequest { public func fetchCount(_ db: Database) throws -> Int { try request.fetchCount(db) } @@ -153,13 +227,6 @@ public struct AnyFetchRequest: FetchRequest { } } -extension AnyFetchRequest { - /// Creates a request that wraps and forwards operations to `request`. - public init(_ request: some FetchRequest) { - self.init(request: ConcreteFetchRequestEraser(request: request)) - } -} - // Class-based type erasure, so that we preserve full type information. private class FetchRequestEraser: FetchRequest { typealias RowDecoder = Void diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 1be94c522..b37822c02 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -1,10 +1,117 @@ import Foundation /// A database row. -public final class Row: Equatable, Hashable, RandomAccessCollection, - ExpressibleByDictionaryLiteral, CustomStringConvertible, - CustomDebugStringConvertible -{ +/// +/// To get `Row` instances, you will generally fetch them from a ``Database`` +/// instance. For example: +/// +/// ```swift +/// try dbQueue.read { db in +/// let rows = try Row.fetchCursor(db, sql: """ +/// SELECT * FROM player +/// """) +/// while let row = try rows.next() { +/// let id: Int64 = row["id"] +/// let name: String = row["name"] +/// } +/// } +/// ``` +/// +/// ## Topics +/// +/// ### Creating Rows +/// +/// - ``init()`` +/// - ``init(_:)-5uezw`` +/// - ``init(_:)-65by6`` +/// +/// ### Copying a Row +/// +/// - ``copy()`` +/// +/// ### Row Informations +/// +/// - ``columnNames`` +/// - ``containsNonNullValue`` +/// - ``count-5flaw`` +/// - ``databaseValues`` +/// - ``hasColumn(_:)`` +/// - ``hasNull(atIndex:)`` +/// +/// ### Accessing Row Values by Int Index +/// +/// - ``subscript(_:)-9c1fw`` +/// - ``subscript(_:)-3jhwm`` +/// - ``subscript(_:)-7krrg`` +/// - ``withUnsafeData(atIndex:_:)`` +/// - ``dataNoCopy(atIndex:)`` +/// +/// ### Accessing Row Values by Column Name +/// +/// - ``subscript(_:)-3tp8o`` +/// - ``subscript(_:)-4k8od`` +/// - ``subscript(_:)-9rbo7`` +/// - ``withUnsafeData(named:_:)`` +/// - ``dataNoCopy(named:)`` +/// +/// ### Accessing Row Values by Column +/// +/// - ``subscript(_:)-9txgm`` +/// - ``subscript(_:)-2esg7`` +/// - ``subscript(_:)-wl9a`` +/// - ``withUnsafeData(at:_:)`` +/// - ``dataNoCopy(_:)`` +/// +/// ### Row Scopes & Associated Rows +/// +/// - ``prefetchedRows`` +/// - ``scopes`` +/// - ``scopesTree`` +/// - ``unadapted`` +/// - ``unscoped`` +/// - ``subscript(_:)-4dx01`` +/// - ``subscript(_:)-8god3`` +/// - ``subscript(_:)-jwnx`` +/// - ``subscript(_:)-6ge6t`` +/// - ``PrefetchedRowsView`` +/// - ``ScopesTreeView`` +/// - ``ScopesView`` +/// +/// ### Fetching Rows from Raw SQL +/// +/// - ``fetchCursor(_:sql:arguments:adapter:)`` +/// - ``fetchAll(_:sql:arguments:adapter:)`` +/// - ``fetchSet(_:sql:arguments:adapter:)`` +/// - ``fetchOne(_:sql:arguments:adapter:)`` +/// +/// ### Fetching Rows from a Prepared Statement +/// +/// - ``fetchCursor(_:arguments:adapter:)`` +/// - ``fetchAll(_:arguments:adapter:)`` +/// - ``fetchSet(_:arguments:adapter:)`` +/// - ``fetchOne(_:arguments:adapter:)`` +/// +/// ### Fetching Rows from a Request +/// +/// - ``fetchCursor(_:_:)`` +/// - ``fetchAll(_:_:)`` +/// - ``fetchSet(_:_:)`` +/// - ``fetchOne(_:_:)`` +/// +/// ### Row as RandomAccessCollection +/// +/// - ``count-5flaw`` +/// - ``subscript(_:)-68yae`` +/// - ``Index`` +/// +/// ### Adapting Rows +/// +/// - ``RowAdapter`` +/// +/// ### Supporting Types +/// +/// - ``RowCursor`` +public final class Row { // It is not a violation of the Demeter law when another type uses this // property, which is exposed for optimizations. let impl: any RowImpl @@ -23,17 +130,30 @@ public final class Row: Equatable, Hashable, RandomAccessCollection, /// A view on the prefetched associated rows. /// + /// Prefetched rows are defined by the ``JoinableRequest/including(all:)`` + /// request method. + /// /// For example: /// - /// let request = Author.including(all: Author.books) - /// let row = try Row.fetchOne(db, request)! + /// ```swift + /// struct Author: TableRecord { + /// static let books = hasMany(Book.self) + /// } /// - /// print(row) - /// // Prints [id:1 name:"Herman Melville"] + /// struct Book: TableRecord { } /// - /// let bookRows = row.prefetchedRows["books"] - /// print(bookRows[0]) - /// // Prints [id:42 title:"Moby-Dick"] + /// let request = Author.including(all: Author.books) + /// let authorRow = try Row.fetchOne(db, request)! + /// + /// print(authorRow) + /// // Prints [id:1, name:"Herman Melville"] + /// + /// let bookRows = authorRow.prefetchedRows["books"]! + /// print(bookRows[0]) + /// // Prints [id:42, title:"Moby-Dick", authorId:1] + /// print(bookRows[1]) + /// // Prints [id:57, title:"Pierre", authorId:1] + /// ``` public internal(set) var prefetchedRows = PrefetchedRowsView() // MARK: - Building rows @@ -43,15 +163,15 @@ public final class Row: Equatable, Hashable, RandomAccessCollection, self.init(impl: EmptyRowImpl()) } - /// Creates a row from a dictionary of values. + /// Creates a row from a dictionary of database values. public convenience init(_ dictionary: [String: (any DatabaseValueConvertible)?]) { self.init(impl: ArrayRowImpl(columns: dictionary.map { ($0, $1?.databaseValue ?? .null) })) } - /// Creates a row from [AnyHashable: Any]. + /// Creates a row from a dictionary. /// /// The result is nil unless all dictionary keys are strings, and values - /// adopt DatabaseValueConvertible. + /// conform to ``DatabaseValueConvertible``. public convenience init?(_ dictionary: [AnyHashable: Any]) { var initDictionary = [String: (any DatabaseValueConvertible)?]() for (key, value) in dictionary { @@ -66,17 +186,6 @@ public final class Row: Equatable, Hashable, RandomAccessCollection, self.init(initDictionary) } - // ExpressibleByDictionaryLiteral - /// Creates a row initialized with elements. Column order is preserved, and - /// duplicated columns names are allowed. - /// - /// let row: Row = ["foo": 1, "foo": "bar", "baz": nil] - /// print(row) - /// // Prints [foo:1 foo:"bar" baz:NULL] - public convenience init(dictionaryLiteral elements: (String, (any DatabaseValueConvertible)?)...) { - self.init(impl: ArrayRowImpl(columns: elements.map { ($0, $1?.databaseValue ?? .null) })) - } - /// Returns an immutable copy of the row. /// /// For performance reasons, rows fetched from a cursor are reused during @@ -140,7 +249,7 @@ extension Row { // MARK: - Columns - /// The names of columns in the row. + /// The names of columns in the row, from left to right. /// /// Columns appear in the same order as they occur as the `.0` member /// of column-value pairs in `self`. @@ -148,9 +257,8 @@ extension Row { lazy.map { $0.0 } } - /// Returns true if and only if the row has that column. - /// - /// This method is case-insensitive. + /// Returns whether the row has one column with the given name + /// (case-insensitive). public func hasColumn(_ columnName: String) -> Bool { index(forColumn: columnName) != nil } @@ -172,17 +280,18 @@ extension Row { GRDBPrecondition(index >= 0 && index < count, "row index out of range", file: file, line: line) } - /// Returns true if and only if one column contains a non-null value, or if - /// the row was fetched with a row adapter that defines a scoped row that - /// contains a non-null value. + /// Returns a boolean value indicating if the row contains one value this + /// is not `NULL`. /// /// For example: /// - /// let row = try Row.fetchOne(db, sql: "SELECT 'foo', 1")! - /// row.containsNonNullValue // true + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT 'foo', NULL")! + /// row.containsNonNullValue // true /// - /// let row = try Row.fetchOne(db, sql: "SELECT NULL, NULL")! - /// row.containsNonNullValue // false + /// let row = try Row.fetchOne(db, sql: "SELECT NULL, NULL")! + /// row.containsNonNullValue // false + /// ``` public var containsNonNullValue: Bool { for i in (0.. Bool { _checkIndex(index) return impl.hasNull(atUncheckedIndex: index) } - /// Returns Int64, Double, String, Data or nil, depending on the value - /// stored at the given index. + /// Returns `Int64`, `Double`, `String`, `Data` or nil, depending on the + /// value stored at the given index. /// - /// Indexes span from 0 for the leftmost column to (row.count - 1) for the + /// Indexes span from `0` for the leftmost column to `row.count - 1` for the /// rightmost column. public subscript(_ index: Int) -> (any DatabaseValueConvertible)? { _checkIndex(index) @@ -220,21 +329,25 @@ extension Row { /// Returns the value at given index, converted to the requested type. /// - /// Indexes span from 0 for the leftmost column to (row.count - 1) for the + /// Indexes span from `0` for the leftmost column to `row.count - 1` for the /// rightmost column. /// /// For example: /// - /// let row = try Row.fetchOne(db, sql: "SELECT 42")! - /// let score: Int = row[0] // 42 + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT 42")! + /// let score: Int = row[0] // 42 /// - /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")! - /// let name: String = row[0] // "Alice" + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")! + /// let name: String = row[0] // "Alice" + /// ``` /// /// When the database value may be nil, ask for an optional: /// - /// let row = try Row.fetchOne(db, sql: "SELECT NULL")! - /// let name: String? = row[0] // nil + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT NULL")! + /// let name: String? = row[0] // nil + /// ``` @inlinable public subscript(_ index: Int) -> Value { try! decode(Value.self, atIndex: index) @@ -242,38 +355,42 @@ extension Row { /// Returns the value at given index, converted to the requested type. /// - /// Indexes span from 0 for the leftmost column to (row.count - 1) for the - /// rightmost column. - /// /// This method exists as an optimization opportunity for types that adopt - /// ``StatementColumnConvertible``. It can trigger SQLite built-in - /// conversions (see ). + /// ``StatementColumnConvertible``. It can trigger [SQLite built-in + /// conversions](https://www.sqlite.org/datatype3.html). + /// + /// Indexes span from `0` for the leftmost column to `row.count - 1` for the + /// rightmost column. /// /// For example: /// - /// let row = try Row.fetchOne(db, sql: "SELECT 42")! - /// let score: Int = row[0] // 42 + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT 42")! + /// let score: Int = row[0] // 42 /// - /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")! - /// let name: String = row[0] // "Alice" + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")! + /// let name: String = row[0] // "Alice" + /// ``` /// /// When the database value may be nil, ask for an optional: /// - /// let row = try Row.fetchOne(db, sql: "SELECT NULL")! - /// let name: String? = row[0] // nil + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT NULL")! + /// let name: String? = row[0] // nil + /// ``` @inline(__always) @inlinable public subscript(_ index: Int) -> Value { try! decode(Value.self, atIndex: index) } - /// Returns Int64, Double, String, Data or nil, depending on the value - /// stored at the given column. + /// Returns `Int64`, `Double`, `String`, `Data` or nil, depending on the + /// value stored at the given column. /// - /// Column name lookup is case-insensitive, and when several columns have + /// Column name lookup is case-insensitive. When several columns exist with /// the same name, the leftmost column is considered. /// - /// The result is nil if the row does not contain the column. + /// The result is nil if the row does not contain any column with that name. public subscript(_ columnName: String) -> (any DatabaseValueConvertible)? { // IMPLEMENTATION NOTE // This method has a single known use case: checking if the value is nil, @@ -290,26 +407,32 @@ extension Row { /// Returns the value at given column, converted to the requested type. /// - /// Column name lookup is case-insensitive, and when several columns have + /// Column name lookup is case-insensitive. When several columns exist with /// the same name, the leftmost column is considered. /// /// For example: /// - /// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")! - /// let score: Int = row["score"] // 42 + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")! + /// let score: Int = row["score"] // 42 /// - /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! - /// let name: String = row["name"] // "Alice" + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! + /// let name: String = row["name"] // "Alice" + /// ``` /// /// When the database value may be nil, ask for an optional: /// - /// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")! - /// let name: String? = row["name"] // nil + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")! + /// let name: String? = row["name"] // nil + /// ``` /// /// When the column does not exist, nil is returned: /// - /// let row = try Row.fetchOne(db, sql: "SELECT ...")! - /// let name: String? = row["missing"] // nil + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! + /// let name: String? = row["missing"] // nil + /// ``` @inlinable public subscript(_ columnName: String) -> Value { try! decode(Value.self, forKey: columnName) @@ -317,68 +440,80 @@ extension Row { /// Returns the value at given column, converted to the requested type. /// - /// Column name lookup is case-insensitive, and when several columns have - /// the same name, the leftmost column is considered. - /// /// This method exists as an optimization opportunity for types that adopt - /// `StatementColumnConvertible`. It can trigger SQLite built-in conversions - /// (see ). + /// ``StatementColumnConvertible``. It can trigger [SQLite built-in + /// conversions](https://www.sqlite.org/datatype3.html). + /// + /// Column name lookup is case-insensitive. When several columns exist with + /// the same name, the leftmost column is considered. /// /// For example: /// - /// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")! - /// let score: Int = row["score"] // 42 + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")! + /// let score: Int = row["score"] // 42 /// - /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! - /// let name: String = row["name"] // "Alice" + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! + /// let name: String = row["name"] // "Alice" + /// ``` /// /// When the database value may be nil, ask for an optional: /// - /// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")! - /// let name: String? = row["name"] // nil + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")! + /// let name: String? = row["name"] // nil + /// ``` /// /// When the column does not exist, nil is returned: /// - /// let row = try Row.fetchOne(db, sql: "SELECT ...")! - /// let name: String? = row["missing"] // nil + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! + /// let name: String? = row["missing"] // nil + /// ``` @inlinable public subscript(_ columnName: String) -> Value { try! decode(Value.self, forKey: columnName) } - /// Returns Int64, Double, String, Data or nil, depending on the value - /// stored at the given column. + /// Returns `Int64`, `Double`, `String`, `Data` or nil, depending on the + /// value stored at the given column. /// - /// Column name lookup is case-insensitive, and when several columns have + /// Column name lookup is case-insensitive. When several columns exist with /// the same name, the leftmost column is considered. /// - /// The result is nil if the row does not contain the column. + /// The result is nil if the row does not contain any column with that name. public subscript(_ column: some ColumnExpression) -> (any DatabaseValueConvertible)? { self[column.name] } /// Returns the value at given column, converted to the requested type. /// - /// Column name lookup is case-insensitive, and when several columns have + /// Column name lookup is case-insensitive. When several columns exist with /// the same name, the leftmost column is considered. /// /// For example: /// - /// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")! - /// let score: Int = row[Column("score")] // 42 + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")! + /// let score: Int = row[Column("score")] // 42 /// - /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! - /// let name: String = row[Column("name")] // "Alice" + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! + /// let name: String = row[Column("name")] // "Alice" + /// ``` /// /// When the database value may be nil, ask for an optional: /// - /// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")! - /// let name: String? = row[Column("name")] // nil + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")! + /// let name: String? = row[Column("name")] // nil + /// ``` /// /// When the column does not exist, nil is returned: /// - /// let row = try Row.fetchOne(db, sql: "SELECT ...")! - /// let name: String? = row[Column("missing")] // nil + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! + /// let name: String? = row[Column("missing")] // nil + /// ``` @inlinable public subscript(_ column: some ColumnExpression) -> Value { try! decode(Value.self, forKey: column.name) @@ -386,30 +521,36 @@ extension Row { /// Returns the value at given column, converted to the requested type. /// - /// Column name lookup is case-insensitive, and when several columns have - /// the same name, the leftmost column is considered. - /// /// This method exists as an optimization opportunity for types that adopt - /// ``StatementColumnConvertible``. It can trigger SQLite built-in conversions - /// (see ). + /// ``StatementColumnConvertible``. It can trigger [SQLite built-in + /// conversions](https://www.sqlite.org/datatype3.html). + /// + /// Column name lookup is case-insensitive. When several columns exist with + /// the same name, the leftmost column is considered. /// /// For example: /// - /// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")! - /// let score: Int = row[Column("score")] // 42 + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")! + /// let score: Int = row[Column("score")] // 42 /// - /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! - /// let name: String = row[Column("name")] // "Alice" + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! + /// let name: String = row[Column("name")] // "Alice" + /// ``` /// /// When the database value may be nil, ask for an optional: /// - /// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")! - /// let name: String? = row[Column("name")] // nil + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")! + /// let name: String? = row[Column("name")] // nil + /// ``` /// /// When the column does not exist, nil is returned: /// - /// let row = try Row.fetchOne(db, sql: "SELECT ...")! - /// let name: String? = row[Column("missing")] // nil + /// ```swift + /// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")! + /// let name: String? = row[Column("missing")] // nil + /// ``` @inlinable public subscript(_ column: some ColumnExpression) -> Value @@ -418,9 +559,57 @@ extension Row { try! decode(Value.self, forKey: column.name) } + /// Calls the given closure with the `Data` at given index. + /// + /// Indexes span from `0` for the leftmost column to `row.count - 1` for the + /// rightmost column. + /// + /// If the SQLite value is `NULL`, the data is nil. If the SQLite value can + /// not be converted to `Data`, an error is thrown. + /// + /// - warning: The `Data` argument to the body must not be stored or used + /// outside of the lifetime of the call to the closure. + public func withUnsafeData(atIndex index: Int, _ body: (Data?) throws -> T) throws -> T { + _checkIndex(index) + return try impl.withUnsafeData(atUncheckedIndex: index, body) + } + + /// Calls the given closure with the `Data` at the given column. + /// + /// Column name lookup is case-insensitive. When several columns exist with + /// the same name, the leftmost column is considered. + /// + /// If the row does not contain any column with that name, or if the SQLite + /// value is `NULL`, the data is nil. If the SQLite value can not be + /// converted to `Data`, an error is thrown. + /// + /// - warning: The `Data` argument to the body must not be stored or used + /// outside of the lifetime of the call to the closure. + public func withUnsafeData(named columnName: String, _ body: (Data?) throws -> T) throws -> T { + guard let index = index(forColumn: columnName) else { + return try body(nil) + } + return try impl.withUnsafeData(atUncheckedIndex: index, body) + } + + /// Calls the given closure with the `Data` at the given column. + /// + /// Column name lookup is case-insensitive. When several columns exist with + /// the same name, the leftmost column is considered. + /// + /// If the row does not contain any column with that name, or if the SQLite + /// value is `NULL`, the data is nil. If the SQLite value can not be + /// converted to `Data`, an error is thrown. + /// + /// - warning: The `Data` argument to the body must not be stored or used + /// outside of the lifetime of the call to the closure. + public func withUnsafeData(at column: some ColumnExpression, _ body: (Data?) throws -> T) throws -> T { + try withUnsafeData(named: column.name, body) + } + /// Returns the optional `Data` at given index. /// - /// Indexes span from 0 for the leftmost column to (row.count - 1) for the + /// Indexes span from `0` for the leftmost column to `row.count - 1` for the /// rightmost column. /// /// If the SQLite value is NULL, the result is nil. If the SQLite value can @@ -428,13 +617,14 @@ extension Row { /// /// The returned data does not owns its bytes: it must not be used longer /// than the row's lifetime. + @available(*, deprecated, message: "Use withUnsafeData(atIndex:_:) instead.") public func dataNoCopy(atIndex index: Int) -> Data? { - try! decodeDataNoCopyIfPresent(atIndex: index) + try! withUnsafeData(atIndex: index, { $0 }) } /// Returns the optional `Data` at given column. /// - /// Column name lookup is case-insensitive, and when several columns have + /// Column name lookup is case-insensitive. When several columns exist with /// the same name, the leftmost column is considered. /// /// If the column is missing or if the SQLite value is NULL, the result is @@ -443,13 +633,17 @@ extension Row { /// /// The returned data does not owns its bytes: it must not be used longer /// than the row's lifetime. + @available(*, deprecated, message: "Use withUnsafeData(named:_:) instead.") public func dataNoCopy(named columnName: String) -> Data? { - try! decodeDataNoCopyIfPresent(forKey: columnName) + guard let index = index(forColumn: columnName) else { + return nil + } + return try! withUnsafeData(atUncheckedIndex: index, { $0 }) } /// Returns the optional `Data` at given column. /// - /// Column name lookup is case-insensitive, and when several columns have + /// Column name lookup is case-insensitive. When several columns exist with /// the same name, the leftmost column is considered. /// /// If the column is missing or if the SQLite value is NULL, the result is @@ -458,8 +652,9 @@ extension Row { /// /// The returned data does not owns its bytes: it must not be used longer /// than the row's lifetime. + @available(*, deprecated, message: "Use withUnsafeData(at:_:) instead.") public func dataNoCopy(_ column: some ColumnExpression) -> Data? { - try! decodeDataNoCopyIfPresent(forKey: column.name) + dataNoCopy(named: column.name) } } @@ -467,7 +662,7 @@ extension Row { // MARK: - Extracting DatabaseValue - /// The database values in the row. + /// The database values in the row, from left to right. /// /// Values appear in the same order as they occur as the `.1` member /// of column-value pairs in `self`. @@ -480,111 +675,152 @@ extension Row { // MARK: - Extracting Records - /// Returns the record associated with the given scope. + /// The record associated to the given scope. + /// + /// Row scopes can be defined manually, with ``ScopeAdapter``. + /// The ``JoinableRequest/including(required:)`` and + /// ``JoinableRequest/including(optional:)`` request methods define scopes + /// named after the key of included associations between record types. + /// + /// A depth-first search is performed in all available scopes in the row, + /// recursively. + /// + /// A fatal error is raised if the scope is not available, or contains only + /// `NULL` values. /// /// For example: /// - /// let request = Book.including(required: Book.author) - /// let row = try Row.fetchOne(db, request)! + /// ```swift + /// struct Book: TableRecord, FetchableRecord { + /// static let author = belongsTo(Author.self) + /// } /// - /// try print(Book(row: row).title) - /// // Prints "Moby-Dick" + /// struct Author: TableRecord, FetchableRecord { + /// static let country = belongsTo(Country.self) + /// } /// - /// let author: Author = row["author"] - /// print(author.name) - /// // Prints "Herman Melville" + /// struct Country: TableRecord, FetchableRecord { } /// - /// Associated records stored in nested associations are available, too: + /// // Fetch a book, with its author, and the country of its author. + /// let request = Book + /// .including(required: Book.author + /// .including(required: Author.country)) + /// let bookRow = try Row.fetchOne(db, request)! /// - /// let request = Book.including(required: Book.author.including(required: Author.country)) - /// let row = try Row.fetchOne(db, request)! + /// let book = try Book(row: bookRow) + /// let author: Author = bookRow["author"] + /// let country: Country = bookRow["country"] + /// ``` /// - /// try print(Book(row: row).title) - /// // Prints "Moby-Dick" + /// See also: ``scopesTree`` /// - /// let country: Country = row["country"] - /// print(country.name) - /// // Prints "United States" - /// - /// A fatal error is raised if the scope is not available, or contains only - /// null values. - /// - /// See - /// for more information. + /// - parameter scope: A scope identifier. public subscript(_ scope: String) -> Record { try! decode(Record.self, forKey: scope) } - /// Returns the eventual record associated with the given scope. + /// The eventual record associated to the given scope. + /// + /// Row scopes can be defined manually, with ``ScopeAdapter``. + /// The ``JoinableRequest/including(required:)`` and + /// ``JoinableRequest/including(optional:)`` request methods define scopes + /// named after the key of included associations between record types. + /// + /// A depth-first search is performed in all available scopes in the row, + /// recursively. + /// + /// The result is nil if the scope is not available, or contains only + /// `NULL` values. /// /// For example: /// - /// let request = Book.including(optional: Book.author) - /// let row = try Row.fetchOne(db, request)! + /// ```swift + /// struct Book: TableRecord, FetchableRecord { + /// static let author = belongsTo(Author.self) + /// } /// - /// try print(Book(row: row).title) - /// // Prints "Moby-Dick" + /// struct Author: TableRecord, FetchableRecord { + /// static let country = belongsTo(Country.self) + /// } /// - /// let author: Author? = row["author"] - /// print(author.name) - /// // Prints "Herman Melville" + /// struct Country: TableRecord, FetchableRecord { } /// - /// Associated records stored in nested associations are available, too: + /// // Fetch a book, with its author, and the country of its author. + /// let request = Book + /// .including(optional: Book.author + /// .including(optional: Author.country)) + /// let bookRow = try Row.fetchOne(db, request)! /// - /// let request = Book.including(optional: Book.author.including(optional: Author.country)) - /// let row = try Row.fetchOne(db, request)! + /// let book = try Book(row: bookRow) + /// let author: Author? = bookRow["author"] + /// let country: Country? = bookRow["country"] + /// ``` /// - /// try print(Book(row: row).title) - /// // Prints "Moby-Dick" + /// See also: ``scopesTree`` /// - /// let country: Country? = row["country"] - /// print(country.name) - /// // Prints "United States" - /// - /// Nil is returned if the scope is not available, or contains only - /// null values. - /// - /// See - /// for more information. + /// - parameter scope: A scope identifier. public subscript(_ scope: String) -> Record? { try! decodeIfPresent(Record.self, forKey: scope) } - /// Returns the records encoded in the given prefetched rows. + /// A collection of prefetched records associated to the given + /// association key. + /// + /// Prefetched rows are defined by the ``JoinableRequest/including(all:)`` + /// request method. /// /// For example: /// - /// let request = Author.including(all: Author.books) - /// let row = try Row.fetchOne(db, request)! + /// ```swift + /// struct Author: TableRecord, FetchableRecord { + /// static let books = hasMany(Book.self) + /// } /// - /// try print(Author(row: row).name) - /// // Prints "Herman Melville" + /// struct Book: TableRecord, FetchableRecord { } /// - /// let books: [Book] = row["books"] - /// print(books[0].title) - /// // Prints "Moby-Dick" - public subscript(_ key: String) - -> Collection + /// let request = Author.including(all: Author.books) + /// let authorRow = try Row.fetchOne(db, request)! + /// + /// let author = try Author(row: authorRow) + /// let books: [Book] = author["books"] + /// ``` + /// + /// See also: ``prefetchedRows`` + /// + /// - parameter key: An association key. + public subscript(_ key: String) + -> Records where - Collection: RangeReplaceableCollection, - Collection.Element: FetchableRecord + Records: RangeReplaceableCollection, + Records.Element: FetchableRecord { - try! decode(Collection.self, forKey: key) + try! decode(Records.self, forKey: key) } - /// Returns the set of records encoded in the given prefetched rows. + /// A set prefetched records associated to the given association key. + /// + /// Prefetched rows are defined by the ``JoinableRequest/including(all:)`` + /// request method. /// /// For example: /// - /// let request = Author.including(all: Author.books) - /// let row = try Row.fetchOne(db, request)! + /// ```swift + /// struct Author: TableRecord, FetchableRecord { + /// static let books = hasMany(Book.self) + /// } /// - /// try print(Author(row: row).name) - /// // Prints "Herman Melville" + /// struct Book: TableRecord, FetchableRecord, Hashable { } /// - /// let books: Set = row["books"] - /// print(books.first!.title) - /// // Prints "Moby-Dick" + /// let request = Author.including(all: Author.books) + /// let authorRow = try Row.fetchOne(db, request)! + /// + /// let author = try Author(row: authorRow) + /// let books: Set = author["books"] + /// ``` + /// + /// See also: ``prefetchedRows`` + /// + /// - parameter key: An association key. public subscript(_ key: String) -> Set { try! decode(Set.self, forKey: key) } @@ -594,63 +830,125 @@ extension Row { // MARK: - Scopes - /// Returns a view on the scopes defined by row adapters. + /// A view on the scopes defined by row adapters. + /// + /// The returned object provides an access to all available scopes in + /// the row. + /// + /// Row scopes can be defined manually, with ``ScopeAdapter``. + /// The ``JoinableRequest/including(required:)`` and + /// ``JoinableRequest/including(optional:)`` request methods define scopes + /// named after the key of included associations between record types. /// /// For example: /// - /// // Define a tree of nested scopes - /// let adapter = ScopeAdapter([ - /// "foo": RangeRowAdapter(0..<1), - /// "bar": RangeRowAdapter(1..<2).addingScopes([ - /// "baz" : RangeRowAdapter(2..<3)])]) + /// ```swift + /// struct Book: TableRecord { + /// static let author = belongsTo(Author.self) + /// } /// - /// // Fetch - /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" - /// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)! + /// struct Author: TableRecord { + /// static let country = belongsTo(Country.self) + /// } /// - /// row.scopes.count // 2 - /// row.scopes.names // ["foo", "bar"] + /// struct Country: TableRecord { } /// - /// row.scopes["foo"] // [foo:1] - /// row.scopes["bar"] // [bar:2] - /// row.scopes["baz"] // nil + /// // Fetch a book, with its author, and the country of its author. + /// let request = Book + /// .including(required: Book.author + /// .including(required: Author.country)) + /// let bookRow = try Row.fetchOne(db, request)! + /// + /// print(bookRow) + /// // Prints [id:42, title:"Moby-Dick", authorId:1] + /// + /// let authorRow = bookRow.scopes["author"]! + /// print(authorRow) + /// // Prints [id:1, name:"Herman Melville", countryCode: "US"] + /// + /// let countryRow = authorRow.scopes["country"]! + /// print(countryRow) + /// // Prints [code:"US" name:"United States of America"] + /// ``` + /// + /// See also ``scopesTree``. public var scopes: ScopesView { impl.scopes(prefetchedRows: prefetchedRows) } - /// Returns a view on the scopes tree defined by row adapters. + /// A view on the scopes tree defined by row adapters. + /// + /// The returned object provides an access to all available scopes in + /// the row, recursively. For any given scope identifier, a depth-first + /// search is performed. + /// + /// Row scopes can be defined manually, with ``ScopeAdapter``. + /// The ``JoinableRequest/including(required:)`` and + /// ``JoinableRequest/including(optional:)`` request methods define scopes + /// named after the key of included associations between record types. /// /// For example: /// - /// // Define a tree of nested scopes - /// let adapter = ScopeAdapter([ - /// "foo": RangeRowAdapter(0..<1), - /// "bar": RangeRowAdapter(1..<2).addingScopes([ - /// "baz" : RangeRowAdapter(2..<3)])]) + /// ```swift + /// struct Book: TableRecord { + /// static let author = belongsTo(Author.self) + /// } /// - /// // Fetch - /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" - /// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)! + /// struct Author: TableRecord { + /// static let country = belongsTo(Country.self) + /// } /// - /// row.scopesTree.names // ["foo", "bar", "baz"] + /// struct Country: TableRecord { } /// - /// row.scopesTree["foo"] // [foo:1] - /// row.scopesTree["bar"] // [bar:2] - /// row.scopesTree["baz"] // [baz:3] + /// // Fetch a book, with its author, and the country of its author. + /// let request = Book + /// .including(required: Book.author + /// .including(required: Author.country)) + /// let bookRow = try Row.fetchOne(db, request)! + /// + /// print(bookRow) + /// // Prints [id:42, title:"Moby-Dick", authorId:1] + /// + /// print(bookRow.scopesTree["author"]) + /// // Prints [id:1, name:"Herman Melville", countryCode: "US"] + /// + /// print(bookRow.scopesTree["country"]) + /// // Prints [code:"US" name:"United States of America"] + /// ``` + /// + /// See also ``scopes``. public var scopesTree: ScopesTreeView { ScopesTreeView(scopes: scopes) } - /// Returns a copy of the row, without any scopes. + /// The row, without any scope of prefetched rows. /// - /// This property can turn out useful when you want to test the content of - /// adapted rows, such as rows fetched from joined requests. + /// This property is useful when testing the content of rows fetched from + /// joined requests. /// - /// let row = ... - /// // Failure because row equality tests for row scopes: - /// XCTAssertEqual(row, ["id": 1, "name": "foo"]) - /// // Success: - /// XCTAssertEqual(row.unscoped, ["id": 1, "name": "foo"]) + /// For example: + /// + /// ```swift + /// struct Book: TableRecord { + /// static let author = belongsTo(Author.self) + /// static let awards = hasMany(Award.self) + /// } + /// + /// struct Author: TableRecord { } + /// struct Award: TableRecord { } + /// + /// // Fetch a book, with its author, and its awards. + /// let request = Book + /// .including(required: Book.author) + /// .including(all: Book.awards) + /// let bookRow = try Row.fetchOne(db, request)! + /// + /// // Failure + /// XCTAssertEqual(bookRow, ["id":42, "title":"Moby-Dick", "authorId":1]) + /// + /// // Success + /// XCTAssertEqual(bookRow.unscoped, ["id":42, "title":"Moby-Dick", "authorId":1]) + /// ``` public var unscoped: Row { var row = impl.unscopedRow(self) @@ -664,10 +962,32 @@ extension Row { return row } - /// Return the raw row fetched from the database. + /// The raw row fetched from the database. /// - /// This property can turn out useful when you debug the consumption of - /// adapted rows, such as rows fetched from joined requests. + /// This property is useful when debugging the content of rows fetched from + /// joined requests. + /// + /// For example: + /// + /// ```swift + /// struct Book: TableRecord { + /// static let author = belongsTo(Author.self) + /// } + /// + /// struct Author: TableRecord { } + /// + /// // SELECT book.*, author.* + /// // FROM book + /// // JOIN author ON author.id = book.authorId + /// let request = Book.including(required: Book.author) + /// let bookRow = try Row.fetchOne(db, request)! + /// + /// print(bookRow) + /// // Prints [id:42, title:"Moby-Dick", authorId:1] + /// + /// print(bookRow.unadapted) + /// // Prints [id:42, title:"Moby-Dick", authorId:1, id:1, name:"Herman Melville"] + /// ``` public var unadapted: Row { impl.unadaptedRow(self) } @@ -678,7 +998,7 @@ extension Row { extension Row { /// Returns the value at given index, converted to the requested type. /// - /// Indexes span from 0 for the leftmost column to (row.count - 1) for the + /// Indexes span from `0` for the leftmost column to `row.count - 1` for the /// rightmost column. /// /// If the SQLite value is NULL, or if the conversion fails, a @@ -695,7 +1015,7 @@ extension Row { /// Returns the value at given column, converted to the requested type. /// - /// Column name lookup is case-insensitive, and when several columns have + /// Column name lookup is case-insensitive. When several columns exist with /// the same name, the leftmost column is considered. /// /// If the row does not contain the column, or if the SQLite value is NULL, @@ -723,15 +1043,15 @@ extension Row { extension Row { /// Returns the value at given index, converted to the requested type. /// - /// Indexes span from 0 for the leftmost column to (row.count - 1) for the + /// This method exists as an optimization opportunity for types that adopt + /// ``StatementColumnConvertible``. It can trigger [SQLite built-in + /// conversions](https://www.sqlite.org/datatype3.html). + /// + /// Indexes span from `0` for the leftmost column to `row.count - 1` for the /// rightmost column. /// /// If the SQLite value is NULL, or if the conversion fails, a /// `RowDecodingError` is thrown. - /// - /// This method exists as an optimization opportunity for types that adopt - /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions - /// (see ). @inline(__always) @inlinable func decode( @@ -745,16 +1065,16 @@ extension Row { /// Returns the value at given column, converted to the requested type. /// - /// Column name lookup is case-insensitive, and when several columns have + /// This method exists as an optimization opportunity for types that adopt + /// ``StatementColumnConvertible``. It can trigger [SQLite built-in + /// conversions](https://www.sqlite.org/datatype3.html). + /// + /// Column name lookup is case-insensitive. When several columns exist with /// the same name, the leftmost column is considered. /// /// If the row does not contain the column, or if the SQLite value is NULL, /// or if the SQLite value can not be converted to `Value`, a /// `RowDecodingError` is thrown. - /// - /// This method exists as an optimization opportunity for types that adopt - /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions - /// (see ). @inlinable func decode( _ type: Value.Type = Value.self, @@ -785,80 +1105,18 @@ extension Row { // MARK: - Throwing Data Decoding Methods extension Row { - /// Returns the optional Data at given index. + /// Calls the given closure with the `Data` at given index. /// - /// Indexes span from 0 for the leftmost column to (row.count - 1) for the + /// Indexes span from `0` for the leftmost column to `row.count - 1` for the /// rightmost column. /// - /// If the SQLite value is NULL, the result is nil. If the SQLite value can - /// not be converted to Data, a `RowDecodingError` is thrown. + /// If the SQLite value is `NULL`, the data is nil. If the SQLite value can + /// not be converted to `Data`, an error is thrown. /// - /// The returned data does not owns its bytes: it must not be used longer - /// than the row's lifetime. - func decodeDataNoCopyIfPresent(atIndex index: Int) throws -> Data? { - _checkIndex(index) - return try impl.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: index) - } - - /// Returns the Data at given index. - /// - /// Indexes span from 0 for the leftmost column to (row.count - 1) for the - /// rightmost column. - /// - /// If the SQLite value is NULL, or if the SQLite value can not be converted - /// to Data, a `RowDecodingError` is thrown. - /// - /// The returned data does not owns its bytes: it must not be used longer - /// than the row's lifetime. - func decodeDataNoCopy(atIndex index: Int) throws -> Data { - _checkIndex(index) - return try impl.fastDecodeDataNoCopy(atUncheckedIndex: index) - } - - /// Returns the optional Data at given column. - /// - /// Column name lookup is case-insensitive, and when several columns have - /// the same name, the leftmost column is considered. - /// - /// If the column is missing or if the SQLite value is NULL, the result is - /// nil. If the SQLite value can not be converted to Data, a - /// `RowDecodingError` is thrown. - /// - /// The returned data does not owns its bytes: it must not be used longer - /// than the row's lifetime. - func decodeDataNoCopyIfPresent(forKey columnName: String) throws -> Data? { - guard let index = index(forColumn: columnName) else { - return nil - } - return try impl.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: index) - } - - /// Returns the Data at given column. - /// - /// Column name lookup is case-insensitive, and when several columns have - /// the same name, the leftmost column is considered. - /// - /// If the column is missing, or if the SQLite value is NULL, or if the - /// SQLite value can not be converted to Data, a - /// `RowDecodingError` is thrown. - /// - /// The returned data does not owns its bytes: it must not be used longer - /// than the row's lifetime. - func decodeDataNoCopy(forKey columnName: String) throws -> Data { - guard let index = index(forColumn: columnName) else { - throw RowDecodingError.columnNotFound(columnName, context: RowDecodingContext(row: self)) - } - return try impl.fastDecodeDataNoCopy(atUncheckedIndex: index) - } - - // Support for fast decoding in scoped rows - func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data { - try impl.fastDecodeDataNoCopy(atUncheckedIndex: index) - } - - // Support for fast decoding in scoped rows - func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? { - try impl.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: index) + /// - warning: The `Data` argument to the body must not be stored or used + /// outside of the lifetime of the call to the closure. + func withUnsafeData(atUncheckedIndex index: Int, _ body: (Data?) throws -> T) throws -> T { + try impl.withUnsafeData(atUncheckedIndex: index, body) } } @@ -1080,16 +1338,26 @@ extension Row { // MARK: - RowCursor -/// A cursor of database rows. For example: +/// A cursor of raw database rows. /// -/// try dbQueue.read { db in -/// let rows: RowCursor = try Row.fetchCursor(db, sql: "SELECT * FROM player") +/// A `RowCursor` iterates all rows from a database request. +/// +/// For example: +/// +/// ```swift +/// try dbQueue.read { db in +/// let rows = try Row.fetchCursor(db, sql: """ +/// SELECT * FROM player +/// """) +/// while let row = try rows.next() { +/// let id: Int64 = row["id"] +/// let name: String = row["name"] /// } +/// } +/// ``` public final class RowCursor: DatabaseCursor { public typealias Element = Row - /// :nodoc: public let _statement: Statement - /// :nodoc: public var _isDone = false @usableFromInline let _row: Row // Reused for performance @@ -1107,7 +1375,6 @@ public final class RowCursor: DatabaseCursor { try? _statement.reset() } - /// :nodoc: @inlinable public func _element(sqliteStatement: SQLiteStatement) -> Row { _row } } @@ -1118,33 +1385,42 @@ extension Row { /// Returns a cursor over rows fetched from a prepared statement. /// - /// let statement = try db.makeStatement(sql: "SELECT ...") - /// let rows = try Row.fetchCursor(statement) // RowCursor - /// while let row = try rows.next() { // Row - /// let id: Int64 = row[0] - /// let name: String = row[1] + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT * FROM player WHERE lastName = ?" + /// let statement = try db.makeStatement(sql: sql) + /// let rows = try Row.fetchCursor(statement, arguments: [lastName]) + /// while let row = try rows.next() { + /// let id: Int64 = row["id"] + /// let name: String = row["name"] /// } + /// } + /// ``` /// /// Fetched rows are reused during the cursor iteration: don't turn a row - /// cursor into an array with `Array(rows)` or `rows.filter { ... }` since - /// you would not get the distinct rows you expect. Use `Row.fetchAll(...)` - /// instead. + /// cursor into an array with `Array(rows)` since you would not get the + /// distinct rows you expect. + /// Use ``fetchAll(_:arguments:adapter:)`` instead. /// /// For the same reason, make sure you make a copy whenever you extract a /// row for later use: `row.copy()`. /// + /// The returned cursor is valid only during the remaining execution of the + /// database access. Do not store or return the cursor for later use. + /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// - /// The cursor must be iterated in a protected dispatch queue. - /// /// - parameters: /// - db: A database connection. - /// - sql: An SQL query. + /// - sql: An SQL string. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter - /// - returns: A cursor over fetched rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: A ``RowCursor`` over fetched rows. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor( _ statement: Statement, arguments: StatementArguments? = nil, @@ -1156,15 +1432,23 @@ extension Row { /// Returns an array of rows fetched from a prepared statement. /// - /// let statement = try db.makeStatement(sql: "SELECT ...") - /// let rows = try Row.fetchAll(statement) + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT * FROM player WHERE lastName = ?" + /// let statement = try db.makeStatement(sql: sql) + /// let rows = try Row.fetchAll(statement, arguments: [lastName]) + /// } + /// ``` /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: An array of rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll( _ statement: Statement, arguments: StatementArguments? = nil, @@ -1177,15 +1461,23 @@ extension Row { /// Returns a set of rows fetched from a prepared statement. /// - /// let statement = try db.makeStatement(sql: "SELECT ...") - /// let rows = try Row.fetchSet(statement) + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT * FROM player WHERE lastName = ?" + /// let statement = try db.makeStatement(sql: sql) + /// let rows = try Row.fetchSet(statement, arguments: [lastName]) + /// } + /// ``` /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: A set of rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet( _ statement: Statement, arguments: StatementArguments? = nil, @@ -1198,15 +1490,23 @@ extension Row { /// Returns a single row fetched from a prepared statement. /// - /// let statement = try db.makeStatement(sql: "SELECT ...") - /// let row = try Row.fetchOne(statement) + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT * FROM player WHERE lastName = ? LIMIT 1" + /// let statement = try db.makeStatement(sql: sql) + /// let row = try Row.fetchOne(statement, arguments: [lastName]) + /// } + /// ``` /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: An optional row. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne( _ statement: Statement, arguments: StatementArguments? = nil, @@ -1227,32 +1527,41 @@ extension Row { /// Returns a cursor over rows fetched from an SQL query. /// - /// let rows = try Row.fetchCursor(db, sql: "SELECT id, name FROM player") // RowCursor - /// while let row = try rows.next() { // Row - /// let id: Int64 = row[0] - /// let name: String = row[1] + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT * FROM player WHERE lastName = ?" + /// let rows = try Row.fetchCursor(db, sql: sql, arguments: [lastName]) + /// while let row = try rows.next() { + /// let id: Int64 = row["id"] + /// let name: String = row["name"] /// } + /// } + /// ``` /// /// Fetched rows are reused during the cursor iteration: don't turn a row - /// cursor into an array with `Array(rows)` or `rows.filter { ... }` since - /// you would not get the distinct rows you expect. Use `Row.fetchAll(...)` - /// instead. + /// cursor into an array with `Array(rows)` since you would not get the + /// distinct rows you expect. + /// Use ``fetchAll(_:sql:arguments:adapter:)`` instead. /// /// For the same reason, make sure you make a copy whenever you extract a /// row for later use: `row.copy()`. /// + /// The returned cursor is valid only during the remaining execution of the + /// database access. Do not store or return the cursor for later use. + /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// - /// The cursor must be iterated in a protected dispatch queue. - /// /// - parameters: /// - db: A database connection. - /// - sql: An SQL query. + /// - sql: An SQL string. /// - arguments: Statement arguments. /// - adapter: Optional RowAdapter - /// - returns: A cursor over fetched rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: A ``RowCursor`` over fetched rows. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor( _ db: Database, sql: String, @@ -1265,19 +1574,23 @@ extension Row { /// Returns an array of rows fetched from an SQL query. /// - /// let rows = try Row.fetchAll(db, sql: "SELECT id, name FROM player") // [Row] - /// for row in rows { - /// let id: Int64 = row[0] - /// let name: String = row[1] - /// } + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT * FROM player WHERE lastName = ?" + /// let rows = try Row.fetchAll(db, sql: sql, arguments: [lastName]) + /// } + /// ``` /// /// - parameters: /// - db: A database connection. - /// - sql: An SQL query. + /// - sql: An SQL string. /// - arguments: Statement arguments. /// - adapter: Optional RowAdapter /// - returns: An array of rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll( _ db: Database, sql: String, @@ -1290,19 +1603,23 @@ extension Row { /// Returns a set of rows fetched from an SQL query. /// - /// let rows = try Row.fetchSet(db, sql: "SELECT id, name FROM player") // Set - /// for row in rows { - /// let id: Int64 = row[0] - /// let name: String = row[1] - /// } + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT * FROM player WHERE lastName = ?" + /// let rows = try Row.fetchSet(db, sql: sql, arguments: [lastName]) + /// } + /// ``` /// /// - parameters: /// - db: A database connection. - /// - sql: An SQL query. + /// - sql: An SQL string. /// - arguments: Statement arguments. /// - adapter: Optional RowAdapter /// - returns: A set of rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet( _ db: Database, sql: String, @@ -1315,19 +1632,23 @@ extension Row { /// Returns a single row fetched from an SQL query. /// - /// let row = try Row.fetchOne(db, sql: "SELECT id, name FROM player") // Row? - /// if let row = row { - /// let id: Int64 = row[0] - /// let name: String = row[1] - /// } + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT * FROM player WHERE lastName = ? LIMIT 1" + /// let row = try Row.fetchOne(db, sql: sql, arguments: [lastName]) + /// } + /// ``` /// /// - parameters: /// - db: A database connection. - /// - sql: An SQL query. + /// - sql: An SQL string. /// - arguments: Statement arguments. /// - adapter: Optional RowAdapter /// - returns: An optional row. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne( _ db: Database, sql: String, @@ -1345,32 +1666,48 @@ extension Row { /// Returns a cursor over rows fetched from a fetch request. /// - /// let request = Player.all() - /// let rows = try Row.fetchCursor(db, request) // RowCursor - /// while let row = try rows.next() { // Row + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player.filter(Column("lastName") == lastName) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT * FROM player WHERE lastName = \(lastName) + /// """ + /// + /// let rows = try Row.fetchCursor(db, request) + /// while let row = try rows.next() { /// let id: Int64 = row["id"] /// let name: String = row["name"] /// } + /// } + /// ``` /// /// Fetched rows are reused during the cursor iteration: don't turn a row - /// cursor into an array with `Array(rows)` or `rows.filter { ... }` since - /// you would not get the distinct rows you expect. Use `Row.fetchAll(...)` - /// instead. + /// cursor into an array with `Array(rows)` since you would not get the + /// distinct rows you expect. + /// Use ``fetchAll(_:_:)`` instead. /// /// For the same reason, make sure you make a copy whenever you extract a /// row for later use: `row.copy()`. /// + /// The returned cursor is valid only during the remaining execution of the + /// database access. Do not store or return the cursor for later use. + /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// - /// The cursor must be iterated in a protected dispatch queue. - /// /// - parameters: /// - db: A database connection. /// - request: A FetchRequest. - /// - returns: A cursor over fetched rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: R) throws -> RowCursor { + /// - returns: A ``RowCursor`` over fetched rows. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public static func fetchCursor(_ db: Database, _ request: some FetchRequest) throws -> RowCursor { let request = try request.makePreparedRequest(db, forSingleResult: false) precondition(request.supplementaryFetch == nil, "Not implemented: fetchCursor with supplementary fetch") return try fetchCursor(request.statement, adapter: request.adapter) @@ -1378,15 +1715,30 @@ extension Row { /// Returns an array of rows fetched from a fetch request. /// - /// let request = Player.all() + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player.filter(Column("lastName") == lastName) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT * FROM player WHERE lastName = \(lastName) + /// """ + /// /// let rows = try Row.fetchAll(db, request) + /// } + /// ``` /// /// - parameters: /// - db: A database connection. /// - request: A FetchRequest. /// - returns: An array of rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: R) throws -> [Row] { + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Row] { let request = try request.makePreparedRequest(db, forSingleResult: false) let rows = try fetchAll(request.statement, adapter: request.adapter) try request.supplementaryFetch?(db, rows) @@ -1395,15 +1747,30 @@ extension Row { /// Returns a set of rows fetched from a fetch request. /// - /// let request = Player.all() + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player.filter(Column("lastName") == lastName) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT * FROM player WHERE lastName = \(lastName) + /// """ + /// /// let rows = try Row.fetchSet(db, request) + /// } + /// ``` /// /// - parameters: /// - db: A database connection. /// - request: A FetchRequest. /// - returns: A set of rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, _ request: R) throws -> Set { + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set { let request = try request.makePreparedRequest(db, forSingleResult: false) if let supplementaryFetch = request.supplementaryFetch { let rows = try fetchAll(request.statement, adapter: request.adapter) @@ -1416,15 +1783,30 @@ extension Row { /// Returns a single row fetched from a fetch request. /// - /// let request = Player.filter(key: 1) + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player.filter(Column("lastName") == lastName) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT * FROM player WHERE lastName = \(lastName) LIMIT 1 + /// """ + /// /// let row = try Row.fetchOne(db, request) + /// } + /// ``` /// /// - parameters: /// - db: A database connection. /// - request: A FetchRequest. /// - returns: An optional row. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, _ request: R) throws -> Row? { + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Row? { let request = try request.makePreparedRequest(db, forSingleResult: true) guard let row = try fetchOne(request.statement, adapter: request.adapter) else { return nil @@ -1438,88 +1820,116 @@ extension FetchRequest { // MARK: Fetching Rows - /// A cursor over fetched rows. + /// Returns a cursor over fetched rows. /// - /// let request: some FetchRequest = ... - /// let rows = try request.fetchCursor(db) // RowCursor - /// while let row = try rows.next() { // Row - /// let id: Int64 = row[0] - /// let name: String = row[1] + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let request: SQLRequest = """ + /// SELECT * FROM player WHERE lastName = \(lastName) + /// """ + /// let rows = try request.fetchCursor(db) + /// while let row = try rows.next() { + /// let id: Int64 = row["id"] + /// let name: String = row["name"] /// } + /// } + /// ``` /// /// Fetched rows are reused during the cursor iteration: don't turn a row - /// cursor into an array with `Array(rows)` or `rows.filter { ... }` since - /// you would not get the distinct rows you expect. Use `Row.fetchAll(...)` - /// instead. + /// cursor into an array with `Array(rows)` since you would not get the + /// distinct rows you expect. + /// Use ``FetchRequest/fetchAll(_:)-7p809`` instead. /// /// For the same reason, make sure you make a copy whenever you extract a /// row for later use: `row.copy()`. /// + /// The returned cursor is valid only during the remaining execution of the + /// database access. Do not store or return the cursor for later use. + /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// - /// The cursor must be iterated in a protected dispatch queue. - /// /// - parameter db: A database connection. - /// - returns: A cursor over fetched rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: A ``RowCursor`` over fetched rows. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchCursor(_ db: Database) throws -> RowCursor { try Row.fetchCursor(db, self) } - /// An array of fetched rows. + /// Returns an array of fetched rows. /// - /// let request: some FetchRequest = ... + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let request: SQLRequest = """ + /// SELECT * FROM player WHERE lastName = \(lastName) + /// """ /// let rows = try request.fetchAll(db) + /// } + /// ``` /// /// - parameter db: A database connection. /// - returns: An array of fetched rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchAll(_ db: Database) throws -> [Row] { try Row.fetchAll(db, self) } - /// A set of fetched rows. + /// Returns a set of fetched rows. /// - /// let request: some FetchRequest = ... + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let request: SQLRequest = """ + /// SELECT * FROM player WHERE lastName = \(lastName) + /// """ /// let rows = try request.fetchSet(db) + /// } + /// ``` /// /// - parameter db: A database connection. /// - returns: A set of fetched rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchSet(_ db: Database) throws -> Set { try Row.fetchSet(db, self) } - /// The first fetched row. + /// Returns a single row. /// - /// let request: some FetchRequest = ... - /// let row = try request.fetchOne(db) + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let request: SQLRequest = """ + /// SELECT * FROM player WHERE lastName = \(lastName) LIMIT 1 + /// """ + /// let rows = try request.fetchOne(db) + /// } + /// ``` /// /// - parameter db: A database connection. /// - returns: An optional row. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchOne(_ db: Database) throws -> Row? { try Row.fetchOne(db, self) } } -// RandomAccessCollection -extension Row { +extension Row: RandomAccessCollection { + public var startIndex: Index { Index(0) } - // MARK: - Row as a Collection of (ColumnName, DatabaseValue) Pairs + public var endIndex: Index { Index(count) } - /// The index of the first (ColumnName, DatabaseValue) pair. - /// :nodoc: - public var startIndex: RowIndex { RowIndex(0) } - - /// The "past-the-end" index, successor of the index of the last - /// (ColumnName, DatabaseValue) pair. - /// :nodoc: - public var endIndex: RowIndex { RowIndex(count) } - - /// Accesses the (ColumnName, DatabaseValue) pair at given index. - public subscript(position: RowIndex) -> (String, DatabaseValue) { + /// Returns the (column, value) pair at given index. + public subscript(position: Index) -> (String, DatabaseValue) { let index = position.index _checkIndex(index) return ( @@ -1528,12 +1938,9 @@ extension Row { } } -// Equatable -extension Row { - +extension Row: Equatable { /// Returns true if and only if both rows have the same columns and values, /// in the same order. Columns are compared in a case-sensitive way. - /// :nodoc: public static func == (lhs: Row, rhs: Row) -> Bool { if lhs === rhs { return true @@ -1574,9 +1981,7 @@ extension Row { } } -// Hashable -extension Row { - /// :nodoc: +extension Row: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(count) for (column, dbValue) in self { @@ -1586,16 +1991,15 @@ extension Row { } } -// CustomStringConvertible & CustomDebugStringConvertible -extension Row { - /// :nodoc: +extension Row: CustomStringConvertible { public var description: String { "[" - + map { (column, dbValue) in "\(column):\(dbValue)" }.joined(separator: " ") - + "]" + + map { (column, dbValue) in "\(column):\(dbValue)" }.joined(separator: " ") + + "]" } - - /// :nodoc: +} + +extension Row: CustomDebugStringConvertible { public var debugDescription: String { debugDescription(level: 0) } @@ -1638,73 +2042,67 @@ extension Row { } } - -// MARK: - RowIndex - -/// Indexes to (ColumnName, DatabaseValue) pairs in a database row. -public struct RowIndex: Comparable, Strideable { - let index: Int - init(_ index: Int) { self.index = index } +extension Row: ExpressibleByDictionaryLiteral { + /// Creates a row initialized with elements. Column order is preserved, and + /// duplicated columns names are allowed. + /// + /// let row: Row = ["foo": 1, "foo": "bar", "baz": nil] + /// print(row) + /// // Prints [foo:1 foo:"bar" baz:NULL] + public convenience init(dictionaryLiteral elements: (String, (any DatabaseValueConvertible)?)...) { + self.init(impl: ArrayRowImpl(columns: elements.map { ($0, $1?.databaseValue ?? .null) })) + } } -// Comparable -extension RowIndex { - /// :nodoc: - public static func == (lhs: RowIndex, rhs: RowIndex) -> Bool { +// MARK: - Index + +@available(*, deprecated, renamed: "Row.Index") +typealias RowIndex = Row.Index + +extension Row { + /// An index to a (column, value) pair in a ``Row``. + public struct Index { + let index: Int + init(_ index: Int) { self.index = index } + } +} + +extension Row.Index: Equatable { + public static func == (lhs: Self, rhs: Self) -> Bool { lhs.index == rhs.index } - - /// :nodoc: - public static func < (lhs: RowIndex, rhs: RowIndex) -> Bool { +} + +extension Row.Index: Comparable { + public static func < (lhs: Self, rhs: Self) -> Bool { lhs.index < rhs.index } } -// Strideable: support for Row: RandomAccessCollection -extension RowIndex { - /// :nodoc: - public func distance(to other: RowIndex) -> Int { +extension Row.Index: Strideable { + public func distance(to other: Self) -> Int { other.index - index } - /// :nodoc: - public func advanced(by n: Int) -> RowIndex { - RowIndex(index + n) + public func advanced(by n: Int) -> Self { + Row.Index(index + n) } } // MARK: - Row.ScopesView extension Row { - /// A view of the scopes defined by row adapters. It is a collection of - /// tuples made of a scope name and a scoped row, which behaves like a - /// dictionary. + /// A view on the scopes defined by row adapters. /// - /// For example: + /// `ScopesView` is a `Collection` of `(name: String, row: Row)` pairs. /// - /// // Define a tree of nested scopes - /// let adapter = ScopeAdapter([ - /// "foo": RangeRowAdapter(0..<1), - /// "bar": RangeRowAdapter(1..<2).addingScopes([ - /// "baz" : RangeRowAdapter(2..<3)])]) - /// - /// // Fetch - /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" - /// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)! - /// - /// row.scopes.count // 2 - /// row.scopes.names // ["foo", "bar"] - /// - /// row.scopes["foo"] // [foo:1] - /// row.scopes["bar"] // [bar:2] - /// row.scopes["baz"] // nil - public struct ScopesView: Collection { - public typealias Index = Dictionary.Index + /// See ``Row/scopes`` for more information. + public struct ScopesView { private let row: Row private let scopes: [String: any _LayoutedRowAdapter] private let prefetchedRows: Row.PrefetchedRowsView - /// The scopes defined on this row. + /// The available scopes in this row. public var names: Dictionary.Keys { scopes.keys } @@ -1719,73 +2117,57 @@ extension Row { self.prefetchedRows = prefetchedRows } - /// :nodoc: - public var startIndex: Index { - scopes.startIndex - } - - /// :nodoc: - public var endIndex: Index { - scopes.endIndex - } - - /// :nodoc: - public func index(after i: Index) -> Index { - scopes.index(after: i) - } - - /// :nodoc: - public subscript(position: Index) -> (name: String, row: Row) { - let (name, adapter) = scopes[position] - let adaptedRow = Row(base: row, adapter: adapter) - if let prefetch = prefetchedRows.prefetches[name] { - // Let the adapted row access its own prefetched rows. - // Use case: - // - // let request = A.including(required: A.b.including(all: B.c)) - // let row = try Row.fetchOne(db, request)! - // row.prefetchedRows["cs"] // Some array - // row.scopes["b"]!.prefetchedRows["cs"] // The same array - adaptedRow.prefetchedRows = Row.PrefetchedRowsView(prefetches: prefetch.prefetches) - } - return (name: name, row: adaptedRow) - } - - /// Returns the row associated with the given scope, or nil if the - /// scope is not defined. + /// The row associated with the given scope, or nil if the scope is + /// not available. public subscript(_ name: String) -> Row? { scopes.index(forKey: name).map { self[$0].row } } } } +extension Row.ScopesView: Collection { + public typealias Index = Dictionary.Index + + public var startIndex: Index { + scopes.startIndex + } + + public var endIndex: Index { + scopes.endIndex + } + + public func index(after i: Index) -> Index { + scopes.index(after: i) + } + + public subscript(position: Index) -> (name: String, row: Row) { + let (name, adapter) = scopes[position] + let adaptedRow = Row(base: row, adapter: adapter) + if let prefetch = prefetchedRows.prefetches[name] { + // Let the adapted row access its own prefetched rows. + // Use case: + // + // let request = A.including(required: A.b.including(all: B.c)) + // let row = try Row.fetchOne(db, request)! + // row.prefetchedRows["cs"] // Some array + // row.scopes["b"]!.prefetchedRows["cs"] // The same array + adaptedRow.prefetchedRows = Row.PrefetchedRowsView(prefetches: prefetch.prefetches) + } + return (name: name, row: adaptedRow) + } +} + // MARK: - Row.ScopesTreeView extension Row { /// A view on the scopes tree defined by row adapters. /// - /// For example: - /// - /// // Define a tree of nested scopes - /// let adapter = ScopeAdapter([ - /// "foo": RangeRowAdapter(0..<1), - /// "bar": RangeRowAdapter(1..<2).addingScopes([ - /// "baz" : RangeRowAdapter(2..<3)])]) - /// - /// // Fetch - /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" - /// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)! - /// - /// row.scopesTree.names // ["foo", "bar", "baz"] - /// - /// row.scopesTree["foo"] // [foo:1] - /// row.scopesTree["bar"] // [bar:2] - /// row.scopesTree["baz"] // [baz:3] + /// See ``Row/scopesTree`` for more information. public struct ScopesTreeView { let scopes: ScopesView - /// The scopes defined on this row, recursively. + /// The scopes available on this row, recursively. public var names: Set { var names = Set() for (name, row) in scopes { @@ -1795,33 +2177,12 @@ extension Row { return names } - /// Returns the row associated with the given scope. + /// The row associated with the given scope, or nil if the scope is + /// not available. /// - /// For example: + /// See ``Row/scopesTree`` for more information. /// - /// let request = Book.including(required: Book.author) - /// let row = try Row.fetchOne(db, request)! - /// - /// print(row) - /// // Prints [id:42 title:"Moby-Dick"] - /// - /// let authorRow = row.scopesTree["author"] - /// print(authorRow) - /// // Prints [id:1 name:"Herman Melville"] - /// - /// Associated rows stored in nested associations are available, too: - /// - /// let request = Book.including(required: Book.author.including(required: Author.country)) - /// let row = try Row.fetchOne(db, request)! - /// - /// print(row) - /// // Prints [id:42 title:"Moby-Dick"] - /// - /// let countryRow = row.scopesTree["country"] - /// print(countryRow) - /// // Prints [code:"US" name:"United States"] - /// - /// Nil is returned if the scope is not available. + /// - parameter key: An association key. public subscript(_ name: String) -> Row? { var fifo = Array(scopes) while !fifo.isEmpty { @@ -1849,36 +2210,43 @@ extension Row { /// A view on the prefetched associated rows. /// - /// For example: - /// - /// let request = Author.including(all: Author.books) - /// let row = try Row.fetchOne(db, request)! - /// - /// print(row) - /// // Prints [id:1 name:"Herman Melville"] - /// - /// let bookRows = row.prefetchedRows["books"] - /// print(bookRows[0]) - /// // Prints [id:42 title:"Moby-Dick"] + /// See ``Row/prefetchedRows`` for more information. public struct PrefetchedRowsView: Equatable { // OrderedDictionary so that breadth-first search gives a consistent result // (we preserve the ordering of associations in the request) fileprivate var prefetches: OrderedDictionary = [:] - /// True if there is no prefetched associated rows. + /// A boolean value indicating if there is no prefetched + /// associated rows. public var isEmpty: Bool { prefetches.isEmpty } - /// The keys for available prefetched rows + /// The available association keys. + /// + /// Keys in the returned set can be used with ``subscript(_:)``. /// /// For example: /// - /// let request = Author.including(all: Author.books) - /// let row = try Row.fetchOne(db, request)! + /// ```swift + /// struct Author: TableRecord { + /// static let books = hasMany(Book.self) + /// } /// - /// print(row.prefetchedRows.keys) - /// // Prints ["books"] + /// struct Book: TableRecord { } + /// + /// let request = Author.including(all: Author.books) + /// let authorRow = try Row.fetchOne(db, request)! + /// + /// print(authorRow.prefetchedRows.keys) + /// // Prints ["books"] + /// + /// let bookRows = authorRow.prefetchedRows["books"]! + /// print(bookRows[0]) + /// // Prints [id:42, title:"Moby-Dick", authorId:1] + /// print(bookRows[1]) + /// // Prints [id:57, title:"Pierre", authorId:1] + /// ``` public var keys: Set { var result: Set = [] var fifo = Array(prefetches) @@ -1892,24 +2260,13 @@ extension Row { return result } - /// Returns the prefetched rows associated with the given key. + /// The prefetched rows associated with the given association key. /// - /// For example: + /// The result is nil if the key is not available. /// - /// let request = Author.including(all: Author.books) - /// let row = try Row.fetchOne(db, request)! + /// See ``Row/prefetchedRows`` for more information. /// - /// print(row) - /// // Prints [id:1 name:"Herman Melville"] - /// - /// let bookRows = row.prefetchedRows["books"] - /// print(bookRows[0]) - /// // Prints [id:42 title:"Moby-Dick"] - /// - /// Prefetched rows stored in nested "to-one" associations are - /// available, too. - /// - /// Nil is returned if the key is not available. + /// - parameter key: An association key. public subscript(_ key: String) -> [Row]? { var fifo = Array(prefetches) while !fifo.isEmpty { @@ -1959,9 +2316,7 @@ protocol RowImpl { atUncheckedIndex index: Int) throws -> Value - func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data - - func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? + func withUnsafeData(atUncheckedIndex index: Int, _ body: (Data?) throws -> T) throws -> T /// Returns the index of the leftmost column that matches *name* (case-insensitive) func index(forColumn name: String) -> Int? @@ -2009,18 +2364,12 @@ extension RowImpl { context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index))) } - func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data { + func withUnsafeData(atUncheckedIndex index: Int, _ body: (Data?) throws -> T) throws -> T { // unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization) - try Data.decode( - fromDatabaseValue: databaseValue(atUncheckedIndex: index), - context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index))) - } - - func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? { - // unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization) - try Optional.decode( + let data = try Optional.decode( fromDatabaseValue: databaseValue(atUncheckedIndex: index), context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index))) + return try body(data) } } @@ -2096,7 +2445,6 @@ private struct StatementCopyRowImpl: RowImpl { } } - /// See Row.init(statement:) private struct StatementRowImpl: RowImpl { let statement: Statement @@ -2142,26 +2490,17 @@ private struct StatementRowImpl: RowImpl { context: RowDecodingContext(statement: statement, index: index)) } - func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data { + func withUnsafeData(atUncheckedIndex index: Int, _ body: (Data?) throws -> T) throws -> T { guard sqlite3_column_type(sqliteStatement, CInt(index)) != SQLITE_NULL else { - throw RowDecodingError.valueMismatch(Data.self, statement: statement, index: index) + return try body(nil) } guard let bytes = sqlite3_column_blob(sqliteStatement, CInt(index)) else { - return Data() + return try body(Data()) } + let count = Int(sqlite3_column_bytes(sqliteStatement, CInt(index))) - return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none) - } - - func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? { - guard sqlite3_column_type(sqliteStatement, CInt(index)) != SQLITE_NULL else { - return nil - } - guard let bytes = sqlite3_column_blob(sqliteStatement, CInt(index)) else { - return Data() - } - let count = Int(sqlite3_column_bytes(sqliteStatement, CInt(index))) - return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none) + let data = Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none) + return try body(data) } func columnName(atUncheckedIndex index: Int) -> String { diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index 18f24625b..c3902faab 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -5,19 +5,21 @@ import Foundation /// /// For example: /// -/// let sql = "SELECT 1, 2,3,4, 5,6, 7,8" -/// // <.><. . .><. .><. .> -/// let adapters = splittingRowAdapters([1, 3, 2]) -/// let adapter = ScopeAdapter([ -/// "a": adapters[0], -/// "b": adapters[1], -/// "c": adapters[2], -/// "d": adapters[3]]) -/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter) -/// row.scopes["a"] // [1] -/// row.scopes["b"] // [2, 3, 4] -/// row.scopes["c"] // [5, 6] -/// row.scopes["d"] // [7, 8] +/// ```swift +/// let sql = "SELECT 1, 2,3,4, 5,6, 7,8" +/// // <.><. . .><. .><. .> +/// let adapters = splittingRowAdapters([1, 3, 2]) +/// let adapter = ScopeAdapter([ +/// "a": adapters[0], +/// "b": adapters[1], +/// "c": adapters[2], +/// "d": adapters[3]]) +/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter) +/// row.scopes["a"] // [1] +/// row.scopes["b"] // [2, 3, 4] +/// row.scopes["c"] // [5, 6] +/// row.scopes["d"] // [7, 8] +/// ``` public func splittingRowAdapters(columnCounts: [Int]) -> [any RowAdapter] { guard !columnCounts.isEmpty else { // Identity adapter @@ -41,8 +43,6 @@ public func splittingRowAdapters(columnCounts: [Int]) -> [any RowAdapter] { } /// _LayoutedColumnMapping is a type that supports the RowAdapter protocol. -/// -/// :nodoc: public struct _LayoutedColumnMapping { /// An array of (baseIndex, mappedName) pairs, where baseIndex is the index /// of a column in a base row, and mappedName the mapped name of @@ -93,7 +93,6 @@ public struct _LayoutedColumnMapping { } } -/// :nodoc: extension _LayoutedColumnMapping: _LayoutedRowAdapter { /// Returns self. public var _mapping: _LayoutedColumnMapping { self } @@ -102,7 +101,6 @@ extension _LayoutedColumnMapping: _LayoutedRowAdapter { public var _scopes: [String: any _LayoutedRowAdapter] { [:] } } -/// :nodoc: extension _LayoutedColumnMapping: _RowLayout { /// Returns the index of the leftmost column named `name`, in a /// case-insensitive way. @@ -118,8 +116,6 @@ extension _LayoutedColumnMapping: _RowLayout { /// /// GRBD ships with a ready-made type that adopts this protocol: /// `_LayoutedColumnMapping`. -/// -/// :nodoc: public protocol _LayoutedRowAdapter { /// A LayoutedColumnMapping that defines how to map a column name to a /// column in a base row. @@ -131,8 +127,6 @@ public protocol _LayoutedRowAdapter { /// `_RowLayout` is a protocol that supports the `RowAdapter` protocol. It /// describes the layout of a base row. -/// -/// :nodoc: public protocol _RowLayout { /// An array of (baseIndex, name) pairs, where baseIndex is the index /// of a column in a base row, and name the name of that column. @@ -144,21 +138,45 @@ public protocol _RowLayout { } extension Statement: _RowLayout { - /// :nodoc: public var _layoutColumns: [(Int, String)] { Array(columnNames.enumerated()) } - /// :nodoc: public func _layoutIndex(ofColumn name: String) -> Int? { index(ofColumn: name) } } -/// Implementation details of `RowAdapter`. +/// A type that helps two incompatible row interfaces working together. /// -/// :nodoc: -public protocol _RowAdapter { +/// You provide row adapters to methods that fetch. For example: +/// +/// ```swift +/// try dbQueue.read { +/// // An adapter that ignores the first two columns +/// let adapter = SuffixRowAdapter(fromIndex: 2) +/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" +/// +/// // [baz:3] +/// try Row.fetchOne(db, sql: sql, adapter: adapter) +/// } +/// ``` +/// +/// ## Topics +/// +/// ### Splitting a Row +/// +/// - ``splittingRowAdapters(columnCounts:)`` +/// +/// ### Built-in Adapters +/// +/// - ``ColumnMapping`` +/// - ``EmptyRowAdapter`` +/// - ``RangeRowAdapter`` +/// - ``RenameColumnAdapter`` +/// - ``ScopeAdapter`` +/// - ``SuffixRowAdapter`` +public protocol RowAdapter { /// You never call this method directly. It is called for you whenever an /// adapter has to be applied. /// @@ -181,27 +199,6 @@ public protocol _RowAdapter { func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter } -/// `RowAdapter` is a protocol that helps two incompatible row interfaces -/// working together. -/// -/// GRDB ships with four concrete types that adopt the RowAdapter protocol: -/// -/// - `ColumnMapping`: renames row columns -/// - `EmptyRowAdapter`: hides all columns -/// - `RangeRowAdapter`: exposes a range of columns -/// - `RenameColumnAdapter`: transforms column names with a function -/// - `ScopeAdapter`: defines row scopes -/// - `SuffixRowAdapter`: hides the first columns of a row -/// -/// To use a row adapter, provide it to any method that fetches: -/// -/// let adapter = SuffixRowAdapter(fromIndex: 2) -/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" -/// -/// // [baz:3] -/// try Row.fetchOne(db, sql: sql, adapter: adapter) -public protocol RowAdapter: _RowAdapter { } - extension RowAdapter { /// Returns an adapter based on self, with added scopes. /// @@ -230,7 +227,6 @@ public struct EmptyRowAdapter: RowAdapter { /// Creates an EmptyRowAdapter public init() { } - /// :nodoc: public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter { _LayoutedColumnMapping(layoutColumns: []) } @@ -253,7 +249,6 @@ public struct ColumnMapping: RowAdapter { self.mapping = mapping } - /// :nodoc: public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter { let layoutColumns = try mapping .map { (mappedColumn, baseColumn) -> (Int, String) in @@ -294,7 +289,6 @@ public struct SuffixRowAdapter: RowAdapter { self.index = index } - /// :nodoc: public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter { _LayoutedColumnMapping(layoutColumns: layout._layoutColumns.suffix(from: index)) } @@ -323,7 +317,6 @@ public struct RangeRowAdapter: RowAdapter { self.range = range.lowerBound..<(range.upperBound + 1) } - /// :nodoc: public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter { _LayoutedColumnMapping(layoutColumns: layout._layoutColumns[range]) } @@ -399,7 +392,6 @@ public struct ScopeAdapter: RowAdapter { self.scopes = scopes } - /// :nodoc: public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter { let layoutedAdapter = try base._layoutedAdapter(from: layout) var layoutedScopes = layoutedAdapter._scopes @@ -445,7 +437,6 @@ public struct RenameColumnAdapter: RowAdapter { self.transform = transform } - /// :nodoc: public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter { let layoutColumns = layout._layoutColumns.map { (index, column) in (index, transform(column)) } return _LayoutedColumnMapping(layoutColumns: layoutColumns) @@ -505,14 +496,9 @@ struct AdaptedRowImpl: RowImpl { return try Value.fastDecode(fromRow: base, atUncheckedIndex: mappedIndex) } - func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data { + func withUnsafeData(atUncheckedIndex index: Int, _ body: (Data?) throws -> T) throws -> T { let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index) - return try base.impl.fastDecodeDataNoCopy(atUncheckedIndex: mappedIndex) - } - - func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? { - let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index) - return try base.impl.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: mappedIndex) + return try base.impl.withUnsafeData(atUncheckedIndex: mappedIndex, body) } func columnName(atUncheckedIndex index: Int) -> String { diff --git a/GRDB/Core/SQL.swift b/GRDB/Core/SQL.swift index c43991798..644251c81 100644 --- a/GRDB/Core/SQL.swift +++ b/GRDB/Core/SQL.swift @@ -1,14 +1,44 @@ -/// `SQL` helps you build SQL literal with -/// [SQL Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md). +/// An SQL literal. /// -/// For example: +/// ``SQL`` literals allow you to safely embed raw values in your SQL, +/// without any risk of syntax errors or SQL injection. For example: /// -/// try dbQueue.write { db in -/// let name: String = ... -/// let id: Int64 = ... -/// let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)" -/// try db.execute(literal: query) -/// } +/// ```swift +/// try dbQueue.write { db in +/// let name: String = "O'Brien" +/// let id: Int64 = 42 +/// let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)" +/// +/// // UPDATE player SET name = 'O''Brien' WHERE id = 42 +/// try db.execute(literal: query) +/// } +/// ``` +/// +/// ## Topics +/// +/// ### Creating an SQL Literal from a Literal Value +/// +/// - ``init(stringLiteral:)`` +/// - ``init(unicodeScalarLiteral:)-7p0al`` +/// - ``init(extendedGraphemeClusterLiteral:)-1oham`` +/// +/// ### Creating an SQL Literal from an Interpolation +/// +/// - ``init(stringInterpolation:)`` +/// - ``SQLInterpolation`` +/// +/// ### Creating an SQL Literal from an SQL String +/// +/// - ``init(sql:arguments:)`` +/// +/// ### Creating an SQL Literal from an SQL Expression +/// +/// - ``init(_:)`` +/// +/// ### Concatenating SQL Literals +/// +/// - ``append(literal:)`` +/// - ``append(sql:arguments:)`` public struct SQL { /// `SQL.Element` is a component of an `SQL` literal. /// @@ -118,9 +148,11 @@ public struct SQL { /// /// For example: /// - /// let query = SQL( - /// sql: "UPDATE player SET name = ? WHERE id = ?", - /// arguments: [name, id]) + /// ```swift + /// let query = SQL( + /// sql: "UPDATE player SET name = ? WHERE id = ?", + /// arguments: [name, id]) + /// ``` public init(sql: String, arguments: StatementArguments = StatementArguments()) { self.init(elements: [.sql(sql, arguments)]) } @@ -129,11 +161,13 @@ public struct SQL { /// /// For example: /// - /// let columnLiteral = SQL(Column("username")) - /// let suffixLiteral = SQL("@example.com".databaseValue) - /// let emailLiteral = [columnLiteral, suffixLiteral].joined(separator: " || ") - /// let request = User.select(emailLiteral.sqlExpression) - /// let emails = try String.fetchAll(db, request) + /// ```swift + /// let columnLiteral = SQL(Column("username")) + /// let suffixLiteral = SQL("@example.com".databaseValue) + /// let emailLiteral = [columnLiteral, suffixLiteral].joined(separator: " || ") + /// let request = User.select(emailLiteral.sqlExpression) + /// let emails = try String.fetchAll(db, request) + /// ``` public init(_ expression: some SQLSpecificExpressible) { self.init(elements: [.expression(expression.sqlExpression)]) } @@ -166,10 +200,14 @@ public struct SQL { extension SQL { /// Returns the `SQL` literal produced by the concatenation of two literals. /// - /// let name = "O'Brien" - /// let selection: SQL = "SELECT * FROM player " - /// let condition: SQL = "WHERE name = \(name)" - /// let query = selection + condition + /// For example: + /// + /// ```swift + /// let name = "O'Brien" + /// let selection: SQL = "SELECT * FROM player " + /// let condition: SQL = "WHERE name = \(name)" + /// let query = selection + condition + /// ``` public static func + (lhs: SQL, rhs: SQL) -> SQL { var result = lhs result += rhs @@ -178,27 +216,39 @@ extension SQL { /// Appends an `SQL` literal to the receiver. /// - /// let name = "O'Brien" - /// var query: SQL = "SELECT * FROM player " - /// query += "WHERE name = \(name)" + /// For example: + /// + /// ```swift + /// let name = "O'Brien" + /// var query: SQL = "SELECT * FROM player " + /// query += "WHERE name = \(name)" + /// ``` public static func += (lhs: inout SQL, rhs: SQL) { lhs.elements += rhs.elements } /// Appends an `SQL` literal to the receiver. /// - /// let name = "O'Brien" - /// var query: SQL = "SELECT * FROM player " - /// query.append(literal: "WHERE name = \(name)") + /// For example: + /// + /// ```swift + /// let name = "O'Brien" + /// var query: SQL = "SELECT * FROM player " + /// query.append(literal: "WHERE name = \(name)") + /// ``` public mutating func append(literal sqlLiteral: SQL) { self += sqlLiteral } /// Appends a plain SQL string to the receiver, and eventual arguments. /// - /// let name = "O'Brien" - /// var query: SQL = "SELECT * FROM player " - /// query.append(sql: "WHERE name = ?", arguments: [name]) + /// For example: + /// + /// ```swift + /// let name = "O'Brien" + /// var query: SQL = "SELECT * FROM player " + /// query.append(sql: "WHERE name = ?", arguments: [name]) + /// ``` public mutating func append(sql: String, arguments: StatementArguments = StatementArguments()) { self += SQL(sql: sql, arguments: arguments) } @@ -210,39 +260,56 @@ extension SQL: SQLSpecificExpressible { /// Use this property when you need an explicit `SQLExpression`. /// For example: /// - /// func date(_ value: some SQLExpressible) -> SQLExpression { - /// SQL("DATE(\(value))").sqlExpression - /// } + /// ```swift + /// func date(_ value: some SQLExpressible) -> SQLExpression { + /// SQL("DATE(\(value))").sqlExpression + /// } /// - /// // SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23' - /// let createdAt = Column("createdAt") - /// let request = Player.filter(date(createdAt) == "2020-01-23") + /// // SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23' + /// let createdAt = Column("createdAt") + /// let request = Player.filter(date(createdAt) == "2020-01-23") + /// ``` public var sqlExpression: SQLExpression { .literal(self) } } extension SQL: SQLSelectable { - /// Creates a literal SQL expression. + /// Creates a literal SQL result column. /// /// Use this property when you need an explicit `SQLSelection`. For example: /// - /// // SELECT firstName AS givenName, lastName AS familyName FROM player - /// let selection = SQL("firstName AS givenName, lastName AS familyName").sqlSelection - /// let request = Player.select(selection) + /// ```swift + /// // SELECT firstName AS givenName, lastName AS familyName FROM player + /// let selection = SQL("firstName AS givenName, lastName AS familyName").sqlSelection + /// let request = Player.select(selection) + /// ``` public var sqlSelection: SQLSelection { .literal(self) } } extension SQL: SQLOrderingTerm { - /// Creates a literal SQL ordering. + /// Creates a literal SQL ordering term. /// /// Use this property when you need an explicit `SQLOrdering`. For example: /// - /// // SELECT * FROM player ORDER BY name DESC - /// let ordering = SQL("name DESC").sqlOrdering - /// let request = Player.order(ordering) + /// ```swift + /// // SELECT * FROM player ORDER BY name DESC + /// let ordering = SQL("name DESC").sqlOrdering + /// let request = Player.order(ordering) + /// ``` + /// + /// An ordering term is only valid if it represent a single ordering terms. + /// + /// ```swift + /// // Valid + /// SQL("score DESC").sqlOrdering + /// SQL("name").sqlOrdering + /// + /// // Invalid + /// SQL("score DESC, name").sqlOrdering + /// ``` public var sqlOrdering: SQLOrdering { .literal(self) } @@ -254,15 +321,16 @@ extension Sequence where Element == SQL { /// /// For example: /// - /// let components: [SQL] = [ - /// "UPDATE player", - /// "SET name = \(name)", - /// "WHERE id = \(id)" - /// ] - /// let query = components.joined(separator: " ") + /// ``` + /// let components: [SQL] = [ + /// "UPDATE player", + /// "SET name = \(name)", + /// "WHERE id = \(id)" + /// ] + /// let query = components.joined(separator: " ") + /// ``` /// - /// - Note: The separator is a raw SQL string, not an SQL literal that - /// supports [SQL Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md). + /// - Note: The separator is a raw SQL string, not an ``SQL`` literal. public func joined(separator: String = "") -> SQL { if separator.isEmpty { return SQL(elements: flatMap(\.elements)) @@ -278,15 +346,16 @@ extension Collection where Element == SQL { /// /// For example: /// - /// let components: [SQL] = [ - /// "UPDATE player", - /// "SET name = \(name)", - /// "WHERE id = \(id)" - /// ] - /// let query = components.joined(separator: " ") + /// ```swift + /// let components: [SQL] = [ + /// "UPDATE player", + /// "SET name = \(name)", + /// "WHERE id = \(id)" + /// ] + /// let query = components.joined(separator: " ") + /// ``` /// - /// - Note: The separator is a raw SQL string, not an SQL literal that - /// supports [SQL Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md). + /// - Note: The separator is a raw SQL string, not an ``SQL`` literal. public func joined(separator: String = "") -> SQL { if separator.isEmpty { return SQL(elements: flatMap(\.elements)) @@ -299,22 +368,19 @@ extension Collection where Element == SQL { // MARK: - ExpressibleByStringInterpolation extension SQL: ExpressibleByStringInterpolation { - /// :nodoc public init(unicodeScalarLiteral: String) { self.init(sql: unicodeScalarLiteral, arguments: []) } - /// :nodoc: public init(extendedGraphemeClusterLiteral: String) { self.init(sql: extendedGraphemeClusterLiteral, arguments: []) } - - /// :nodoc: + + /// Creates an `SQL` literal from the given literal SQL string. public init(stringLiteral: String) { self.init(sql: stringLiteral, arguments: []) } - /// :nodoc: public init(stringInterpolation sqlInterpolation: SQLInterpolation) { self.init(elements: sqlInterpolation.elements) } diff --git a/GRDB/Core/SQLInterpolation.swift b/GRDB/Core/SQLInterpolation.swift index 2ed497066..ec0dfe0bb 100644 --- a/GRDB/Core/SQLInterpolation.swift +++ b/GRDB/Core/SQLInterpolation.swift @@ -1,4 +1,3 @@ -/// :nodoc: public struct SQLInterpolation: StringInterpolationProtocol { var elements: [SQL.Element] diff --git a/GRDB/Core/SQLRequest.swift b/GRDB/Core/SQLRequest.swift index 1d97599e2..a9e6304e4 100644 --- a/GRDB/Core/SQLRequest.swift +++ b/GRDB/Core/SQLRequest.swift @@ -1,4 +1,44 @@ -/// A FetchRequest built from raw SQL. +/// An SQL request that can decode database rows. +/// +/// `SQLRequest` allows you to safely embed raw values in your SQL, +/// without any risk of syntax errors or SQL injection: +/// +/// ```swift +/// extension Player { +/// static func filter(name: String) -> SQLRequest { +/// "SELECT * FROM player WHERE name = \(name)" +/// } +/// } +/// +/// try dbQueue.read { db in +/// let players = try Player.filter(name: "O'Brien").fetchAll(db) +/// } +/// ``` +/// +/// An `SQLRequest` can be created from a string literal, as in the above +/// example, or from one of the initializers documented below. +/// +/// ## Topics +/// +/// ### Creating an SQL Request from a Literal Value +/// +/// - ``init(stringLiteral:)`` +/// - ``init(unicodeScalarLiteral:)-84mq8`` +/// - ``init(extendedGraphemeClusterLiteral:)-1sf75`` +/// +/// ### Creating an SQL Request from an Interpolation +/// +/// - ``init(stringInterpolation:)`` +/// +/// ### Creating an SQL Request from an SQL Literal +/// +/// - ``init(literal:adapter:cached:)-4vuxn`` +/// - ``init(literal:adapter:cached:)-82f97`` +/// +/// ### Creating an SQL Request from an SQL String +/// +/// - ``init(sql:arguments:adapter:cached:)-3qq8t`` +/// - ``init(sql:arguments:adapter:cached:)-5ecx2`` public struct SQLRequest { /// There are two statement caches: one "public" for statements generated by /// the user, and one "internal" for the statements generated by GRDB. Those @@ -12,7 +52,7 @@ public struct SQLRequest { case `internal` } - /// The request adapter + /// The row adapter. public var adapter: (any RowAdapter)? private(set) var sqlLiteral: SQL @@ -31,23 +71,23 @@ public struct SQLRequest { } extension SQLRequest { - /// Creates a request from an SQL string, optional arguments, and - /// optional row adapter. + /// Creates a request from an SQL string. /// - /// let request = SQLRequest(sql: """ - /// SELECT name FROM player - /// """) - /// let request = SQLRequest(sql: """ - /// SELECT * FROM player WHERE id = ? - /// """, arguments: [1]) + /// ```swift + /// let request = SQLRequest(sql: """ + /// SELECT name FROM player + /// """) + /// let request = SQLRequest(sql: """ + /// SELECT * FROM player WHERE name = ? + /// """, arguments: ["O'Brien"]) + /// ``` /// /// - parameters: - /// - sql: An SQL query. + /// - sql: An SQL string. /// - arguments: Statement arguments. /// - adapter: Optional RowAdapter. /// - cached: Defaults to false. If true, the request reuses a cached /// prepared statement. - /// - returns: A SQLRequest public init( sql: String, arguments: StatementArguments = StatementArguments(), @@ -61,22 +101,23 @@ extension SQLRequest { type: RowDecoder.self) } - /// Creates a request from an `SQL` literal, and optional row adapter. + /// Creates a request from an ``SQL`` literal. /// - /// Literals allow you to safely embed raw values in your SQL, without any - /// risk of syntax errors or SQL injection: + /// ``SQL`` literals allow you to safely embed raw values in your SQL, + /// without any risk of syntax errors or SQL injection: /// - /// let name = "O'brien" - /// let request = SQLRequest(literal: """ - /// SELECT * FROM player WHERE name = \(name) - /// """) + /// ```swift + /// let name = "O'Brien" + /// let request = SQLRequest(literal: """ + /// SELECT * FROM player WHERE name = \(name) + /// """) + /// ``` /// /// - parameters: /// - sqlLiteral: An `SQL` literal. /// - adapter: Optional RowAdapter. /// - cached: Defaults to false. If true, the request reuses a cached /// prepared statement. - /// - returns: A SQLRequest public init(literal sqlLiteral: SQL, adapter: (any RowAdapter)? = nil, cached: Bool = false) { self.init( literal: sqlLiteral, @@ -87,20 +128,20 @@ extension SQLRequest { } extension SQLRequest { - /// Creates a request from an SQL string, optional arguments, and - /// optional row adapter. + /// Creates a request of database rows, from an SQL string. /// - /// let request = SQLRequest(sql: """ - /// SELECT * FROM player WHERE id = ? - /// """, arguments: [1]) + /// ```swift + /// let request = SQLRequest(sql: """ + /// SELECT * FROM player WHERE name = ? + /// """, arguments: ["O'Brien"]) + /// ``` /// /// - parameters: - /// - sql: An SQL query. + /// - sql: An SQL string. /// - arguments: Statement arguments. /// - adapter: Optional RowAdapter. /// - cached: Defaults to false. If true, the request reuses a cached /// prepared statement. - /// - returns: A SQLRequest public init( sql: String, arguments: StatementArguments = StatementArguments(), @@ -114,22 +155,23 @@ extension SQLRequest { type: Row.self) } - /// Creates a request from an `SQL` literal, and optional row adapter. + /// Creates a request of database rows, from an ``SQL`` literal. /// - /// Literals allow you to safely embed raw values in your SQL, without any - /// risk of syntax errors or SQL injection: + /// ``SQL`` literals allow you to safely embed raw values in your SQL, + /// without any risk of syntax errors or SQL injection: /// - /// let name = "O'brien" - /// let request = SQLRequest(literal: """ - /// SELECT * FROM player WHERE name = \(name) - /// """) + /// ```swift + /// let name = "O'Brien" + /// let request = SQLRequest(literal: """ + /// SELECT * FROM player WHERE name = \(name) + /// """) + /// ``` /// /// - parameters: /// - sqlLiteral: An `SQL` literal. /// - adapter: Optional RowAdapter. /// - cached: Defaults to false. If true, the request reuses a cached /// prepared statement. - /// - returns: A SQLRequest public init(literal sqlLiteral: SQL, adapter: (any RowAdapter)? = nil, cached: Bool = false) { self.init( literal: sqlLiteral, @@ -170,22 +212,19 @@ extension SQLRequest: FetchRequest { } extension SQLRequest: ExpressibleByStringInterpolation { - /// :nodoc public init(unicodeScalarLiteral: String) { self.init(sql: unicodeScalarLiteral) } - /// :nodoc: public init(extendedGraphemeClusterLiteral: String) { self.init(sql: extendedGraphemeClusterLiteral) } - /// :nodoc: + /// Creates an `SQLRequest` from the given literal SQL string. public init(stringLiteral: String) { self.init(sql: stringLiteral) } - /// :nodoc: public init(stringInterpolation sqlInterpolation: SQLInterpolation) { self.init(literal: SQL(stringInterpolation: sqlInterpolation)) } diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 6ba7f5bf1..7567b128b 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -25,7 +25,59 @@ extension String { } } -/// A statement represents an SQL query. +/// A prepared statement. +/// +/// You create prepared statements from a ``Database`` instance. For example: +/// +/// ```swift +/// try dbQueue.write { db in +/// let statement = try db.makeStatement(sql: """ +/// DELETE FROM player WHERE id = ? +/// """) +/// try statement.execute(arguments: [1])! +/// try statement.execute(arguments: [12])! +/// } +/// ``` +/// +/// To fetch rows and values from a prepared statement, use a fetching method of +///``Row``, ``DatabaseValueConvertible``, or ``FetchableRecord``: +/// +/// ```swift +/// try dbQueue.read { db in +/// let statement = try db.makeStatement(sql: """ +/// SELECT name FROM player WHERE id = ? +/// """) +/// let name1 = try String.fetchOne(statement, arguments: [1])! +/// let name2 = try String.fetchOne(statement, arguments: [12])! +/// } +/// ``` +/// +/// Related SQLite documentation: +/// +/// ## Topics +/// +/// ### Executing a Prepared Statement +/// +/// - ``execute(arguments:)`` +/// +/// ### Arguments +/// +/// - ``arguments`` +/// - ``setArguments(_:)`` +/// - ``setUncheckedArguments(_:)`` +/// - ``validateArguments(_:)`` +/// - ``StatementArguments`` +/// +/// ### Statement Informations +/// +/// - ``columnCount`` +/// - ``columnNames`` +/// - ``databaseRegion`` +/// - ``index(ofColumn:)`` +/// - ``isReadonly`` +/// - ``sql`` +/// - ``sqliteStatement`` +/// - ``SQLiteStatement`` public final class Statement { enum TransactionEffect { case beginTransaction @@ -39,7 +91,7 @@ public final class Statement { /// The raw SQLite statement, suitable for the SQLite C API. public let sqliteStatement: SQLiteStatement - /// The SQL query + /// The SQL query. public var sql: String { SchedulingWatchdog.preconditionValidQueue(database) @@ -69,15 +121,15 @@ public final class Statement { /// The effects on the database (reported by `sqlite3_set_authorizer`). private(set) var authorizerEventKinds: [DatabaseEventKind] = [] - /// Returns true if and only if the prepared statement makes no direct + /// A boolean value indicating if the prepared statement makes no direct /// changes to the content of the database file. /// - /// See . + /// Related SQLite documentation: . public var isReadonly: Bool { sqlite3_stmt_readonly(sqliteStatement) != 0 } - /// Returns whether the statement deletes some rows + /// A boolean value indicating if the statement deletes some rows. var isDeleteStatement: Bool { authorizerEventKinds.contains(where: \.isDelete) } @@ -185,22 +237,26 @@ public final class Statement { } } - /// Throws a DatabaseError of code SQLITE_ERROR if arguments don't fill all - /// statement arguments. + /// Throws a ``DatabaseError`` of code `SQLITE_ERROR` if arguments don't + /// fill all statement arguments. /// /// For example: /// - /// let statement = try db.makeUpdateArgument(sql: """ - /// INSERT INTO player (id, name) VALUES (?, ?) - /// """) + /// ```swift + /// let statement = try db.makeUpdateArgument(sql: """ + /// INSERT INTO player (id, name) VALUES (?, ?) + /// """) /// - /// // OK - /// statement.validateArguments([1, "Arthur"]) + /// // OK + /// statement.validateArguments([1, "Arthur"]) /// - /// // Throws - /// statement.validateArguments([1]) + /// // Throws + /// statement.validateArguments([1]) + /// ``` /// - /// See also setArguments(_:) + /// See also ``setArguments(_:)``. + /// + /// - throws: A ``DatabaseError`` if `arguments` don't fit the expected ones. public func validateArguments(_ arguments: StatementArguments) throws { var arguments = arguments _ = try arguments.extractBindings(forStatement: self, allowingRemainingValues: false) @@ -213,20 +269,22 @@ public final class Statement { /// /// For example: /// - /// let statement = try db.makeUpdateArgument(sql: """ - /// INSERT INTO player (id, name) VALUES (?, ?) - /// """) + /// ```swift + /// let statement = try db.makeUpdateArgument(sql: """ + /// INSERT INTO player (id, name) VALUES (?, ?) + /// """) /// - /// // OK - /// statement.setUncheckedArguments([1, "Arthur"]) + /// // OK + /// statement.setUncheckedArguments([1, "Arthur"]) /// - /// // OK - /// let arguments: StatementArguments = ... // some untrusted arguments - /// try statement.validateArguments(arguments) - /// statement.setUncheckedArguments(arguments) + /// // OK + /// let arguments: StatementArguments = ... // some untrusted arguments + /// try statement.validateArguments(arguments) + /// statement.setUncheckedArguments(arguments) /// - /// // NOT OK - /// statement.setUncheckedArguments([1]) + /// // NOT OK + /// statement.setUncheckedArguments([1]) + /// ``` public func setUncheckedArguments(_ arguments: StatementArguments) { _arguments = arguments argumentsNeedValidation = false @@ -244,20 +302,26 @@ public final class Statement { } } - /// Set the statement arguments, or throws a DatabaseError of code - /// SQLITE_ERROR if arguments don't fill all statement arguments. + /// Sets the statement arguments. + /// + /// This method throws a ``DatabaseError`` of code `SQLITE_ERROR` if + /// arguments don't fill all statement arguments. /// /// For example: /// - /// let statement = try db.makeUpdateArgument(sql: """ - /// INSERT INTO player (id, name) VALUES (?, ?) - /// """) + /// ```swift + /// let statement = try db.makeUpdateArgument(sql: """ + /// INSERT INTO player (id, name) VALUES (?, ?) + /// """) /// - /// // OK - /// try statement.setArguments([1, "Arthur"]) + /// // OK + /// try statement.setArguments([1, "Arthur"]) /// - /// // Throws an error - /// try statement.setArguments([1]) + /// // Throws + /// try statement.setArguments([1]) + /// ``` + /// + /// - throws: A ``DatabaseError`` if `arguments` don't fit the expected ones. public func setArguments(_ arguments: StatementArguments) throws { // Validate var consumedArguments = arguments @@ -318,8 +382,36 @@ public final class Statement { /// Executes the prepared statement. /// + /// For example: + /// + /// ```swift + /// let dbQueue = try DatabaseQueue() + /// try dbQueue.write { db in + /// // Statement without argument + /// let createTableStatement = try db.makeStatement(sql: """ + /// CREATE TABLE player ( + /// id INTEGER PRIMARY KEY AUTOINCREMENT, + /// name TEXT NOT NULL + /// ) + /// """) + /// try createTableStatement.execute() + /// + /// // Statement with argument + /// let insertStatement = try db.makeStatement(sql: """ + /// INSERT INTO player (name) VALUES (?) + /// """) + /// + /// // Set argument and execute + /// try insertStatement.setArguments(["Arthur"]) + /// try insertStatement.execute() + /// + /// // Set argument and execute in one shot + /// try insertStatement.execute(arguments: ["Barbara"]) + /// } + /// ``` + /// /// - parameter arguments: Optional statement arguments. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func execute(arguments: StatementArguments? = nil) throws { try reset(withArguments: arguments) try database.statementWillExecute(self) @@ -396,8 +488,9 @@ extension Statement { Int(sqlite3_column_count(self.sqliteStatement)) } - /// Returns the index of the leftmost column named `name`, in a - /// case-insensitive way. + /// Returns the index of the leftmost column with the given name. + /// + /// This method is case-insensitive. public func index(ofColumn name: String) -> Int? { columnIndexes[name.lowercased()] } @@ -412,11 +505,8 @@ extension Statement { // MARK: - Cursors -/// Implementation details of `DatabaseCursor`. -/// -/// :nodoc: -public protocol _DatabaseCursor: Cursor { - /// Reserved to `_DatabaseCursor` implementation. +/// A cursor that iterates the result of a prepared ``Statement``. +public protocol DatabaseCursor: Cursor { /// Must be initialized to false. var _isDone: Bool { get set } @@ -428,16 +518,13 @@ public protocol _DatabaseCursor: Cursor { func _element(sqliteStatement: SQLiteStatement) throws -> Element } -/// A protocol for cursors that iterate a database statement. -public protocol DatabaseCursor: _DatabaseCursor { } - // Read-only access to statement information. We don't want the user to modify // a statement through a cursor, in case this would mess with the cursor state. extension DatabaseCursor { - /// The SQL query + /// The SQL query. public var sql: String { _statement.sql } - /// The SQL statement arguments. + /// The statement arguments. public var arguments: StatementArguments { _statement.arguments } /// The column names, ordered from left to right. @@ -463,8 +550,8 @@ extension DatabaseCursor { return nil } - /// Specific implementation of `forEach`, for a slight performance - /// improvement due to the single `sqlite3_stmt_busy` check. + // Specific implementation of `forEach`, for a slight performance + // improvement due to the single `sqlite3_stmt_busy` check. @inlinable public func forEach(_ body: (Element) throws -> Void) throws { if _isDone { return } @@ -533,6 +620,9 @@ extension Statement { // MARK: - StatementBinding +/// A type that can bind a statement argument. +/// +/// Related SQLite documentation: public protocol StatementBinding { /// Binds a statement argument. /// @@ -544,11 +634,11 @@ public protocol StatementBinding { // MARK: - StatementArguments -/// StatementArguments provide values to argument placeholders in raw -/// SQL queries. +/// An instance of `StatementArguments` provides the values for argument +/// placeholders in a prepared `Statement`. /// -/// Placeholders can take several forms (see -/// for more information): +/// Argument placeholders can take several forms in SQL queries (see +/// for more information): /// /// - `?NNN` (e.g. `?2`): the NNN-th argument (starts at 1) /// - `?`: the N-th argument, where N is one greater than the largest argument @@ -557,75 +647,97 @@ public protocol StatementBinding { /// - `@AAAA` (e.g. `@name`): named argument /// - `$AAAA` (e.g. `$name`): named argument /// +/// GRDB does not allow to distinguish between the `:AAAA`, `@AAAA`, and `$AAAA` +/// syntaxes. You are encouraged to write named arguments with a +/// colon prefix: `:name`. +/// /// ## Positional Arguments /// -/// To fill question marks placeholders, feed StatementArguments with an array: +/// To fill question marks placeholders, feed `StatementArguments` with an array: /// -/// db.execute( -/// sql: "INSERT ... (?, ?)", -/// arguments: StatementArguments(["Arthur", 41])) +/// ```swift +/// try db.execute( +/// sql: "INSERT INTO player (name, score) VALUES (?, ?)", +/// arguments: StatementArguments(["Arthur", 41])) /// -/// // Array literals are automatically converted: -/// db.execute( -/// sql: "INSERT ... (?, ?)", -/// arguments: ["Arthur", 41]) +/// // Array literals are automatically converted: +/// try db.execute( +/// sql: "INSERT INTO player (name, score) VALUES (?, ?)", +/// arguments: ["Arthur", 41]) +/// ``` /// /// ## Named Arguments /// -/// To fill named arguments, feed StatementArguments with a dictionary: +/// To fill named arguments, feed `StatementArguments` with a dictionary: /// -/// db.execute( -/// sql: "INSERT ... (:name, :score)", -/// arguments: StatementArguments(["name": "Arthur", "score": 41])) +/// ```swift +/// try db.execute( +/// sql: "INSERT INTO player (name, score) VALUES (:name, :score)", +/// arguments: StatementArguments(["name": "Arthur", "score": 41])) /// -/// // Dictionary literals are automatically converted: -/// db.execute( -/// sql: "INSERT ... (:name, :score)", -/// arguments: ["name": "Arthur", "score": 41]) +/// // Dictionary literals are automatically converted: +/// try db.execute( +/// sql: "INSERT INTO player (name, score) VALUES (:name, :score)", +/// arguments: ["name": "Arthur", "score": 41]) +/// ``` /// /// ## Concatenating Arguments /// /// Several arguments can be concatenated and mixed with the -/// `append(contentsOf:)` method and the `+`, `&+`, `+=` operators: +/// ``append(contentsOf:)`` method and the `+`, `&+`, `+=` operators: /// -/// var arguments: StatementArguments = ["Arthur"] -/// arguments += [41] -/// db.execute(sql: "INSERT ... (?, ?)", arguments: arguments) +/// ```swift +/// var arguments: StatementArguments = ["Arthur"] +/// arguments += [41] +/// try db.execute( +/// sql: "INSERT INTO player (name, score) VALUES (?, ?)", +/// arguments: arguments) +/// ``` /// -/// `+` and `+=` operators consider that overriding named arguments is a +/// The `+` and `+=` operators consider that overriding named arguments is a /// programmer error: /// -/// var arguments: StatementArguments = ["name": "Arthur"] -/// arguments += ["name": "Barbara"] -/// // fatal error: already defined statement argument: name +/// ```swift +/// var arguments: StatementArguments = ["name": "Arthur"] /// -/// `&+` and `append(contentsOf:)` allow overriding named arguments: +/// // fatal error: already defined statement argument: name +/// arguments += ["name": "Barbara"] +/// ``` /// -/// var arguments: StatementArguments = ["name": "Arthur"] -/// arguments = arguments &+ ["name": "Barbara"] -/// print(arguments) -/// // Prints ["name": "Barbara"] +/// On the other side, `&+` and ``append(contentsOf:)`` allow overriding +/// named arguments: +/// +/// ```swift +/// var arguments: StatementArguments = ["name": "Arthur"] +/// arguments = arguments &+ ["name": "Barbara"] +/// +/// // Prints ["name": "Barbara"] +/// print(arguments) +/// ``` /// /// ## Mixed Arguments /// /// It is possible to mix named and positional arguments. Yet this is usually /// confusing, and it is best to avoid this practice: /// -/// let sql = "SELECT ?2 AS two, :foo AS foo, ?1 AS one, :foo AS foo2, :bar AS bar" -/// var arguments: StatementArguments = [1, 2, "bar"] + ["foo": "foo"] -/// let row = try Row.fetchOne(db, sql: sql, arguments: arguments)! -/// print(row) -/// // Prints [two:2 foo:"foo" one:1 foo2:"foo" bar:"bar"] +/// ```swift +/// let sql = "SELECT ?2 AS two, :foo AS foo, ?1 AS one, :foo AS foo2, :bar AS bar" +/// var arguments: StatementArguments = [1, 2, "bar"] + ["foo": "foo"] +/// let row = try Row.fetchOne(db, sql: sql, arguments: arguments)! +/// +/// // Prints [two:2 foo:"foo" one:1 foo2:"foo" bar:"bar"] +/// print(row) +/// ``` /// /// Mixed arguments exist as a support for requests like the following: /// -/// let players = try Player -/// .filter(sql: "team = :team", arguments: ["team": "Blue"]) -/// .filter(sql: "score > ?", arguments: [1000]) -/// .fetchAll(db) -public struct StatementArguments: CustomStringConvertible, Hashable, - ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral -{ +/// ```swift +/// let players = try Player +/// .filter(sql: "team = :team", arguments: ["team": "Blue"]) +/// .filter(sql: "score > ?", arguments: [1000]) +/// .fetchAll(db) +/// ``` +public struct StatementArguments: Hashable { private(set) var values: [DatabaseValue] private(set) var namedValues: [String: DatabaseValue] @@ -636,7 +748,7 @@ public struct StatementArguments: CustomStringConvertible, Hashable, // MARK: Empty Arguments - /// Creates empty StatementArguments. + /// Creates an empty `StatementArguments`. public init() { values = .init() namedValues = .init() @@ -644,13 +756,14 @@ public struct StatementArguments: CustomStringConvertible, Hashable, // MARK: Positional Arguments - /// Creates statement arguments from a sequence of optional values. + /// Creates a `StatementArguments` from a sequence of values. /// - /// let values: [(any DatabaseValueConvertible)?] = ["foo", 1, nil] - /// db.execute(sql: "INSERT ... (?,?,?)", arguments: StatementArguments(values)) + /// For example: /// - /// - parameter sequence: A sequence of DatabaseValueConvertible values. - /// - returns: A StatementArguments. + /// ```swift + /// let values: [(any DatabaseValueConvertible)?] = ["foo", 1, nil] + /// db.execute(sql: "INSERT ... (?,?,?)", arguments: StatementArguments(values)) + /// ``` public init(_ sequence: S) where S: Sequence, S.Element == (any DatabaseValueConvertible)? { @@ -658,13 +771,14 @@ public struct StatementArguments: CustomStringConvertible, Hashable, namedValues = .init() } - /// Creates statement arguments from a sequence of optional values. + /// Creates a `StatementArguments` from a sequence of values. /// - /// let values: [String] = ["foo", "bar"] - /// db.execute(sql: "INSERT ... (?,?)", arguments: StatementArguments(values)) + /// For example: /// - /// - parameter sequence: A sequence of DatabaseValueConvertible values. - /// - returns: A StatementArguments. + /// ```swift + /// let values: [String] = ["foo", "bar"] + /// db.execute(sql: "INSERT ... (?,?)", arguments: StatementArguments(values)) + /// ``` public init(_ sequence: S) where S: Sequence, S.Element: DatabaseValueConvertible { @@ -672,11 +786,10 @@ public struct StatementArguments: CustomStringConvertible, Hashable, namedValues = .init() } - /// Creates statement arguments from any array. The result is nil unless all - /// array elements adopt DatabaseValueConvertible. + /// Creates a `StatementArguments` from an array. /// - /// - parameter array: An array - /// - returns: A StatementArguments. + /// The result is nil unless all array elements conform to the + /// ``DatabaseValueConvertible`` protocol. public init?(_ array: [Any]) { var values = [DatabaseValueConvertible?]() for value in array { @@ -695,27 +808,21 @@ public struct StatementArguments: CustomStringConvertible, Hashable, // MARK: Named Arguments - /// Creates statement arguments from a sequence of (key, value) dictionary, - /// such as a dictionary. + /// Creates a `StatementArguments` of named arguments from a dictionary. /// - /// let values: [String: (any DatabaseValueConvertible)?] = ["firstName": nil, "lastName": "Miller"] - /// db.execute(sql: "INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values)) + /// For example: /// - /// - parameter sequence: A sequence of (key, value) pairs - /// - returns: A StatementArguments. + /// ```swift + /// let values: [String: (any DatabaseValueConvertible)?] = ["firstName": nil, "lastName": "Miller"] + /// db.execute(sql: "INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values)) + /// ``` public init(_ dictionary: [String: (any DatabaseValueConvertible)?]) { namedValues = dictionary.mapValues { $0?.databaseValue ?? .null } values = .init() } - /// Creates statement arguments from a sequence of (key, value) pairs, such - /// as a dictionary. - /// - /// let values: [String: (any DatabaseValueConvertible)?] = ["firstName": nil, "lastName": "Miller"] - /// db.execute(sql: "INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values)) - /// - /// - parameter sequence: A sequence of (key, value) pairs - /// - returns: A StatementArguments. + /// Creates a `StatementArguments` of named arguments from a sequence of + /// (key, value) pairs. public init(_ sequence: S) where S: Sequence, S.Element == (String, (any DatabaseValueConvertible)?) { @@ -726,13 +833,12 @@ public struct StatementArguments: CustomStringConvertible, Hashable, values = .init() } - /// Creates statement arguments from [AnyHashable: Any]. + /// Creates a `StatementArguments` from a dictionary. /// /// The result is nil unless all dictionary keys are strings, and values /// adopt DatabaseValueConvertible. /// /// - parameter dictionary: A dictionary. - /// - returns: A StatementArguments. public init?(_ dictionary: [AnyHashable: Any]) { var initDictionary = [String: (any DatabaseValueConvertible)?]() for (key, value) in dictionary { @@ -750,38 +856,52 @@ public struct StatementArguments: CustomStringConvertible, Hashable, // MARK: Adding arguments - /// Extends statement arguments with other arguments. + /// Appends statement arguments. /// - /// Positional arguments (provided as arrays) are concatenated: + /// Positional arguments are concatenated: /// - /// var arguments: StatementArguments = [1] - /// arguments.append(contentsOf: [2, 3]) - /// print(arguments) - /// // Prints [1, 2, 3] + /// ```swift + /// var arguments: StatementArguments = [1] + /// arguments.append(contentsOf: [2, 3]) /// - /// Named arguments (provided as dictionaries) are updated: + /// // Prints [1, 2, 3] + /// print(arguments) + /// ``` /// - /// var arguments: StatementArguments = ["foo": 1] - /// arguments.append(contentsOf: ["bar": 2]) - /// print(arguments) - /// // Prints ["foo": 1, "bar": 2] + /// Named arguments are inserted or updated: /// - /// Arguments that were replaced, if any, are returned: + /// ```swift + /// var arguments: StatementArguments = ["foo": 1] + /// arguments.append(contentsOf: ["bar": 2]) /// - /// var arguments: StatementArguments = ["foo": 1, "bar": 2] - /// let replacedValues = arguments.append(contentsOf: ["foo": 3]) - /// print(arguments) - /// // Prints ["foo": 3, "bar": 2] - /// print(replacedValues) - /// // Prints ["foo": 1] + /// // Prints ["foo": 1, "bar": 2] + /// print(arguments) + /// ``` /// - /// You can mix named and positional arguments (see documentation of - /// the StatementArguments type for more information about mixed arguments): + /// Named arguments that were replaced, if any, are returned: /// - /// var arguments: StatementArguments = ["foo": 1] - /// arguments.append(contentsOf: [2, 3]) - /// print(arguments) - /// // Prints ["foo": 1, 2, 3] + /// ```swift + /// var arguments: StatementArguments = ["foo": 1, "bar": 2] + /// let replacedValues = arguments.append(contentsOf: ["foo": 3]) + /// + /// // Prints ["foo": 3, "bar": 2] + /// print(arguments) + /// + /// // Prints ["foo": 1] + /// print(replacedValues) + /// ``` + /// + /// You can mix named and positional arguments (see the documentation of + /// the ``StatementArguments`` type for more information about + /// mixed arguments): + /// + /// ```swift + /// var arguments: StatementArguments = ["foo": 1] + /// arguments.append(contentsOf: [2, 3]) + /// + /// // Prints ["foo": 1, 2, 3] + /// print(arguments) + /// ``` public mutating func append(contentsOf arguments: StatementArguments) -> [String: DatabaseValue] { var replacedValues: [String: DatabaseValue] = [:] values.append(contentsOf: arguments.values) @@ -793,70 +913,94 @@ public struct StatementArguments: CustomStringConvertible, Hashable, return replacedValues } - /// Creates a new StatementArguments by extending the left-hand size + /// Creates a new `StatementArguments` by extending the left-hand size /// arguments with the right-hand side arguments. /// - /// Positional arguments (provided as arrays) are concatenated: + /// Positional arguments are concatenated: /// - /// let arguments: StatementArguments = [1] + [2, 3] - /// print(arguments) - /// // Prints [1, 2, 3] + /// ```swift + /// let arguments: StatementArguments = [1] + [2, 3] /// - /// Named arguments (provided as dictionaries) are updated: + /// // Prints [1, 2, 3] + /// print(arguments) + /// ``` /// - /// let arguments: StatementArguments = ["foo": 1] + ["bar": 2] - /// print(arguments) - /// // Prints ["foo": 1, "bar": 2] + /// Named arguments are inserted: /// - /// You can mix named and positional arguments (see documentation of - /// the StatementArguments type for more information about mixed arguments): + /// ```swift + /// let arguments: StatementArguments = ["foo": 1] + ["bar": 2] /// - /// let arguments: StatementArguments = ["foo": 1] + [2, 3] - /// print(arguments) - /// // Prints ["foo": 1, 2, 3] + /// // Prints ["foo": 1, "bar": 2] + /// print(arguments) + /// ``` /// /// If the arguments on the right-hand side has named parameters that are /// already defined on the left, a fatal error is raised: /// - /// let arguments: StatementArguments = ["foo": 1] + ["foo": 2] - /// // fatal error: already defined statement argument: foo + /// ```swift + /// let arguments: StatementArguments = ["foo": 1] + ["foo": 2] + /// // fatal error: already defined statement argument: foo + /// ``` /// /// This fatal error can be avoided with the &+ operator, or the - /// append(contentsOf:) method. + /// ``append(contentsOf:)`` method. + /// + /// You can mix named and positional arguments (see the documentation of + /// the ``StatementArguments`` type for more information about + /// mixed arguments): + /// + /// ```swift + /// let arguments: StatementArguments = ["foo": 1] + [2, 3] + /// + /// // Prints ["foo": 1, 2, 3] + /// print(arguments) + /// ``` public static func + (lhs: StatementArguments, rhs: StatementArguments) -> StatementArguments { var lhs = lhs lhs += rhs return lhs } - /// Creates a new StatementArguments by extending the left-hand size + /// Creates a new `StatementArguments` by extending the left-hand size /// arguments with the right-hand side arguments. /// - /// Positional arguments (provided as arrays) are concatenated: + /// Positional arguments are concatenated: /// - /// let arguments: StatementArguments = [1] &+ [2, 3] - /// print(arguments) - /// // Prints [1, 2, 3] + /// ```swift + /// let arguments: StatementArguments = [1] &+ [2, 3] /// - /// Named arguments (provided as dictionaries) are updated: + /// // Prints [1, 2, 3] + /// print(arguments) + /// ``` /// - /// let arguments: StatementArguments = ["foo": 1] &+ ["bar": 2] - /// print(arguments) - /// // Prints ["foo": 1, "bar": 2] + /// Named arguments are inserted or updated: /// - /// You can mix named and positional arguments (see documentation of - /// the StatementArguments type for more information about mixed arguments): + /// ```swift + /// let arguments: StatementArguments = ["foo": 1] &+ ["bar": 2] /// - /// let arguments: StatementArguments = ["foo": 1] &+ [2, 3] - /// print(arguments) - /// // Prints ["foo": 1, 2, 3] + /// // Prints ["foo": 1, "bar": 2] + /// print(arguments) + /// ``` /// /// If a named arguments is defined in both arguments, the right-hand /// side wins: /// - /// let arguments: StatementArguments = ["foo": 1] &+ ["foo": 2] - /// print(arguments) - /// // Prints ["foo": 2] + /// ```swift + /// let arguments: StatementArguments = ["foo": 1] &+ ["foo": 2] + /// + /// // Prints ["foo": 2] + /// print(arguments) + /// ``` + /// + /// You can mix named and positional arguments (see the documentation of + /// the ``StatementArguments`` type for more information about + /// mixed arguments): + /// + /// ```swift + /// let arguments: StatementArguments = ["foo": 1] &+ [2, 3] + /// // Prints ["foo": 1, 2, 3] + /// print(arguments) + /// ``` public static func &+ (lhs: StatementArguments, rhs: StatementArguments) -> StatementArguments { var lhs = lhs _ = lhs.append(contentsOf: rhs) @@ -865,37 +1009,50 @@ public struct StatementArguments: CustomStringConvertible, Hashable, /// Extends the left-hand size arguments with the right-hand side arguments. /// - /// Positional arguments (provided as arrays) are concatenated: + /// Positional arguments are concatenated: /// - /// var arguments: StatementArguments = [1] - /// arguments += [2, 3] - /// print(arguments) - /// // Prints [1, 2, 3] + /// ```swift + /// var arguments: StatementArguments = [1] + /// arguments += [2, 3] /// - /// Named arguments (provided as dictionaries) are updated: + /// // Prints [1, 2, 3] + /// print(arguments) + /// ``` /// - /// var arguments: StatementArguments = ["foo": 1] - /// arguments += ["bar": 2] - /// print(arguments) - /// // Prints ["foo": 1, "bar": 2] + /// Named arguments are inserted: /// - /// You can mix named and positional arguments (see documentation of - /// the StatementArguments type for more information about mixed arguments): + /// ```swift + /// var arguments: StatementArguments = ["foo": 1] + /// arguments += ["bar": 2] /// - /// var arguments: StatementArguments = ["foo": 1] - /// arguments.append(contentsOf: [2, 3]) - /// print(arguments) - /// // Prints ["foo": 1, 2, 3] + /// // Prints ["foo": 1, "bar": 2] + /// print(arguments) + /// ``` /// /// If the arguments on the right-hand side has named parameters that are /// already defined on the left, a fatal error is raised: /// - /// var arguments: StatementArguments = ["foo": 1] - /// arguments += ["foo": 2] - /// // fatal error: already defined statement argument: foo + /// ```swift + /// var arguments: StatementArguments = ["foo": 1] + /// + /// // fatal error: already defined statement argument: foo + /// arguments += ["foo": 2] + /// ``` /// /// This fatal error can be avoided with the &+ operator, or the - /// append(contentsOf:) method. + /// ``append(contentsOf:)`` method. + /// + /// You can mix named and positional arguments (see the documentation of + /// the ``StatementArguments`` type for more information about + /// mixed arguments): + /// + /// ```swift + /// var arguments: StatementArguments = ["foo": 1] + /// arguments.append(contentsOf: [2, 3]) + /// + /// // Prints ["foo": 1, 2, 3] + /// print(arguments) + /// ``` public static func += (lhs: inout StatementArguments, rhs: StatementArguments) { let replacedValues = lhs.append(contentsOf: rhs) GRDBPrecondition( @@ -945,35 +1102,39 @@ public struct StatementArguments: CustomStringConvertible, Hashable, } } -// ExpressibleByArrayLiteral -extension StatementArguments { - /// Returns a StatementArguments from an array literal: +extension StatementArguments: ExpressibleByArrayLiteral { + /// Creates a `StatementArguments` from an array literal. /// - /// let arguments: StatementArguments = ["Arthur", 41] - /// try db.execute( - /// sql: "INSERT INTO player (name, score) VALUES (?, ?)" - /// arguments: arguments) + /// For example: + /// + /// ```swift + /// let arguments: StatementArguments = ["Arthur", 41] + /// try db.execute( + /// sql: "INSERT INTO player (name, score) VALUES (?, ?)" + /// arguments: arguments) + /// ``` public init(arrayLiteral elements: (any DatabaseValueConvertible)?...) { self.init(elements) } } -// ExpressibleByDictionaryLiteral -extension StatementArguments { - /// Returns a StatementArguments from a dictionary literal: +extension StatementArguments: ExpressibleByDictionaryLiteral { + /// Creates a `StatementArguments` from a dictionary literal. /// - /// let arguments: StatementArguments = ["name": "Arthur", "score": 41] - /// try db.execute( - /// sql: "INSERT INTO player (name, score) VALUES (:name, :score)" - /// arguments: arguments) + /// For example: + /// + /// ```swift + /// let arguments: StatementArguments = ["name": "Arthur", "score": 41] + /// try db.execute( + /// sql: "INSERT INTO player (name, score) VALUES (:name, :score)" + /// arguments: arguments) + /// ``` public init(dictionaryLiteral elements: (String, (any DatabaseValueConvertible)?)...) { self.init(elements) } } -// CustomStringConvertible -extension StatementArguments { - /// :nodoc: +extension StatementArguments: CustomStringConvertible { public var description: String { let valuesDescriptions = values.map(\.description) let namedValuesDescriptions = namedValues.map { (key, value) in diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index b7009b92a..27995317e 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -1,25 +1,76 @@ -/// The `StatementColumnConvertible` protocol grants access to the low-level C -/// interface that extracts values from query results: -/// . It can bring performance -/// improvements. +/// A type that can decode itself from the low-level C interface to +/// SQLite results. /// -/// To use it, have a value type adopt both `StatementColumnConvertible` and -/// `DatabaseValueConvertible`. GRDB will then automatically apply the -/// optimization whenever direct access to SQLite is possible: +/// `StatementColumnConvertible` is adopted by `Bool`, `Int`, `String`, +/// `Date`, and most common values. /// -/// let rows = Row.fetchCursor(db, sql: "SELECT ...") -/// while let row = try rows.next() { -/// let int: Int = row[0] // there -/// } -/// let ints = Int.fetchAll(db, sql: "SELECT ...") // there -/// struct Player { -/// init(row: Row) { -/// name = row["name"] // there -/// score = row["score"] // there -/// } +/// When a type conforms to both ``DatabaseValueConvertible`` and +/// `StatementColumnConvertible`, GRDB can apply some optimization whenever +/// direct access to SQLite is possible. For example: +/// +/// ```swift +/// // Optimized +/// let scores = Int.fetchAll(db, sql: "SELECT score FROM player") +/// +/// let rows = Row.fetchCursor(db, sql: "SELECT * FROM player") +/// while let row = try rows.next() { +/// // Optimized +/// let int: Int = row[0] +/// let name: String = row[1] +/// } +/// +/// struct Player: FetchableRecord { +/// var name: String +/// var score: Int +/// +/// init(row: Row) { +/// // Optimized +/// name = row["name"] +/// score = row["score"] /// } +/// } +/// ``` +/// +/// To conform to `StatementColumnConvertible`, provide a custom implementation +/// of ``init(sqliteStatement:index:)-354je``. This implementation is ready-made +/// for `RawRepresentable` types whose `RawValue` +/// is `StatementColumnConvertible`. +/// +/// Related SQLite documentation: +/// +/// ## Topics +/// +/// ### Creating a Value +/// +/// - ``init(sqliteStatement:index:)-354je`` +/// - ``fromStatement(_:atUncheckedIndex:)-2i8y6`` +/// +/// ### Fetching Values from Raw SQL +/// +/// - ``DatabaseValueConvertible/fetchCursor(_:sql:arguments:adapter:)-4xfxh`` +/// - ``DatabaseValueConvertible/fetchAll(_:sql:arguments:adapter:)-7bn2i`` +/// - ``DatabaseValueConvertible/fetchSet(_:sql:arguments:adapter:)-1ythd`` +/// - ``DatabaseValueConvertible/fetchOne(_:sql:arguments:adapter:)-563lc`` +/// +/// ### Fetching Values from a Prepared Statement +/// +/// - ``DatabaseValueConvertible/fetchCursor(_:arguments:adapter:)-81f9d`` +/// - ``DatabaseValueConvertible/fetchAll(_:arguments:adapter:)-64gua`` +/// - ``DatabaseValueConvertible/fetchSet(_:arguments:adapter:)-9fh2b`` +/// - ``DatabaseValueConvertible/fetchOne(_:arguments:adapter:)-8cbzp`` +/// +/// ### Fetching Values from a Request +/// +/// - ``DatabaseValueConvertible/fetchCursor(_:_:)-77a34`` +/// - ``DatabaseValueConvertible/fetchAll(_:_:)-7tnun`` +/// - ``DatabaseValueConvertible/fetchSet(_:_:)-4bc1m`` +/// - ``DatabaseValueConvertible/fetchOne(_:_:)-94q4e`` +/// +/// ### Supporting Types +/// +/// - ``FastDatabaseValueCursor`` public protocol StatementColumnConvertible { - /// Creates a value from a raw SQLite statement pointer, if possible. + /// Creates an instance from a raw SQLite statement pointer, if possible. /// /// This method can be called with a NULL database value. /// @@ -34,20 +85,26 @@ public protocol StatementColumnConvertible { atUncheckedIndex index: CInt) -> Self? - /// Creates a value from a raw SQLite statement pointer, if possible. + /// Creates an instance from a raw SQLite statement pointer, if possible. + /// + /// Do not check for `NULL` in your implementation of this method. Null + /// database values are handled + /// in ``fromStatement(_:atUncheckedIndex:)-2i8y6``. /// /// For example, here is the how Int64 adopts StatementColumnConvertible: /// - /// extension Int64: StatementColumnConvertible { - /// init?(sqliteStatement: SQLiteStatement, index: CInt) { - /// self = sqlite3_column_int64(sqliteStatement, index) - /// } + /// ```swift + /// extension Int64: StatementColumnConvertible { + /// public init(sqliteStatement: SQLiteStatement, index: CInt) { + /// self = sqlite3_column_int64(sqliteStatement, index) /// } + /// } + /// ``` /// - /// See for more information. + /// Related SQLite documentation: /// - /// - precondition: This initializer must not be called with NULL database - /// values. + /// - precondition: This initializer is not called with a NULL + /// database value. /// - parameters: /// - sqliteStatement: A pointer to an SQLite statement. /// - index: The column index. @@ -131,22 +188,28 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { // MARK: - Cursors -/// A cursor of database values extracted from a single column. +/// A cursor of database values. +/// +/// A `FastDatabaseValueCursor` iterates all rows from a database request. Its +/// elements are the database values decoded from the leftmost column. +/// /// For example: /// -/// try dbQueue.read { db in -/// let names: ColumnCursor = try String.fetchCursor(db, sql: "SELECT name FROM player") -/// while let name = names.next() { // String -/// print(name) -/// } +/// ```swift +/// try dbQueue.read { db in +/// let names: FastDatabaseValueCursor = try String.fetchCursor(db, sql: """ +/// SELECT name FROM player +/// """) +/// while let name = names.next() { // String +/// print(name) /// } +/// } +/// ``` public final class FastDatabaseValueCursor: DatabaseCursor where Value: DatabaseValueConvertible & StatementColumnConvertible { public typealias Element = Value - /// :nodoc: public let _statement: Statement - /// :nodoc: public var _isDone = false @usableFromInline let columnIndex: CInt @@ -169,7 +232,6 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible try? _statement.reset() } - /// :nodoc: @inlinable public func _element(sqliteStatement: SQLiteStatement) throws -> Value { try Value.fastDecode( @@ -190,23 +252,35 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// Returns a cursor over values fetched from a prepared statement. /// - /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") - /// let names = try String.fetchCursor(statement) // Cursor of String - /// while let name = try names.next() { // String - /// ... + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT score FROM player WHERE lastName = ?" + /// let statement = try db.makeStatement(sql: sql) + /// let scores = try Int.fetchCursor(statement, arguments: [lastName]) + /// while let score = try scores.next() { + /// print(score) /// } + /// } + /// ``` + /// + /// Values are decoded from the leftmost column if the `adapter` argument + /// is nil. + /// + /// The returned cursor is valid only during the remaining execution of the + /// database access. Do not store or return the cursor for later use. /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// - /// The cursor must be iterated in a protected dispatch queue. - /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter - /// - returns: A cursor over fetched values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: A ``FastDatabaseValueCursor`` over fetched values. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor( _ statement: Statement, arguments: StatementArguments? = nil, @@ -218,15 +292,26 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// Returns an array of values fetched from a prepared statement. /// - /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") - /// let names = try String.fetchAll(statement) // [String] + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT score FROM player WHERE lastName = ?" + /// let statement = try db.makeStatement(sql: sql) + /// let scores = try Int.fetchAll(statement, arguments: [lastName]) + /// } + /// ``` + /// + /// Values are decoded from the leftmost column if the `adapter` argument + /// is nil. /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: An array of values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll( _ statement: Statement, arguments: StatementArguments? = nil, @@ -238,15 +323,29 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// Returns a single value fetched from a prepared statement. /// - /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") - /// let name = try String.fetchOne(statement) // String? + /// The value is decoded from the leftmost column if the `adapter` argument + /// is nil. + /// + /// The result is nil if the request returns no row, or one row with a + /// `NULL` value. + /// + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT score FROM player WHERE lastName = ? LIMIT 1" + /// let statement = try db.makeStatement(sql: sql) + /// let score = try Int.fetchOne(statement, arguments: [lastName]) + /// } + /// ``` /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: An optional value. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne( _ statement: Statement, arguments: StatementArguments? = nil, @@ -265,15 +364,26 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hashable { /// Returns a set of values fetched from a prepared statement. /// - /// let statement = try db.makeStatement(sql: "SELECT name FROM ...") - /// let names = try String.fetchSet(statement) // Set + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT score FROM player WHERE lastName = ?" + /// let statement = try db.makeStatement(sql: sql) + /// let scores = try Int.fetchSet(statement, arguments: [lastName]) + /// } + /// ``` + /// + /// Values are decoded from the leftmost column if the `adapter` argument + /// is nil. /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: A set of values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet( _ statement: Statement, arguments: StatementArguments? = nil, @@ -290,23 +400,35 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// Returns a cursor over values fetched from an SQL query. /// - /// let names = try String.fetchCursor(db, sql: "SELECT name FROM ...") // Cursor of String - /// while let name = try names.next() { // String - /// ... + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT score FROM player WHERE lastName = ?" + /// let scores = try Int.fetchCursor(db, sql: sql, arguments: [lastName]) + /// while let score = try scores.next() { + /// print(score) /// } + /// } + /// ``` + /// + /// Values are decoded from the leftmost column if the `adapter` argument + /// is nil. + /// + /// The returned cursor is valid only during the remaining execution of the + /// database access. Do not store or return the cursor for later use. /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// - /// The cursor must be iterated in a protected dispatch queue. - /// /// - parameters: /// - db: A database connection. - /// - sql: An SQL query. + /// - sql: An SQL string. /// - arguments: Statement arguments. /// - adapter: Optional RowAdapter - /// - returns: A cursor over fetched values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: A ``FastDatabaseValueCursor`` over fetched values. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor( _ db: Database, sql: String, @@ -319,15 +441,26 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// Returns an array of values fetched from an SQL query. /// - /// let names = try String.fetchAll(db, sql: "SELECT name FROM ...") // [String] + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT score FROM player WHERE lastName = ?" + /// let scores = try Int.fetchAll(db, sql: sql, arguments: [lastName]) + /// } + /// ``` + /// + /// Values are decoded from the leftmost column if the `adapter` argument + /// is nil. /// /// - parameters: /// - db: A database connection. - /// - sql: An SQL query. + /// - sql: An SQL string. /// - arguments: Statement arguments. /// - adapter: Optional RowAdapter /// - returns: An array of values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll( _ db: Database, sql: String, @@ -340,15 +473,29 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// Returns a single value fetched from an SQL query. /// - /// let name = try String.fetchOne(db, sql: "SELECT name FROM ...") // String? + /// The value is decoded from the leftmost column if the `adapter` argument + /// is nil. + /// + /// The result is nil if the request returns no row, or one row with a + /// `NULL` value. + /// + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT score FROM player WHERE lastName = ?" + /// let score = try Int.fetchOne(db, sql: sql, arguments: [lastName]) + /// } + /// ``` /// /// - parameters: /// - db: A database connection. - /// - sql: An SQL query. + /// - sql: An SQL string. /// - arguments: Statement arguments. /// - adapter: Optional RowAdapter /// - returns: An optional value. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne( _ db: Database, sql: String, @@ -363,15 +510,26 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hashable { /// Returns a set of values fetched from an SQL query. /// - /// let names = try String.fetchSet(db, sql: "SELECT name FROM ...") // Set + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT score FROM player WHERE lastName = ?" + /// let scores = try Int.fetchSet(db, sql: sql, arguments: [lastName]) + /// } + /// ``` + /// + /// Values are decoded from the leftmost column if the `adapter` argument + /// is nil. /// /// - parameters: /// - db: A database connection. - /// - sql: An SQL query. + /// - sql: An SQL string. /// - arguments: Statement arguments. /// - adapter: Optional RowAdapter /// - returns: A set of values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet( _ db: Database, sql: String, @@ -389,23 +547,43 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// Returns a cursor over values fetched from a fetch request. /// - /// let request = Player.select(Column("name")) - /// let names = try String.fetchCursor(db, request) // Cursor of String - /// while let name = try names.next() { // String - /// ... + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player + /// .select(Column("score")) + /// .filter(Column("lastName") == lastName) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT score FROM player WHERE lastName = \(lastName) + /// """ + /// + /// let scores = try Int.fetchCursor(db, request) + /// while let score = try scores.next() { + /// print(score) /// } + /// } + /// ``` + /// + /// Values are decoded from the leftmost column. + /// + /// The returned cursor is valid only during the remaining execution of the + /// database access. Do not store or return the cursor for later use. /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// - /// The cursor must be iterated in a protected dispatch queue. - /// /// - parameters: /// - db: A database connection. /// - request: A FetchRequest. - /// - returns: A cursor over fetched values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: R) + /// - returns: A ``FastDatabaseValueCursor`` over fetched values. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public static func fetchCursor(_ db: Database, _ request: some FetchRequest) throws -> FastDatabaseValueCursor { let request = try request.makePreparedRequest(db, forSingleResult: false) @@ -414,30 +592,71 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// Returns an array of values fetched from a fetch request. /// - /// let request = Player.select(Column("name")) - /// let names = try String.fetchAll(db, request) // [String] + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player + /// .select(Column("score")) + /// .filter(Column("lastName") == lastName) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT score FROM player WHERE lastName = \(lastName) + /// """ + /// + /// let scores = try Int.fetchAll(db, request) + /// } + /// ``` + /// + /// Values are decoded from the leftmost column. /// /// - parameters: /// - db: A database connection. /// - request: A FetchRequest. /// - returns: An array of values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: R) throws -> [Self] { + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchAll(request.statement, adapter: request.adapter) } /// Returns a single value fetched from a fetch request. /// - /// let request = Player.filter(key: 1).select(Column("name")) - /// let name = try String.fetchOne(db, request) // String? + /// The value is decoded from the leftmost column. + /// + /// The result is nil if the request returns no row, or one row with a + /// `NULL` value. + /// + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player + /// .select(Column("score")) + /// .filter(Column("lastName") == lastName) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT score FROM player WHERE lastName = \(lastName) LIMIT 1 + /// """ + /// + /// let scores = try Int.fetchOne(db, request) + /// } + /// ``` /// /// - parameters: /// - db: A database connection. /// - request: A FetchRequest. /// - returns: An optional value. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, _ request: R) throws -> Self? { + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? { let request = try request.makePreparedRequest(db, forSingleResult: true) return try fetchOne(request.statement, adapter: request.adapter) } @@ -446,15 +665,34 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hashable { /// Returns a set of values fetched from a fetch request. /// - /// let request = Player.select(Column("name")) - /// let names = try String.fetchSet(db, request) // Set + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player + /// .select(Column("score")) + /// .filter(Column("lastName") == lastName) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT score FROM player WHERE lastName = \(lastName) + /// """ + /// + /// let scores = try Int.fetchAll(db, request) + /// } + /// ``` + /// + /// Values are decoded from the leftmost column. /// /// - parameters: /// - db: A database connection. /// - request: A FetchRequest. /// - returns: A set of values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, _ request: R) throws -> Set { + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchSet(request.statement, adapter: request.adapter) } @@ -464,63 +702,140 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol // MARK: Fetching Values - /// A cursor over fetched values. + /// Returns a cursor over fetched values. /// - /// let request: some FetchRequest = ... - /// let strings = try request.fetchCursor(db) // Cursor of String - /// while let string = try strings.next() { // String - /// ... + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player + /// .filter(Column("lastName") == lastName) + /// .select(Column("score"), as: Int.self) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT score FROM player WHERE lastName = \(lastName) + /// """ + /// + /// let scores = try request.fetchCursor(db) + /// while let score = try scores.next() { + /// print(score) /// } + /// } + /// ``` + /// + /// Values are decoded from the leftmost column. + /// + /// The returned cursor is valid only during the remaining execution of the + /// database access. Do not store or return the cursor for later use. /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// - /// The cursor must be iterated in a protected dispatch queue. - /// /// - parameter db: A database connection. - /// - returns: A cursor over fetched values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: A ``FastDatabaseValueCursor`` over fetched values. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchCursor(_ db: Database) throws -> FastDatabaseValueCursor { try RowDecoder.fetchCursor(db, self) } - /// An array of fetched values. + /// Returns an array of fetched values. /// - /// let request: some FetchRequest = ... - /// let strings = try request.fetchAll(db) // [String] + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player + /// .filter(Column("lastName") == lastName) + /// .select(Column("score"), as: Int.self) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT score FROM player WHERE lastName = \(lastName) + /// """ + /// + /// let scores = try request.fetchAll(db) + /// } + /// ``` + /// + /// Values are decoded from the leftmost column. /// /// - parameter db: A database connection. /// - returns: An array of values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchAll(_ db: Database) throws -> [RowDecoder] { try RowDecoder.fetchAll(db, self) } - /// The first fetched value. + /// Returns a single fetched value. /// - /// The result is nil if the request returns no row, or if no value can be - /// extracted from the first row. + /// The value is decoded from the leftmost column. /// - /// let request: some FetchRequest = ... - /// let string = try request.fetchOne(db) // String? + /// The result is nil if the request returns no row, or one row with a + /// `NULL` value. + /// + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player + /// .filter(Column("lastName") == lastName) + /// .select(Column("score"), as: Int.self) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT score FROM player WHERE lastName = \(lastName) LIMIT 1 + /// """ + /// + /// let score = try request.fetchOne(db) + /// } + /// ``` /// /// - parameter db: A database connection. /// - returns: An optional value. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchOne(_ db: Database) throws -> RowDecoder? { try RowDecoder.fetchOne(db, self) } } extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible & Hashable { - /// A set of fetched values. + /// Returns a set of fetched values. /// - /// let request: some FetchRequest = ... - /// let strings = try request.fetchSet(db) // Set + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player + /// .filter(Column("lastName") == lastName) + /// .select(Column("score"), as: Int.self) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT score FROM player WHERE lastName = \(lastName) + /// """ + /// + /// let scores = try request.fetchSet(db) + /// } + /// ``` + /// + /// Values are decoded from the leftmost column. /// /// - parameter db: A database connection. - /// - returns: An array of values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: A set of values. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchSet(_ db: Database) throws -> Set { try RowDecoder.fetchSet(db, self) } diff --git a/GRDB/Core/Support/CoreGraphics/CGFloat.swift b/GRDB/Core/Support/CoreGraphics/CGFloat.swift index 124b15681..6b0fb6053 100644 --- a/GRDB/Core/Support/CoreGraphics/CGFloat.swift +++ b/GRDB/Core/Support/CoreGraphics/CGFloat.swift @@ -3,13 +3,11 @@ import CoreGraphics /// CGFloat adopts DatabaseValueConvertible extension CGFloat: DatabaseValueConvertible { - - /// Returns a value that can be stored in the database. + /// Returns a REAL database value. public var databaseValue: DatabaseValue { Double(self).databaseValue } - /// Returns a CGFloat initialized from *dbValue*, if possible. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> CGFloat? { guard let double = Double.fromDatabaseValue(dbValue) else { return nil diff --git a/GRDB/Core/Support/Foundation/Data.swift b/GRDB/Core/Support/Foundation/Data.swift index 7248b6fc0..21b647ae5 100644 --- a/GRDB/Core/Support/Foundation/Data.swift +++ b/GRDB/Core/Support/Foundation/Data.swift @@ -11,13 +11,19 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible { } } - /// Returns a value that can be stored in the database. + /// Returns a BLOB database value. public var databaseValue: DatabaseValue { DatabaseValue(storage: .blob(self)) } - /// Returns a Data initialized from *dbValue*, if it contains - /// a Blob. + /// Returns a `Data` from the specified database value. + /// + /// If the database value contains a data blob, returns it. + /// + /// If the database value contains a string, returns this string converted + /// to UTF8 data. + /// + /// Otherwise, returns nil. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Data? { switch dbValue.storage { case .blob(let data): @@ -60,50 +66,4 @@ extension Data { let count = Int(sqlite3_column_bytes(sqliteStatement, index)) return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none) } - - static func fastDecodeNoCopy( - fromRow row: Row, - atUncheckedIndex index: Int) - throws -> Data - { - if let sqliteStatement = row.sqliteStatement { - return try fastDecodeNoCopy( - fromStatement: sqliteStatement, - atUncheckedIndex: CInt(index), - context: RowDecodingContext(row: row, key: .columnIndex(index))) - } - // Support for fast decoding from adapted rows - return try row.fastDecodeDataNoCopy(atUncheckedIndex: index) - } - - static func fastDecodeNoCopyIfPresent( - fromStatement sqliteStatement: SQLiteStatement, - atUncheckedIndex index: CInt, - context: @autoclosure () -> RowDecodingContext) - -> Data? - { - guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL else { - return nil - } - guard let bytes = sqlite3_column_blob(sqliteStatement, index) else { - return Data() - } - let count = Int(sqlite3_column_bytes(sqliteStatement, index)) - return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none) - } - - static func fastDecodeNoCopyIfPresent( - fromRow row: Row, - atUncheckedIndex index: Int) - throws -> Data? - { - if let sqliteStatement = row.sqliteStatement { - return fastDecodeNoCopyIfPresent( - fromStatement: sqliteStatement, - atUncheckedIndex: CInt(index), - context: RowDecodingContext(row: row, key: .columnIndex(index))) - } - // Support for fast decoding from adapted rows - return try row.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: index) - } } diff --git a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift index 37463d044..fd31c3724 100644 --- a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift +++ b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift @@ -1,9 +1,9 @@ import Foundation -/// DatabaseDateComponents reads and stores DateComponents in the database. -public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnConvertible, Codable { +/// A database value that holds date components. +public struct DatabaseDateComponents { - /// The available formats for reading and storing date components. + /// The SQLite formats for date components. public enum Format: String { /// The format "yyyy-MM-dd". @@ -43,8 +43,6 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC } } - // MARK: - NSDateComponents conversion - /// The date components public let dateComponents: DateComponents @@ -61,9 +59,9 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC self.format = format self.dateComponents = dateComponents } - - // MARK: - StatementColumnConvertible adoption - +} + +extension DatabaseDateComponents: StatementColumnConvertible { /// Returns a value initialized from a raw SQLite statement pointer. /// /// - parameters: @@ -86,10 +84,10 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC } self.init(components.dateComponents, format: components.format) } - - // MARK: - DatabaseValueConvertible adoption - - /// Returns a value that can be stored in the database. +} + +extension DatabaseDateComponents: DatabaseValueConvertible { + /// Returns a TEXT database value. public var databaseValue: DatabaseValue { let dateString: String? switch format { @@ -128,39 +126,32 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC return [dateString, timeString].compactMap { $0 }.joined(separator: " ").databaseValue } - /// Returns a DatabaseDateComponents if *dbValue* contains a - /// valid date. + /// Creates a `DatabaseDateComponents` from the specified database value. + /// + /// The supported formats are: + /// + /// - `YYYY-MM-DD` + /// - `YYYY-MM-DD HH:MM` + /// - `YYYY-MM-DD HH:MM:SS` + /// - `YYYY-MM-DD HH:MM:SS.SSS` + /// - `YYYY-MM-DDTHH:MM` + /// - `YYYY-MM-DDTHH:MM:SS` + /// - `YYYY-MM-DDTHH:MM:SS.SSS` + /// - `HH:MM` + /// - `HH:MM:SS` + /// - `HH:MM:SS.SSS` + /// + /// Related SQLite documentation: public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> DatabaseDateComponents? { - // https://www.sqlite.org/lang_datefunc.html - // - // Supported formats are: - // - // - YYYY-MM-DD - // - YYYY-MM-DD HH:MM - // - YYYY-MM-DD HH:MM:SS - // - YYYY-MM-DD HH:MM:SS.SSS - // - YYYY-MM-DDTHH:MM - // - YYYY-MM-DDTHH:MM:SS - // - YYYY-MM-DDTHH:MM:SS.SSS - // - HH:MM - // - HH:MM:SS - // - HH:MM:SS.SSS - - // We need a String guard let string = String.fromDatabaseValue(dbValue) else { return nil } return SQLiteDateParser().components(from: string) } - - // MARK: - Codable adoption - - - /// Creates a new instance by decoding from the given decoder. - /// - /// - parameters: - /// - decoder: The decoder to read data from. +} + +extension DatabaseDateComponents: Decodable { public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let stringValue = try container.decode(String.self) @@ -170,11 +161,9 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC } self = decodedValue } - - /// Encodes this value into the given encoder. - /// - /// - parameters: - /// - encoder: The encoder to write data to. +} + +extension DatabaseDateComponents: Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(String.fromDatabaseValue(databaseValue)!) diff --git a/GRDB/Core/Support/Foundation/DatabaseValueConvertible+ReferenceConvertible.swift b/GRDB/Core/Support/Foundation/DatabaseValueConvertible+ReferenceConvertible.swift index 8d9e44376..9afc83363 100644 --- a/GRDB/Core/Support/Foundation/DatabaseValueConvertible+ReferenceConvertible.swift +++ b/GRDB/Core/Support/Foundation/DatabaseValueConvertible+ReferenceConvertible.swift @@ -15,12 +15,10 @@ import Foundation /// extension Foo : DatabaseValueConvertible { /* empty */ } extension DatabaseValueConvertible where Self: ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible { - /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { (self as! ReferenceType).databaseValue } - /// Returns a value initialized from *dbValue*, if possible. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { ReferenceType.fromDatabaseValue(dbValue).flatMap { cast($0) } } diff --git a/GRDB/Core/Support/Foundation/Date.swift b/GRDB/Core/Support/Foundation/Date.swift index cc1d9490a..cc056bea4 100644 --- a/GRDB/Core/Support/Foundation/Date.swift +++ b/GRDB/Core/Support/Foundation/Date.swift @@ -4,22 +4,24 @@ import Foundation /// NSDate is stored in the database using the format /// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone. extension NSDate: DatabaseValueConvertible { - /// Returns a database value that contains the date encoded as + /// Returns a TEXT database value that contains the date encoded as /// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone. public var databaseValue: DatabaseValue { (self as Date).databaseValue } - /// Returns a date initialized from dbValue, if possible. + /// Creates an `NSDate` with the specified database value. /// - /// If database value contains a number, that number is interpreted as a + /// If the database value contains a number, that number is interpreted as a /// timeinterval since 00:00:00 UTC on 1 January 1970. /// - /// If database value contains a string, that string is interpreted as a + /// If the database value contains a string, that string is interpreted as a /// [SQLite date](https://sqlite.org/lang_datefunc.html) in the UTC time /// zone. Nil is returned if the date string does not contain at least the /// year, month and day components. Other components (minutes, etc.) /// are set to zero if missing. + /// + /// Otherwise, returns nil. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { guard let date = Date.fromDatabaseValue(dbValue) else { return nil @@ -32,22 +34,24 @@ extension NSDate: DatabaseValueConvertible { /// Date is stored in the database using the format /// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone. extension Date: DatabaseValueConvertible { - /// Returns a database value that contains the date encoded as + /// Returns a TEXT database value that contains the date encoded as /// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone. public var databaseValue: DatabaseValue { storageDateFormatter.string(from: self).databaseValue } - /// Returns a date initialized from dbValue, if possible. + /// Creates an `Date` with the specified database value. /// - /// If database value contains a number, that number is interpreted as a + /// If the database value contains a number, that number is interpreted as a /// timeinterval since 00:00:00 UTC on 1 January 1970. /// - /// If database value contains a string, that string is interpreted as a + /// If the database value contains a string, that string is interpreted as a /// [SQLite date](https://sqlite.org/lang_datefunc.html) in the UTC time /// zone. Nil is returned if the date string does not contain at least the /// year, month and day components. Other components (minutes, etc.) /// are set to zero if missing. + /// + /// Otherwise, returns nil. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Date? { if let databaseDateComponents = DatabaseDateComponents.fromDatabaseValue(dbValue) { return Date(databaseDateComponents: databaseDateComponents) diff --git a/GRDB/Core/Support/Foundation/Decimal.swift b/GRDB/Core/Support/Foundation/Decimal.swift index 07b72f168..44fe2eaeb 100644 --- a/GRDB/Core/Support/Foundation/Decimal.swift +++ b/GRDB/Core/Support/Foundation/Decimal.swift @@ -3,12 +3,22 @@ import Foundation /// Decimal adopts DatabaseValueConvertible extension Decimal: DatabaseValueConvertible { + /// Returns a TEXT decimal value. public var databaseValue: DatabaseValue { NSDecimalNumber(decimal: self) .description(withLocale: Locale(identifier: "en_US_POSIX")) .databaseValue } + /// Creates an `Decimal` with the specified database value. + /// + /// If the database value contains a integer or a double, returns a + /// `Decimal` initialized from this number. + /// + /// If the database value contains a string, parses the string with the + /// `en_US_POSIX` locale. + /// + /// Otherwise, returns nil. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { switch dbValue.storage { case .int64(let int64): diff --git a/GRDB/Core/Support/Foundation/NSData.swift b/GRDB/Core/Support/Foundation/NSData.swift index b3f08a3a8..72861ac02 100644 --- a/GRDB/Core/Support/Foundation/NSData.swift +++ b/GRDB/Core/Support/Foundation/NSData.swift @@ -4,13 +4,19 @@ import Foundation /// NSData is convertible to and from DatabaseValue. extension NSData: DatabaseValueConvertible { - /// Returns a value that can be stored in the database. + /// Returns a BLOB database value. public var databaseValue: DatabaseValue { (self as Data).databaseValue } - /// Returns an NSData initialized from *dbValue*, if it contains - /// a Blob. + /// Returns a `NSData` from the specified database value. + /// + /// If the database value contains a data blob, returns it. + /// + /// If the database value contains a string, returns this string converted + /// to UTF8 data. + /// + /// Otherwise, returns nil. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { guard let data = Data.fromDatabaseValue(dbValue) else { return nil diff --git a/GRDB/Core/Support/Foundation/NSNull.swift b/GRDB/Core/Support/Foundation/NSNull.swift index ec27ab934..f4683f52a 100644 --- a/GRDB/Core/Support/Foundation/NSNull.swift +++ b/GRDB/Core/Support/Foundation/NSNull.swift @@ -3,7 +3,7 @@ import Foundation /// NSNull adopts DatabaseValueConvertible extension NSNull: DatabaseValueConvertible { - /// Returns DatabaseValue.null. + /// Returns the NULL database value. public var databaseValue: DatabaseValue { .null } /// Returns nil. diff --git a/GRDB/Core/Support/Foundation/NSNumber.swift b/GRDB/Core/Support/Foundation/NSNumber.swift index 6e8e03663..9867e8f43 100644 --- a/GRDB/Core/Support/Foundation/NSNumber.swift +++ b/GRDB/Core/Support/Foundation/NSNumber.swift @@ -12,7 +12,13 @@ private let integerRoundingBehavior = NSDecimalNumberHandler( /// NSNumber adopts DatabaseValueConvertible extension NSNumber: DatabaseValueConvertible { - /// Returns a value that can be stored in the database. + /// A database value. + /// + /// If the number is an integer `NSDecimalNumber`, returns an INTEGER + /// database value. + /// + /// Otherwise, returns an INTEGER or REAL database value, according to the + /// value stored in the `NSNumber`. public var databaseValue: DatabaseValue { // Don't lose precision: store integers that fits in Int64 as Int64 if let decimal = self as? NSDecimalNumber, @@ -64,7 +70,15 @@ extension NSNumber: DatabaseValueConvertible { } } - /// Returns an NSNumber initialized from *dbValue*, if possible. + /// Returns a `NSNumber` from the specified database value. + /// + /// If the database value is an integer or a double, returns an `NSNumber` + /// initialized from this number. + /// + /// If the database value is a string, returns an `NSDecimalNumber` parsed + /// with the `en_US_POSIX` locale. + /// + /// Otherwise, returns nil. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { switch dbValue.storage { case .int64(let int64): diff --git a/GRDB/Core/Support/Foundation/NSString.swift b/GRDB/Core/Support/Foundation/NSString.swift index 7b956a265..acddddb35 100644 --- a/GRDB/Core/Support/Foundation/NSString.swift +++ b/GRDB/Core/Support/Foundation/NSString.swift @@ -4,12 +4,19 @@ import Foundation /// NSString adopts DatabaseValueConvertible extension NSString: DatabaseValueConvertible { - /// Returns a value that can be stored in the database. + /// Returns a TEXT database value. public var databaseValue: DatabaseValue { (self as String).databaseValue } - /// Returns an NSString initialized from *dbValue*, if possible. + /// Returns a `NSString` from the specified database value. + /// + /// If the database value contains a string, returns it. + /// + /// If the database value contains a data blob, parses this data as an + /// UTF8 string. + /// + /// Otherwise, returns nil. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { guard let string = String.fromDatabaseValue(dbValue) else { return nil diff --git a/GRDB/Core/Support/Foundation/URL.swift b/GRDB/Core/Support/Foundation/URL.swift index 13ea34509..cf4b96d12 100644 --- a/GRDB/Core/Support/Foundation/URL.swift +++ b/GRDB/Core/Support/Foundation/URL.swift @@ -4,13 +4,11 @@ import Foundation /// NSURL stores its absoluteString in the database. extension NSURL: DatabaseValueConvertible { - /// Returns a value that can be stored in the database. - /// (the URL's absoluteString). + /// Returns a TEXT database value containing the absolute URL. public var databaseValue: DatabaseValue { absoluteString?.databaseValue ?? .null } - /// Returns an NSURL initialized from *dbValue*, if possible. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { guard let string = String.fromDatabaseValue(dbValue) else { return nil diff --git a/GRDB/Core/Support/Foundation/UUID.swift b/GRDB/Core/Support/Foundation/UUID.swift index 8802db099..8aa88d090 100644 --- a/GRDB/Core/Support/Foundation/UUID.swift +++ b/GRDB/Core/Support/Foundation/UUID.swift @@ -3,6 +3,7 @@ import Foundation #if !os(Linux) /// NSUUID adopts DatabaseValueConvertible extension NSUUID: DatabaseValueConvertible { + /// Returns a BLOB database value containing the uuid bytes. public var databaseValue: DatabaseValue { var uuidBytes = ContiguousArray(repeating: UInt8(0), count: 16) return uuidBytes.withUnsafeMutableBufferPointer { buffer in @@ -11,6 +12,14 @@ extension NSUUID: DatabaseValueConvertible { } } + /// Returns a `NSUUID` from the specified database value. + /// + /// If the database value contains a string, parses this string as an uuid. + /// + /// If the database value contains a data blob that contains 16 bytes, + /// returns a uuid from those bytes. + /// + /// Otherwise, returns nil. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { switch dbValue.storage { case .blob(let data) where data.count == 16: @@ -28,12 +37,21 @@ extension NSUUID: DatabaseValueConvertible { /// UUID adopts DatabaseValueConvertible extension UUID: DatabaseValueConvertible { + /// Returns a BLOB database value containing the uuid bytes. public var databaseValue: DatabaseValue { withUnsafeBytes(of: uuid) { Data(bytes: $0.baseAddress!, count: $0.count).databaseValue } } + /// Returns a `UUID` from the specified database value. + /// + /// If the database value contains a string, parses this string as an uuid. + /// + /// If the database value contains a data blob that contains 16 bytes, + /// returns a uuid from those bytes. + /// + /// Otherwise, returns nil. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UUID? { switch dbValue.storage { case .blob(let data) where data.count == 16: diff --git a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift index 1cb6a403d..d3528bbca 100644 --- a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift +++ b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift @@ -12,12 +12,17 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible { self = sqlite3_column_int64(sqliteStatement, index) != 0 } - /// Returns a value that can be stored in the database. + /// Returns an INTEGER database value. public var databaseValue: DatabaseValue { (self ? 1 : 0).databaseValue } - /// Returns a Bool initialized from *dbValue*, if possible. + /// Returns a `Bool` from the specified database value. + /// + /// If the database value contains an integer or a double, returns whether + /// this number is zero. + /// + /// Otherwise, returns nil. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Bool? { // IMPLEMENTATION NOTE // @@ -106,12 +111,20 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible { self = v } - /// Returns a value that can be stored in the database. + /// Returns an INTEGER database value. public var databaseValue: DatabaseValue { Int64(self).databaseValue } - /// Returns an Int initialized from *dbValue*, if possible. + /// Returns a `Int` from the specified database value. + /// + /// If the database value contains a integer representable in this type, + /// returns this integer. + /// + /// If the database value contains a double representable in this type after + /// rounding toward zero, returns the conversion. + /// + /// Otherwise, returns nil. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int? { Int64.fromDatabaseValue(dbValue).flatMap { Int(exactly: $0) } } @@ -137,12 +150,20 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible { self = v } - /// Returns a value that can be stored in the database. + /// Returns an INTEGER database value. public var databaseValue: DatabaseValue { Int64(self).databaseValue } - /// Returns an Int8 initialized from *dbValue*, if possible. + /// Returns a `Int8` from the specified database value. + /// + /// If the database value contains a integer representable in this type, + /// returns this integer. + /// + /// If the database value contains a double representable in this type after + /// rounding toward zero, returns the conversion. + /// + /// Otherwise, returns nil. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int8? { Int64.fromDatabaseValue(dbValue).flatMap { Int8(exactly: $0) } } @@ -168,12 +189,20 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible { self = v } - /// Returns a value that can be stored in the database. + /// Returns an INTEGER database value. public var databaseValue: DatabaseValue { Int64(self).databaseValue } - /// Returns an Int16 initialized from *dbValue*, if possible. + /// Returns a `Int16` from the specified database value. + /// + /// If the database value contains a integer representable in this type, + /// returns this integer. + /// + /// If the database value contains a double representable in this type after + /// rounding toward zero, returns the conversion. + /// + /// Otherwise, returns nil. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int16? { Int64.fromDatabaseValue(dbValue).flatMap { Int16(exactly: $0) } } @@ -199,12 +228,20 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible { self = v } - /// Returns a value that can be stored in the database. + /// Returns an INTEGER database value. public var databaseValue: DatabaseValue { Int64(self).databaseValue } - /// Returns an Int32 initialized from *dbValue*, if possible. + /// Returns a `Int32` from the specified database value. + /// + /// If the database value contains a integer representable in this type, + /// returns this integer. + /// + /// If the database value contains a double representable in this type after + /// rounding toward zero, returns the conversion. + /// + /// Otherwise, returns nil. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int32? { Int64.fromDatabaseValue(dbValue).flatMap { Int32(exactly: $0) } } @@ -226,12 +263,19 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible { self = sqlite3_column_int64(sqliteStatement, index) } - /// Returns a value that can be stored in the database. + /// Returns an INTEGER database value. public var databaseValue: DatabaseValue { DatabaseValue(storage: .int64(self)) } - /// Returns an Int64 initialized from *dbValue*, if possible. + /// Returns a `Int64` from the specified database value. + /// + /// If the database value contains a integer, returns this integer. + /// + /// If the database value contains a double representable in this type after + /// rounding toward zero, returns the conversion. + /// + /// Otherwise, returns nil. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int64? { switch dbValue.storage { case .int64(let int64): @@ -266,12 +310,20 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible { self = v } - /// Returns a value that can be stored in the database. + /// Returns an INTEGER database value. public var databaseValue: DatabaseValue { Int64(self).databaseValue } - /// Returns an Int initialized from *dbValue*, if possible. + /// Returns a `UInt` from the specified database value. + /// + /// If the database value contains a integer representable in this type, + /// returns this integer. + /// + /// If the database value contains a double representable in this type after + /// rounding toward zero, returns the conversion. + /// + /// Otherwise, returns nil. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt? { Int64.fromDatabaseValue(dbValue).flatMap { UInt(exactly: $0) } } @@ -297,12 +349,20 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible { self = v } - /// Returns a value that can be stored in the database. + /// Returns an INTEGER database value. public var databaseValue: DatabaseValue { Int64(self).databaseValue } - /// Returns an UInt8 initialized from *dbValue*, if possible. + /// Returns a `UInt8` from the specified database value. + /// + /// If the database value contains a integer representable in this type, + /// returns this integer. + /// + /// If the database value contains a double representable in this type after + /// rounding toward zero, returns the conversion. + /// + /// Otherwise, returns nil. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt8? { Int64.fromDatabaseValue(dbValue).flatMap { UInt8(exactly: $0) } } @@ -328,12 +388,20 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible { self = v } - /// Returns a value that can be stored in the database. + /// Returns an INTEGER database value. public var databaseValue: DatabaseValue { Int64(self).databaseValue } - /// Returns an UInt16 initialized from *dbValue*, if possible. + /// Returns a `UInt16` from the specified database value. + /// + /// If the database value contains a integer representable in this type, + /// returns this integer. + /// + /// If the database value contains a double representable in this type after + /// rounding toward zero, returns the conversion. + /// + /// Otherwise, returns nil. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt16? { Int64.fromDatabaseValue(dbValue).flatMap { UInt16(exactly: $0) } } @@ -359,12 +427,20 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible { self = v } - /// Returns a value that can be stored in the database. + /// Returns an INTEGER database value. public var databaseValue: DatabaseValue { Int64(self).databaseValue } - /// Returns an UInt32 initialized from *dbValue*, if possible. + /// Returns a `UInt32` from the specified database value. + /// + /// If the database value contains a integer representable in this type, + /// returns this integer. + /// + /// If the database value contains a double representable in this type after + /// rounding toward zero, returns the conversion. + /// + /// Otherwise, returns nil. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt32? { Int64.fromDatabaseValue(dbValue).flatMap { UInt32(exactly: $0) } } @@ -390,12 +466,20 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible { self = v } - /// Returns a value that can be stored in the database. + /// Returns an INTEGER database value. public var databaseValue: DatabaseValue { Int64(self).databaseValue } - /// Returns an UInt64 initialized from *dbValue*, if possible. + /// Returns a `UInt64` from the specified database value. + /// + /// If the database value contains a integer representable in this type, + /// returns this integer. + /// + /// If the database value contains a double representable in this type after + /// rounding toward zero, returns the conversion. + /// + /// Otherwise, returns nil. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt64? { Int64.fromDatabaseValue(dbValue).flatMap { UInt64(exactly: $0) } } @@ -417,12 +501,18 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible { self = sqlite3_column_double(sqliteStatement, index) } - /// Returns a value that can be stored in the database. + /// Returns a REAL database value. public var databaseValue: DatabaseValue { DatabaseValue(storage: .double(self)) } - /// Returns a Double initialized from *dbValue*, if possible. + /// Returns a `Double` from the specified database value. + /// + /// If the database value contains a integer, returns the conversion. + /// + /// If the database value contains a double, returns this double. + /// + /// Otherwise, returns nil. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Double? { switch dbValue.storage { case .int64(let int64): @@ -451,12 +541,18 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible { self = Float(sqlite3_column_double(sqliteStatement, index)) } - /// Returns a value that can be stored in the database. + /// Returns a REAL database value. public var databaseValue: DatabaseValue { Double(self).databaseValue } - /// Returns a Float initialized from *dbValue*, if possible. + /// Returns a `Float` from the specified database value. + /// + /// If the database value contains a integer, returns the conversion. + /// + /// If the database value contains a double, returns the conversion. + /// + /// Otherwise, returns nil. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Float? { switch dbValue.storage { case .int64(let int64): @@ -485,12 +581,19 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible { self = String(cString: sqlite3_column_text(sqliteStatement, index)!) } - /// Returns a value that can be stored in the database. + /// Returns a TEXT database value. public var databaseValue: DatabaseValue { DatabaseValue(storage: .string(self)) } - /// Returns a String initialized from *dbValue*, if possible. + /// Returns a `String` from the specified database value. + /// + /// If the database value contains a string, returns it. + /// + /// If the database value contains a data blob, parses this data as an + /// UTF8 string. + /// + /// Otherwise, returns nil. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> String? { switch dbValue.storage { case .blob(let data): @@ -513,18 +616,20 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible { // MARK: - SQL Functions extension DatabaseFunction { - /// An SQL function that returns the Swift built-in capitalized - /// String property. + /// An SQL function that calls the Foundation + /// `String.capitalized` property. /// - /// The function returns NULL for non-strings values. + /// `NULL` is returned for non-strings values. /// /// This function is automatically added by GRDB to your database /// connections. It is the function used by the query interface's - /// capitalized: + /// ``SQLSpecificExpressible/capitalized``: /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn.capitalized) - /// let names = try String.fetchAll(dbQueue, request) // [String] + /// ```swift + /// let nameColumn = Column("name") + /// let request = Player.select(nameColumn.capitalized) + /// let names = try String.fetchAll(dbQueue, request) // [String] + /// ``` public static let capitalize = DatabaseFunction("swiftCapitalizedString", argumentCount: 1, pure: true) { dbValues in guard let string = String.fromDatabaseValue(dbValues[0]) else { @@ -533,18 +638,20 @@ extension DatabaseFunction { return string.capitalized } - /// An SQL function that returns the Swift built-in lowercased - /// String property. + /// An SQL function that calls the Swift + /// `String.lowercased()` method. /// - /// The function returns NULL for non-strings values. + /// `NULL` is returned for non-strings values. /// /// This function is automatically added by GRDB to your database /// connections. It is the function used by the query interface's - /// lowercased: + /// ``SQLSpecificExpressible/lowercased``: /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn.lowercased()) - /// let names = try String.fetchAll(dbQueue, request) // [String] + /// ```swift + /// let nameColumn = Column("name") + /// let request = Player.select(nameColumn.lowercased) + /// let names = try String.fetchAll(dbQueue, request) // [String] + /// ``` public static let lowercase = DatabaseFunction("swiftLowercaseString", argumentCount: 1, pure: true) { dbValues in guard let string = String.fromDatabaseValue(dbValues[0]) else { @@ -553,18 +660,20 @@ extension DatabaseFunction { return string.lowercased() } - /// An SQL function that returns the Swift built-in uppercased - /// String property. + /// An SQL function that calls the Swift + /// `String.uppercased()` method. /// - /// The function returns NULL for non-strings values. + /// `NULL` is returned for non-strings values. /// /// This function is automatically added by GRDB to your database /// connections. It is the function used by the query interface's - /// uppercased: + /// ``SQLSpecificExpressible/uppercased``: /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn.uppercased()) - /// let names = try String.fetchAll(dbQueue, request) // [String] + /// ```swift + /// let nameColumn = Column("name") + /// let request = Player.select(nameColumn.uppercased) + /// let names = try String.fetchAll(dbQueue, request) // [String] + /// ``` public static let uppercase = DatabaseFunction("swiftUppercaseString", argumentCount: 1, pure: true) { dbValues in guard let string = String.fromDatabaseValue(dbValues[0]) else { @@ -572,21 +681,21 @@ extension DatabaseFunction { } return string.uppercased() } -} -extension DatabaseFunction { - /// An SQL function that returns the Swift built-in - /// localizedCapitalized String property. + /// An SQL function that calls the Foundation + /// `String.localizedCapitalized` property. /// - /// The function returns NULL for non-strings values. + /// `NULL` is returned for non-strings values. /// /// This function is automatically added by GRDB to your database /// connections. It is the function used by the query interface's - /// localizedCapitalized: + /// ``SQLSpecificExpressible/localizedCapitalized``: /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn.localizedCapitalized) - /// let names = try String.fetchAll(dbQueue, request) // [String] + /// ```swift + /// let nameColumn = Column("name") + /// let request = Player.select(nameColumn.localizedCapitalized) + /// let names = try String.fetchAll(dbQueue, request) // [String] + /// ``` public static let localizedCapitalize = DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { dbValues in guard let string = String.fromDatabaseValue(dbValues[0]) else { @@ -595,18 +704,21 @@ extension DatabaseFunction { return string.localizedCapitalized } - /// An SQL function that returns the Swift built-in - /// localizedLowercased String property. + + /// An SQL function that calls the Foundation + /// `String.localizedLowercase` property. /// - /// The function returns NULL for non-strings values. + /// `NULL` is returned for non-strings values. /// /// This function is automatically added by GRDB to your database /// connections. It is the function used by the query interface's - /// localizedLowercased: + /// ``SQLSpecificExpressible/localizedLowercased``: /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn.localizedLowercased) - /// let names = try String.fetchAll(dbQueue, request) // [String] + /// ```swift + /// let nameColumn = Column("name") + /// let request = Player.select(nameColumn.localizedLowercase) + /// let names = try String.fetchAll(dbQueue, request) // [String] + /// ``` public static let localizedLowercase = DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { dbValues in guard let string = String.fromDatabaseValue(dbValues[0]) else { @@ -615,18 +727,20 @@ extension DatabaseFunction { return string.localizedLowercase } - /// An SQL function that returns the Swift built-in - /// localizedUppercased String property. + /// An SQL function that calls the Foundation + /// `String.localizedUppercase` property. /// - /// The function returns NULL for non-strings values. + /// `NULL` is returned for non-strings values. /// /// This function is automatically added by GRDB to your database /// connections. It is the function used by the query interface's - /// localizedUppercased: + /// ``SQLSpecificExpressible/localizedUppercased``: /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn.localizedUppercased) - /// let names = try String.fetchAll(dbQueue, request) // [String] + /// ```swift + /// let nameColumn = Column("name") + /// let request = Player.select(nameColumn.localizedUppercase) + /// let names = try String.fetchAll(dbQueue, request) // [String] + /// ``` public static let localizedUppercase = DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { dbValues in guard let string = String.fromDatabaseValue(dbValues[0]) else { @@ -651,96 +765,146 @@ extension DatabaseCollation { // collation names with sqlite3_collation_needed(). // See https://www.sqlite.org/capi3ref.html#sqlite3_collation_needed - /// A collation, or SQL string comparison function, that compares strings - /// according to the the Swift built-in == and <= operators. + /// A collation that compares strings according to the built-in `==` and + /// `<=` operators of the Swift String. /// /// This collation is automatically added by GRDB to your database /// connections. /// - /// You can use it when creating database tables: + /// You can use the collation when creating database tables: /// - /// let collationName = DatabaseCollation.caseInsensitiveCompare.name - /// dbQueue.execute(sql: """ - /// CREATE TABLE players ( - /// name TEXT COLLATE \(collationName) - /// ) - /// """) + /// ```swift + /// try db.create(table: "player") { t in + /// t.column("name", .text).collate(.unicodeCompare) + /// } + /// ``` + /// + /// Embed the collation name in your raw SQL queries: + /// + /// ```swift + /// let collationName = DatabaseCollation.unicodeCompare.name + /// dbQueue.execute(sql: """ + /// CREATE TABLE player ( + /// name TEXT COLLATE \(collationName) + /// ) + /// """) + /// ``` public static let unicodeCompare = DatabaseCollation("swiftCompare") { (lhs, rhs) in (lhs < rhs) ? .orderedAscending : ((lhs == rhs) ? .orderedSame : .orderedDescending) } - /// A collation, or SQL string comparison function, that compares strings - /// according to the the Swift built-in caseInsensitiveCompare(_:) method. + /// A collation that compares strings according to the Foundation + /// `String.caseInsensitiveCompare(_:)` method. /// /// This collation is automatically added by GRDB to your database /// connections. /// - /// You can use it when creating database tables: + /// You can use the collation when creating database tables: /// - /// let collationName = DatabaseCollation.caseInsensitiveCompare.name - /// dbQueue.execute(sql: """ - /// CREATE TABLE players ( - /// name TEXT COLLATE \(collationName) - /// ) - /// """) + /// ```swift + /// try db.create(table: "player") { t in + /// t.column("name", .text).collate(.caseInsensitiveCompare) + /// } + /// ``` + /// + /// Embed the collation name in your raw SQL queries: + /// + /// ```swift + /// let collationName = DatabaseCollation.caseInsensitiveCompare.name + /// dbQueue.execute(sql: """ + /// CREATE TABLE player ( + /// name TEXT COLLATE \(collationName) + /// ) + /// """) + /// ``` public static let caseInsensitiveCompare = DatabaseCollation("swiftCaseInsensitiveCompare") { (lhs, rhs) in lhs.caseInsensitiveCompare(rhs) } - /// A collation, or SQL string comparison function, that compares strings - /// according to the the Swift built-in localizedCaseInsensitiveCompare(_:) method. + /// A collation that compares strings according to the Foundation + /// `String.localizedCaseInsensitiveCompare(_:)` method. /// /// This collation is automatically added by GRDB to your database /// connections. /// - /// You can use it when creating database tables: + /// You can use the collation when creating database tables: /// - /// let collationName = DatabaseCollation.localizedCaseInsensitiveCompare.name - /// dbQueue.execute(sql: """ - /// CREATE TABLE players ( - /// name TEXT COLLATE \(collationName) - /// ) - /// """) + /// ```swift + /// try db.create(table: "player") { t in + /// t.column("name", .text).collate(.localizedCaseInsensitiveCompare) + /// } + /// ``` + /// + /// Embed the collation name in your raw SQL queries: + /// + /// ```swift + /// let collationName = DatabaseCollation.localizedCaseInsensitiveCompare.name + /// dbQueue.execute(sql: """ + /// CREATE TABLE player ( + /// name TEXT COLLATE \(collationName) + /// ) + /// """) + /// ``` public static let localizedCaseInsensitiveCompare = DatabaseCollation("swiftLocalizedCaseInsensitiveCompare") { (lhs, rhs) in lhs.localizedCaseInsensitiveCompare(rhs) } - /// A collation, or SQL string comparison function, that compares strings - /// according to the the Swift built-in localizedCompare(_:) method. + /// A collation that compares strings according to the Foundation + /// `String.localizedCompare(_:)` method. /// /// This collation is automatically added by GRDB to your database /// connections. /// - /// You can use it when creating database tables: + /// You can use the collation when creating database tables: /// - /// let collationName = DatabaseCollation.localizedCompare.name - /// dbQueue.execute(sql: """ - /// CREATE TABLE players ( - /// name TEXT COLLATE \(collationName) - /// ) - /// """) + /// ```swift + /// try db.create(table: "player") { t in + /// t.column("name", .text).collate(.localizedCompare) + /// } + /// ``` + /// + /// Embed the collation name in your raw SQL queries: + /// + /// ```swift + /// let collationName = DatabaseCollation.localizedCompare.name + /// dbQueue.execute(sql: """ + /// CREATE TABLE player ( + /// name TEXT COLLATE \(collationName) + /// ) + /// """) + /// ``` public static let localizedCompare = DatabaseCollation("swiftLocalizedCompare") { (lhs, rhs) in lhs.localizedCompare(rhs) } - /// A collation, or SQL string comparison function, that compares strings - /// according to the the Swift built-in localizedStandardCompare(_:) method. + /// A collation that compares strings according to the Foundation + /// `String.localizedStandardCompare(_:)` method. /// /// This collation is automatically added by GRDB to your database /// connections. /// - /// You can use it when creating database tables: + /// You can use the collation when creating database tables: /// - /// let collationName = DatabaseCollation.localizedStandardCompare.name - /// dbQueue.execute(sql: """ - /// CREATE TABLE players ( - /// name TEXT COLLATE \(collationName) - /// ) - /// """) + /// ```swift + /// try db.create(table: "player") { t in + /// t.column("name", .text).collate(.localizedStandardCompare) + /// } + /// ``` + /// + /// Embed the collation name in your raw SQL queries: + /// + /// ```swift + /// let collationName = DatabaseCollation.localizedStandardCompare.name + /// dbQueue.execute(sql: """ + /// CREATE TABLE player ( + /// name TEXT COLLATE \(collationName) + /// ) + /// """) + /// ``` public static let localizedStandardCompare = DatabaseCollation("swiftLocalizedStandardCompare") { (lhs, rhs) in lhs.localizedStandardCompare(rhs) diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index a1f0beec2..531b8ce42 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -2,8 +2,8 @@ extension Database { // MARK: - Database Observation - /// Add a transaction observer, so that it gets notified of - /// database changes. + /// Adds a transaction observer, so that it gets notified of + /// database changes and transactions. /// /// This method has no effect on read-only database connections. /// @@ -26,7 +26,7 @@ extension Database { observationBroker.add(transactionObserver: transactionObserver, extent: extent) } - /// Remove a transaction observer. + /// Removes a transaction observer. public func remove(transactionObserver: some TransactionObserver) { SchedulingWatchdog.preconditionValidQueue(self) guard let observationBroker else { return } @@ -40,21 +40,25 @@ extension Database { } /// Registers closures to be executed after the next or current - /// transaction completion. + /// transaction completes. /// - /// try dbQueue.write { db in - /// db.afterNextTransaction { _ in - /// print("success") - /// } - /// ... - /// } // prints "commit" + /// For example: + /// + /// ```swift + /// try dbQueue.write { db in + /// db.afterNextTransaction { _ in + /// print("success") + /// } + /// ... + /// } // prints "success" + /// ``` /// /// Closure are executed in a protected dispatch queue, serialized will all /// database updates. /// - /// - precondition: Database is not read-only. - /// - parameter onCommit: A closure execute on transaction commit. - /// - parameter onRollback: A closure execute on transaction rollback. + /// - precondition: Database connection is not read-only. + /// - parameter onCommit: A closure executed on transaction commit. + /// - parameter onRollback: A closure executed on transaction rollback. public func afterNextTransaction( onCommit: @escaping (Database) -> Void, onRollback: @escaping (Database) -> Void = { _ in }) @@ -93,11 +97,11 @@ extension Database { /// /// See ``Database/add(transactionObserver:extent:)``. public enum TransactionObservationExtent { - /// Observation lasts until observer is deallocated + /// Observation lasts until observer is deallocated. case observerLifetime - /// Observation lasts until the next transaction + /// Observation lasts until the next transaction. case nextTransaction - /// Observation lasts until the database is closed + /// Observation lasts until the database is closed. case databaseLifetime } } @@ -714,73 +718,113 @@ class DatabaseObservationBroker { // MARK: - TransactionObserver -/// A transaction observer is notified of all changes and transactions committed -/// or rollbacked on a database. +/// A type that tracks all database changes and transactions performed in +/// a database. /// -/// Adopting types must be a class. +/// An observer starts receiving change notifications after it has been added to +/// a database connection with the +/// ``DatabaseWriter/add(transactionObserver:extent:)`` or +/// ``Database/add(transactionObserver:extent:)`` methods. +/// +/// All observer methods are called in a the writer dispatch queue, serialized +/// with all database updates (see ``DatabaseWriter``). +/// +/// Some changes and transactions are not notified: +/// +/// - Transactions performed in read-only database connections. +/// - Changes and transactions performed by other database connections. +/// - Changes to internal system tables (such as `sqlite_master`). +/// - Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables +/// - The deletion of duplicate rows triggered by +/// [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses +/// (this last exception might change in a future release of SQLite). +/// +/// ## Topics +/// +/// ### Handling Database Changes +/// +/// - ``observes(eventsOfKind:)`` +/// - ``databaseDidChange(with:)`` +/// - ``stopObservingDatabaseChangesUntilNextTransaction()`` +/// - ``DatabaseEvent`` +/// - ``DatabaseEventKind`` +/// +/// ### Handling Transactions +/// +/// - ``databaseWillCommit()-7mksu`` +/// - ``databaseDidCommit(_:)`` +/// - ``databaseDidRollback(_:)`` public protocol TransactionObserver: AnyObject { - /// Filters database changes that should be notified the the - /// databaseDidChange(with:) method. + /// Returns whether specific kinds of database changes should be notified + /// to the observer. + /// + /// When this method returns false, database events of this kind are not + /// notified to the ``databaseDidChange(with:)`` method. + /// + /// For example: + /// + /// ```swift + /// // An observer that is only interested in the "player" table + /// class PlayerObserver: TransactionObserver { + /// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { + /// return eventKind.tableName == "player" + /// } + /// } + /// ``` func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool - /// Notifies a database change (insert, update, or delete). + /// Called when the database is changed by an insert, update, or + /// delete event. /// /// The change is pending until the current transaction ends. See - /// databaseWillCommit, databaseDidCommit and databaseDidRollback. - /// - /// This method is called in a protected dispatch queue, serialized will all - /// database updates. - /// - /// The event is only valid for the duration of this method call. If you - /// need to keep it longer, store a copy: `event.copy()` + /// ``databaseWillCommit()-7mksu``, ``databaseDidCommit(_:)`` and + /// ``databaseDidRollback(_:)``. /// /// The observer has an opportunity to stop receiving further change events /// from the current transaction by calling the - /// stopObservingDatabaseChangesUntilNextTransaction() method. + /// ``stopObservingDatabaseChangesUntilNextTransaction()`` method. /// - /// - warning: this method must not change the database. + /// - note: The event is only valid for the duration of this method call. + /// If you need to keep it longer, store a copy: `event.copy()`. + /// + /// - precondition: This method must not access the database. func databaseDidChange(with event: DatabaseEvent) - /// When a transaction is about to be committed, the transaction observer - /// has an opportunity to rollback pending changes by throwing an error. + /// Called when a transaction is about to be committed. /// - /// This method is called on the database queue. + /// The transaction observer has an opportunity to rollback pending changes + /// by throwing an error from this method. /// - /// - warning: this method must not change the database. - /// - /// - throws: An eventual error that rollbacks pending changes. + /// - precondition: This method must not access the database. + /// - throws: The eventual error that rollbacks pending changes. func databaseWillCommit() throws - /// Database changes have been committed. - /// - /// This method is called on the database queue. It can change the database. + /// Called when a transaction has been committed on disk. func databaseDidCommit(_ db: Database) - /// Database changes have been rollbacked. - /// - /// This method is called on the database queue. It can change the database. + /// Called when a transaction has been rollbacked. func databaseDidRollback(_ db: Database) #if SQLITE_ENABLE_PREUPDATE_HOOK + /// Called when the database is changed by an insert, update, or + /// delete event. + /// /// Notifies before a database change (insert, update, or delete) /// with change information (initial / final values for the row's - /// columns). (Called *before* databaseDidChangeWithEvent.) + /// columns). (Called *before* ``databaseDidChange(with:)``.) /// /// The change is pending until the end of the current transaction, /// and you always get a second chance to get basic event information in - /// the databaseDidChangeWithEvent callback. + /// the ``databaseDidChange(with:)`` callback. /// /// This callback is mostly useful for calculating detailed change /// information for a row, and provides the initial / final values. /// - /// This method is called in a protected dispatch queue, serialized will all - /// database updates. - /// /// The event is only valid for the duration of this method call. If you /// need to keep it longer, store a copy: `event.copy()` /// - /// - warning: this method must not change the database. + /// - warning: this method must not access the database. /// /// **Availability Info** /// @@ -790,45 +834,47 @@ public protocol TransactionObserver: AnyObject { /// does not have this enabled, so you'll need to compile your own /// version of SQLite: /// See - /// - /// The databaseDidChangeWithEvent callback is always available, - /// and may provide most/all of what you need. func databaseWillChange(with event: DatabasePreUpdateEvent) #endif } extension TransactionObserver { - /// Default implementation does nothing - public func databaseWillCommit() throws { - } + /// The default implementation does nothing. + public func databaseWillCommit() throws { } #if SQLITE_ENABLE_PREUPDATE_HOOK - /// Default implementation does nothing - public func databaseWillChange(with event: DatabasePreUpdateEvent) { - } + /// The default implementation does nothing. + public func databaseWillChange(with event: DatabasePreUpdateEvent) { } #endif - /// After this method has been called, the `databaseDidChange(with:)` + /// Prevents the observer from receiving further change notifications until + /// the next transaction. + /// + /// After this method has been called, the ``databaseDidChange(with:)`` /// method won't be called until the next transaction. /// /// For example: /// - /// class PlayerObserver: TransactionObserver { - /// var playerTableWasModified = false + /// ```swift + /// // An observer that is only interested in the "player" table + /// class PlayerObserver: TransactionObserver { + /// var playerTableWasModified = false /// - /// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - /// return eventKind.tableName == "player" - /// } - /// - /// func databaseDidChange(with event: DatabaseEvent) { - /// playerTableWasModified = true - /// - /// // It is pointless to keep on tracking further changes: - /// stopObservingDatabaseChangesUntilNextTransaction() - /// } + /// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { + /// return eventKind.tableName == "player" /// } /// - /// - precondition: This method must be called from `databaseDidChange(with:)`. + /// func databaseDidChange(with event: DatabaseEvent) { + /// playerTableWasModified = true + /// + /// // It is pointless to keep on tracking further changes: + /// stopObservingDatabaseChangesUntilNextTransaction() + /// } + /// } + /// ``` + /// + /// - precondition: This method must be called from + /// ``databaseDidChange(with:)``. public func stopObservingDatabaseChangesUntilNextTransaction() { guard let broker = SchedulingWatchdog.current?.databaseObservationBroker else { fatalError(""" @@ -944,17 +990,19 @@ struct StatementObservation { // MARK: - Database events -/// A kind of database event. See the `TransactionObserver` protocol for -/// more information. +/// A kind of database event. +/// +/// See the ``TransactionObserver/observes(eventsOfKind:)`` method in the +/// ``TransactionObserver`` protocol for more information. @frozen public enum DatabaseEventKind { - /// The insertion of a row in a database table + /// The insertion of a row in a database table. case insert(tableName: String) - /// The deletion of a row in a database table + /// The deletion of a row in a database table. case delete(tableName: String) - /// The update of a set of columns in a database table + /// The update of a set of columns in a database table. case update(tableName: String, columnNames: Set) var modifiedRegion: DatabaseRegion { @@ -979,7 +1027,7 @@ public enum DatabaseEventKind { } extension DatabaseEventKind { - /// The impacted database table + /// The name of the impacted database table. public var tableName: String { switch self { case let .insert(tableName: tableName): return tableName @@ -994,43 +1042,51 @@ protocol DatabaseEventProtocol { func matchesKind(_ databaseEventKind: DatabaseEventKind) -> Bool } -/// A database event, notified to TransactionObserver. +/// A database event. +/// +/// See the ``TransactionObserver/databaseDidChange(with:)`` method in the +/// ``TransactionObserver`` protocol for more information. public struct DatabaseEvent { - - /// An event kind + /// An event kind. public enum Kind: CInt { - /// SQLITE_INSERT - case insert = 18 + /// An insertion event + case insert = 18 // SQLITE_INSERT - /// SQLITE_DELETE - case delete = 9 + /// A deletion event + case delete = 9 // SQLITE_DELETE - /// SQLITE_UPDATE - case update = 23 + /// An update event + case update = 23 // SQLITE_UPDATE } private let impl: any DatabaseEventImpl - /// The event kind + /// The event kind (insert, delete, or update). public let kind: Kind - /// The database name + /// The name of the changed database. public var databaseName: String { impl.databaseName } - /// The table name + /// The name of the changed database table. public var tableName: String { impl.tableName } /// The rowID of the changed row. public let rowID: Int64 - /// Returns an event that can be stored: + /// Returns a copy of the event. /// - /// class MyObserver: TransactionObserver { - /// var events: [DatabaseEvent] - /// func databaseDidChange(with event: DatabaseEvent) { - /// events.append(event.copy()) - /// } + /// An event is only valid for the duration of the + /// ``TransactionObserver/databaseDidChange(with:)`` method. You must copy + /// the event when you want to store it for later: + /// + /// ```swift + /// class MyObserver: TransactionObserver { + /// var events: [DatabaseEvent] + /// func databaseDidChange(with event: DatabaseEvent) { + /// events.append(event.copy()) /// } + /// } + /// ``` public func copy() -> DatabaseEvent { impl.copy(self) } diff --git a/GRDB/Documentation.docc/DatabaseConnections.md b/GRDB/Documentation.docc/DatabaseConnections.md new file mode 100644 index 000000000..3723df5d2 --- /dev/null +++ b/GRDB/Documentation.docc/DatabaseConnections.md @@ -0,0 +1,18 @@ +# Database Connections + +Open database connections to SQLite databases. + +## Topics + +### Opening Database Connections + +- ``Configuration`` +- ``DatabasePool`` +- ``DatabaseQueue`` +- ``DatabaseSnapshot`` +- ``DatabaseReader`` +- ``DatabaseWriter`` + +### Using Database Connections + +- ``Database`` diff --git a/GRDB/Documentation.docc/DatabaseObservation.md b/GRDB/Documentation.docc/DatabaseObservation.md new file mode 100644 index 000000000..286801012 --- /dev/null +++ b/GRDB/Documentation.docc/DatabaseObservation.md @@ -0,0 +1,18 @@ +# Database Observation + +Observe database changes and transactions. + +## Topics + +### Observing Database Values + +- ``AsyncValueObservation`` +- ``SharedValueObservation`` +- ``ValueObservation`` + +### Observing Database Transactions + +- ``DatabaseRegion`` +- ``DatabaseRegionObservation`` +- ``DatabaseRegionConvertible`` +- ``TransactionObserver`` diff --git a/GRDB/Documentation.docc/Documentation.md b/GRDB/Documentation.docc/Documentation.md new file mode 100644 index 000000000..8281a882a --- /dev/null +++ b/GRDB/Documentation.docc/Documentation.md @@ -0,0 +1,37 @@ +# ``GRDB`` + +A toolkit for SQLite databases, with a focus on application development + +## Overview + +GRDB provides raw access to SQL and advanced SQLite features, because one sometimes enjoys a sharp tool. It has robust concurrency primitives, so that multi-threaded applications can efficiently use their databases. It grants your application models with persistence and fetching methods, so that you don't have to deal with SQL and raw database rows when you don't want to. + + +## Topics + +### Fundamentals + +- +- +- + +### Migrations + +- ``DatabaseMigrator`` + +### Record Types and the Query Interface + +- + +### Database Observation + +- + +### Full-Text Search + +- ``FTS3`` +- ``FTS4`` + +### Combine Publishers + +- ``DatabasePublishers`` diff --git a/GRDB/Documentation.docc/Errors.md b/GRDB/Documentation.docc/Errors.md new file mode 100644 index 000000000..4e27efb31 --- /dev/null +++ b/GRDB/Documentation.docc/Errors.md @@ -0,0 +1,13 @@ +# Database Errors + +The errors thrown when accessing an SQLite database. + +## Topics + +### SQLite Errors + +- ``DatabaseError`` + +### Record Errors + +- ``PersistenceError`` diff --git a/GRDB/Documentation.docc/QueryInterface.md b/GRDB/Documentation.docc/QueryInterface.md new file mode 100644 index 000000000..0c7bcd7ad --- /dev/null +++ b/GRDB/Documentation.docc/QueryInterface.md @@ -0,0 +1,33 @@ +# Record Types and the Query Interface + +Record types and the query interface build SQL queries for you + +## Topics + +### Records + +- ``Record`` +- ``EncodableRecord`` +- ``FetchableRecord`` +- ``MutablePersistableRecord`` +- ``PersistableRecord`` +- ``TableRecord`` + +### Associations + +- ``Association`` + +### Query Interface Requests + +- ``CommonTableExpression`` +- ``QueryInterfaceRequest`` +- ``Table`` + +### Supporting Types + +- ``DerivableRequest`` +- ``SQLExpressible`` +- ``SQLSpecificExpressible`` +- ``SQLOrderingTerm`` +- ``SQLSelectable`` +- ``SQLSubqueryable`` diff --git a/GRDB/Documentation.docc/SQLSupport.md b/GRDB/Documentation.docc/SQLSupport.md new file mode 100644 index 000000000..cdae48a7f --- /dev/null +++ b/GRDB/Documentation.docc/SQLSupport.md @@ -0,0 +1,32 @@ +# SQL, Prepared Statements, Rows, and Values + +SQL is the fundamental language for accessing SQLite databases. + +## Topics + +### Prepared Statements + +- ``Statement`` + +### Database Rows + +- ``Row`` + +### Database Values + +- ``DatabaseDateComponents`` +- ``DatabaseValue`` +- ``DatabaseValueConvertible`` +- ``StatementColumnConvertible`` + +### SQL Literals and Requests + +- ``databaseQuestionMarks(count:)`` +- ``SQL`` +- ``SQLRequest`` +- ``FetchRequest`` + +### Cursors + +- ``Cursor`` +- ``DatabaseCursor`` diff --git a/GRDB/FTS/FTS3.swift b/GRDB/FTS/FTS3.swift index 6c14f0cfe..d93549816 100644 --- a/GRDB/FTS/FTS3.swift +++ b/GRDB/FTS/FTS3.swift @@ -1,59 +1,94 @@ -/// FTS3 lets you define "fts3" virtual tables. +/// The virtual table module for the FTS3 full-text engine. /// -/// // CREATE VIRTUAL TABLE document USING fts3(content) -/// try db.create(virtualTable: "document", using: FTS3()) { t in -/// t.column("content") -/// } -public struct FTS3: VirtualTableModule { - /// Options for Latin script characters. Matches the raw "remove_diacritics" - /// tokenizer argument. - /// - /// See +/// To create FTS3 tables, use the ``Database`` method +/// ``Database/create(virtualTable:ifNotExists:using:_:)``. +/// +/// Related SQLite documentation: +/// +/// ## Topics +/// +/// ### The FTS3 Module +/// +/// - ``init()`` +/// - ``FTS3TableDefinition`` +/// - ``FTS3TokenizerDescriptor`` +/// +/// ### Full-Text Search Pattern +/// +/// - ``FTS3Pattern`` +/// +/// ### Tokenizing Strings +/// +/// - ``tokenize(_:withTokenizer:)`` +public struct FTS3 { + /// Options for Latin script characters. public enum Diacritics { - /// Do not remove diacritics from Latin script characters. This - /// option matches the raw "remove_diacritics=0" tokenizer argument. + /// Do not remove diacritics from Latin script characters. + /// + /// This option matches the `remove_diacritics=0` tokenizer argument. case keep - /// Remove diacritics from Latin script characters. This - /// option matches the raw "remove_diacritics=1" tokenizer argument. + + /// Remove diacritics from Latin script characters. + /// + /// This option matches the `remove_diacritics=1` tokenizer argument. case removeLegacy + #if GRDBCUSTOMSQLITE - /// Remove diacritics from Latin script characters. This - /// option matches the raw "remove_diacritics=2" tokenizer argument, - /// available from SQLite 3.27.0 + /// Remove diacritics from Latin script characters. + /// + /// This option matches the `remove_diacritics=2` tokenizer argument. case remove #elseif !GRDBCIPHER - /// Remove diacritics from Latin script characters. This - /// option matches the raw "remove_diacritics=2" tokenizer argument, - /// available from SQLite 3.27.0 - @available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) + /// Remove diacritics from Latin script characters. + /// + /// This option matches the `remove_diacritics=2` tokenizer argument. + @available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) // SQLite 3.27+ case remove #endif } - /// Creates a FTS3 module suitable for the Database - /// `create(virtualTable:using:)` method. + /// Creates an FTS3 module. /// - /// // CREATE VIRTUAL TABLE document USING fts3(content) - /// try db.create(virtualTable: "document", using: FTS3()) { t in - /// t.column("content") - /// } + /// For example: + /// + /// ```swift + /// // CREATE VIRTUAL TABLE document USING fts3(content) + /// try db.create(virtualTable: "document", using: FTS3()) { t in + /// t.column("content") + /// } + /// ``` + /// + /// See ``Database/create(virtualTable:ifNotExists:using:_:)`` public init() { } /// Returns an array of tokens found in the string argument. /// /// For example: /// - /// try FTS3.tokenize("SQLite database") // ["sqlite", "database"] - /// try FTS3.tokenize("Gustave Doré") // ["gustave", "doré"]) + /// ```swift + /// // ["sqlite", "database"] + /// try FTS3.tokenize("SQLite database") /// - /// Results can be altered with an explicit tokenizer - default is `.simple`. - /// See . + /// // ["gustave", "doré"]) + /// try FTS3.tokenize("Gustave Doré") + /// ``` /// - /// try FTS3.tokenize("SQLite database", withTokenizer: .porter) // ["sqlite", "databas"] - /// try FTS3.tokenize("Gustave Doré", withTokenizer: .unicode61()) // ["gustave", "dore"]) + /// Results can be altered with the `tokenizer` argument: /// - /// Tokenization is performed by the `fts3tokenize` virtual table described - /// at . + /// ```swift + /// // ["sqlite", "databas"] + /// try FTS3.tokenize("SQLite database", withTokenizer: .porter) + /// + /// // ["gustave", "dore"]) + /// try FTS3.tokenize("Gustave Doré", withTokenizer: .unicode61()) + /// ``` + /// + /// Related SQLite documentation: + /// + /// - + /// - + /// + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func tokenize( _ string: String, withTokenizer tokenizer: FTS3TokenizerDescriptor = .simple) @@ -72,22 +107,15 @@ public struct FTS3: VirtualTableModule { """, arguments: [string]) } } +} + +extension FTS3: VirtualTableModule { + public var moduleName: String { "fts3" } - // MARK: - VirtualTableModule Adoption - - /// The virtual table module name - public let moduleName = "fts3" - - /// Reserved; part of the VirtualTableModule protocol. - /// - /// See Database.create(virtualTable:using:) public func makeTableDefinition(configuration: VirtualTableConfiguration) -> FTS3TableDefinition { FTS3TableDefinition() } - /// Reserved; part of the VirtualTableModule protocol. - /// - /// See Database.create(virtualTable:using:) public func moduleArguments(for definition: FTS3TableDefinition, in db: Database) -> [String] { var arguments = definition.columns if let tokenizer = definition.tokenizer { @@ -103,37 +131,47 @@ public struct FTS3: VirtualTableModule { return arguments } - /// Reserved; part of the VirtualTableModule protocol. - /// - /// See Database.create(virtualTable:using:) - public func database(_ db: Database, didCreate tableName: String, using definition: FTS3TableDefinition) { - } + public func database(_ db: Database, didCreate tableName: String, using definition: FTS3TableDefinition) { } } -/// The FTS3TableDefinition class lets you define columns of a FTS3 virtual table. +/// A `FTS3TableDefinition` lets you define the components of an FTS3 +/// virtual table. /// -/// You don't create instances of this class. Instead, you use the Database -/// `create(virtualTable:using:)` method: +/// You don't create instances of this class. Instead, you use the `Database` +/// ``Database/create(virtualTable:ifNotExists:using:_:)`` method: /// -/// try db.create(virtualTable: "document", using: FTS3()) { t in // t is FTS3TableDefinition -/// t.column("content") -/// } +/// ```swift +/// try db.create(virtualTable: "document", using: FTS3()) { t in // t is FTS3TableDefinition +/// t.column("content") +/// } +/// ``` public final class FTS3TableDefinition { fileprivate var columns: [String] = [] - /// The virtual table tokenizer + /// The virtual table tokenizer. /// - /// try db.create(virtualTable: "document", using: FTS3()) { t in - /// t.tokenizer = .porter - /// } - /// See + /// For example: + /// + /// ```swift + /// // CREATE VIRTUAL TABLE documents USING fts3(tokenize=porter) + /// try db.create(virtualTable: "document", using: FTS3()) { t in + /// t.tokenizer = .porter + /// } + /// ``` + /// + /// Related SQLite documentation: public var tokenizer: FTS3TokenizerDescriptor? /// Appends a table column. /// - /// try db.create(virtualTable: "document", using: FTS3()) { t in - /// t.column("content") - /// } + /// For example: + /// + /// ```swift + /// // CREATE VIRTUAL TABLE document USING fts3(content) + /// try db.create(virtualTable: "document", using: FTS3()) { t in + /// t.column("content") + /// } + /// ``` /// /// - parameter name: the column name. public func column(_ name: String) { diff --git a/GRDB/FTS/FTS3Pattern.swift b/GRDB/FTS/FTS3Pattern.swift index 4cf34e82b..9862566f2 100644 --- a/GRDB/FTS/FTS3Pattern.swift +++ b/GRDB/FTS/FTS3Pattern.swift @@ -1,16 +1,42 @@ -/// A full text pattern that can query FTS3 and FTS4 virtual tables. +/// A full text pattern for querying FTS3 virtual tables. +/// +/// `FTS3Pattern` can be used with both ``FTS3`` and ``FTS4`` tables. +/// +/// Related SQLite documentation: +/// +/// ## Topics +/// +/// ### Creating Raw FTS3 Patterns +/// +/// - ``init(rawPattern:)`` +/// +/// ### Creating FTS3 Patterns from User Input +/// +/// - ``init(matchingAllPrefixesIn:)`` +/// - ``init(matchingAllTokensIn:)`` +/// - ``init(matchingAnyTokenIn:)`` +/// - ``init(matchingPhrase:)`` public struct FTS3Pattern { - - /// The raw pattern string. Guaranteed to be a valid FTS3/4 pattern. + /// The raw pattern string. + /// + /// It is guaranteed to be a valid FTS3/4 pattern. public let rawPattern: String - /// Creates a pattern from a raw pattern string; throws DatabaseError on - /// invalid syntax. + /// Creates a pattern from a raw pattern string. /// /// The pattern syntax is documented at /// - /// try FTS3Pattern(rawPattern: "and") // OK - /// try FTS3Pattern(rawPattern: "AND") // malformed MATCH expression: [AND] + /// For example: + /// + /// ```swift + /// // OK + /// let pattern = try FTS3Pattern(rawPattern: "and") + /// + /// // Throws an error: malformed MATCH expression: [AND] + /// let pattern = try FTS3Pattern(rawPattern: "AND") + /// ``` + /// + /// - throws: A ``DatabaseError`` if the pattern has an invalid syntax. public init(rawPattern: String) throws { // Correctness above all: use SQLite to validate the pattern. // @@ -33,13 +59,18 @@ public struct FTS3Pattern { self.rawPattern = rawPattern } - /// Creates a pattern that matches any token found in the input string; - /// returns nil if no pattern could be built. + /// Creates a pattern that matches any token found in the input string. /// - /// FTS3Pattern(matchingAnyTokenIn: "") // nil - /// FTS3Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar + /// The result is nil if no pattern could be built. /// - /// - parameter string: The string to turn into an FTS3 pattern + /// For example: + /// + /// ```swift + /// FTS3Pattern(matchingAnyTokenIn: "") // nil + /// FTS3Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar + /// ``` + /// + /// - parameter string: The string to turn into an FTS3 pattern. public init?(matchingAnyTokenIn string: String) { guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple), !tokens.isEmpty @@ -47,13 +78,18 @@ public struct FTS3Pattern { try? self.init(rawPattern: tokens.joined(separator: " OR ")) } - /// Creates a pattern that matches all tokens found in the input string; - /// returns nil if no pattern could be built. + /// Creates a pattern that matches all tokens found in the input string. /// - /// FTS3Pattern(matchingAllTokensIn: "") // nil - /// FTS3Pattern(matchingAllTokensIn: "foo bar") // foo bar + /// The result is nil if no pattern could be built. /// - /// - parameter string: The string to turn into an FTS3 pattern + /// For example: + /// + /// ```swift + /// FTS3Pattern(matchingAllTokensIn: "") // nil + /// FTS3Pattern(matchingAllTokensIn: "foo bar") // foo bar + /// ``` + /// + /// - parameter string: The string to turn into an FTS3 pattern. public init?(matchingAllTokensIn string: String) { guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple), !tokens.isEmpty @@ -62,12 +98,18 @@ public struct FTS3Pattern { } /// Creates a pattern that matches all token prefixes found in the input - /// string; returns nil if no pattern could be built. + /// string. /// - /// FTS3Pattern(matchingAllTokensIn: "") // nil - /// FTS3Pattern(matchingAllTokensIn: "foo bar") // foo* bar* + /// The result is nil if no pattern could be built. /// - /// - parameter string: The string to turn into an FTS3 pattern + /// For example: + /// + /// ```swift + /// FTS3Pattern(matchingAllTokensIn: "") // nil + /// FTS3Pattern(matchingAllTokensIn: "foo bar") // foo* bar* + /// ``` + /// + /// - parameter string: The string to turn into an FTS3 pattern. public init?(matchingAllPrefixesIn string: String) { guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple), !tokens.isEmpty @@ -75,13 +117,18 @@ public struct FTS3Pattern { try? self.init(rawPattern: tokens.map { "\($0)*" }.joined(separator: " ")) } - /// Creates a pattern that matches a contiguous string; returns nil if no - /// pattern could be built. + /// Creates a pattern that matches a contiguous string. /// - /// FTS3Pattern(matchingPhrase: "") // nil - /// FTS3Pattern(matchingPhrase: "foo bar") // "foo bar" + /// The result is nil if no pattern could be built. /// - /// - parameter string: The string to turn into an FTS3 pattern + /// For example: + /// + /// ```swift + /// FTS3Pattern(matchingPhrase: "") // nil + /// FTS3Pattern(matchingPhrase: "foo bar") // "foo bar" + /// ``` + /// + /// - parameter string: The string to turn into an FTS3 pattern. public init?(matchingPhrase string: String) { guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple), !tokens.isEmpty @@ -91,13 +138,10 @@ public struct FTS3Pattern { } extension FTS3Pattern: DatabaseValueConvertible { - /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { rawPattern.databaseValue } - /// Returns an FTS3Pattern initialized from *dbValue*, if it contains - /// a suitable value. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> FTS3Pattern? { String .fromDatabaseValue(dbValue) diff --git a/GRDB/FTS/FTS3TokenizerDescriptor.swift b/GRDB/FTS/FTS3TokenizerDescriptor.swift index a1eb0cf62..375ec7f53 100644 --- a/GRDB/FTS/FTS3TokenizerDescriptor.swift +++ b/GRDB/FTS/FTS3TokenizerDescriptor.swift @@ -1,10 +1,25 @@ -/// An FTS3 tokenizer, suitable for FTS3 and FTS4 table definitions: +/// An ``FTS3`` tokenizer. /// -/// db.create(virtualTable: "book", using: FTS4()) { t in -/// t.tokenizer = .simple // FTS3TokenizerDescriptor -/// } +/// `FTS3TokenizerDescriptor` can be used in both ``FTS3`` and ``FTS4`` tables. /// -/// See +/// For example: +/// +/// ```swift +/// db.create(virtualTable: "book", using: FTS4()) { t in +/// t.tokenizer = .simple // FTS3TokenizerDescriptor +/// } +/// ``` +/// +/// Related SQLite documentation: +/// +/// ## Topics +/// +/// ### Creating Tokenizers +/// +/// - ``porter`` +/// - ``simple`` +/// - ``unicode61(diacritics:separators:tokenCharacters:)`` +/// - ``FTS3/Diacritics`` public struct FTS3TokenizerDescriptor { let name: String let arguments: [String] @@ -14,29 +29,43 @@ public struct FTS3TokenizerDescriptor { self.arguments = arguments } - /// The "simple" tokenizer. + /// The simple tokenizer. /// - /// db.create(virtualTable: "book", using: FTS4()) { t in - /// t.tokenizer = .simple - /// } + /// For example: /// - /// See + /// ```swift + /// db.create(virtualTable: "book", using: FTS4()) { t in + /// t.tokenizer = .simple + /// } + /// ``` + /// + /// Related SQLite documentation: public static let simple = FTS3TokenizerDescriptor("simple") - /// The "porter" tokenizer. + /// The porter tokenizer. /// - /// db.create(virtualTable: "book", using: FTS4()) { t in - /// t.tokenizer = .porter - /// } + /// For example: /// - /// See + /// ```swift + /// db.create(virtualTable: "book", using: FTS4()) { t in + /// t.tokenizer = .porter + /// } + /// ``` + /// + /// Related SQLite documentation: public static let porter = FTS3TokenizerDescriptor("porter") - /// The "unicode61" tokenizer. + /// The unicode61 tokenizer. /// - /// db.create(virtualTable: "book", using: FTS4()) { t in - /// t.tokenizer = .unicode61() - /// } + /// For example: + /// + /// ```swift + /// db.create(virtualTable: "book", using: FTS4()) { t in + /// t.tokenizer = .unicode61() + /// } + /// ``` + /// + /// Related SQLite documentation: /// /// - parameters: /// - diacritics: By default SQLite will strip diacritics from @@ -45,8 +74,6 @@ public struct FTS3TokenizerDescriptor { /// characters as token separators. /// - tokenCharacters: Unless empty (the default), SQLite will consider /// these characters as token characters. - /// - /// See public static func unicode61( diacritics: FTS3.Diacritics = .removeLegacy, separators: Set = [], diff --git a/GRDB/FTS/FTS4.swift b/GRDB/FTS/FTS4.swift index e08080082..ab5cbefef 100644 --- a/GRDB/FTS/FTS4.swift +++ b/GRDB/FTS/FTS4.swift @@ -1,40 +1,40 @@ -/// FTS4 lets you define "fts4" virtual tables. +/// The virtual table module for the FTS4 full-text engine. /// -/// // CREATE VIRTUAL TABLE document USING fts4(content) -/// try db.create(virtualTable: "document", using: FTS4()) { t in -/// t.column("content") -/// } +/// To create FTS4 tables, use the ``Database`` method +/// ``Database/create(virtualTable:ifNotExists:using:_:)``. /// -/// See -public struct FTS4: VirtualTableModule { - - /// Creates a FTS4 module suitable for the Database - /// `create(virtualTable:using:)` method. +/// Related SQLite documentation: +/// +/// ## Topics +/// +/// ### The FTS4 Module +/// +/// - ``init()`` +/// - ``FTS4TableDefinition`` +/// - ``FTS4ColumnDefinition`` +public struct FTS4 { + /// Creates an FTS4 module. /// - /// // CREATE VIRTUAL TABLE document USING fts4(content) - /// try db.create(virtualTable: "document", using: FTS4()) { t in - /// t.column("content") - /// } + /// For example: /// - /// See - public init() { - } - - // MARK: - VirtualTableModule Adoption - - /// The virtual table module name - public let moduleName = "fts4" - - /// Reserved; part of the VirtualTableModule protocol. + /// ```swift + /// // CREATE VIRTUAL TABLE document USING fts4(content) + /// try db.create(virtualTable: "document", using: FTS4()) { t in + /// t.column("content") + /// } + /// ``` /// - /// See Database.create(virtualTable:using:) + /// See ``Database/create(virtualTable:ifNotExists:using:_:)`` + public init() { } +} + +extension FTS4: VirtualTableModule { + public var moduleName: String { "fts4" } + public func makeTableDefinition(configuration: VirtualTableConfiguration) -> FTS4TableDefinition { FTS4TableDefinition(configuration: configuration) } - /// Reserved; part of the VirtualTableModule protocol. - /// - /// See Database.create(virtualTable:using:) public func moduleArguments(for definition: FTS4TableDefinition, in db: Database) -> [String] { var arguments: [String] = [] @@ -88,9 +88,6 @@ public struct FTS4: VirtualTableModule { return arguments } - /// Reserved; part of the VirtualTableModule protocol. - /// - /// See Database.create(virtualTable:using:) public func database(_ db: Database, didCreate tableName: String, using definition: FTS4TableDefinition) throws { switch definition.contentMode { case .raw: @@ -141,16 +138,36 @@ public struct FTS4: VirtualTableModule { } } -/// The FTS4TableDefinition class lets you define columns of a FTS4 virtual table. +/// A `FTS4TableDefinition` lets you define the components of an FTS4 +/// virtual table. /// -/// You don't create instances of this class. Instead, you use the Database -/// `create(virtualTable:using:)` method: +/// You don't create instances of this class. Instead, you use the `Database` +/// ``Database/create(virtualTable:ifNotExists:using:_:)`` method: /// -/// try db.create(virtualTable: "document", using: FTS4()) { t in // t is FTS4TableDefinition -/// t.column("content") -/// } +/// ```swift +/// try db.create(virtualTable: "document", using: FTS4()) { t in // t is FTS4TableDefinition +/// t.column("content") +/// } +/// ``` /// -/// See +/// ## Topics +/// +/// ### Define Columns +/// +/// - ``column(_:)`` +/// +/// ### External Content Tables +/// +/// - ``synchronize(withTable:)`` +/// +/// ### FTS4 Options +/// +/// - ``compress`` +/// - ``content`` +/// - ``matchinfo`` +/// - ``prefixes`` +/// - ``tokenizer`` +/// - ``uncompress`` public final class FTS4TableDefinition { enum ContentMode { case raw(content: String?) @@ -161,25 +178,30 @@ public final class FTS4TableDefinition { fileprivate var columns: [FTS4ColumnDefinition] = [] fileprivate var contentMode: ContentMode = .raw(content: nil) - /// The virtual table tokenizer + /// The virtual table tokenizer. /// - /// try db.create(virtualTable: "document", using: FTS4()) { t in - /// t.tokenizer = .porter - /// } + /// For example: /// - /// See + /// ```swift + /// // CREATE VIRTUAL TABLE documents USING fts4(tokenize=porter) + /// try db.create(virtualTable: "document", using: FTS4()) { t in + /// t.tokenizer = .porter + /// } + /// ``` + /// + /// Related SQLite documentation: public var tokenizer: FTS3TokenizerDescriptor? - /// The FTS4 `content` option + /// The FTS4 `content` option. /// /// When you want the full-text table to be synchronized with the - /// content of an external table, prefer the `synchronize(withTable:)` - /// method. + /// content of an external table, prefer the + /// ``synchronize(withTable:)`` method. /// /// Setting this property invalidates any synchronization previously - /// established with the `synchronize(withTable:)` method. + /// established with the ``synchronize(withTable:)`` method. /// - /// See + /// Related SQLite documentation: public var content: String? { get { switch contentMode { @@ -194,22 +216,22 @@ public final class FTS4TableDefinition { } } - /// The FTS4 `compress` option + /// The FTS4 `compress` option. /// - /// See + /// Related SQLite documentation: public var compress: String? - /// The FTS4 `uncompress` option + /// The FTS4 `uncompress` option. /// - /// See + /// Related SQLite documentation: public var uncompress: String? - /// The FTS4 `matchinfo` option + /// The FTS4 `matchinfo` option. /// - /// See + /// Related SQLite documentation: public var matchinfo: String? - /// Support for the FTS5 `prefix` option + /// The FTS4 `prefix` option. /// /// // CREATE VIRTUAL TABLE document USING FTS4(content, prefix='2 4'); /// db.create(virtualTable: "document", using:FTS4()) { t in @@ -217,7 +239,7 @@ public final class FTS4TableDefinition { /// t.column("content") /// } /// - /// See + /// Related SQLite documentation: public var prefixes: Set? init(configuration: VirtualTableConfiguration) { @@ -226,11 +248,18 @@ public final class FTS4TableDefinition { /// Appends a table column. /// - /// try db.create(virtualTable: "document", using: FTS4()) { t in - /// t.column("content") - /// } + /// For example: + /// + /// ```swift + /// // CREATE VIRTUAL TABLE document USING fts4(content) + /// try db.create(virtualTable: "document", using: FTS4()) { t in + /// t.column("content") + /// } + /// ``` /// /// - parameter name: the column name. + /// - returns: A ``FTS4ColumnDefinition`` that allows you to refine the + /// column definition. @discardableResult public func column(_ name: String) -> FTS4ColumnDefinition { let column = FTS4ColumnDefinition(name: name) @@ -245,22 +274,50 @@ public final class FTS4TableDefinition { /// content in the external table. SQL triggers make sure that the /// full-text table is kept up to date with the external table. /// - /// See + /// SQLite automatically deletes those triggers when the content + /// (not full-text) table is dropped. + /// + /// However, those triggers remain after the full-text table has been + /// dropped. Unless they are dropped too, they will prevent future + /// insertion, updates, and deletions in the content table, and the creation + /// of a new full-text table. + /// + /// To drop those triggers, call the `Database` + /// ``Database/dropFTS4SynchronizationTriggers(forTable:)`` method: + /// + /// ```swift + /// // Create tables + /// try db.create(table: "book") { t in + /// ... + /// } + /// try db.create(virtualTable: "book_ft", using: FTS4()) { t in + /// t.synchronize(withTable: "book") + /// ... + /// } + /// + /// // Drop full-text table + /// try db.drop(table: "book_ft") + /// try db.dropFTS4SynchronizationTriggers(forTable: "book_ft") + /// ``` + /// + /// Related SQLite documentation: public func synchronize(withTable tableName: String) { contentMode = .synchronized(contentTable: tableName) } } -/// The FTS4ColumnDefinition class lets you refine a column of an FTS4 -/// virtual table. +/// Describes a column in an ``FTS4`` virtual table. /// -/// You get instances of this class when you create an FTS4 table: +/// You get instances of `FTS4ColumnDefinition` when you create an ``FTS4`` +/// virtual table. For example: /// -/// try db.create(virtualTable: "document", using: FTS4()) { t in -/// t.column("content") // FTS4ColumnDefinition -/// } +/// ```swift +/// try db.create(virtualTable: "document", using: FTS4()) { t in +/// t.column("content") // FTS4ColumnDefinition +/// } +/// ``` /// -/// See +/// Related SQLite documentation: public final class FTS4ColumnDefinition { fileprivate let name: String fileprivate var isIndexed: Bool @@ -274,14 +331,18 @@ public final class FTS4ColumnDefinition { /// Excludes the column from the full-text index. /// - /// try db.create(virtualTable: "document", using: FTS4()) { t in - /// t.column("a") - /// t.column("b").notIndexed() - /// } + /// For example: /// - /// See + /// ```swift + /// try db.create(virtualTable: "document", using: FTS4()) { t in + /// t.column("a") + /// t.column("b").notIndexed() + /// } + /// ``` /// - /// - returns: Self so that you can further refine the column definition. + /// Related SQLite documentation: + /// + /// - returns: `self` so that you can further refine the column definition. @discardableResult public func notIndexed() -> Self { self.isIndexed = false @@ -290,14 +351,18 @@ public final class FTS4ColumnDefinition { /// Uses the column as the language id hidden column. /// - /// try db.create(virtualTable: "document", using: FTS4()) { t in - /// t.column("a") - /// t.column("lid").asLanguageId() - /// } + /// For example: /// - /// See + /// ```swift + /// try db.create(virtualTable: "document", using: FTS4()) { t in + /// t.column("a") + /// t.column("lid").asLanguageId() + /// } + /// ``` /// - /// - returns: Self so that you can further refine the column definition. + /// Related SQLite documentation: + /// + /// - returns: `self` so that you can further refine the column definition. @discardableResult public func asLanguageId() -> Self { self.isLanguageId = true @@ -306,7 +371,9 @@ public final class FTS4ColumnDefinition { } extension Database { - /// Deletes the synchronization triggers for a synchronized FTS4 table + /// Deletes the synchronization triggers for a synchronized FTS4 table. + /// + /// See ``FTS4TableDefinition/synchronize(withTable:)``. public func dropFTS4SynchronizationTriggers(forTable tableName: String) throws { try execute(sql: """ DROP TRIGGER IF EXISTS \("__\(tableName)_bu".quotedDatabaseIdentifier); diff --git a/GRDB/FTS/FTS5.swift b/GRDB/FTS/FTS5.swift index f0d7c7964..5c1c7fb36 100644 --- a/GRDB/FTS/FTS5.swift +++ b/GRDB/FTS/FTS5.swift @@ -444,7 +444,7 @@ extension Column { } extension Database { - /// Deletes the synchronization triggers for a synchronized FTS5 table + /// Deletes the synchronization triggers for a synchronized FTS5 table. public func dropFTS5SynchronizationTriggers(forTable tableName: String) throws { try execute(sql: """ DROP TRIGGER IF EXISTS \("__\(tableName)_ai".quotedDatabaseIdentifier); diff --git a/GRDB/FTS/FTS5Pattern.swift b/GRDB/FTS/FTS5Pattern.swift index e1852f58a..c9ac77aa1 100644 --- a/GRDB/FTS/FTS5Pattern.swift +++ b/GRDB/FTS/FTS5Pattern.swift @@ -1,5 +1,5 @@ #if SQLITE_ENABLE_FTS5 -/// A full text pattern that can query FTS5 virtual tables. +/// A full text pattern for querying FTS5 virtual tables. public struct FTS5Pattern { /// The raw pattern string. Guaranteed to be a valid FTS5 pattern. @@ -126,13 +126,10 @@ extension Database { } extension FTS5Pattern: DatabaseValueConvertible { - /// Returns a value that can be stored in the database. public var databaseValue: DatabaseValue { rawPattern.databaseValue } - /// Returns an FTS5Pattern initialized from *dbValue*, if it - /// contains a suitable value. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> FTS5Pattern? { String .fromDatabaseValue(dbValue) diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index ba873a719..d997af7c4 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -4,64 +4,95 @@ import Combine import Foundation // TODO: provide concurrent apis for migrations that run @Sendable closures. -/// A DatabaseMigrator registers and applies database migrations. +/// A `DatabaseMigrator` registers and applies database migrations. /// -/// Migrations are named blocks of SQL statements that are guaranteed to be +/// Migrations are named blocks of database operations that are guaranteed to be /// applied in order, once and only once. /// -/// When a user upgrades your application, only non-applied migration are run. +/// When a migrator migrates a database, only non-applied migration are run. /// /// Usage: /// -/// var migrator = DatabaseMigrator() +/// ```swift +/// // Define a DatabaseMigrator +/// var migrator = DatabaseMigrator() /// -/// // 1st migration -/// migrator.registerMigration("createLibrary") { db in -/// try db.create(table: "author") { t in -/// t.autoIncrementedPrimaryKey("id") -/// t.column("creationDate", .datetime) -/// t.column("name", .text).notNull() -/// } -/// -/// try db.create(table: "book") { t in -/// t.autoIncrementedPrimaryKey("id") -/// t.column("authorId", .integer) -/// .notNull() -/// .references("author", onDelete: .cascade) -/// t.column("title", .text).notNull() -/// } +/// // 1st migration +/// migrator.registerMigration("createLibrary") { db in +/// try db.create(table: "author") { t in +/// t.autoIncrementedPrimaryKey("id") +/// t.column("creationDate", .datetime) +/// t.column("name", .text).notNull() /// } /// -/// // 2nd migration -/// migrator.registerMigration("AddBirthYearToAuthors") { db in -/// try db.alter(table: "author") { t -/// t.add(column: "birthYear", .integer) -/// } +/// try db.create(table: "book") { t in +/// t.autoIncrementedPrimaryKey("id") +/// t.column("authorId", .integer) +/// .notNull() +/// .references("author", onDelete: .cascade) +/// t.column("title", .text).notNull() /// } +/// } /// -/// // Migrations for future versions will be inserted here: -/// // -/// // // 3rd migration -/// // migrator.registerMigration("...") { db in -/// // ... -/// // } +/// // 2nd migration +/// migrator.registerMigration("AddBirthYearToAuthors") { db in +/// try db.alter(table: "author") { t +/// t.add(column: "birthYear", .integer) +/// } +/// } /// -/// try migrator.migrate(dbQueue) +/// // Migrations for future versions will be inserted here: +/// // +/// // // 3rd migration +/// // migrator.registerMigration("...") { db in +/// // ... +/// // } +/// +/// // Connect and migrate a database +/// let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite") +/// try migrator.migrate(dbQueue) +/// ``` +/// +/// ## Topics +/// +/// ### Creating and Configuring a DatabaseMigrator +/// +/// - ``init()`` +/// - ``eraseDatabaseOnSchemaChange`` +/// - ``disablingDeferredForeignKeyChecks()`` +/// - ``registerMigration(_:foreignKeyChecks:migrate:)`` +/// - ``ForeignKeyChecks`` +/// +/// ### Migrating a Database +/// +/// - ``asyncMigrate(_:completion:)`` +/// - ``migrate(_:)`` +/// - ``migrate(_:upTo:)`` +/// - ``migratePublisher(_:receiveOn:)`` +/// +/// ### Querying Migrations +/// +/// - ``migrations`` +/// - ``appliedIdentifiers(_:)`` +/// - ``appliedMigrations(_:)`` +/// - ``completedMigrations(_:)`` +/// - ``hasBeenSuperseded(_:)`` +/// - ``hasCompletedMigrations(_:)`` public struct DatabaseMigrator { - /// Controls how migrations handle foreign keys constraints. + /// Controls how a migration handle foreign keys constraints. public enum ForeignKeyChecks { /// The migration runs with disabled foreign keys, until foreign keys /// are checked right before changes are committed on disk. /// - /// These deferred checks are not executed if the migrator comes - /// from `disablingDeferredForeignKeyChecks()`. + /// These deferred checks are not executed if the migrator is the + /// result of ``DatabaseMigrator/disablingDeferredForeignKeyChecks()``. /// /// Deferred foreign key checks are necessary for migrations that /// perform schema changes as described in /// case deferred - /// The migration runs for foreign keys on. + /// The migration runs with enabled foreign keys. /// /// Immediate foreign key checks are not compatible with migrations that /// perform schema changes as described in @@ -69,30 +100,35 @@ public struct DatabaseMigrator { case immediate } - /// When the `eraseDatabaseOnSchemaChange` flag is true, the migrator will - /// automatically wipe out the full database content, and recreate the whole - /// database from scratch, if it detects that a migration has changed its - /// definition. + /// A boolean value indicating whether the migrator recreates the whole + /// database from scratch if it detects a change in the definition + /// of migrations. /// - /// This flag can destroy your precious users' data! + /// - warning: This flag can destroy your precious users' data! /// - /// But it may be useful in two situations: + /// When true, the database migrator wipes out the full database content, + /// and runs all migrations from the start, if one of those conditions + /// is met: /// - /// 1. During application development, as you are still designing - /// migrations, and the schema changes often. + /// - A migration has been removed, or renamed. + /// - A schema change is detected. A schema change is any difference in + /// the `sqlite_master` table, which contains the SQL used to create + /// database tables, indexes, triggers, and views. /// - /// In this case, it is recommended that you make sure this flag does - /// not ship in the distributed application, in order to avoid undesired - /// data loss: + /// This flag is useful during application development: you are still + /// designing migrations, and the schema changes often. /// - /// var migrator = DatabaseMigrator() - /// #if DEBUG - /// // Speed up development by nuking the database when migrations change - /// migrator.eraseDatabaseOnSchemaChange = true - /// #endif + /// It is recommended to not ship it in the distributed application, in + /// order to avoid undesired data loss. Use the `DEBUG` + /// compilation condition: /// - /// 2. When the database content can easily be recreated, such as a cache - /// for some downloaded data. + /// ```swift + /// var migrator = DatabaseMigrator() + /// #if DEBUG + /// // Speed up development by nuking the database when migrations change + /// migrator.eraseDatabaseOnSchemaChange = true + /// #endif + /// ``` public var eraseDatabaseOnSchemaChange = false private var defersForeignKeyChecks = true private var _migrations: [Migration] = [] @@ -103,37 +139,41 @@ public struct DatabaseMigrator { // MARK: - Disabling Foreign Key Checks - /// Returns a migrator that will not perform deferred foreign key checks in - /// all newly registered migrations. + /// Returns a migrator that disables foreign key checks in all newly + /// registered migrations. /// /// The returned migrator is _unsafe_, because it no longer guarantees the - /// integrity of the database. It is your responsibility to register - /// migrations that do not break foreign key constraints. + /// integrity of the database. It is now _your_ responsibility to register + /// migrations that do not break foreign key constraints. See + /// ``Database/checkForeignKeys()`` and ``Database/checkForeignKeys(in:)``. /// /// Running migrations without foreign key checks can improve migration /// performance on huge databases. /// /// Example: /// - /// var migrator = DatabaseMigrator() - /// migrator.registerMigration("A") { db in - /// // Runs with deferred foreign key checks - /// } - /// migrator.registerMigration("B", foreignKeyChecks: .immediate) { db in - /// // Runs with immediate foreign key checks - /// } + /// ```swift + /// var migrator = DatabaseMigrator() + /// migrator.registerMigration("A") { db in + /// // Runs with deferred foreign key checks + /// } + /// migrator.registerMigration("B", foreignKeyChecks: .immediate) { db in + /// // Runs with immediate foreign key checks + /// } /// - /// migrator = migrator.disablingDeferredForeignKeyChecks() - /// migrator.registerMigration("C") { db in - /// // Runs with disabled foreign key checks - /// } - /// migrator.registerMigration("D", foreignKeyChecks: .immediate) { db in - /// // Runs with immediate foreign key checks - /// } + /// migrator = migrator.disablingDeferredForeignKeyChecks() + /// migrator.registerMigration("C") { db in + /// // Runs without foreign key checks + /// } + /// migrator.registerMigration("D", foreignKeyChecks: .immediate) { db in + /// // Runs with immediate foreign key checks + /// } + /// ``` /// - /// - warning: Before using this unsafe method, try to run your migrations with - /// `.immediate` foreign key checks, if possible. This may enhance migration - /// performances, while preserving the database integrity guarantee. + /// - warning: Before using this unsafe method, try to register your + /// migrations with the `foreignKeyChecks: .immediate` option, _if + /// possible_, as in the example above. This will enhance migration + /// performances, while preserving the database integrity guarantee. public func disablingDeferredForeignKeyChecks() -> DatabaseMigrator { with { $0.defersForeignKeyChecks = false } } @@ -142,33 +182,55 @@ public struct DatabaseMigrator { /// Registers a migration. /// - /// migrator.registerMigration("createAuthors") { db in - /// try db.create(table: "author") { t in - /// t.autoIncrementedPrimaryKey("id") - /// t.column("creationDate", .datetime) - /// t.column("name", .text).notNull() - /// } + /// The registered migration is appended to the list of migrations to run: + /// it will execute after previously registered migrations, after before + /// migrations that are registered later. + /// + /// For example: + /// + /// ```swift + /// migrator.registerMigration("createAuthors") { db in + /// try db.create(table: "author") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("creationDate", .datetime) + /// t.column("name", .text).notNull() /// } + /// } + /// ``` + /// + /// Database operations are wrapped in a transaction. If they throw an + /// error, the transaction is rollbacked, migrations are aborted, and the + /// error is thrown by the migrating method. + /// + /// By default, database operations run with disabled foreign keys, and + /// foreign keys are checked right before changes are committed on disk. You + /// can control this behavior with the `foreignKeyChecks` argument. + /// + /// Database operations run in the writer dispatch queue, serialized + /// with all database updates performed by the migrated `DatabaseWriter`. + /// + /// The `Database` argument to `migrate` is valid only during the execution + /// of the closure. Do not store or return the database connection for + /// later use. /// /// - parameters: /// - identifier: The migration identifier. - /// - foreignKeyChecks: This parameter is ignored if the database has - /// not enabled foreign keys. + /// - foreignKeyChecks: This parameter is ignored if the database + /// ``Configuration`` has disabled foreign keys. /// /// The default `.deferred` checks have the migration run with /// disabled foreign keys, until foreign keys are checked right before /// changes are committed on disk. These deferred checks are not - /// executed if the migrator comes - /// from `disablingDeferredForeignKeyChecks()`. + /// executed if the migrator is the result of + /// ``disablingDeferredForeignKeyChecks()``. /// /// The `.immediate` checks have the migration run with foreign - /// keys enabled. - /// - /// Only use `.immediate` if you are sure that the migration does not - /// perform schema changes described in + /// keys enabled. Make sure you only use `.immediate` if the migration + /// does not perform schema changes described in /// - /// - block: The migration block that performs SQL statements. - /// - precondition: No migration with the same same as already been registered. + /// - migrate: A closure that performs database operations. + /// - precondition: No migration with the same identifier as already + /// been registered. public mutating func registerMigration( _ identifier: String, foreignKeyChecks: ForeignKeyChecks = .deferred, @@ -190,13 +252,11 @@ public struct DatabaseMigrator { // MARK: - Applying Migrations - /// Iterate migrations in the same order as they were registered. If a - /// migration has not yet been applied, its block is executed in - /// a transaction. + /// Runs all unapplied migrations, in the same order as they + /// were registered. /// - /// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool) - /// where migrations should apply. - /// - throws: An eventual error thrown by the registered migration blocks. + /// - parameter writer: A DatabaseWriter. + /// - throws: The error thrown by the first failed migration. public func migrate(_ writer: some DatabaseWriter) throws { guard let lastMigration = _migrations.last else { return @@ -204,29 +264,31 @@ public struct DatabaseMigrator { try migrate(writer, upTo: lastMigration.identifier) } - /// Iterate migrations in the same order as they were registered, up to the - /// provided target. If a migration has not yet been applied, its block is - /// executed in a transaction. + /// Runs all unapplied migrations, in the same order as they + /// were registered, up to the target migration identifier (included). /// - /// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool) - /// where migrations should apply. - /// - parameter targetIdentifier: The identifier of a registered migration. - /// - throws: An eventual error thrown by the registered migration blocks. + /// - precondition: `targetIdentifier` is the identifier of a + /// registered migration. + /// + /// - precondition: The database has not already been migrated beyond the + /// target migration. + /// + /// - parameter writer: A DatabaseWriter. + /// - parameter targetIdentifier: A migration identifier. + /// - throws: The error thrown by the first failed migration. public func migrate(_ writer: some DatabaseWriter, upTo targetIdentifier: String) throws { try writer.barrierWriteWithoutTransaction { db in try migrate(db, upTo: targetIdentifier) } } - /// Iterate migrations in the same order as they were registered. If a - /// migration has not yet been applied, its block is executed in - /// a transaction. + /// Schedules unapplied migrations for execution, and returns immediately. /// - /// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool) - /// where migrations should apply. + /// - parameter writer: A DatabaseWriter. /// - parameter completion: A function that can access the database. Its /// argument is a `Result` that provides a connection to the migrated - /// database, or the failure that would prevent the migration to complete. + /// database, or the failure that prevented the migrations + /// from succeeding. public func asyncMigrate( _ writer: some DatabaseWriter, completion: @escaping (Result) -> Void) @@ -255,10 +317,8 @@ public struct DatabaseMigrator { /// Returns the identifiers of registered and applied migrations, in the /// order of registration. /// - /// See also `appliedIdentifiers(_:)`. - /// /// - parameter db: A database connection. - /// - throws: An eventual database error. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func appliedMigrations(_ db: Database) throws -> [String] { let appliedIdentifiers = try self.appliedIdentifiers(db) return _migrations.map { $0.identifier }.filter { appliedIdentifiers.contains($0) } @@ -266,10 +326,8 @@ public struct DatabaseMigrator { /// Returns the applied migration identifiers, even unregistered ones. /// - /// See also `appliedMigrations(_:)`. - /// /// - parameter db: A database connection. - /// - throws: An eventual database error. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func appliedIdentifiers(_ db: Database) throws -> Set { do { return try String.fetchSet(db, sql: "SELECT identifier FROM grdb_migrations") @@ -282,11 +340,14 @@ public struct DatabaseMigrator { } } - /// Returns the identifiers of completed migrations, of which all previous - /// migrations have been applied. + /// Returns the identifiers of registered and completed migrations, in the + /// order of registration. + /// + /// A migration is completed if and only if all previous migrations have + /// been applied. /// /// - parameter db: A database connection. - /// - throws: An eventual database error. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func completedMigrations(_ db: Database) throws -> [String] { let appliedIdentifiers = try appliedMigrations(db) let knownIdentifiers = _migrations.map(\.identifier) @@ -295,20 +356,23 @@ public struct DatabaseMigrator { .map { $0.0 } } - /// Returns true if all migrations are applied. + /// A boolean value indicating whether all registered migrations, and only + /// registered migrations, have been applied. /// /// - parameter db: A database connection. - /// - throws: An eventual database error. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func hasCompletedMigrations(_ db: Database) throws -> Bool { try completedMigrations(db).last == _migrations.last?.identifier } - /// Returns whether database contains unknown migration - /// identifiers, which is likely the sign that the database - /// has migrated further than the migrator itself supports. + /// A boolean value indicating whether the database refers to + /// unregistered migrations. + /// + /// When the result is true, the database has likely been migrated by a + /// more recent migrator. /// /// - parameter db: A database connection. - /// - throws: An eventual database error. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func hasBeenSuperseded(_ db: Database) throws -> Bool { let appliedIdentifiers = try self.appliedIdentifiers(db) let knownIdentifiers = _migrations.map(\.identifier) @@ -447,32 +511,16 @@ extension DatabaseMigrator { /// Returns a Publisher that asynchronously migrates a database. /// - /// let migrator: DatabaseMigrator = ... - /// let dbQueue: DatabaseQueue = ... - /// let publisher = migrator.migratePublisher(dbQueue) + /// The database is not accessed until subscription. Value and completion + /// are published on `scheduler` (the main dispatch queue by default). /// - /// It completes on the main dispatch queue. - /// - /// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool) - /// where migrations should apply. - @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) - public func migratePublisher(_ writer: some DatabaseWriter) -> DatabasePublishers.Migrate { - migratePublisher(writer, receiveOn: DispatchQueue.main) - } - - /// Returns a Publisher that asynchronously migrates a database. - /// - /// let migrator: DatabaseMigrator = ... - /// let dbQueue: DatabaseQueue = ... - /// let publisher = migrator.migratePublisher(dbQueue, receiveOn: DispatchQueue.global()) - /// - /// It completes on `scheduler`. - /// - /// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool) + /// - parameter writer: A DatabaseWriter. /// where migrations should apply. /// - parameter scheduler: A Combine Scheduler. @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) - public func migratePublisher(_ writer: some DatabaseWriter, receiveOn scheduler: some Scheduler) + public func migratePublisher( + _ writer: some DatabaseWriter, + receiveOn scheduler: some Scheduler = DispatchQueue.main) -> DatabasePublishers.Migrate { DatabasePublishers.Migrate( @@ -489,10 +537,11 @@ extension DatabaseMigrator { @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) extension DatabasePublishers { - /// A publisher that migrates a database. It publishes exactly - /// one element, or an error. + /// A publisher that migrates a database. /// - /// See `DatabaseMigrator.migratePublisher(_:receiveOn:)`. + /// `Migrate` publishes exactly one element, or an error. + /// + /// You build such a publisher from ``DatabaseMigrator``. public struct Migrate: Publisher { public typealias Output = Void public typealias Failure = Error diff --git a/GRDB/QueryInterface/FTS3+QueryInterface.swift b/GRDB/QueryInterface/FTS3+QueryInterface.swift index fcc2b520d..49fbc559c 100644 --- a/GRDB/QueryInterface/FTS3+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS3+QueryInterface.swift @@ -2,15 +2,19 @@ extension TableRequest where Self: FilteredRequest { // MARK: Full Text Search - /// Creates a request with a full-text predicate added to the eventual - /// set of already applied predicates. + /// Filters rows that match an ``FTS3`` full-text pattern. /// - /// // SELECT * FROM book WHERE book MATCH '...' - /// var request = Book.all() - /// request = request.matching(pattern) + /// For example: /// - /// If the search pattern is nil, the request does not match any - /// database row. + /// ```swift + /// // SELECT * FROM book WHERE book MATCH 'sqlite OR database' + /// let pattern = FTS3Pattern(matchingAnyTokenIn: "SQLite Database") + /// let request = Book.all().matching(pattern) + /// ``` + /// + /// If `pattern` is nil, the returned request fetches no row. + /// + /// - parameter pattern: An ``FTS3Pattern``. public func matching(_ pattern: FTS3Pattern?) -> Self { guard let pattern else { return none() @@ -25,17 +29,20 @@ extension TableRecord { // MARK: Full Text Search - /// Returns a QueryInterfaceRequest with a matching predicate. + /// Returns a request filtered on records that match an ``FTS3`` + /// full-text pattern. /// - /// // SELECT * FROM book WHERE book MATCH '...' - /// var request = Book.matching(pattern) + /// For example: /// - /// If the search pattern is nil, the request does not match any - /// database row. + /// ```swift + /// // SELECT * FROM book WHERE book MATCH 'sqlite OR database' + /// let pattern = FTS3Pattern(matchingAnyTokenIn: "SQLite Database") + /// let request = Book.matching(pattern) + /// ``` /// - /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableRecord.databaseSelection` property, or - /// for individual requests with the `TableRecord.select` method. + /// If `pattern` is nil, the returned request fetches no row. + /// + /// - parameter pattern: An ``FTS3Pattern``. public static func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest { all().matching(pattern) } diff --git a/GRDB/QueryInterface/FTS5+QueryInterface.swift b/GRDB/QueryInterface/FTS5+QueryInterface.swift index 242085fdd..b49f10514 100644 --- a/GRDB/QueryInterface/FTS5+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS5+QueryInterface.swift @@ -3,19 +3,19 @@ extension TableRequest where Self: FilteredRequest { // MARK: Full Text Search - /// Creates a request with a full-text predicate added to the eventual - /// set of already applied predicates. + /// Filters rows that match an ``FTS5`` full-text pattern. /// - /// // SELECT * FROM book WHERE book MATCH '...' - /// var request = Book.all() - /// request = request.matching(pattern) + /// For example: /// - /// If the search pattern is nil, the request does not match any - /// database row. + /// ```swift + /// // SELECT * FROM book WHERE book MATCH 'sqlite OR database' + /// let pattern = FTS5Pattern(matchingAnyTokenIn: "SQLite Database") + /// let request = Book.all().matching(pattern) + /// ``` /// - /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableRecord.databaseSelection` property, or - /// for individual requests with the `TableRecord.select` method. + /// If `pattern` is nil, the returned request fetches no row. + /// + /// - parameter pattern: An ``FTS5Pattern``. public func matching(_ pattern: FTS5Pattern?) -> Self { guard let pattern else { return none() @@ -30,13 +30,20 @@ extension TableRecord { // MARK: Full Text Search - /// Returns a QueryInterfaceRequest with a matching predicate. + /// Returns a request filtered on records that match an ``FTS5`` + /// full-text pattern. /// - /// // SELECT * FROM book WHERE book MATCH '...' - /// var request = Book.matching(pattern) + /// For example: /// - /// If the search pattern is nil, the request does not match any - /// database row. + /// ```swift + /// // SELECT * FROM book WHERE book MATCH 'sqlite OR database' + /// let pattern = FTS5Pattern(matchingAnyTokenIn: "SQLite Database") + /// let request = Book.matching(pattern) + /// ``` + /// + /// If `pattern` is nil, the returned request fetches no row. + /// + /// - parameter pattern: An ``FTS5Pattern``. public static func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest { all().matching(pattern) } diff --git a/GRDB/QueryInterface/ForeignKey.swift b/GRDB/QueryInterface/ForeignKey.swift index 9a4e407a7..f89ee964c 100644 --- a/GRDB/QueryInterface/ForeignKey.swift +++ b/GRDB/QueryInterface/ForeignKey.swift @@ -1,5 +1,8 @@ -/// A ForeignKey helps building associations when GRDB can't infer a foreign -/// key from the database schema. +/// A `ForeignKey` defines on which columns an association between two tables +/// is established. +/// +/// You will need a `ForeignKey` when you define an ``Association`` between two +/// tables that are not unambiguously related with a single SQLite foreign key. /// /// Sometimes the database schema does not define any foreign key between two /// tables. And sometimes, there are several foreign keys from a table @@ -17,91 +20,81 @@ /// foreign key from book to person", or "Could not infer foreign key from book /// to person". /// -/// Your help is needed. You have to instruct GRDB which foreign key to use: +/// Your help is needed. You have to instruct which foreign key to use. +/// For example: /// -/// struct Book: TableRecord { -/// // Define foreign keys -/// static let authorForeignKey = ForeignKey(["authorId"])) -/// static let translatorForeignKey = ForeignKey(["translatorId"])) +/// ```swift +/// struct Book: TableRecord { +/// // Define foreign keys +/// static let authorForeignKey = ForeignKey(["authorId"])) +/// static let translatorForeignKey = ForeignKey(["translatorId"])) /// -/// // Use foreign keys to define associations: -/// static let author = belongsTo(Person.self, using: authorForeignKey) -/// static let translator = belongsTo(Person.self, using: translatorForeignKey) -/// } -/// -/// Foreign keys are always defined from the table that contains the columns at -/// the origin of the foreign key. Person's symmetric HasMany associations reuse -/// Book's foreign keys: -/// -/// struct Person: TableRecord { -/// static let writtenBooks = hasMany(Book.self, using: Book.authorForeignKey) -/// static let translatedBooks = hasMany(Book.self, using: Book.translatorForeignKey) -/// } +/// // Use foreign keys to define associations: +/// static let author = belongsTo( +/// Person.self, +/// key: "author", +/// using: authorForeignKey) +/// static let translator = belongsTo( +/// Person.self, +/// key: "translator", +/// using: translatorForeignKey) +/// } +/// ``` /// /// Foreign keys can also be defined from query interface columns: /// -/// struct Book: TableRecord { -/// enum Columns: String, ColumnExpression { -/// case id, title, authorId, translatorId -/// } -/// -/// static let authorForeignKey = ForeignKey([Columns.authorId])) -/// static let translatorForeignKey = ForeignKey([Columns.translatorId])) +/// ```swift +/// struct Book: TableRecord { +/// enum Columns: String, ColumnExpression { +/// case id, title, authorId, translatorId /// } /// -/// When the destination table of a foreign key does not define any primary key, -/// you need to provide the full definition of a foreign key: +/// static let authorForeignKey = ForeignKey([Columns.authorId])) +/// static let translatorForeignKey = ForeignKey([Columns.translatorId])) +/// } +/// ``` /// -/// struct Book: TableRecord { -/// static let authorForeignKey = ForeignKey(["authorId"], to: ["id"])) -/// static let author = belongsTo(Person.self, using: authorForeignKey) -/// } +/// When the destination table does not define any primary key, you need to +/// provide the destination columns: +/// +/// ```swift +/// struct Book: TableRecord { +/// static let authorForeignKey = ForeignKey(["authorId"], to: ["id"])) +/// static let translatorForeignKey = ForeignKey(["translatorId"], to: ["id"])) +/// } +/// ``` +/// +/// Foreign keys are always defined from the table that contains the columns at +/// the origin of the foreign key. `Person`'s symmetric associations reuse +/// foreign keys of `Book`: +/// +/// ```swift +/// struct Person: TableRecord { +/// static let writtenBooks = hasMany( +/// Book.self, +/// key: "writtenBooks", +/// using: Book.authorForeignKey) +/// static let translatedBooks = hasMany( +/// Book.self, +/// key: "translatedBooks", +/// using: Book.translatorForeignKey) +/// } +/// ``` public struct ForeignKey: Equatable { var originColumns: [String] var destinationColumns: [String]? - /// Creates a ForeignKey intended to define a record association. - /// - /// struct Book: TableRecord { - /// // Define foreign keys - /// static let authorForeignKey = ForeignKey(["authorId"])) - /// static let translatorForeignKey = ForeignKey(["translatorId"])) - /// - /// // Use foreign keys to define associations: - /// static let author = belongsTo(Person.self, using: authorForeignKey) - /// static let translator = belongsTo(Person.self, using: translatorForeignKey) - /// } - /// /// - parameter originColumns: The columns at the origin of the foreign key. /// - parameter destinationColumns: The columns at the destination of the - /// foreign key. When nil (the default), GRDB automatically uses the - /// primary key. + /// foreign key. Use nil for the columns of the primary key. public init(_ originColumns: [String], to destinationColumns: [String]? = nil) { self.originColumns = originColumns self.destinationColumns = destinationColumns } - /// Creates a ForeignKey intended to define a record association. - /// - /// struct Book: TableRecord { - /// // Define columns - /// enum Columns: String, ColumnExpression { - /// case id, title, authorId, translatorId - /// } - /// - /// // Define foreign keys - /// static let authorForeignKey = ForeignKey([Columns.authorId])) - /// static let translatorForeignKey = ForeignKey([Columns.translatorId])) - /// - /// // Use foreign keys to define associations: - /// static let author = belongsTo(Person.self, using: authorForeignKey) - /// static let translator = belongsTo(Person.self, using: translatorForeignKey) - /// } - /// /// - parameter originColumns: The columns at the origin of the foreign key. /// - parameter destinationColumns: The columns at the destination of the - /// foreign key. When nil (the default), GRDB automatically uses the - /// primary key. + /// foreign key. Use nil for the columns of the primary key. public init(_ originColumns: [any ColumnExpression], to destinationColumns: [any ColumnExpression]? = nil) { self.init(originColumns.map(\.name), to: destinationColumns?.map(\.name)) } diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index 5eb6fbf25..222ac6dcb 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -1,15 +1,39 @@ import Foundation -/// Implementation details of `Association`. +/// A type that defines a connection between two tables. /// -/// :nodoc: -public protocol _Association { - var _sqlAssociation: _SQLAssociation { get set } -} - -/// The base protocol for all associations that define a connection between two -/// record types. -public protocol Association: _Association, DerivableRequest { +/// ``Association`` feeds methods of the ``JoinableRequest`` protocol. They are +/// built from a ``TableRecord`` type, or a ``Table`` instance. +/// +/// ## Topics +/// +/// ### Instance Methods +/// +/// - ``forKey(_:)-247af`` +/// - ``forKey(_:)-54yh6`` +/// +/// ### Associations To One +/// +/// - ``BelongsToAssociation`` +/// - ``HasOneAssociation`` +/// - ``HasOneThroughAssociation`` +/// - ``AssociationToOne`` +/// +/// ### Associations To Many +/// +/// - ``HasManyAssociation`` +/// - ``HasManyThroughAssociation`` +/// - ``AssociationToMany`` +/// +/// ### Associations to Common Table Expressions +/// +/// - ``JoinAssociation`` +/// +/// ### Supporting Types +/// +/// - ``ForeignKey`` +/// - ``Inflections`` +public protocol Association: DerivableRequest { // OriginRowDecoder and RowDecoder inherited from DerivableRequest provide // type safety: // @@ -18,28 +42,42 @@ public protocol Association: _Association, DerivableRequest { /// The record type at the origin of the association. /// - /// In the `belongsTo` association below, it is Book: + /// In the ``BelongsToAssociation`` association below, it is `Book`: /// - /// struct Book: TableRecord { - /// // BelongsToAssociation - /// static let author = belongsTo(Author.self) - /// } + /// ```swift + /// struct Book: TableRecord { + /// // BelongsToAssociation + /// static let author = belongsTo(Author.self) + /// } + /// ``` associatedtype OriginRowDecoder - /// Creates an association with the given key. + var _sqlAssociation: _SQLAssociation { get set } + + /// Returns an association with the given key. /// - /// This new key impacts how rows fetched from the resulting association - /// should be consumed: + /// For example: /// - /// struct Player: TableRecord { - /// static let team = belongsTo(Team.self) - /// } + /// ```swift + /// struct Employee: FetchableRecord, TableRecord { + /// static let manager = belongsTo(Employee.self).forKey("manager") + /// static let subordinates = hasMany(Employee.self).forKey("subordinates") + /// } /// - /// // Consume rows: - /// let request = Player.including(required: Player.team.forKey("custom")) - /// for row in Row.fetchAll(db, request) { - /// let team: Team = row["custom"] - /// } + /// struct EmployeeInfo: FetchableRecord, Decodable { + /// var employee: Employee + /// var manager: Employee? // property name matches the association key + /// var subordinates: [Employee] // property name matches the association key + /// } + /// + /// try dbQueue.read { db in + /// let employeeInfos: [EmployeeInfo] = try Employee + /// .including(optional: Employee.manager) + /// .including(all: Employee.subordinates) + /// .asRequest(of: EmployeeInfo.self) + /// .fetchAll(db) + /// } + /// ``` func forKey(_ key: String) -> Self } @@ -60,35 +98,30 @@ extension Association { } extension Association { - /// :nodoc: public func _including(all association: _SQLAssociation) -> Self { withDestinationRelation { relation in relation = relation._including(all: association) } } - /// :nodoc: public func _including(optional association: _SQLAssociation) -> Self { withDestinationRelation { relation in relation = relation._including(optional: association) } } - /// :nodoc: public func _including(required association: _SQLAssociation) -> Self { withDestinationRelation { relation in relation = relation._including(required: association) } } - /// :nodoc: public func _joining(optional association: _SQLAssociation) -> Self { withDestinationRelation { relation in relation = relation._joining(optional: association) } } - /// :nodoc: public func _joining(required association: _SQLAssociation) -> Self { withDestinationRelation { relation in relation = relation._joining(required: association) @@ -123,60 +156,14 @@ extension Association { /// } var key: SQLAssociationKey { _sqlAssociation.destination.key } - /// Creates an association with the given key. - /// - /// This new key helps Decodable records decode rows fetched from the - /// resulting association: - /// - /// struct Player: TableRecord { - /// static let team = belongsTo(Team.self) - /// } - /// - /// struct PlayerInfo: FetchableRecord, Decodable { - /// let player: Player - /// let team: Team - /// - /// static func all() -> QueryInterfaceRequest { - /// return Player - /// .including(required: Player.team.forKey(CodingKeys.team)) - /// .asRequest(of: PlayerInfo.self) - /// } - /// } - /// - /// let playerInfos = PlayerInfo.all().fetchAll(db) - /// print(playerInfos.first?.team) + /// Returns an association with the given key. public func forKey(_ codingKey: some CodingKey) -> Self { forKey(codingKey.stringValue) } - - /// Creates an association that allows you to define expressions that target - /// a specific database table. - /// - /// In the example below, the "team.color = 'red'" condition in the where - /// clause could be not achieved without table aliases. - /// - /// struct Player: TableRecord { - /// static let team = belongsTo(Team.self) - /// } - /// - /// // SELECT player.*, team.* - /// // JOIN team ON ... - /// // WHERE team.color = 'red' - /// let teamAlias = TableAlias() - /// let request = Player - /// .including(required: Player.team.aliased(teamAlias)) - /// .filter(teamAlias[Column("color")] == "red") - /// - /// When you give a name to a table alias, you can reliably inject sql - /// snippets in your requests: - /// - /// // SELECT player.*, custom.* - /// // JOIN team custom ON ... - /// // WHERE custom.color = 'red' - /// let teamAlias = TableAlias(name: "custom") - /// let request = Player - /// .including(required: Player.team.aliased(teamAlias)) - /// .filter(sql: "custom.color = ?", arguments: ["red"]) +} + +// TableRequest conformance +extension Association { public func aliased(_ alias: TableAlias) -> Self { withDestinationRelation { relation in relation = relation.aliased(alias) @@ -186,28 +173,6 @@ extension Association { // SelectionRequest conformance extension Association { - - /// Creates an association which selects *selection*. - /// - /// struct Player: TableRecord { - /// static let team = belongsTo(Team.self) - /// } - /// - /// // SELECT player.*, team.color - /// // FROM player - /// // JOIN team ON team.id = player.teamId - /// let association = Player.team.select { db in [Column("color")] - /// var request = Player.including(required: association) - /// - /// Any previous selection is replaced: - /// - /// // SELECT player.*, team.color - /// // FROM player - /// // JOIN team ON team.id = player.teamId - /// let association = Player.team - /// .select { db in [Column("id")] } - /// .select { db in [Column("color") } - /// var request = Player.including(required: association) public func selectWhenConnected(_ selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self { withDestinationRelation { relation in relation = relation.selectWhenConnected { db in @@ -216,19 +181,6 @@ extension Association { } } - /// Creates an association which appends *selection*. - /// - /// struct Player: TableRecord { - /// static let team = belongsTo(Team.self) - /// } - /// - /// // SELECT player.*, team.color, team.name - /// // FROM player - /// // JOIN team ON team.id = player.teamId - /// let association = Player.team - /// .select([Column("color")]) - /// .annotated(with: { db in [Column("name")] }) - /// var request = Player.including(required: association) public func annotatedWhenConnected(with selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self { withDestinationRelation { relation in relation = relation.annotatedWhenConnected { db in @@ -240,18 +192,6 @@ extension Association { // FilteredRequest conformance extension Association { - /// Creates an association with the provided *predicate promise* added to - /// the eventual set of already applied predicates. - /// - /// struct Player: TableRecord { - /// static let team = belongsTo(Team.self) - /// } - /// - /// // SELECT player.*, team.* - /// // FROM player - /// // JOIN team ON team.id = player.teamId AND 1 - /// let association = Player.team.filter { db in true } - /// var request = Player.including(required: association) public func filterWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self { withDestinationRelation { relation in relation = relation.filterWhenConnected { db in @@ -263,30 +203,6 @@ extension Association { // OrderedRequest conformance extension Association { - /// Creates an association with the provided *orderings promise*. - /// - /// struct Player: TableRecord { - /// static let team = belongsTo(Team.self) - /// } - /// - /// // SELECT player.*, team.* - /// // FROM player - /// // JOIN team ON team.id = player.teamId - /// // ORDER BY team.name - /// let association = Player.team.order { _ in [Column("name")] } - /// var request = Player.including(required: association) - /// - /// Any previous ordering is replaced: - /// - /// // SELECT player.*, team.* - /// // FROM player - /// // JOIN team ON team.id = player.teamId - /// // ORDER BY team.name - /// let association = Player.team - /// .order{ _ in [Column("color")] } - /// .reversed() - /// .order{ _ in [Column("name")] } - /// var request = Player.including(required: association) public func orderWhenConnected(_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) -> Self { withDestinationRelation { relation in relation = relation.orderWhenConnected { db in @@ -295,43 +211,12 @@ extension Association { } } - /// Creates an association that reverses applied orderings. - /// - /// struct Player: TableRecord { - /// static let team = belongsTo(Team.self) - /// } - /// - /// // SELECT player.*, team.* - /// // FROM player - /// // JOIN team ON team.id = player.teamId - /// // ORDER BY team.name DESC - /// let association = Player.team.order(Column("name")).reversed() - /// var request = Player.including(required: association) - /// - /// If no ordering was applied, the returned association is identical. - /// - /// // SELECT player.*, team.* - /// // FROM player - /// // JOIN team ON team.id = player.teamId - /// let association = Player.team.reversed() - /// var request = Player.including(required: association) public func reversed() -> Self { withDestinationRelation { relation in relation = relation.reversed() } } - /// Creates an association without any ordering. - /// - /// struct Player: TableRecord { - /// static let team = belongsTo(Team.self) - /// } - /// - /// // SELECT player.*, team.* - /// // FROM player - /// // JOIN team ON team.id = player.teamId - /// let association = Player.team.order(Column("name")).unordered() - /// var request = Player.including(required: association) public func unordered() -> Self { withDestinationRelation { relation in relation = relation.unordered() @@ -348,7 +233,6 @@ extension Association { // AggregatingRequest conformance extension Association { - /// Creates an association grouped according to *expressions promise*. public func groupWhenConnected(_ expressions: @escaping (Database) throws -> [any SQLExpressible]) -> Self { withDestinationRelation { relation in relation = relation.groupWhenConnected { db in @@ -357,8 +241,6 @@ extension Association { } } - /// Creates an association with the provided *predicate promise* added to - /// the eventual set of already applied predicates. public func havingWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self { withDestinationRelation { relation in relation = relation.havingWhenConnected { db in @@ -370,16 +252,12 @@ extension Association { // DerivableRequest conformance extension Association { - /// Creates an association for returns distinct rows. public func distinct() -> Self { withDestinationRelation { relation in relation.isDistinct = true } } - /// Returns an association that embeds the common table expression. - /// - /// See `QueryInterfaceRequest.with(_:)` for more information. public func with(_ cte: CommonTableExpression) -> Self { withDestinationRelation { relation in relation.ctes[cte.tableName] = cte.cte @@ -389,7 +267,7 @@ extension Association { // MARK: - AssociationToOne -/// The base protocol for all associations that define a one-to-one connection. +/// An association that defines a to-one connection. public protocol AssociationToOne: Association { } extension AssociationToOne { @@ -403,7 +281,21 @@ extension AssociationToOne { // MARK: - AssociationToMany -/// The base protocol for all associations that define a one-to-many connection. +/// An association that defines a to-many connection. +/// +/// ## Topics +/// +/// ### Building Association Aggregates +/// +/// - ``average(_:)`` +/// - ``count`` +/// - ``isEmpty`` +/// - ``max(_:)`` +/// - ``min(_:)`` +/// - ``sum(_:)`` +/// - ``total(_:)`` +/// +/// - ``AssociationAggregate`` public protocol AssociationToMany: Association { } extension AssociationToMany { diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index 2e75d4ff2..08b8af6f8 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -7,61 +7,125 @@ extension AssociationToMany { /// The number of associated records. /// - /// It has a default name, which is "[key]Count", where key is the key of - /// the association. For example: - /// /// For example: /// - /// struct TeamInfo: FetchableRecord, Decodable { - /// var team: Team - /// var playerCount: Int - /// } - /// let request = Team.annotated(with: Team.players.count()) - /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// ```swift + /// struct Player: TableRecord { } + /// struct Team: FetchableRecord, TableRecord { + /// static let players = Team.hasMany(Player.self) + /// } /// - /// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db) + /// try dbQueue.read { db in + /// // Fetch all teams with at least ten players: + /// let teams: [Team] = try Team + /// .having(Team.players.count >= 10) + /// .fetchAll(db) + /// } + /// ``` + /// + /// The returned association aggregate is named `"[key]Count"`, where `key` + /// is the association key. For example: + /// + /// ```swift + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var playerCount: Int + /// } + /// + /// try dbQueue.read { db in + /// let infos: [TeamInfo] = try Team + /// .annotated(with: Team.players.count) + /// .asRequest(of: TeamInfo.self) + /// .fetchAll(db) + /// } + /// ``` public var count: AssociationAggregate { makeAggregate(.countDistinct(.fastPrimaryKey)) .forKey("\(key.singularizedName)Count") } - /// Creates an aggregate that is true if there exists no associated records. + /// Returns a boolean aggregate that is true if no associated + /// records exist. /// - /// It has a default name, which is "hasNo[Key]", where key is the key of - /// the association. For example: + /// For example: /// - /// struct TeamInfo: FetchableRecord, Decodable { - /// var team: Team - /// var hasNoPlayer: Bool - /// } - /// let request = Team.annotated(with: Team.players.isEmpty) - /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// ```swift + /// struct Player: TableRecord { } + /// struct Team: FetchableRecord, TableRecord { + /// static let players = Team.hasMany(Player.self) + /// } /// - /// let teams: [Team] = try Team.having(Team.players.isEmpty).fetchAll(db) - /// let teams: [Team] = try Team.having(!Team.players.isEmpty) - /// let teams: [Team] = try Team.having(Team.players.isEmpty == false) + /// try dbQueue.read { db in + /// // Fetch all teams without any player + /// let teams: [Team] = try Team + /// .having(Team.players.isEmpty) + /// .fetchAll(db) + /// + /// // Fetch all teams without some player + /// let teams: [Team] = try Team + /// .having(Team.players.isEmpty == false) + /// .fetchAll(db) + /// } + /// ``` + /// + /// The returned association aggregate is named `"hasNo[key]"`, where `key` + /// is the association key. For example: + /// + /// ```swift + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var hasNoPlayer: Int + /// } + /// + /// try dbQueue.read { db in + /// let infos: [TeamInfo] = try Team + /// .annotated(with: Team.players.isEmpty) + /// .asRequest(of: TeamInfo.self) + /// .fetchAll(db) + /// } + /// ``` public var isEmpty: AssociationAggregate { makeAggregate(.isEmpty(.countDistinct(.fastPrimaryKey))) .forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)") } - /// Creates an aggregate which evaluate to the average value of the given - /// expression in associated records. - /// - /// When the averaged expression is a column, the aggregate has a default - /// name which is "average[Key][Column]", where key is the key of the - /// association. For example: + /// Returns the average of the given expression in associated records. /// /// For example: /// - /// struct TeamInfo: FetchableRecord, Decodable { - /// var team: Team - /// var averagePlayerScore: Double - /// } - /// let request = Team.annotated(with: Team.players.average(Column("score"))) - /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// ```swift + /// struct Player: TableRecord { } + /// struct Team: FetchableRecord, TableRecord { + /// static let players = Team.hasMany(Player.self) + /// } /// - /// let teams: [Team] = try Team.having(Team.players.average(Column("score")) > 100).fetchAll(db) + /// try dbQueue.read { db in + /// // Fetch all teams whose average player score is greater than 1000 + /// let averageScore = Team.players.average(Column("score")) + /// let teams: [Team] = try Team + /// .having(averageScore >= 1000) + /// .fetchAll(db) + /// } + /// ``` + /// + /// When the input expression is a ``ColumnExpression``, the returned + /// association aggregate is named `"average[Key][Column]"`, where `key` is + /// the association key. For example: + /// + /// ```swift + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var averagePlayerScore: Double + /// } + /// + /// try dbQueue.read { db in + /// let averageScore = Team.players.average(Column("score")) + /// let infos: [TeamInfo] = try Team + /// .annotated(with: averageScore) + /// .asRequest(of: TeamInfo.self) + /// .fetchAll(db) + /// } + /// ``` public func average(_ expression: some SQLSpecificExpressible) -> AssociationAggregate { let aggregate = makeAggregate(.aggregate("AVG", [expression.sqlExpression])) if let column = expression as? any ColumnExpression { @@ -72,23 +136,43 @@ extension AssociationToMany { } } - /// Creates an aggregate which evaluate to the maximum value of the given - /// expression in associated records. - /// - /// When the maximized expression is a column, the aggregate has a default - /// name which is "maximum[Key][Column]", where key is the key of the - /// association. For example: + /// Returns the maximum value of the given expression in associated records. /// /// For example: /// - /// struct TeamInfo: FetchableRecord, Decodable { - /// var team: Team - /// var maxPlayerScore: Double - /// } - /// let request = Team.annotated(with: Team.players.max(Column("score"))) - /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// ```swift + /// struct Player: TableRecord { } + /// struct Team: FetchableRecord, TableRecord { + /// static let players = Team.hasMany(Player.self) + /// } /// - /// let teams: [Team] = try Team.having(Team.players.max(Column("score")) < 100).fetchAll(db) + /// try dbQueue.read { db in + /// // Fetch all teams whose maximum player score is greater than 1000 + /// let maxScore = Team.players.max(Column("score")) + /// let teams: [Team] = try Team + /// .having(maxScore >= 1000) + /// .fetchAll(db) + /// } + /// ``` + /// + /// When the input expression is a ``ColumnExpression``, the returned + /// association aggregate is named `"maximum[Key][Column]"`, where `key` is + /// the association key. For example: + /// + /// ```swift + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var maximumPlayerScore: Double + /// } + /// + /// try dbQueue.read { db in + /// let maxScore = Team.players.max(Column("score")) + /// let infos: [TeamInfo] = try Team + /// .annotated(with: maxScore) + /// .asRequest(of: TeamInfo.self) + /// .fetchAll(db) + /// } + /// ``` public func max(_ expression: some SQLSpecificExpressible) -> AssociationAggregate { let aggregate = makeAggregate(.aggregate("MAX", [expression.sqlExpression])) if let column = expression as? any ColumnExpression { @@ -99,23 +183,43 @@ extension AssociationToMany { } } - /// Creates an aggregate which evaluate to the minimum value of the given - /// expression in associated records. - /// - /// When the minimized expression is a column, the aggregate has a default - /// name which is "minimum[Key][Column]", where key is the key of the - /// association. For example: + /// Returns the minimum value of the given expression in associated records. /// /// For example: /// - /// struct TeamInfo: FetchableRecord, Decodable { - /// var team: Team - /// var minPlayerScore: Double - /// } - /// let request = Team.annotated(with: Team.players.min(Column("score"))) - /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// ```swift + /// struct Player: TableRecord { } + /// struct Team: FetchableRecord, TableRecord { + /// static let players = Team.hasMany(Player.self) + /// } /// - /// let teams: [Team] = try Team.having(Team.players.min(Column("score")) > 100).fetchAll(db) + /// try dbQueue.read { db in + /// // Fetch all teams whose minimum player score is less than 1000 + /// let minScore = Team.players.min(Column("score")) + /// let teams: [Team] = try Team + /// .having(minScore < 1000) + /// .fetchAll(db) + /// } + /// ``` + /// + /// When the input expression is a ``ColumnExpression``, the returned + /// association aggregate is named `"minimum[Key][Column]"`, where `key` is + /// the association key. For example: + /// + /// ```swift + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var minimumPlayerScore: Double + /// } + /// + /// try dbQueue.read { db in + /// let minScore = Team.players.min(Column("score")) + /// let infos: [TeamInfo] = try Team + /// .annotated(with: minScore) + /// .asRequest(of: TeamInfo.self) + /// .fetchAll(db) + /// } + /// ``` public func min(_ expression: some SQLSpecificExpressible) -> AssociationAggregate { let aggregate = makeAggregate(.aggregate("MIN", [expression.sqlExpression])) if let column = expression as? any ColumnExpression { @@ -126,26 +230,46 @@ extension AssociationToMany { } } - /// Creates an aggregate which evaluate to the sum of the given expression - /// in associated records. + /// Returns the sum of the given expression in associated records. /// - /// When the summed expression is a column, the aggregate has a default - /// name which is "[key][Column]Sum", where key is the key of the - /// association. For example: + /// This aggregate invokes the `SUM` SQL function. See also ``total(_:)`` + /// and . /// /// For example: /// - /// struct TeamInfo: FetchableRecord, Decodable { - /// var team: Team - /// var playerScoreSum: Double - /// } - /// let request = Team.annotated(with: Team.players.sum(Column("score"))) - /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// ```swift + /// struct Player: TableRecord { } + /// struct Team: FetchableRecord, TableRecord { + /// static let players = Team.hasMany(Player.self) + /// } /// - /// let teams: [Team] = try Team.having(Team.players.sum(Column("score")) > 100).fetchAll(db) + /// try dbQueue.read { db in + /// // Fetch all teams whose sum of player scores is greater than 1000 + /// let scoreSum = Team.players.sum(Column("score")) + /// let teams: [Team] = try Team + /// .having(scoreSum >= 1000) + /// .fetchAll(db) + /// } + /// ``` /// - /// This aggregate invokes the `SUM` SQL function. See also `total(_:)`, and - /// . + /// When the input expression is a ``ColumnExpression``, the returned + /// association aggregate is named `"[key][Column]Sum"`, where `key` is the + /// association key. For example: + /// + /// ```swift + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var playerScoreSum: Double + /// } + /// + /// try dbQueue.read { db in + /// let scoreSum = Team.players.sum(Column("score")) + /// let infos: [TeamInfo] = try Team + /// .annotated(with: scoreSum) + /// .asRequest(of: TeamInfo.self) + /// .fetchAll(db) + /// } + /// ``` public func sum(_ expression: some SQLSpecificExpressible) -> AssociationAggregate { let aggregate = makeAggregate(.aggregate("SUM", [expression.sqlExpression])) if let column = expression as? any ColumnExpression { @@ -156,26 +280,46 @@ extension AssociationToMany { } } - /// Creates an aggregate which evaluate to the sum of the given expression - /// in associated records. + /// Returns the sum of the given expression in associated records. /// - /// When the summed expression is a column, the aggregate has a default - /// name which is "[key][Column]Sum", where key is the key of the - /// association. For example: + /// This aggregate invokes the `TOTAL` SQL function. See also ``sum(_:)`` + /// and . /// /// For example: /// - /// struct TeamInfo: FetchableRecord, Decodable { - /// var team: Team - /// var playerScoreSum: Double - /// } - /// let request = Team.annotated(with: Team.players.total(Column("score"))) - /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// ```swift + /// struct Player: TableRecord { } + /// struct Team: FetchableRecord, TableRecord { + /// static let players = Team.hasMany(Player.self) + /// } /// - /// let teams: [Team] = try Team.having(Team.players.total(Column("score")) > 100).fetchAll(db) + /// try dbQueue.read { db in + /// // Fetch all teams whose sum of player scores is greater than 1000 + /// let totalScore = Team.players.total(Column("score")) + /// let teams: [Team] = try Team + /// .having(totalScore >= 1000) + /// .fetchAll(db) + /// } + /// ``` /// - /// This aggregate invokes the `TOTAL` SQL function. See also `sum(_:)`, and - /// . + /// When the input expression is a ``ColumnExpression``, the returned + /// association aggregate is named `"[key][Column]Sum"`, where `key` is the + /// association key. For example: + /// + /// ```swift + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var playerScoreSum: Double + /// } + /// + /// try dbQueue.read { db in + /// let totalScore = Team.players.total(Column("score")) + /// let infos: [TeamInfo] = try Team + /// .annotated(with: totalScore) + /// .asRequest(of: TeamInfo.self) + /// .fetchAll(db) + /// } + /// ``` public func total(_ expression: some SQLSpecificExpressible) -> AssociationAggregate { let aggregate = makeAggregate(.aggregate("TOTAL", [expression.sqlExpression])) if let column = expression as? any ColumnExpression { @@ -189,28 +333,40 @@ extension AssociationToMany { } } -/// An AssociationAggregate is able to compute aggregated values from a -/// population of associated records. +/// A value aggregated from a population of associated records. +/// +/// You build an `AssociationAggregate` from an ``AssociationToMany``. /// /// For example: /// -/// struct Author: TableRecord { -/// static let books = hasMany(Book.self) -/// } +/// ```swift +/// struct Player: TableRecord { } +/// struct Team: FetchableRecord, TableRecord { +/// static let players = Team.hasMany(Player.self) +/// } /// -/// let bookCount = Author.books.count // AssociationAggregate +/// try dbQueue.read { db in +/// // An association aggregate +/// let playerCount = Team.players.count /// -/// Association aggregates can be used in the `annotated(with:)` and -/// `having(_:)` request methods: +/// // Fetch all teams with at least ten players: +/// let teams: [Team] = try Team +/// .having(playerCount >= 10) +/// .fetchAll(db) +/// } +/// ``` /// -/// let request = Author.annotated(with: bookCount) -/// let request = Author.having(bookCount >= 10) +/// ## Topics /// -/// The RowDecoder generic type helps the compiler prevent incorrect use -/// of aggregates: +/// ### Instance Methods /// -/// // Won't compile because Fruit is not Author. -/// let request = Fruit.annotated(with: bookCount) +/// - ``forKey(_:)-1rvux`` +/// - ``forKey(_:)-1ua4j`` +/// +/// ### Top-Level Functions +/// +/// - ``abs(_:)-43n8v`` +/// - ``length(_:)-9dr2v`` public struct AssociationAggregate { fileprivate let preparation: AssociationAggregatePreparation @@ -259,11 +415,26 @@ extension AssociationAggregate: Refinable { /// /// For example: /// - /// let aggregate = Author.books.count.forKey("numberOfBooks") - /// let request = Author.annotated(with: aggregate) - /// if let row = try Row.fetchOne(db, request) { - /// let numberOfBooks: Int = row["numberOfBooks"] - /// } + /// ```swift + /// struct Player: TableRecord { } + /// struct Team: FetchableRecord, TableRecord { + /// static let players = Team.hasMany(Player.self) + /// } + /// + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var numberOfBooks: Int + /// } + /// + /// try dbQueue.read { db in + /// let playerCount = Team.players.count.forKey("numberOfBooks") + /// + /// let infos: [TeamInfo] = try Team + /// .annotated(with: playerCount) + /// .asRequest(of: TeamInfo.self) + /// .fetchAll(db) + /// } + /// ``` public func forKey(_ key: String) -> Self { with { $0.key = key @@ -273,18 +444,7 @@ extension AssociationAggregate: Refinable { /// Returns an aggregate that is selected in a column named like the given /// coding key. /// - /// For example: - /// - /// struct AuthorInfo: Decodable, FetchableRecord { - /// var author: Author - /// var numberOfBooks: Int - /// - /// static func fetchAll(_ db: Database) throws -> [AuthorInfo] { - /// let aggregate = Author.books.count.forKey(CodingKeys.numberOfBooks) - /// let request = Author.annotated(with: aggregate) - /// return try AuthorInfo.fetchAll(db, request) - /// } - /// } + /// See ``forKey(_:)-1rvux``. public func forKey(_ key: some CodingKey) -> Self { forKey(key.stringValue) } @@ -398,620 +558,305 @@ private func combine( // MARK: - Logical Operators (AND, OR, NOT) -/// Returns a logically negated aggregate. -/// -/// For example: -/// -/// Author.having(!Author.books.isEmpty) -public prefix func ! (aggregate: AssociationAggregate) -> AssociationAggregate { - aggregate.map { !$0 } -} - -/// Groups two aggregates with the `AND` SQL operator. -/// -/// For example: -/// -/// Author.having(Author.books.isEmpty && Author.paintings.isEmpty) -public func && ( - lhs: AssociationAggregate, - rhs: AssociationAggregate) --> AssociationAggregate -{ - combine(lhs, rhs, with: &&) -} - -// TODO: test -/// :nodoc: -public func && ( - lhs: AssociationAggregate, - rhs: some SQLExpressible) --> AssociationAggregate -{ - lhs.map { $0 && rhs } -} - -// TODO: test -/// :nodoc: -public func && ( - lhs: some SQLExpressible, - rhs: AssociationAggregate) --> AssociationAggregate -{ - rhs.map { lhs && $0 } -} - - -/// Groups two aggregates with the `OR` SQL operator. -/// -/// For example: -/// -/// Author.having(!Author.books.isEmpty || !Author.paintings.isEmpty) -public func || ( - lhs: AssociationAggregate, - rhs: AssociationAggregate) --> AssociationAggregate -{ - combine(lhs, rhs, with: ||) -} - -// TODO: test -/// :nodoc: -public func || ( - lhs: AssociationAggregate, - rhs: some SQLExpressible) --> AssociationAggregate -{ - lhs.map { $0 || rhs } -} - -// TODO: test -/// :nodoc: -public func || ( - lhs: some SQLExpressible, - rhs: AssociationAggregate) --> AssociationAggregate -{ - rhs.map { lhs || $0 } +extension AssociationAggregate { + /// A negated logical aggregate. + /// + /// For example: + /// + /// ```swift + /// Author.having(!Author.books.isEmpty) + /// ``` + public static prefix func ! (aggregate: Self) -> Self { + aggregate.map { !$0 } + } + + /// The `AND` SQL operator. + public static func && (lhs: Self, rhs: Self) -> Self { + combine(lhs, rhs, with: &&) + } + + // TODO: test + /// The `AND` SQL operator. + public static func && (lhs: Self, rhs: some SQLExpressible) -> Self { + lhs.map { $0 && rhs } + } + + // TODO: test + /// The `AND` SQL operator. + public static func && (lhs: some SQLExpressible, rhs: Self) -> Self { + rhs.map { lhs && $0 } + } + + + /// The `OR` SQL operator. + public static func || (lhs: Self, rhs: Self) -> Self { + combine(lhs, rhs, with: ||) + } + + // TODO: test + /// The `OR` SQL operator. + public static func || (lhs: Self, rhs: some SQLExpressible) -> Self { + lhs.map { $0 || rhs } + } + + // TODO: test + /// The `OR` SQL operator. + public static func || (lhs: some SQLExpressible, rhs: Self) -> Self { + rhs.map { lhs || $0 } + } } // MARK: - Egality and Identity Operators (=, <>, IS, IS NOT) -/// Returns an aggregate that compares two aggregates with the `=` SQL operator. -/// -/// For example: -/// -/// Author.having(Author.books.count == Author.paintings.count) -public func == ( - lhs: AssociationAggregate, - rhs: AssociationAggregate) --> AssociationAggregate -{ - combine(lhs, rhs, with: ==) -} - -/// Returns an aggregate that compares an aggregate with the `=` SQL operator. -/// -/// For example: -/// -/// Author.having(Author.books.count == 3) -public func == ( - lhs: AssociationAggregate, - rhs: some SQLExpressible) --> AssociationAggregate -{ - lhs.map { $0 == rhs } -} - -/// Returns an aggregate that compares an aggregate with the `=` SQL operator. -/// -/// For example: -/// -/// Author.having(3 == Author.books.count) -public func == ( - lhs: some SQLExpressible, - rhs: AssociationAggregate) --> AssociationAggregate -{ - rhs.map { lhs == $0 } -} - -/// Returns an aggregate that checks the boolean value of an aggregate. -/// -/// For example: -/// -/// Author.having(Author.books.isEmpty == false) -public func == (lhs: AssociationAggregate, rhs: Bool) -> AssociationAggregate { - lhs.map { $0 == rhs } -} - -/// Returns an aggregate that checks the boolean value of an aggregate. -/// -/// For example: -/// -/// Author.having(false == Author.books.isEmpty) -public func == (lhs: Bool, rhs: AssociationAggregate) -> AssociationAggregate { - rhs.map { lhs == $0 } -} - -/// Returns an aggregate that compares two aggregates with the `<>` SQL operator. -/// -/// For example: -/// -/// Author.having(Author.books.count != Author.paintings.count) -public func != ( - lhs: AssociationAggregate, - rhs: AssociationAggregate) --> AssociationAggregate -{ - combine(lhs, rhs, with: !=) -} - -/// Returns an aggregate that compares an aggregate with the `<>` SQL operator. -/// -/// For example: -/// -/// Author.having(Author.books.count != 3) -public func != ( - lhs: AssociationAggregate, - rhs: some SQLExpressible) --> AssociationAggregate -{ - lhs.map { $0 != rhs } -} - -/// Returns an aggregate that compares an aggregate with the `<>` SQL operator. -/// -/// For example: -/// -/// Author.having(3 != Author.books.count) -public func != ( - lhs: some SQLExpressible, - rhs: AssociationAggregate) --> AssociationAggregate -{ - rhs.map { lhs != $0 } -} - -/// Returns an aggregate that checks the boolean value of an aggregate. -/// -/// For example: -/// -/// Author.having(Author.books.isEmpty != true) -public func != (lhs: AssociationAggregate, rhs: Bool) -> AssociationAggregate { - lhs.map { $0 != rhs } -} - -/// Returns an aggregate that checks the boolean value of an aggregate. -/// -/// For example: -/// -/// Author.having(true != Author.books.isEmpty) -public func != (lhs: Bool, rhs: AssociationAggregate) -> AssociationAggregate { - rhs.map { lhs != $0 } -} - -/// Returns an aggregate that compares two aggregates with the `IS` SQL operator. -/// -/// For example: -/// -/// Author.having(Author.books.count === Author.paintings.count) -public func === ( - lhs: AssociationAggregate, - rhs: AssociationAggregate) --> AssociationAggregate -{ - combine(lhs, rhs, with: ===) -} - -/// Returns an aggregate that compares an aggregate with the `IS` SQL operator. -/// -/// For example: -/// -/// Author.having(Author.books.count === 3) -public func === ( - lhs: AssociationAggregate, - rhs: some SQLExpressible) --> AssociationAggregate -{ - lhs.map { $0 === rhs } -} - -/// Returns an aggregate that compares an aggregate with the `IS` SQL operator. -/// -/// For example: -/// -/// Author.having(3 === Author.books.count) -public func === ( - lhs: some SQLExpressible, - rhs: AssociationAggregate) --> AssociationAggregate -{ - rhs.map { lhs === $0 } -} - -/// Returns an aggregate that compares two aggregates with the `IS NOT` SQL operator. -/// -/// For example: -/// -/// Author.having(Author.books.count !== Author.paintings.count) -public func !== ( - lhs: AssociationAggregate, - rhs: AssociationAggregate) --> AssociationAggregate -{ - combine(lhs, rhs, with: !==) -} - -/// Returns an aggregate that compares an aggregate with the `IS NOT` SQL operator. -/// -/// For example: -/// -/// Author.having(Author.books.count !== 3) -public func !== ( - lhs: AssociationAggregate, - rhs: some SQLExpressible) --> AssociationAggregate -{ - lhs.map { $0 !== rhs } -} - -/// Returns an aggregate that compares an aggregate with the `IS NOT` SQL operator. -/// -/// For example: -/// -/// Author.having(3 !== Author.books.count) -public func !== ( - lhs: some SQLExpressible, - rhs: AssociationAggregate) --> AssociationAggregate -{ - rhs.map { lhs !== $0 } +extension AssociationAggregate { + /// The `=` SQL operator. + public static func == (lhs: Self, rhs: Self) -> Self { + combine(lhs, rhs, with: ==) + } + + /// The `=` SQL operator. + /// + /// When the right operand is nil, `IS NULL` is used instead of the + /// `=` operator. + public static func == (lhs: Self, rhs: (any SQLExpressible)?) -> Self { + lhs.map { $0 == rhs } + } + + /// The `=` SQL operator. + /// + /// When the left operand is nil, `IS NULL` is used instead of the + /// `=` operator. + public static func == (lhs: (any SQLExpressible)?, rhs: Self) -> Self { + rhs.map { lhs == $0 } + } + + /// The `=` SQL operator. + public static func == (lhs: Self, rhs: Bool) -> Self { + lhs.map { $0 == rhs } + } + + /// The `=` SQL operator. + public static func == (lhs: Bool, rhs: Self) -> Self { + rhs.map { lhs == $0 } + } + + /// The `<>` SQL operator. + public static func != (lhs: Self, rhs: Self) -> Self { + combine(lhs, rhs, with: !=) + } + + /// The `<>` SQL operator. + /// + /// When the right operand is nil, `IS NOT NULL` is used instead of the + /// `<>` operator. + public static func != (lhs: Self, rhs: (any SQLExpressible)?) -> Self { + lhs.map { $0 != rhs } + } + + /// The `<>` SQL operator. + /// + /// When the left operand is nil, `IS NOT NULL` is used instead of the + /// `<>` operator. + public static func != (lhs: (any SQLExpressible)?, rhs: Self) -> Self { + rhs.map { lhs != $0 } + } + + /// The `<>` SQL operator. + public static func != (lhs: Self, rhs: Bool) -> Self { + lhs.map { $0 != rhs } + } + + /// The `<>` SQL operator. + public static func != (lhs: Bool, rhs: Self) -> Self { + rhs.map { lhs != $0 } + } + + /// The `IS` SQL operator. + public static func === (lhs: Self, rhs: Self) -> Self { + combine(lhs, rhs, with: ===) + } + + /// The `IS` SQL operator. + public static func === (lhs: Self, rhs: (any SQLExpressible)?) -> Self { + lhs.map { $0 === rhs } + } + + /// The `IS` SQL operator. + public static func === (lhs: (any SQLExpressible)?, rhs: Self) -> Self { + rhs.map { lhs === $0 } + } + + /// The `IS NOT` SQL operator. + public static func !== (lhs: Self, rhs: Self) -> Self { + combine(lhs, rhs, with: !==) + } + + /// The `IS NOT` SQL operator. + public static func !== (lhs: Self, rhs: (any SQLExpressible)?) -> Self { + lhs.map { $0 !== rhs } + } + + /// The `IS NOT` SQL operator. + public static func !== (lhs: (any SQLExpressible)?, rhs: Self) -> Self { + rhs.map { lhs !== $0 } + } } // MARK: - Comparison Operators (<, >, <=, >=) -/// Returns an aggregate that compares two aggregates with the `<=` SQL operator. -/// -/// For example: -/// -/// Author.having(Author.books.count <= Author.paintings.count) -public func <= ( - lhs: AssociationAggregate, - rhs: AssociationAggregate) --> AssociationAggregate -{ - combine(lhs, rhs, with: <=) -} - -/// Returns an aggregate that compares an aggregate with the `<=` SQL operator. -/// -/// For example: -/// -/// Author.having(Author.books.count <= 3) -public func <= ( - lhs: AssociationAggregate, - rhs: some SQLExpressible) --> AssociationAggregate -{ - lhs.map { $0 <= rhs } -} - -/// Returns an aggregate that compares an aggregate with the `<=` SQL operator. -/// -/// For example: -/// -/// Author.having(3 <= Author.books.count) -public func <= ( - lhs: some SQLExpressible, - rhs: AssociationAggregate) --> AssociationAggregate -{ - rhs.map { lhs <= $0 } -} - -/// Returns an aggregate that compares two aggregates with the `<` SQL operator. -/// -/// For example: -/// -/// Author.having(Author.books.count < Author.paintings.count) -public func < ( - lhs: AssociationAggregate, - rhs: AssociationAggregate) --> AssociationAggregate -{ - combine(lhs, rhs, with: <) -} - -/// Returns an aggregate that compares an aggregate with the `<` SQL operator. -/// -/// For example: -/// -/// Author.having(Author.books.count < 3) -public func < ( - lhs: AssociationAggregate, - rhs: some SQLExpressible) --> AssociationAggregate -{ - lhs.map { $0 < rhs } -} - -/// Returns an aggregate that compares an aggregate with the `<` SQL operator. -/// -/// For example: -/// -/// Author.having(3 < Author.books.count) -public func < ( - lhs: some SQLExpressible, - rhs: AssociationAggregate) --> AssociationAggregate -{ - rhs.map { lhs < $0 } -} - -/// Returns an aggregate that compares two aggregates with the `>` SQL operator. -/// -/// For example: -/// -/// Author.having(Author.books.count > Author.paintings.count) -public func > ( - lhs: AssociationAggregate, - rhs: AssociationAggregate) --> AssociationAggregate -{ - combine(lhs, rhs, with: >) -} - -/// Returns an aggregate that compares an aggregate with the `>` SQL operator. -/// -/// For example: -/// -/// Author.having(Author.books.count > 3) -public func > ( - lhs: AssociationAggregate, - rhs: some SQLExpressible) --> AssociationAggregate -{ - lhs.map { $0 > rhs } -} - -/// Returns an aggregate that compares an aggregate with the `>` SQL operator. -/// -/// For example: -/// -/// Author.having(3 > Author.books.count) -public func > ( - lhs: some SQLExpressible, - rhs: AssociationAggregate) --> AssociationAggregate -{ - rhs.map { lhs > $0 } -} - -/// Returns an aggregate that compares two aggregates with the `>=` SQL operator. -/// -/// For example: -/// -/// Author.having(Author.books.count >= Author.paintings.count) -public func >= ( - lhs: AssociationAggregate, - rhs: AssociationAggregate) --> AssociationAggregate -{ - combine(lhs, rhs, with: >=) -} - -/// Returns an aggregate that compares an aggregate with the `>=` SQL operator. -/// -/// For example: -/// -/// Author.having(Author.books.count >= 3) -public func >= ( - lhs: AssociationAggregate, - rhs: some SQLExpressible) --> AssociationAggregate -{ - lhs.map { $0 >= rhs } -} - -/// Returns an aggregate that compares an aggregate with the `>=` SQL operator. -/// -/// For example: -/// -/// Author.having(3 >= Author.books.count) -public func >= ( - lhs: some SQLExpressible, - rhs: AssociationAggregate) --> AssociationAggregate -{ - rhs.map { lhs >= $0 } +extension AssociationAggregate { + /// The `<=` SQL operator. + public static func <= (lhs: Self, rhs: Self) -> Self { + combine(lhs, rhs, with: <=) + } + + /// The `<=` SQL operator. + public static func <= (lhs: Self, rhs: some SQLExpressible) -> Self { + lhs.map { $0 <= rhs } + } + + /// The `<=` SQL operator. + public static func <= (lhs: some SQLExpressible, rhs: Self) -> Self { + rhs.map { lhs <= $0 } + } + + /// The `<` SQL operator. + public static func < (lhs: Self, rhs: Self) -> Self { + combine(lhs, rhs, with: <) + } + + /// The `<` SQL operator. + public static func < (lhs: Self, rhs: some SQLExpressible) -> Self { + lhs.map { $0 < rhs } + } + + /// The `<` SQL operator. + public static func < (lhs: some SQLExpressible, rhs: Self) -> Self { + rhs.map { lhs < $0 } + } + + /// The `>` SQL operator. + public static func > (lhs: Self, rhs: Self) -> Self { + combine(lhs, rhs, with: >) + } + + /// The `>` SQL operator. + public static func > (lhs: Self, rhs: some SQLExpressible) -> Self { + lhs.map { $0 > rhs } + } + + /// The `>` SQL operator. + public static func > (lhs: some SQLExpressible, rhs: Self) -> Self { + rhs.map { lhs > $0 } + } + + /// The `>=` SQL operator. + public static func >= (lhs: Self, rhs: Self) -> Self { + combine(lhs, rhs, with: >=) + } + + /// The `>=` SQL operator. + public static func >= (lhs: Self, rhs: some SQLExpressible) -> Self { + lhs.map { $0 >= rhs } + } + + /// The `>=` SQL operator. + public static func >= (lhs: some SQLExpressible, rhs: Self) -> Self { + rhs.map { lhs >= $0 } + } } // MARK: - Arithmetic Operators (+, -, *, /) -/// Returns an arithmetically negated aggregate. -/// -/// For example: -/// -/// Author.annotated(with: -Author.books.count) -public prefix func - (aggregate: AssociationAggregate) -> AssociationAggregate { - aggregate.map { -$0 } -} - -/// Returns an aggregate that sums two aggregates with the `+` SQL operator. -/// -/// For example: -/// -/// Author.annotated(with: Author.books.count + Author.paintings.count) -public func + ( - lhs: AssociationAggregate, - rhs: AssociationAggregate) --> AssociationAggregate -{ - combine(lhs, rhs, with: +) -} - -/// Returns an aggregate that sums an aggregate with the `+` SQL operator. -/// -/// For example: -/// -/// Author.annotated(with: Author.books.count + 1) -public func + ( - lhs: AssociationAggregate, - rhs: some SQLExpressible) --> AssociationAggregate -{ - lhs.map { $0 + rhs } -} - -/// Returns an aggregate that sums an aggregate with the `+` SQL operator. -/// -/// For example: -/// -/// Author.annotated(with: 1 + Author.books.count) -public func + ( - lhs: some SQLExpressible, - rhs: AssociationAggregate) --> AssociationAggregate -{ - rhs.map { lhs + $0 } -} - -/// Returns an aggregate that substracts two aggregates with the `-` SQL operator. -/// -/// For example: -/// -/// Author.annotated(with: Author.books.count - Author.paintings.count) -public func - ( - lhs: AssociationAggregate, - rhs: AssociationAggregate) --> AssociationAggregate -{ - combine(lhs, rhs, with: -) -} - -/// Returns an aggregate that substracts an aggregate with the `-` SQL operator. -/// -/// For example: -/// -/// Author.annotated(with: Author.books.count - 1) -public func - ( - lhs: AssociationAggregate, - rhs: some SQLExpressible) --> AssociationAggregate -{ - lhs.map { $0 - rhs } -} - -/// Returns an aggregate that substracts an aggregate with the `-` SQL operator. -/// -/// For example: -/// -/// Author.annotated(with: 1 - Author.books.count) -public func - ( - lhs: some SQLExpressible, - rhs: AssociationAggregate) --> AssociationAggregate -{ - rhs.map { lhs - $0 } -} - -/// Returns an aggregate that multiplies two aggregates with the `*` SQL operator. -/// -/// For example: -/// -/// Author.annotated(with: Author.books.count * Author.paintings.count) -public func * ( - lhs: AssociationAggregate, - rhs: AssociationAggregate) --> AssociationAggregate -{ - combine(lhs, rhs, with: *) -} - -/// Returns an aggregate that substracts an aggregate with the `*` SQL operator. -/// -/// For example: -/// -/// Author.annotated(with: Author.books.count * 2) -public func * ( - lhs: AssociationAggregate, - rhs: some SQLExpressible) --> AssociationAggregate -{ - lhs.map { $0 * rhs } -} - -/// Returns an aggregate that substracts an aggregate with the `*` SQL operator. -/// -/// For example: -/// -/// Author.annotated(with: 2 * Author.books.count) -public func * ( - lhs: some SQLExpressible, - rhs: AssociationAggregate) --> AssociationAggregate -{ - rhs.map { lhs * $0 } -} - -/// Returns an aggregate that multiplies two aggregates with the `/` SQL operator. -/// -/// For example: -/// -/// Author.annotated(with: Author.books.count / Author.paintings.count) -public func / ( - lhs: AssociationAggregate, - rhs: AssociationAggregate) --> AssociationAggregate -{ - combine(lhs, rhs, with: /) -} - -/// Returns an aggregate that substracts an aggregate with the `/` SQL operator. -/// -/// For example: -/// -/// Author.annotated(with: Author.books.count / 2) -public func / ( - lhs: AssociationAggregate, - rhs: some SQLExpressible) --> AssociationAggregate -{ - lhs.map { $0 / rhs } -} - -/// Returns an aggregate that substracts an aggregate with the `/` SQL operator. -/// -/// For example: -/// -/// Author.annotated(with: 2 / Author.books.count) -public func / ( - lhs: some SQLExpressible, - rhs: AssociationAggregate) --> AssociationAggregate -{ - rhs.map { lhs / $0 } +extension AssociationAggregate { + /// The `-` SQL operator. + public static prefix func - (aggregate: Self) -> Self { + aggregate.map { -$0 } + } + + /// The `+` SQL operator. + public static func + (lhs: Self, rhs: Self) -> Self { + combine(lhs, rhs, with: +) + } + + /// The `+` SQL operator. + public static func + (lhs: Self, rhs: some SQLExpressible) -> Self { + lhs.map { $0 + rhs } + } + + /// The `+` SQL operator. + public static func + (lhs: some SQLExpressible, rhs: Self) -> Self { + rhs.map { lhs + $0 } + } + + /// The `-` SQL operator. + public static func - (lhs: Self, rhs: Self) -> Self { + combine(lhs, rhs, with: -) + } + + /// The `-` SQL operator. + public static func - (lhs: Self, rhs: some SQLExpressible) -> Self { + lhs.map { $0 - rhs } + } + + /// The `-` SQL operator. + public static func - (lhs: some SQLExpressible, rhs: Self) -> Self { + rhs.map { lhs - $0 } + } + + /// The `*` SQL operator. + public static func * (lhs: Self, rhs: Self) -> Self { + combine(lhs, rhs, with: *) + } + + /// The `*` SQL operator. + public static func * (lhs: Self, rhs: some SQLExpressible) -> Self { + lhs.map { $0 * rhs } + } + + /// The `*` SQL operator. + public static func * (lhs: some SQLExpressible, rhs: Self) -> Self { + rhs.map { lhs * $0 } + } + + /// The `/` SQL operator. + public static func / (lhs: Self, rhs: Self) -> Self { + combine(lhs, rhs, with: /) + } + + /// The `/` SQL operator. + public static func / (lhs: Self, rhs: some SQLExpressible) -> Self { + lhs.map { $0 / rhs } + } + + /// The `/` SQL operator. + public static func / (lhs: some SQLExpressible, rhs: Self) -> Self { + rhs.map { lhs / $0 } + } } // MARK: - IFNULL(...) -/// Returns an aggregate that evaluates the `IFNULL` SQL function. -/// -/// Team.annotated(with: Team.players.min(Column("score")) ?? 0) -public func ?? ( - lhs: AssociationAggregate, - rhs: some SQLExpressible) --> AssociationAggregate -{ - lhs - .map { $0 ?? rhs } - .with { $0.key = lhs.key } // Preserve key +extension AssociationAggregate { + /// The `IFNULL` SQL function. + /// + /// For example: + /// + /// ```swift + /// Team.annotated(with: Team.players.min(Column("score")) ?? 0) + /// ``` + /// + /// The returned aggregate has the same key as the input. + public static func ?? (lhs: Self, rhs: some SQLExpressible) -> Self { + lhs + .map { $0 ?? rhs } + .with { $0.key = lhs.key } // Preserve key + } } // MARK: - ABS(...) -/// Returns an aggregate that evaluates to the absolute value of the -/// input aggregate. +/// The `ABS` SQL function. public func abs(_ aggregate: AssociationAggregate) -> AssociationAggregate { @@ -1020,8 +865,7 @@ public func abs(_ aggregate: AssociationAggregate) // MARK: - LENGTH(...) -/// Returns an aggregate that evaluates the `LENGTH` SQL function on the -/// input aggregate. +/// The `LENGTH` SQL function. public func length(_ aggregate: AssociationAggregate) -> AssociationAggregate { diff --git a/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift index 7ce78d7e1..ea04513d6 100644 --- a/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift @@ -1,46 +1,49 @@ -/// The BelongsTo association sets up a one-to-one connection from a record +/// Thes `BelongsToAssociation` sets up a one-to-one connection from a record /// type to another record type, such as each instance of the declaring record /// "belongs to" an instance of the other record. /// /// For example, if your application includes authors and books, and each book /// is assigned its author, you'd declare the association this way: /// -/// struct Author: TableRecord { ... } -/// struct Book: TableRecord { -/// static let author = belongsTo(Author.self) -/// ... -/// } +/// ```swift +/// struct Author: TableRecord { } +/// struct Book: TableRecord { +/// static let author = belongsTo(Author.self) +/// } +/// ``` /// -/// A BelongsTo associations should be supported by an SQLite foreign key. +/// A `BelongsToAssociation` should be supported by an SQLite foreign key. /// /// Foreign keys are the recommended way to declare relationships between /// database tables because not only will SQLite guarantee the integrity of your /// data, but GRDB will be able to use those foreign keys to automatically -/// configure your association. +/// configure your associations. /// /// You define the foreign key when you create database tables. For example: /// -/// try db.create(table: "author") { t in -/// t.autoIncrementedPrimaryKey("id") // (1) -/// t.column("name", .text) -/// } -/// try db.create(table: "book") { t in -/// t.autoIncrementedPrimaryKey("id") -/// t.column("authorId", .integer) // (2) -/// .notNull() // (3) -/// .indexed() // (4) -/// .references("author", onDelete: .cascade) // (5) -/// t.column("title", .text) -/// } +/// ```swift +/// try db.create(table: "author") { t in +/// t.autoIncrementedPrimaryKey("id") // (1) +/// t.column("name", .text) +/// } +/// try db.create(table: "book") { t in +/// t.autoIncrementedPrimaryKey("id") +/// t.column("authorId", .integer) // (2) +/// .notNull() // (3) +/// .indexed() // (4) +/// .references("author", onDelete: .cascade) // (5) +/// t.column("title", .text) +/// } +/// ``` /// /// 1. The author table has a primary key. -/// 2. The book.authorId column is used to link a book to the author it +/// 2. The `book.authorId` column is used to link a book to the author it /// belongs to. -/// 3. Make the book.authorId column not null if you want SQLite to guarantee +/// 3. Make the `book.authorId` column not null if you want SQLite to guarantee /// that all books have an author. -/// 4. Create an index on the book.authorId column in order to ease the +/// 4. Create an index on the `book.authorId` column in order to ease the /// selection of an author's books. -/// 5. Create a foreign key from book.authorId column to authors.id, so that +/// 5. Create a foreign key from `book.authorId` column to `author.id`, so that /// SQLite guarantees that no book refers to a missing author. The /// `onDelete: .cascade` option has SQLite automatically delete all of an /// author's books when that author is deleted. @@ -50,22 +53,15 @@ /// speaking, all primary keys are supported. /// /// If the database schema does not define foreign keys between tables, you can -/// still use BelongsTo associations. But your help is needed to define the +/// still use `BelongsToAssociation`. But your help is needed to define the /// missing foreign key: /// -/// struct Book: FetchableRecord, TableRecord { -/// static let author = belongsTo(Author.self, using: ForeignKey(...)) -/// } -/// -/// See ForeignKey for more information. -public struct BelongsToAssociation: AssociationToOne { - /// :nodoc: - public typealias OriginRowDecoder = Origin - - /// :nodoc: - public typealias RowDecoder = Destination - - /// :nodoc: +/// ```swift +/// struct Book: TableRecord { +/// static let author = belongsTo(Author.self, using: ForeignKey(...)) +/// } +/// ``` +public struct BelongsToAssociation { public var _sqlAssociation: _SQLAssociation init( @@ -94,3 +90,8 @@ public struct BelongsToAssociation: AssociationToOne { cardinality: .toOne) } } + +extension BelongsToAssociation: AssociationToOne { + public typealias OriginRowDecoder = Origin + public typealias RowDecoder = Destination +} diff --git a/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift index 9e00ab85e..2b3973005 100644 --- a/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift @@ -1,46 +1,49 @@ -/// The HasMany association indicates a one-to-many connection between two +/// The `HasManyAssociation` indicates a one-to-many connection between two /// record types, such as each instance of the declaring record "has many" /// instances of the other record. /// /// For example, if your application includes authors and books, and each author /// is assigned zero or more books, you'd declare the association this way: /// -/// struct Book: TableRecord { ... } -/// struct Author: TableRecord { -/// static let books = hasMany(Book.self) -/// ... -/// } +/// ```swift +/// struct Book: TableRecord { } +/// struct Author: TableRecord { +/// static let books = hasMany(Book.self) +/// } +/// ``` /// -/// HasMany associations should be supported by an SQLite foreign key. +/// A `HasManyAssociation` should be supported by an SQLite foreign key. /// /// Foreign keys are the recommended way to declare relationships between /// database tables because not only will SQLite guarantee the integrity of your /// data, but GRDB will be able to use those foreign keys to automatically -/// configure your association. +/// configure your associations. /// /// You define the foreign key when you create database tables. For example: /// -/// try db.create(table: "author") { t in -/// t.autoIncrementedPrimaryKey("id") // (1) -/// t.column("name", .text) -/// } -/// try db.create(table: "book") { t in -/// t.autoIncrementedPrimaryKey("id") -/// t.column("authorId", .integer) // (2) -/// .notNull() // (3) -/// .indexed() // (4) -/// .references("author", onDelete: .cascade) // (5) -/// t.column("title", .text) -/// } +/// ```swift +/// try db.create(table: "author") { t in +/// t.autoIncrementedPrimaryKey("id") // (1) +/// t.column("name", .text) +/// } +/// try db.create(table: "book") { t in +/// t.autoIncrementedPrimaryKey("id") +/// t.column("authorId", .integer) // (2) +/// .notNull() // (3) +/// .indexed() // (4) +/// .references("author", onDelete: .cascade) // (5) +/// t.column("title", .text) +/// } +/// ``` /// /// 1. The author table has a primary key. -/// 2. The book.authorId column is used to link a book to the author it +/// 2. The `book.authorId` column is used to link a book to the author it /// belongs to. -/// 3. Make the book.authorId column not null if you want SQLite to guarantee +/// 3. Make the `book.authorId` column not null if you want SQLite to guarantee /// that all books have an author. -/// 4. Create an index on the book.authorId column in order to ease the +/// 4. Create an index on the `book.authorId` column in order to ease the /// selection of an author's books. -/// 5. Create a foreign key from book.authorId column to authors.id, so that +/// 5. Create a foreign key from `book.authorId` column to `author.id`, so that /// SQLite guarantees that no book refers to a missing author. The /// `onDelete: .cascade` option has SQLite automatically delete all of an /// author's books when that author is deleted. @@ -50,22 +53,15 @@ /// speaking, all primary keys are supported. /// /// If the database schema does not define foreign keys between tables, you can -/// still use HasMany associations. But your help is needed to define the +/// still use `HasManyAssociation`. But your help is needed to define the /// missing foreign key: /// -/// struct Author: TableRecord { -/// static let books = hasMany(Book.self, using: ForeignKey(...)) -/// } -/// -/// See ForeignKey for more information. -public struct HasManyAssociation: AssociationToMany { - /// :nodoc: - public typealias OriginRowDecoder = Origin - - /// :nodoc: - public typealias RowDecoder = Destination - - /// :nodoc: +/// ```swift +/// struct Author: TableRecord { +/// static let books = hasMany(Book.self, using: ForeignKey(...)) +/// } +/// ``` +public struct HasManyAssociation { public var _sqlAssociation: _SQLAssociation init( @@ -94,3 +90,8 @@ public struct HasManyAssociation: AssociationToMany { cardinality: .toMany) } } + +extension HasManyAssociation: AssociationToMany { + public typealias OriginRowDecoder = Origin + public typealias RowDecoder = Destination +} diff --git a/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift b/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift index 7a9068c4b..d0ecb09f7 100644 --- a/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift @@ -1,54 +1,50 @@ -/// The **HasManyThrough** association is often used to set up a many-to-many +/// The `HasManyThroughAssociation` is often used to set up a many-to-many /// connection with another record. This association indicates that the /// declaring record can be matched with zero or more instances of another /// record by proceeding through a third record. /// -/// For example, consider the practice of passport delivery. One coutry +/// For example, consider the practice of passport delivery. One country /// "has many" citizens "through" its passports: /// -/// struct Country: TableRecord { -/// static let passports = hasMany(Passport.self) -/// static let citizens = hasMany(Citizen.self, through: passports, using: Passport.citizen) -/// ... -/// } +/// ```swift +/// struct Citizen: TableRecord { } /// -/// struct Passport: TableRecord { -/// static let citizen = belongsTo(Citizen.self) -/// ... -/// } +/// struct Passport: TableRecord { +/// static let citizen = belongsTo(Citizen.self) +/// } /// -/// struct Citizen: TableRecord { ... } +/// struct Country: TableRecord { +/// static let passports = hasMany(Passport.self) +/// static let citizens = hasMany(Citizen.self, +/// through: passports, +/// using: Passport.citizen) +/// } +/// ``` /// -/// The **HasManyThrough** association is also useful for setting up -/// "shortcuts" through nested HasMany associations. For example, if a document -/// has many sections, and a section has many paragraphs, you may sometimes want -/// to get a simple collection of all paragraphs in the document. You could set +/// The `HasManyThroughAssociation` is also useful for setting up "shortcuts" +/// through nested associations. For example, if a document has many sections, +/// and a section has many paragraphs, you may sometimes want to get a simple +/// collection of all paragraphs in the document. You could set /// that up this way: /// -/// struct Document: TableRecord { -/// static let sections = hasMany(Section.self) -/// static let paragraphs = hasMany(Paragraph.self, through: sections, using: Section.paragraphs) -/// } +/// ```swift +/// struct Paragraph: TableRecord { } /// -/// struct Section: TableRecord { -/// static let paragraphs = hasMany(Paragraph.self) -/// } +/// struct Section: TableRecord { +/// static let paragraphs = hasMany(Paragraph.self) +/// } /// -/// struct Paragraph: TableRecord { -/// } +/// struct Document: TableRecord { +/// static let sections = hasMany(Section.self) +/// static let paragraphs = hasMany(Paragraph.self, +/// through: sections, +/// using: Section.paragraphs) +/// } +/// ``` /// -/// As in the examples above, **HasManyThrough** association is always built from -/// two other associations: the `through:` and `using:` arguments. Those -/// associations can be any other association (BelongsTo, HasMany, -/// HasManyThrough, etc). -public struct HasManyThroughAssociation: AssociationToMany { - /// :nodoc: - public typealias OriginRowDecoder = Origin - - /// :nodoc: - public typealias RowDecoder = Destination - - /// :nodoc: +/// As in the examples above, `HasManyThroughAssociation` is always built from +/// two other associations. Those associations can be any ``Association``. +public struct HasManyThroughAssociation { public var _sqlAssociation: _SQLAssociation init( @@ -63,3 +59,8 @@ public struct HasManyThroughAssociation: AssociationToMany _sqlAssociation = target._sqlAssociation.through(pivot._sqlAssociation) } } + +extension HasManyThroughAssociation: AssociationToMany { + public typealias OriginRowDecoder = Origin + public typealias RowDecoder = Destination +} diff --git a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift index f701ff9dd..b3ac2cded 100644 --- a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift @@ -1,4 +1,4 @@ -/// The HasOne association indicates a one-to-one connection between two +/// The `HasOneAssociation` indicates a one-to-one connection between two /// record types, such as each instance of the declaring record "has one" /// instances of the other record. /// @@ -6,44 +6,47 @@ /// another for their demographic profiles, you'd declare the association /// this way: /// -/// struct Demographics: TableRecord { ... } -/// struct Country: TableRecord { -/// static let demographics = hasOne(Demographics.self) -/// ... -/// } +/// ```swift +/// struct Demographics: TableRecord { } +/// struct Country: TableRecord { +/// static let demographics = hasOne(Demographics.self) +/// } +/// ``` /// -/// HasOne associations should be supported by an SQLite foreign key. +/// A `HasOneAssociation` should be supported by an SQLite foreign key. /// /// Foreign keys are the recommended way to declare relationships between /// database tables because not only will SQLite guarantee the integrity of your /// data, but GRDB will be able to use those foreign keys to automatically -/// configure your association. +/// configure your associations. /// /// You define the foreign key when you create database tables. For example: /// -/// try db.create(table: "country") { t in -/// t.column("code", .text).primaryKey() // (1) -/// t.column("name", .text) -/// } -/// try db.create(table: "demographics") { t in -/// t.autoIncrementedPrimaryKey("id") -/// t.column("countryCode", .text) // (2) -/// .notNull() // (3) -/// .unique() // (4) -/// .references("country", onDelete: .cascade) // (5) -/// t.column("population", .integer) -/// t.column("density", .double) -/// } +/// ```swift +/// try db.create(table: "country") { t in +/// t.column("code", .text).primaryKey() // (1) +/// t.column("name", .text) +/// } +/// try db.create(table: "demographics") { t in +/// t.autoIncrementedPrimaryKey("id") +/// t.column("countryCode", .text) // (2) +/// .notNull() // (3) +/// .unique() // (4) +/// .references("country", onDelete: .cascade) // (5) +/// t.column("population", .integer) +/// t.column("density", .double) +/// } +/// ``` /// /// 1. The country table has a primary key. -/// 2. The demographics.countryCode column is used to link a demographic +/// 2. The `demographics.countryCode` column is used to link a demographic /// profile to the country it belongs to. -/// 3. Make the demographics.countryCode column not null if you want SQLite to +/// 3. Make the `demographics.countryCode` column not null if you want SQLite to /// guarantee that all profiles are linked to a country. -/// 4. Create a unique index on the demographics.countryCode column in order to -/// guarantee the unicity of any country's profile. -/// 5. Create a foreign key from demographics.countryCode column to -/// country.code, so that SQLite guarantees that no profile refers to a +/// 4. Create a unique index on the `demographics.countryCode` column in order +/// to guarantee the unicity of any country's demographics. +/// 5. Create a foreign key from `demographics.countryCode` column to +/// `country.code`, so that SQLite guarantees that no profile refers to a /// missing country. The `onDelete: .cascade` option has SQLite automatically /// delete a profile when its country is deleted. /// See for more information. @@ -51,23 +54,17 @@ /// The example above uses a string primary for the country table. But generally /// speaking, all primary keys are supported. /// -/// If the database schema does not follow this convention, and does not define -/// foreign keys between tables, you can still use HasOne associations. But -/// your help is needed to define the missing foreign key: +/// If the database schema does not define foreign keys between tables, you can +/// still use `HasOneAssociation`. But your help is needed to define the +/// missing foreign key: /// -/// struct Country: FetchableRecord, TableRecord { -/// static let demographics = hasOne(Demographics.self, using: ForeignKey(...)) -/// } -/// -/// See ForeignKey for more information. -public struct HasOneAssociation: AssociationToOne { - /// :nodoc: - public typealias OriginRowDecoder = Origin - - /// :nodoc: - public typealias RowDecoder = Destination - - /// :nodoc: +/// ```swift +/// struct Demographics: TableRecord { } +/// struct Country: TableRecord { +/// static let demographics = hasOne(Demographics.self, using: ForeignKey(...) +/// } +/// ``` +public struct HasOneAssociation { public var _sqlAssociation: _SQLAssociation init( @@ -96,3 +93,8 @@ public struct HasOneAssociation: AssociationToOne { cardinality: .toOne) } } + +extension HasOneAssociation: AssociationToOne { + public typealias OriginRowDecoder = Origin + public typealias RowDecoder = Destination +} diff --git a/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift b/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift index 29a9bbac8..35eab6064 100644 --- a/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift @@ -1,34 +1,31 @@ -/// A **HasOneThrough** association sets up a one-to-one connection with +/// The `HasOneThroughAssociation` sets up a one-to-one connection with /// another record. This association indicates that the declaring record can be /// matched with one instance of another record by proceeding through a third -/// record. For example, if each book belongs to a library, and each library has +/// record. +/// +/// For example, if each book belongs to a library, and each library has /// one address, then one knows where the book should be returned to: /// -/// struct Book: TableRecord { -/// static let library = belongsTo(Library.self) -/// static let returnAddress = hasOne(Address.self, through: library, using: Library.address) -/// ... -/// } -/// -/// struct Library: TableRecord { -/// static let address = hasOne(Address.self) -/// ... -/// } -/// -/// struct Address: TableRecord { ... } +/// ```swift +/// struct Address: TableRecord { } /// -/// As in the example above, **HasOneThrough** association is always built from -/// two other associations: the `through:` and `using:` arguments. Those -/// associations can be any other association to one (BelongsTo, HasOne, -/// HasOneThrough). -public struct HasOneThroughAssociation: AssociationToOne { - /// :nodoc: - public typealias OriginRowDecoder = Origin - - /// :nodoc: - public typealias RowDecoder = Destination - - /// :nodoc: +/// struct Library: TableRecord { +/// static let address = hasOne(Address.self) +/// } +/// +/// struct Book: TableRecord { +/// static let library = belongsTo(Library.self) +/// static let returnAddress = hasOne(Address.self, +/// through: library, +/// using: Library.address, +/// key: "returnAddress") +/// } +/// ``` +/// +/// As in the example above, `HasOneThroughAssociation` is always built from +/// two other associations. Those associations can be any association that +/// declares a to-one connection (``AssociationToOne``). +public struct HasOneThroughAssociation { public var _sqlAssociation: _SQLAssociation init( @@ -43,3 +40,8 @@ public struct HasOneThroughAssociation: AssociationToOne { _sqlAssociation = target._sqlAssociation.through(pivot._sqlAssociation) } } + +extension HasOneThroughAssociation: AssociationToOne { + public typealias OriginRowDecoder = Origin + public typealias RowDecoder = Destination +} diff --git a/GRDB/QueryInterface/Request/Association/JoinAssociation.swift b/GRDB/QueryInterface/Request/Association/JoinAssociation.swift index 3e142448b..f6caa99a1 100644 --- a/GRDB/QueryInterface/Request/Association/JoinAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/JoinAssociation.swift @@ -1,13 +1,6 @@ -/// The Join association is used to join common table expression to regular +/// The `JoinAssociation` joins common table expression to regular /// tables or other common table expressions. -public struct JoinAssociation: AssociationToOne { - /// :nodoc: - public typealias OriginRowDecoder = Origin - - /// :nodoc: - public typealias RowDecoder = Destination - - /// :nodoc: +public struct JoinAssociation { public var _sqlAssociation: _SQLAssociation /// Creates a `JoinAssociation` whose key is the table name of the relation. @@ -22,3 +15,8 @@ public struct JoinAssociation: AssociationToOne { cardinality: .toOne) } } + +extension JoinAssociation: AssociationToOne { + public typealias OriginRowDecoder = Origin + public typealias RowDecoder = Destination +} diff --git a/GRDB/QueryInterface/Request/CommonTableExpression.swift b/GRDB/QueryInterface/Request/CommonTableExpression.swift index 4853b4240..813677ebe 100644 --- a/GRDB/QueryInterface/Request/CommonTableExpression.swift +++ b/GRDB/QueryInterface/Request/CommonTableExpression.swift @@ -104,7 +104,7 @@ extension CommonTableExpression { /// - parameter tableName: The table name of the common table expression. /// - parameter columns: The columns of the common table expression. If nil, /// the columns are the columns of the request. - /// - parameter sql: An SQL query. + /// - parameter sql: An SQL string. /// - parameter arguments: Statement arguments. public init( recursive: Bool = false, @@ -123,8 +123,8 @@ extension CommonTableExpression { /// Creates a common table expression from an SQL *literal*. /// - /// Literals allow you to safely embed raw values in your SQL, without any - /// risk of syntax errors or SQL injection: + /// ``SQL`` literals allow you to safely embed raw values in your SQL, + /// without any risk of syntax errors or SQL injection: /// /// // WITH p AS (SELECT * FROM player WHERE name = 'O''Brien') ... /// let name = "O'Brien" @@ -137,7 +137,7 @@ extension CommonTableExpression { /// - parameter tableName: The table name of the common table expression. /// - parameter columns: The columns of the common table expression. If nil, /// the columns are the columns of the request. - /// - parameter sqlLiteral: An `SQL` literal. + /// - parameter sqlLiteral: An ``SQL`` literal. public init( recursive: Bool = false, named tableName: String, @@ -204,7 +204,7 @@ extension CommonTableExpression { /// - parameter tableName: The table name of the common table expression. /// - parameter columns: The columns of the common table expression. If nil, /// the columns are the columns of the request. - /// - parameter sql: An SQL query. + /// - parameter sql: An SQL string. /// - parameter arguments: Statement arguments. public init( recursive: Bool = false, @@ -223,8 +223,8 @@ extension CommonTableExpression { /// Creates a common table expression from an SQL *literal*. /// - /// Literals allow you to safely embed raw values in your SQL, without any - /// risk of syntax errors or SQL injection: + /// ``SQL`` literals allow you to safely embed raw values in your SQL, + /// without any risk of syntax errors or SQL injection: /// /// // WITH p AS (SELECT * FROM player WHERE name = 'O''Brien') ... /// let name = "O'Brien" @@ -237,7 +237,7 @@ extension CommonTableExpression { /// - parameter tableName: The table name of the common table expression. /// - parameter columns: The columns of the common table expression. If nil, /// the columns are the columns of the request. - /// - parameter sqlLiteral: An `SQL` literal. + /// - parameter sqlLiteral: An ``SQL`` literal. public init( recursive: Bool = false, named tableName: String, diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index d648dc8c3..e3415ff5a 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -1,4 +1,5 @@ -// QueryInterfaceRequest is the type of requests generated by TableRecord: +// QueryInterfaceRequest is the type of requests generated by `Table` +// and `TableRecord`: // // struct Player: TableRecord { ... } // let playerRequest = Player.all() // QueryInterfaceRequest @@ -16,18 +17,64 @@ // playerRequest.including(required: Player.team) // OK // fruitRequest.including(required: Player.team) // Does not compile -/// QueryInterfaceRequest is a request that generates SQL for you. +/// A request that builds SQL queries with Swift. /// -/// For example: +/// You build a `QueryInterfaceRequest` from a ``TableRecord`` type, or a +/// ``Table`` instance. For example: /// -/// try dbQueue.read { db in -/// let request = Player -/// .filter(Column("score") > 1000) -/// .order(Column("name")) -/// let players = try request.fetchAll(db) // [Player] -/// } +/// ```swift +/// struct Player: TableRecord, FetchableRecord, DecodableRecord { } /// -/// See +/// try dbQueue.read { db in +/// // SELECT * FROM player +/// // WHERE name = 'O''Reilly' +/// // ORDER BY score DESC +/// let request = Player +/// .filter(Column("name") == "O'Reilly") +/// .order(Column("score").desc) +/// let players: [Player] = try request.fetchAll(db) +/// } +/// ``` +/// +/// Most features of `QueryInterfaceRequest` come from the protocols it +/// conforms to. In particular: +/// +/// - **Fetching methods** are defined by ``FetchRequest``. +/// - **Request building methods** are defined by ``DerivableRequest``. +/// +/// ## Topics +/// +/// ### Instance Methods +/// +/// - ``isEmpty(_:)`` +/// - ``limit(_:offset:)`` +/// +/// ### Changing The Type of Fetched Results +/// +/// - ``asRequest(of:)`` +/// - ``select(_:as:)-282xc`` +/// - ``select(_:as:)-3o8qw`` +/// - ``select(literal:as:)`` +/// - ``select(sql:arguments:as:)`` +/// - ``selectPrimaryKey(as:)`` +/// +/// ### Batch Delete +/// +/// - ``deleteAll(_:)`` +/// - ``deleteAndFetchCursor(_:)`` +/// - ``deleteAndFetchAll(_:)`` +/// - ``deleteAndFetchSet(_:)`` +/// - ``deleteAndFetchStatement(_:selection:)`` +/// +/// ### Batch Update +/// +/// - ``updateAll(_:onConflict:_:)-9r4v`` +/// - ``updateAll(_:onConflict:_:)-49qg8`` +/// - ``updateAndFetchCursor(_:onConflict:_:)`` +/// - ``updateAndFetchAll(_:onConflict:_:)`` +/// - ``updateAndFetchSet(_:onConflict:_:)`` +/// - ``updateAndFetchStatement(_:onConflict:_:selection:)`` +/// - ``ColumnAssignment`` public struct QueryInterfaceRequest { var relation: SQLRelation } @@ -64,21 +111,9 @@ extension QueryInterfaceRequest: FetchRequest { // MARK: - Request Derivation extension QueryInterfaceRequest: SelectionRequest { - /// Creates a request which selects *selection promise*. - /// - /// // SELECT id, email FROM player - /// var request = Player.all() - /// request = request.select { db in [Column("id"), Column("email")] } - /// - /// Any previous selection is replaced: - /// - /// // SELECT email FROM player - /// request - /// .select { db in [Column("id")] } - /// .select { db in [Column("email")] } public func selectWhenConnected( _ selection: @escaping (Database) throws -> [any SQLSelectable]) - -> QueryInterfaceRequest + -> Self { with { $0.relation = $0.relation.selectWhenConnected { db in @@ -87,83 +122,147 @@ extension QueryInterfaceRequest: SelectionRequest { } } - /// Creates a request which selects *selection*, and fetches values of - /// type *type*. + /// Defines the result columns, and defines the type of decoded rows. /// - /// try dbQueue.read { db in - /// // SELECT max(score) FROM player - /// let request = Player.all().select([max(Column("score"))], as: Int.self) - /// let maxScore: Int? = try request.fetchOne(db) - /// } - public func select(_ selection: [any SQLSelectable], as type: RowDecoder.Type = RowDecoder.self) - -> QueryInterfaceRequest + /// For example: + /// + /// ```swift + /// let minScore = min(Column("score")) + /// let maxScore = max(Column("score")) + /// + /// // SELECT MAX(score) FROM player + /// let request = Player.all() + /// .select([maxScore], as: Int.self) + /// let maxScore = try request.fetchOne(db) // Int? + /// + /// // SELECT MIN(score), MAX(score) FROM player + /// let request = Player.all() + /// .select([minScore, maxScore], as: Row.self) + /// if let row = try request.fetchOne(db) { + /// let minScore: Int = row[0] + /// let maxScore: Int = row[1] + /// } + /// ``` + /// + /// Any previous selection is discarded. + public func select(_ selection: [any SQLSelectable], as type: T.Type = T.self) + -> QueryInterfaceRequest { - select(selection).asRequest(of: RowDecoder.self) + select(selection).asRequest(of: T.self) } - /// Creates a request which selects *selection*, and fetches values of - /// type *type*. + /// Defines the result columns, and defines the type of decoded rows. /// - /// try dbQueue.read { db in - /// // SELECT max(score) FROM player - /// let request = Player.all().select(max(Column("score")), as: Int.self) - /// let maxScore: Int? = try request.fetchOne(db) - /// } - public func select(_ selection: any SQLSelectable..., as type: RowDecoder.Type = RowDecoder.self) - -> QueryInterfaceRequest + /// For example: + /// + /// ```swift + /// let minScore = min(Column("score")) + /// let maxScore = max(Column("score")) + /// + /// // SELECT MAX(score) FROM player + /// let request = Player.all() + /// .select(maxScore, as: Int.self) + /// let maxScore = try request.fetchOne(db) // Int? + /// + /// // SELECT MIN(score), MAX(score) FROM player + /// let request = Player.all() + /// .select(minScore, maxScore, as: Row.self) + /// if let row = try request.fetchOne(db) { + /// let minScore: Int = row[0] + /// let maxScore: Int = row[1] + /// } + /// ``` + /// + /// Any previous selection is discarded. + public func select(_ selection: any SQLSelectable..., as type: T.Type = T.self) + -> QueryInterfaceRequest { select(selection, as: type) } - /// Creates a request which selects *sql*, and fetches values of - /// type *type*. + /// Defines the result columns with an SQL string, and defines the type of + /// decoded rows. /// - /// try dbQueue.read { db in - /// // SELECT max(score) FROM player - /// let request = Player.all().select(sql: "max(score)", as: Int.self) - /// let maxScore: Int? = try request.fetchOne(db) - /// } - public func select( + /// For example: + /// + /// ```swift + /// // SELECT name FROM player + /// let request = Player.all() + /// .select(sql: "name", as: String.self) + /// let names = try request.fetchAll(db) // [String] + /// + /// // SELECT IFNULL(name, 'Anonymous') FROM player + /// let defaultName = "Anonymous" + /// let request = Player.all() + /// .select(sql: "IFNULL(name, ?)", arguments: [defaultName], as: String.self) + /// let names = try request.fetchAll(db) // [String] + /// ``` + /// + /// Any previous selection is discarded. + public func select( sql: String, arguments: StatementArguments = StatementArguments(), - as type: RowDecoder.Type = RowDecoder.self) - -> QueryInterfaceRequest + as type: T.Type = T.self) + -> QueryInterfaceRequest { select(SQL(sql: sql, arguments: arguments), as: type) } - /// Creates a request which selects an SQL *literal*, and fetches values of - /// type *type*. + /// Defines the result columns with an ``SQL`` literal, and defines the type + /// of decoded rows. /// - /// Literals allow you to safely embed raw values in your SQL, without any - /// risk of syntax errors or SQL injection: + /// ``SQL`` literals allow you to safely embed raw values in your SQL, + /// without any risk of syntax errors or SQL injection: /// - /// // SELECT IFNULL(name, 'Anonymous') FROM player - /// let defaultName = "Anonymous" - /// let request = Player.all().select( - /// literal: "IFNULL(name, \(defaultName))", - /// as: String.self) - /// let name: String? = try request.fetchOne(db) - public func select( + /// ```swift + /// // SELECT IFNULL(name, 'Anonymous') FROM player + /// let defaultName = "Anonymous" + /// let request = Player.all() + /// .select(literal: "IFNULL(name, \(defaultName))", as: String.self) + /// let names = try request.fetchAll(db) // [String] + /// ``` + /// + /// Any previous selection is discarded. + public func select( literal sqlLiteral: SQL, - as type: RowDecoder.Type = RowDecoder.self) - -> QueryInterfaceRequest + as type: T.Type = T.self) + -> QueryInterfaceRequest { select(sqlLiteral, as: type) } - /// Creates a request which selects the primary key. + /// Selects the primary key. /// /// All primary keys are supported: /// - /// // SELECT id FROM player WHERE ... - /// let request = try Player.filter(...).selectPrimaryKey(as: Int64.self) + /// ```swift + /// // SELECT id FROM player WHERE ... + /// let request = try Player.all().selectPrimaryKey(as: Int64.self) + /// let ids = try request.fetchAll(db) // [Int64] /// - /// // SELECT code FROM country WHERE ... - /// let request = try Country.filter(...).selectPrimaryKey(as: String.self) + /// // SELECT code FROM country WHERE ... + /// let request = try Country.all().selectPrimaryKey(as: String.self) + /// let countryCodes = try request.fetchAll(db) // [String] /// - /// // SELECT citizenId, countryCode FROM citizenship WHERE ... - /// let request = try Citizenship.filter(...).selectPrimaryKey(as: Row.self) + /// // SELECT citizenId, countryCode FROM citizenship WHERE ... + /// let request = try Citizenship.all().selectPrimaryKey(as: Row.self) + /// let rows = try request.fetchAll(db) // [Row] + /// ``` + /// + /// For composite primary keys, you can define a ``FetchableRecord`` type: + /// + /// ```swift + /// extension Citizenship { + /// struct ID: Decodable, FetchableRecord { + /// var citizenId: Int64 + /// var countryCode: String + /// } + /// } + /// let request = try Citizenship.all().selectPrimaryKey(as: Citizenship.ID.self) + /// let ids = try request.fetchAll(db) // [Citizenship.ID] + /// ``` + /// + /// Any previous selection is discarded. public func selectPrimaryKey(as type: PrimaryKey.Type = PrimaryKey.self) -> QueryInterfaceRequest { @@ -176,16 +275,9 @@ extension QueryInterfaceRequest: SelectionRequest { .asRequest(of: PrimaryKey.self) } - /// Creates a request which appends *selection promise*. - /// - /// // SELECT id, email, name FROM player - /// var request = Player.all() - /// request = request - /// .select([Column("id"), Column("email")]) - /// .annotated(with: { db in [Column("name")] }) public func annotatedWhenConnected( with selection: @escaping (Database) throws -> [any SQLSelectable]) - -> QueryInterfaceRequest + -> Self { with { $0.relation = $0.relation.annotatedWhenConnected { db in @@ -196,15 +288,9 @@ extension QueryInterfaceRequest: SelectionRequest { } extension QueryInterfaceRequest: FilteredRequest { - /// Creates a request with the provided *predicate promise* added to the - /// eventual set of already applied predicates. - /// - /// // SELECT * FROM player WHERE 1 - /// var request = Player.all() - /// request = request.filter { db in true } public func filterWhenConnected( _ predicate: @escaping (Database) throws -> any SQLExpressible) - -> QueryInterfaceRequest + -> Self { with { $0.relation = $0.relation.filterWhenConnected { db in @@ -215,22 +301,9 @@ extension QueryInterfaceRequest: FilteredRequest { } extension QueryInterfaceRequest: OrderedRequest { - /// Creates a request with the provided *orderings promise*. - /// - /// // SELECT * FROM player ORDER BY name - /// var request = Player.all() - /// request = request.order { _ in [Column("name")] } - /// - /// Any previous ordering is replaced: - /// - /// // SELECT * FROM player ORDER BY name - /// request - /// .order{ _ in [Column("email")] } - /// .reversed() - /// .order{ _ in [Column("name")] } public func orderWhenConnected( _ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) - -> QueryInterfaceRequest + -> Self { with { $0.relation = $0.relation.orderWhenConnected { db in @@ -250,7 +323,7 @@ extension QueryInterfaceRequest: OrderedRequest { /// // SELECT * FROM player /// var request = Player.all() /// request = request.reversed() - public func reversed() -> QueryInterfaceRequest { + public func reversed() -> Self { with { $0.relation = $0.relation.reversed() } @@ -261,7 +334,7 @@ extension QueryInterfaceRequest: OrderedRequest { /// // SELECT * FROM player /// var request = Player.all().order(Column("name")) /// request = request.unordered() - public func unordered() -> QueryInterfaceRequest { + public func unordered() -> Self { with { $0.relation = $0.relation.unordered() } @@ -269,10 +342,9 @@ extension QueryInterfaceRequest: OrderedRequest { } extension QueryInterfaceRequest: AggregatingRequest { - /// Creates a request grouped according to *expressions promise*. public func groupWhenConnected( _ expressions: @escaping (Database) throws -> [any SQLExpressible]) - -> QueryInterfaceRequest + -> Self { with { $0.relation = $0.relation.groupWhenConnected { db in @@ -281,11 +353,9 @@ extension QueryInterfaceRequest: AggregatingRequest { } } - /// Creates a request with the provided *predicate promise* added to the - /// eventual set of already applied predicates. public func havingWhenConnected( _ predicate: @escaping (Database) throws -> any SQLExpressible) - -> QueryInterfaceRequest + -> Self { with { $0.relation = $0.relation.havingWhenConnected { db in @@ -295,70 +365,44 @@ extension QueryInterfaceRequest: AggregatingRequest { } } -/// :nodoc: -extension QueryInterfaceRequest: _JoinableRequest { - /// :nodoc: - public func _including(all association: _SQLAssociation) -> QueryInterfaceRequest { +extension QueryInterfaceRequest: JoinableRequest { + public func _including(all association: _SQLAssociation) -> Self { with { $0.relation = $0.relation._including(all: association) } } - /// :nodoc: - public func _including(optional association: _SQLAssociation) -> QueryInterfaceRequest { + public func _including(optional association: _SQLAssociation) -> Self { with { $0.relation = $0.relation._including(optional: association) } } - /// :nodoc: - public func _including(required association: _SQLAssociation) -> QueryInterfaceRequest { + public func _including(required association: _SQLAssociation) -> Self { with { $0.relation = $0.relation._including(required: association) } } - /// :nodoc: - public func _joining(optional association: _SQLAssociation) -> QueryInterfaceRequest { + public func _joining(optional association: _SQLAssociation) -> Self { with { $0.relation = $0.relation._joining(optional: association) } } - /// :nodoc: - public func _joining(required association: _SQLAssociation) -> QueryInterfaceRequest { + public func _joining(required association: _SQLAssociation) -> Self { with { $0.relation = $0.relation._joining(required: association) } } } -extension QueryInterfaceRequest: JoinableRequest { } - extension QueryInterfaceRequest: TableRequest { - /// :nodoc: public var databaseTableName: String { relation.source.tableName } - /// Creates a request that allows you to define expressions that target - /// a specific database table. - /// - /// In the example below, the "team.avgScore < player.score" condition in - /// the ON clause could be not achieved without table aliases. - /// - /// struct Player: TableRecord { - /// static let team = belongsTo(Team.self) - /// } - /// - /// // SELECT player.*, team.* - /// // JOIN team ON ... AND team.avgScore < player.score - /// let playerAlias = TableAlias() - /// let request = Player - /// .all() - /// .aliased(playerAlias) - /// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")]) - public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { + public func aliased(_ alias: TableAlias) -> Self { with { $0.relation = $0.relation.aliased(alias) } @@ -366,20 +410,27 @@ extension QueryInterfaceRequest: TableRequest { } extension QueryInterfaceRequest: DerivableRequest { - public func distinct() -> QueryInterfaceRequest { + public func distinct() -> Self { with { $0.relation.isDistinct = true } } - /// Creates a request which fetches *limit* rows, starting at *offset*. + /// Returns a limited request. /// - /// // SELECT * FROM player LIMIT 10 OFFSET 20 - /// var request = Player.all() - /// request = request.limit(10, offset: 20) + /// The returned request fetches `limit` rows, starting at `offset`. For + /// example: /// - /// Any previous limit is replaced. - public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { + /// ```swift + /// // SELECT * FROM player LIMIT 10 + /// let request = Player.all().limit(10) + /// + /// // SELECT * FROM player LIMIT 10 OFFSET 20 + /// let request = Player.all().limit(10, offset: 20) + /// ``` + /// + /// Any previously applied limit is discarded. + public func limit(_ limit: Int, offset: Int? = nil) -> Self { with { $0.relation.limit = SQLLimit(limit: limit, offset: offset) } @@ -393,33 +444,40 @@ extension QueryInterfaceRequest: DerivableRequest { } extension QueryInterfaceRequest { - /// Creates a request bound to type RowDecoder. + /// Returns a request that performs an identical database query, but decodes + /// database rows with `type`. /// - /// The returned request can fetch if the type RowDecoder is fetchable (Row, - /// value, record). + /// For example: /// - /// // Int? - /// let maxScore = try Player + /// ```swift + /// try dbQueue.read { db in + /// let maxScore: Int? = try Player /// .select(max(scoreColumn)) /// .asRequest(of: Int.self) // <-- /// .fetchOne(db) - /// - /// - parameter type: The fetched type RowDecoder - /// - returns: A request bound to type RowDecoder. - public func asRequest(of type: RowDecoder.Type) -> QueryInterfaceRequest { - QueryInterfaceRequest(relation: relation) + /// } + /// ``` + public func asRequest(of type: T.Type) -> QueryInterfaceRequest { + QueryInterfaceRequest(relation: relation) } } // MARK: - Check Existence extension QueryInterfaceRequest { - /// Returns true if the request matches no row in the database. + /// Returns whether the requests does not match any row in the database. /// - /// try Player.filter(Column("name") == "Arthur").isEmpty(db) + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let arthurIsMissing = try Player + /// .filter(Column("name") == "Arthur") + /// .isEmpty(db) + /// } + /// ``` /// /// - parameter db: A database connection. - /// - returns: Whether the request matches no row in the database. public func isEmpty(_ db: Database) throws -> Bool { try !SQLRequest("SELECT \(exists())").fetchOne(db)! } @@ -432,7 +490,7 @@ extension QueryInterfaceRequest { /// /// - parameter db: A database connection. /// - returns: The number of deleted rows - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult public func deleteAll(_ db: Database) throws -> Int { let statement = try SQLQueryGenerator(relation: relation).makeDeleteStatement(db) @@ -445,15 +503,17 @@ extension QueryInterfaceRequest { extension QueryInterfaceRequest { #if GRDBCUSTOMSQLITE || GRDBCIPHER - /// Returns a `DELETE ... RETURNING ...` prepared statement. + /// Returns a `DELETE RETURNING` prepared statement. /// /// For example: /// - /// // Delete all players and return their names - /// // DELETE FROM player RETURNING name - /// let request = Player.all() - /// let statement = try request.deleteAndFetchStatement(db, selection: [Column("name")]) - /// let deletedNames = try String.fetchSet(statement) + /// ```swift + /// // Delete all players and return their names + /// // DELETE FROM player RETURNING name + /// let request = Player.all() + /// let statement = try request.deleteAndFetchStatement(db, selection: [Column("name")]) + /// let deletedNames = try String.fetchSet(statement) + /// ``` /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: @@ -462,7 +522,7 @@ extension QueryInterfaceRequest { /// - parameter db: A database connection. /// - parameter selection: The returned columns (must not be empty). /// - returns: A prepared statement. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// - precondition: `selection` is not empty. public func deleteAndFetchStatement( _ db: Database, @@ -473,23 +533,28 @@ extension QueryInterfaceRequest { return try SQLQueryGenerator(relation: relation).makeDeleteStatement(db, selection: selection) } - /// Returns a cursor over a `DELETE ... RETURNING ...` statement. + /// Returns a cursor over the record deleted by a + /// `DELETE RETURNING` statement. /// /// For example: /// - /// // Fetch all deleted players - /// // DELETE FROM player RETURNING * - /// let request = Player.all() - /// let cursor = try request.deleteAndFetchCursor(db) - /// let deletedPlayers = try Array(cursor) // [Player] + /// ```swift + /// // Fetch all deleted players + /// // DELETE FROM player RETURNING * + /// let request = Player.all() + /// let players = try request.deleteAndFetchCursor(db) + /// while let player = try players.next() { + /// print("Player \(player) was deleted") + /// } + /// ``` /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: /// . /// /// - parameter db: A database connection. - /// - returns: A cursor over the deleted records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: A ``RecordCursor`` over deleted records. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func deleteAndFetchCursor(_ db: Database) throws -> RecordCursor where RowDecoder: FetchableRecord & TableRecord @@ -498,15 +563,17 @@ extension QueryInterfaceRequest { return try RowDecoder.fetchCursor(statement) } - /// Executes a `DELETE ... RETURNING ...` statement and returns the + /// Executes a `DELETE RETURNING` statement and returns the array of /// deleted records. /// /// For example: /// - /// // Fetch all deleted players - /// // DELETE FROM player RETURNING * - /// let request = Player.all() - /// let deletedPlayers = try request.deleteAndFetchAll(db) + /// ```swift + /// // Fetch all deleted players + /// // DELETE FROM player RETURNING * + /// let request = Player.all() + /// let deletedPlayers = try request.deleteAndFetchAll(db) + /// ``` /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: @@ -514,7 +581,7 @@ extension QueryInterfaceRequest { /// /// - parameter db: A database connection. /// - returns: An array of deleted records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func deleteAndFetchAll(_ db: Database) throws -> [RowDecoder] where RowDecoder: FetchableRecord & TableRecord @@ -522,15 +589,17 @@ extension QueryInterfaceRequest { try Array(deleteAndFetchCursor(db)) } - /// Executes a `DELETE ... RETURNING ...` statement and returns the + /// Executes a `DELETE RETURNING` statement and returns the set of /// deleted records. /// /// For example: /// - /// // Fetch all deleted players - /// // DELETE FROM player RETURNING * - /// let request = Player.all() - /// let deletedPlayers = try request.deleteAndFetchSet(db) + /// ```swift + /// // Fetch all deleted players + /// // DELETE FROM player RETURNING * + /// let request = Player.all() + /// let deletedPlayers = try request.deleteAndFetchSet(db) + /// ``` /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: @@ -538,7 +607,7 @@ extension QueryInterfaceRequest { /// /// - parameter db: A database connection. /// - returns: A set of deleted records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func deleteAndFetchSet(_ db: Database) throws -> Set where RowDecoder: FetchableRecord & TableRecord & Hashable @@ -546,15 +615,17 @@ extension QueryInterfaceRequest { try Set(deleteAndFetchCursor(db)) } #else - /// Returns a `DELETE ... RETURNING ...` prepared statement. + /// Returns a `DELETE RETURNING` prepared statement. /// /// For example: /// - /// // Delete all players and return their names - /// // DELETE FROM player RETURNING name - /// let request = Player.all() - /// let statement = try request.deleteAndFetchStatement(db, selection: [Column("name")]) - /// let deletedNames = try String.fetchSet(statement) + /// ```swift + /// // Delete all players and return their names + /// // DELETE FROM player RETURNING name + /// let request = Player.all() + /// let statement = try request.deleteAndFetchStatement(db, selection: [Column("name")]) + /// let deletedNames = try String.fetchSet(statement) + /// ``` /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: @@ -563,7 +634,7 @@ extension QueryInterfaceRequest { /// - parameter db: A database connection. /// - parameter selection: The returned columns (must not be empty). /// - returns: A prepared statement. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// - precondition: `selection` is not empty. @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public func deleteAndFetchStatement( @@ -575,23 +646,28 @@ extension QueryInterfaceRequest { return try SQLQueryGenerator(relation: relation).makeDeleteStatement(db, selection: selection) } - /// Returns a cursor over a `DELETE ... RETURNING ...` statement. + /// Returns a cursor over the record deleted by a + /// `DELETE RETURNING` statement. /// /// For example: /// - /// // Fetch all deleted players - /// // DELETE FROM player RETURNING * - /// let request = Player.all() - /// let cursor = try request.deleteAndFetchCursor(db) - /// let deletedPlayers = try Array(cursor) // [Player] + /// ```swift + /// // Fetch all deleted players + /// // DELETE FROM player RETURNING * + /// let request = Player.all() + /// let players = try request.deleteAndFetchCursor(db) + /// while let player = try players.next() { + /// print("Player \(player) was deleted") + /// } + /// ``` /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: /// . /// /// - parameter db: A database connection. - /// - returns: A cursor over the deleted records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: A ``RecordCursor`` over deleted records. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public func deleteAndFetchCursor(_ db: Database) throws -> RecordCursor @@ -601,15 +677,17 @@ extension QueryInterfaceRequest { return try RowDecoder.fetchCursor(statement) } - /// Executes a `DELETE ... RETURNING ...` statement and returns the + /// Executes a `DELETE RETURNING` statement and returns the array of /// deleted records. /// /// For example: /// - /// // Fetch all deleted players - /// // DELETE FROM player RETURNING * - /// let request = Player.all() - /// let deletedPlayers = try request.deleteAndFetchAll(db) + /// ```swift + /// // Fetch all deleted players + /// // DELETE FROM player RETURNING * + /// let request = Player.all() + /// let deletedPlayers = try request.deleteAndFetchAll(db) + /// ``` /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: @@ -617,7 +695,7 @@ extension QueryInterfaceRequest { /// /// - parameter db: A database connection. /// - returns: An array of deleted records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public func deleteAndFetchAll(_ db: Database) throws -> [RowDecoder] @@ -626,15 +704,17 @@ extension QueryInterfaceRequest { try Array(deleteAndFetchCursor(db)) } - /// Executes a `DELETE ... RETURNING ...` statement and returns the + /// Executes a `DELETE RETURNING` statement and returns the set of /// deleted records. /// /// For example: /// - /// // Fetch all deleted players - /// // DELETE FROM player RETURNING * - /// let request = Player.all() - /// let deletedPlayers = try request.deleteAndFetchSet(db) + /// ```swift + /// // Fetch all deleted players + /// // DELETE FROM player RETURNING * + /// let request = Player.all() + /// let deletedPlayers = try request.deleteAndFetchSet(db) + /// ``` /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: @@ -642,7 +722,7 @@ extension QueryInterfaceRequest { /// /// - parameter db: A database connection. /// - returns: A set of deleted records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public func deleteAndFetchSet(_ db: Database) throws -> Set @@ -673,17 +753,19 @@ extension QueryInterfaceRequest { /// /// For example: /// - /// try dbQueue.write { db in - /// // UPDATE player SET score = 0 - /// let request = Player.all() - /// try request.updateAll(db, [Column("score").set(to: 0)]) - /// } + /// ```swift + /// try dbQueue.write { db in + /// // UPDATE player SET score = 0 + /// let request = Player.all() + /// try request.updateAll(db, [Column("score").set(to: 0)]) + /// } + /// ``` /// /// - parameter db: A database connection. /// - parameter conflictResolution: A policy for conflict resolution. /// - parameter assignments: An array of column assignments. /// - returns: The number of updated rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult public func updateAll( _ db: Database, @@ -707,17 +789,19 @@ extension QueryInterfaceRequest { /// /// For example: /// - /// try dbQueue.write { db in - /// // UPDATE player SET score = 0 - /// let request = Player.all() - /// try request.updateAll(db, Column("score").set(to: 0)) - /// } + /// ```swift + /// try dbQueue.write { db in + /// // UPDATE player SET score = 0 + /// let request = Player.all() + /// try request.updateAll(db, Column("score").set(to: 0)) + /// } + /// ``` /// /// - parameter db: A database connection. /// - parameter conflictResolution: A policy for conflict resolution. /// - parameter assignments: Column assignments. /// - returns: The number of updated rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult public func updateAll( _ db: Database, @@ -733,17 +817,19 @@ extension QueryInterfaceRequest { extension QueryInterfaceRequest { #if GRDBCUSTOMSQLITE || GRDBCIPHER - /// Returns an `UPDATE ... RETURNING ...` prepared statement. + /// Returns an `UPDATE RETURNING` prepared statement. /// /// For example: /// - /// // Fetch all updated scores - /// // UPDATE player SET score = score + 10 RETURNING score - /// let request = Player.all() - /// let statement = try request.updateAndFetchStatement( - /// db, [Column("score") += 10], - /// select: [Column("score")]) - /// let updatedScores = try Int.fetchAll(statement) + /// ```swift + /// // Fetch all updated scores + /// // UPDATE player SET score = score + 10 RETURNING score + /// let request = Player.all() + /// let statement = try request.updateAndFetchStatement( + /// db, [Column("score") += 10], + /// select: [Column("score")]) + /// let updatedScores = try Int.fetchAll(statement) + /// ``` /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: @@ -755,7 +841,7 @@ extension QueryInterfaceRequest { /// (must not be empty). /// - parameter selection: The returned columns (must not be empty). /// - returns: A prepared statement. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// - precondition: `selection` and `assignments` are not empty. public func updateAndFetchStatement( _ db: Database, @@ -779,15 +865,20 @@ extension QueryInterfaceRequest { return updateStatement } - /// Returns a cursor over an `UPDATE ... RETURNING ...` statement. + /// Returns a cursor over the record updated by an + /// `UPDATE RETURNING` statement. /// /// For example: /// - /// // Fetch all updated players - /// // UPDATE player SET score = score + 10 RETURNING * - /// let request = Player.all() - /// let cursor = try request.updateAndFetchCursor(db, [Column("score") += 10]) - /// let updatedPlayers = try Array(cursor) // [Player] + /// ```swift + /// // Fetch all updated players + /// // UPDATE player SET score = score + 10 RETURNING * + /// let request = Player.all() + /// let players = try request.updateAndFetchCursor(db, [Column("score") += 10]) + /// while let player = try players.next() { + /// print("Player \(player) was updated") + /// } + /// ``` /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: @@ -797,7 +888,7 @@ extension QueryInterfaceRequest { /// - parameter conflictResolution: A policy for conflict resolution. /// - parameter assignments: An array of column assignments. /// - returns: A cursor over the updated records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// - precondition: `assignments` is not empty. public func updateAndFetchCursor( _ db: Database, @@ -814,15 +905,17 @@ extension QueryInterfaceRequest { return try RowDecoder.fetchCursor(statement) } - /// Execute an `UPDATE ... RETURNING ...` statement and returns the + /// Execute an `UPDATE RETURNING` statement and returns the array of /// updated records. /// /// For example: /// - /// // Fetch all updated players - /// // UPDATE player SET score = score + 10 RETURNING * - /// let request = Player.all() - /// let updatedPlayers = try request.updateAndFetchAll(db, [Column("score") += 10]) + /// ```swift + /// // Fetch all updated players + /// // UPDATE player SET score = score + 10 RETURNING * + /// let request = Player.all() + /// let updatedPlayers = try request.updateAndFetchAll(db, [Column("score") += 10]) + /// ``` /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: @@ -832,7 +925,7 @@ extension QueryInterfaceRequest { /// - parameter conflictResolution: A policy for conflict resolution. /// - parameter assignments: An array of column assignments. /// - returns: An array of updated records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// - precondition: `assignments` is not empty. public func updateAndFetchAll( _ db: Database, @@ -844,15 +937,17 @@ extension QueryInterfaceRequest { try Array(updateAndFetchCursor(db, onConflict: conflictResolution, assignments)) } - /// Execute an `UPDATE ... RETURNING ...` statement and returns the + /// Execute an `UPDATE RETURNING` statement and returns the set of /// updated records. /// /// For example: /// - /// // Fetch all updated players - /// // UPDATE player SET score = score + 10 RETURNING * - /// let request = Player.all() - /// let updatedPlayers = try request.updateAndFetchSet(db, [Column("score") += 10]) + /// ```swift + /// // Fetch all updated players + /// // UPDATE player SET score = score + 10 RETURNING * + /// let request = Player.all() + /// let updatedPlayers = try request.updateAndFetchSet(db, [Column("score") += 10]) + /// ``` /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: @@ -862,7 +957,7 @@ extension QueryInterfaceRequest { /// - parameter conflictResolution: A policy for conflict resolution. /// - parameter assignments: An array of column assignments. /// - returns: A set of updated records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// - precondition: `assignments` is not empty. public func updateAndFetchSet( _ db: Database, @@ -874,17 +969,19 @@ extension QueryInterfaceRequest { try Set(updateAndFetchCursor(db, onConflict: conflictResolution, assignments)) } #else - /// Returns an `UPDATE ... RETURNING ...` prepared statement. + /// Returns an `UPDATE RETURNING` prepared statement. /// /// For example: /// - /// // Fetch all updated scores - /// // UPDATE player SET score = score + 10 RETURNING score - /// let request = Player.all() - /// let statement = try request.updateAndFetchStatement( - /// db, [Column("score") += 10], - /// select: [Column("score")]) - /// let updatedScores = try Int.fetchAll(statement) + /// ```swift + /// // Fetch all updated scores + /// // UPDATE player SET score = score + 10 RETURNING score + /// let request = Player.all() + /// let statement = try request.updateAndFetchStatement( + /// db, [Column("score") += 10], + /// select: [Column("score")]) + /// let updatedScores = try Int.fetchAll(statement) + /// ``` /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: @@ -896,7 +993,7 @@ extension QueryInterfaceRequest { /// (must not be empty). /// - parameter selection: The returned columns (must not be empty). /// - returns: A prepared statement. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// - precondition: `selection` and `assignments` are not empty. @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public func updateAndFetchStatement( @@ -921,15 +1018,20 @@ extension QueryInterfaceRequest { return updateStatement } - /// Returns a cursor over an `UPDATE ... RETURNING ...` statement. + /// Returns a cursor over the record updated by an + /// `UPDATE RETURNING` statement. /// /// For example: /// - /// // Fetch all updated players - /// // UPDATE player SET score = score + 10 RETURNING * - /// let request = Player.all() - /// let cursor = try request.updateAndFetchCursor(db, [Column("score") += 10]) - /// let updatedPlayers = try Array(cursor) // [Player] + /// ```swift + /// // Fetch all updated players + /// // UPDATE player SET score = score + 10 RETURNING * + /// let request = Player.all() + /// let players = try request.updateAndFetchCursor(db, [Column("score") += 10]) + /// while let player = try players.next() { + /// print("Player \(player) was updated") + /// } + /// ``` /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: @@ -939,7 +1041,7 @@ extension QueryInterfaceRequest { /// - parameter conflictResolution: A policy for conflict resolution. /// - parameter assignments: An array of column assignments. /// - returns: A cursor over the updated records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// - precondition: `assignments` is not empty. @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public func updateAndFetchCursor( @@ -957,15 +1059,17 @@ extension QueryInterfaceRequest { return try RowDecoder.fetchCursor(statement) } - /// Execute an `UPDATE ... RETURNING ...` statement and returns the + /// Execute an `UPDATE RETURNING` statement and returns the array of /// updated records. /// /// For example: /// - /// // Fetch all updated players - /// // UPDATE player SET score = score + 10 RETURNING * - /// let request = Player.all() - /// let updatedPlayers = try request.updateAndFetchAll(db, [Column("score") += 10]) + /// ```swift + /// // Fetch all updated players + /// // UPDATE player SET score = score + 10 RETURNING * + /// let request = Player.all() + /// let updatedPlayers = try request.updateAndFetchAll(db, [Column("score") += 10]) + /// ``` /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: @@ -975,7 +1079,7 @@ extension QueryInterfaceRequest { /// - parameter conflictResolution: A policy for conflict resolution. /// - parameter assignments: An array of column assignments. /// - returns: An array of updated records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// - precondition: `assignments` is not empty. @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public func updateAndFetchAll( @@ -988,15 +1092,17 @@ extension QueryInterfaceRequest { try Array(updateAndFetchCursor(db, onConflict: conflictResolution, assignments)) } - /// Execute an `UPDATE ... RETURNING ...` statement and returns the + /// Execute an `UPDATE RETURNING` statement and returns the set of /// updated records. /// /// For example: /// - /// // Fetch all updated players - /// // UPDATE player SET score = score + 10 RETURNING * - /// let request = Player.all() - /// let updatedPlayers = try request.updateAndFetchSet(db, [Column("score") += 10]) + /// ```swift + /// // Fetch all updated players + /// // UPDATE player SET score = score + 10 RETURNING * + /// let request = Player.all() + /// let updatedPlayers = try request.updateAndFetchSet(db, [Column("score") += 10]) + /// ``` /// /// - important: Make sure you check the documentation of the `RETURNING` /// clause, which describes important limitations and caveats: @@ -1006,7 +1112,7 @@ extension QueryInterfaceRequest { /// - parameter conflictResolution: A policy for conflict resolution. /// - parameter assignments: An array of column assignments. /// - returns: A set of updated records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// - precondition: `assignments` is not empty. @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public func updateAndFetchSet( @@ -1023,16 +1129,18 @@ extension QueryInterfaceRequest { // MARK: - ColumnAssignment -/// A ColumnAssignment can update rows in the database. +/// A `ColumnAssignment` assigns a value to a column. /// /// You create an assignment from a column and an assignment method or operator, -/// such as `set(to:)` or `+=`: +/// such as ``ColumnExpression/set(to:)`` or `+=`: /// -/// try dbQueue.write { db in -/// // UPDATE player SET score = 0 -/// let assignment = Column("score").set(to: 0) -/// try Player.updateAll(db, assignment) -/// } +/// ```swift +/// try dbQueue.write { db in +/// // UPDATE player SET score = 0 +/// let assignment = Column("score").set(to: 0) +/// try Player.updateAll(db, assignment) +/// } +/// ``` public struct ColumnAssignment { var columnName: String @@ -1052,77 +1160,125 @@ public struct ColumnAssignment { } extension ColumnExpression { - /// Creates an assignment to a value. + /// Returns an assignment of this column to an SQL expression. /// - /// Column("valid").set(to: true) - /// Column("score").set(to: 0) - /// Column("score").set(to: nil) - /// Column("score").set(to: Column("score") + Column("bonus")) + /// For example: /// - /// try dbQueue.write { db in - /// // UPDATE player SET score = 0 - /// try Player.updateAll(db, Column("score").set(to: 0)) - /// } + /// ```swift + /// Column("valid").set(to: true) + /// Column("score").set(to: 0) + /// Column("score").set(to: nil) + /// Column("score").set(to: Column("score") + Column("bonus")) + /// ``` + /// + /// For convenience, the last assignment can also be written as: + /// + /// ```swift + /// Column("score") += Column("bonus") + /// ``` + /// + /// Usage: + /// + /// ```swift + /// try dbQueue.write { db in + /// // UPDATE player SET score = 0 + /// try Player.updateAll(db, Column("score").set(to: 0)) + /// } + /// ``` public func set(to value: (any SQLExpressible)?) -> ColumnAssignment { ColumnAssignment(columnName: name, value: value?.sqlExpression ?? .null) } - /// Returns an assignment that does not modify this column. + /// An assignment that does not modify this column. public var noOverwrite: ColumnAssignment { ColumnAssignment(columnName: name, value: nil) } } -/// Creates an assignment that adds a value -/// -/// Column("score") += 1 -/// Column("score") += Column("bonus") -/// -/// try dbQueue.write { db in -/// // UPDATE player SET score = score + 1 -/// try Player.updateAll(db, Column("score") += 1) -/// } -public func += (column: some ColumnExpression, value: some SQLExpressible) -> ColumnAssignment { - column.set(to: column + value) -} - -/// Creates an assignment that subtracts a value -/// -/// Column("score") -= 1 -/// Column("score") -= Column("bonus") -/// -/// try dbQueue.write { db in -/// // UPDATE player SET score = score - 1 -/// try Player.updateAll(db, Column("score") -= 1) -/// } -public func -= (column: some ColumnExpression, value: some SQLExpressible) -> ColumnAssignment { - column.set(to: column - value) -} - -/// Creates an assignment that multiplies by a value -/// -/// Column("score") *= 2 -/// Column("score") *= Column("factor") -/// -/// try dbQueue.write { db in -/// // UPDATE player SET score = score * 2 -/// try Player.updateAll(db, Column("score") *= 2) -/// } -public func *= (column: some ColumnExpression, value: some SQLExpressible) -> ColumnAssignment { - column.set(to: column * value) -} - -/// Creates an assignment that divides by a value -/// -/// Column("score") /= 2 -/// Column("score") /= Column("factor") -/// -/// try dbQueue.write { db in -/// // UPDATE player SET score = score / 2 -/// try Player.updateAll(db, Column("score") /= 2) -/// } -public func /= (column: some ColumnExpression, value: some SQLExpressible) -> ColumnAssignment { - column.set(to: column / value) +extension ColumnExpression { + /// Creates an assignment that adds an SQL expression. + /// + /// For example: + /// + /// ```swift + /// Column("score") += 1 + /// Column("score") += Column("bonus") + /// ``` + /// + /// Usage: + /// + /// ```swift + /// try dbQueue.write { db in + /// // UPDATE player SET score = score + 1 + /// try Player.updateAll(db, Column("score") += 1) + /// } + /// ``` + public static func += (column: Self, value: some SQLExpressible) -> ColumnAssignment { + column.set(to: column + value) + } + + /// Creates an assignment that subtracts an SQL expression. + /// + /// For example: + /// + /// ```swift + /// Column("score") -= 1 + /// Column("score") -= Column("bonus") + /// ``` + /// + /// Usage: + /// + /// ```swift + /// try dbQueue.write { db in + /// // UPDATE player SET score = score - 1 + /// try Player.updateAll(db, Column("score") -= 1) + /// } + /// ``` + public static func -= (column: Self, value: some SQLExpressible) -> ColumnAssignment { + column.set(to: column - value) + } + + /// Creates an assignment that multiplies by an SQL expression. + /// + /// For example: + /// + /// ```swift + /// Column("score") *= 2 + /// Column("score") *= Column("factor") + /// ``` + /// + /// Usage: + /// + /// ```swift + /// try dbQueue.write { db in + /// // UPDATE player SET score = score * 2 + /// try Player.updateAll(db, Column("score") *= 2) + /// } + /// ``` + public static func *= (column: Self, value: some SQLExpressible) -> ColumnAssignment { + column.set(to: column * value) + } + + /// Creates an assignment that divides by an SQL expression. + /// + /// For example: + /// + /// ```swift + /// Column("score") /= 2 + /// Column("score") /= Column("factor") + /// ``` + /// + /// Usage: + /// + /// ```swift + /// try dbQueue.write { db in + /// // UPDATE player SET score = score / 2 + /// try Player.updateAll(db, Column("score") /= 2) + /// } + /// ``` + public static func /= (column: Self, value: some SQLExpressible) -> ColumnAssignment { + column.set(to: column / value) + } } // MARK: - Eager loading of hasMany associations @@ -1248,7 +1404,7 @@ private func prefetch( /// Returns a request for prefetched rows. /// -/// - parameter assocciation: The prefetched association. +/// - parameter association: The prefetched association. /// - parameter pivotFilter: The expression that filters the pivot of /// the association. /// - parameter pivotColumns: The pivot columns that annotate the diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index d983b46f6..2ee094189 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -2,135 +2,202 @@ import Foundation // MARK: - TypedRequest -/// The protocol for all requests that know how database rows should -/// be interpreted. +/// A request that knows how to decode database rows. public protocol TypedRequest { /// The type that can decode database rows. /// - /// In the request below, it is Player: + /// For example, it is `Player` in the request below: /// - /// let request = Player.all() + /// ```swift + /// let request = Player.all() + /// ``` associatedtype RowDecoder } // MARK: - SelectionRequest -/// The protocol for all requests that can refine their selection. +/// A request that can define the selected columns. +/// +/// ## Topics +/// +/// ### The SELECT Clause +/// +/// - ``annotated(with:)-4qcem`` +/// - ``annotated(with:)-6ehs4`` +/// - ``annotatedWhenConnected(with:)`` +/// - ``select(_:)-30yzl`` +/// - ``select(_:)-7e2y5`` +/// - ``select(literal:)`` +/// - ``select(sql:arguments:)`` +/// - ``selectWhenConnected(_:)`` public protocol SelectionRequest { - /// Creates a request which selects *selection promise*. + /// Defines the result columns. /// - /// // SELECT id, email FROM player - /// var request = Player.all() - /// request = request.selectWhenConnected { db in [Column("id"), Column("email") }) + /// The `selection` parameter is a closure that accepts a database + /// connection and returns an array of result columns. It is evaluated when + /// the request has an access to the database, and can perform database + /// requests in order to build its result. /// - /// Any previous selection is replaced: + /// For example: /// - /// // SELECT email FROM player - /// request - /// .selectWhenConnected { db in [Column("id")] } - /// .selectWhenConnected { db in [Column("email")] } + /// ```swift + /// // SELECT id, name FROM player + /// let request = Player.all().selectWhenConnected { db in + /// [Column("id"), Column("name")] + /// } + /// ``` + /// + /// Any previous selection is discarded: + /// + /// ```swift + /// // SELECT name FROM player + /// let request = Player.all() + /// .selectWhenConnected { db in [Column("id")] } + /// .selectWhenConnected { db in [Column("name")] } + /// ``` + /// + /// - parameter selection: A closure that accepts a database connection and + /// returns an array of result columns. func selectWhenConnected(_ selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self - /// Creates a request which appends *selection promise*. + /// Appends result columns to the selected columns. /// - /// // SELECT id, email, name FROM player - /// var request = Player.all() - /// request = request - /// .select([Column("id"), Column("email")]) - /// .annotatedWhenConnected(with: { db in [Column("name")] }) + /// The `selection` parameter is a closure that accepts a database + /// connection and returns an array of result columns. It is evaluated when + /// the request has an access to the database, and can perform database + /// requests in order to build its result. + /// + /// For example: + /// + /// ```swift + /// // SELECT *, score + bonus AS totalScore FROM player + /// let request = Player.all().annotatedWhenConnected { db in + /// [(Column("score") + Column("bonus")).forKey("totalScore")] + /// } + /// ``` + /// + /// - parameter selection: A closure that accepts a database connection and + /// returns an array of result columns. func annotatedWhenConnected(with selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self } extension SelectionRequest { - /// Creates a request which selects *selection*. + /// Defines the result columns. /// - /// // SELECT id, email FROM player - /// var request = Player.all() - /// request = request.select([Column("id"), Column("email")]) + /// For example: + /// + /// ```swift + /// // SELECT id, score FROM player + /// let request = Player.all().select([Column("id"), Column("score")]) + /// ``` /// /// Any previous selection is replaced: /// - /// // SELECT email FROM player - /// request - /// .select([Column("id")]) - /// .select([Column("email")]) + /// ```swift + /// // SELECT score FROM player + /// let request = Player.all() + /// .select([Column("id")]) + /// .select([Column("score")]) + /// ``` public func select(_ selection: [any SQLSelectable]) -> Self { selectWhenConnected { _ in selection } } - /// Creates a request which selects *selection*. + /// Defines the result columns. /// - /// // SELECT id, email FROM player - /// var request = Player.all() - /// request = request.select(Column("id"), Column("email")) + /// For example: /// - /// Any previous selection is replaced: + /// ```swift + /// // SELECT id, score FROM player + /// let request = Player.all().select(Column("id"), Column("score")) + /// ``` /// - /// // SELECT email FROM player - /// request - /// .select(Column("id")) - /// .select(Column("email")) + /// Any previous selection is discarded: + /// + /// ```swift + /// // SELECT score FROM player + /// let request = Player.all() + /// .select(Column("id")) + /// .select(Column("score")) + /// ``` public func select(_ selection: any SQLSelectable...) -> Self { select(selection) } - /// Creates a request which selects *sql*. + /// Defines the result columns with an SQL string. /// - /// // SELECT id, email FROM player - /// var request = Player.all() - /// request = request.select(sql: "id, email") + /// For example: /// - /// Any previous selection is replaced: + /// ```swift + /// // SELECT id, name FROM player + /// let request = Player.all() + /// .select(sql: "id, name") /// - /// // SELECT email FROM player - /// request - /// .select(sql: "id") - /// .select(sql: "email") + /// // SELECT id, IFNULL(name, 'Anonymous') FROM player + /// let defaultName = "Anonymous" + /// let request = Player.all() + /// .select(sql: "id, IFNULL(name, ?)", arguments: [defaultName]) + /// ``` + /// + /// Any previous selection is discarded: + /// + /// ```swift + /// // SELECT score FROM player + /// let request = Player.all() + /// .select(sql: "id") + /// .select(sql: "name") + /// ``` public func select(sql: String, arguments: StatementArguments = StatementArguments()) -> Self { select(SQL(sql: sql, arguments: arguments)) } - /// Creates a request which selects an SQL *literal*. + /// Defines the result columns with an ``SQL`` literal. /// - /// Literals allow you to safely embed raw values in your SQL, without any - /// risk of syntax errors or SQL injection: + /// ``SQL`` literals allow you to safely embed raw values in your SQL, + /// without any risk of syntax errors or SQL injection: /// - /// // SELECT id, email, score + 1000 FROM player - /// let bonus = 1000 - /// var request = Player.all() - /// request = request.select(literal: """ - /// id, email, score + \(bonus) - /// """) + /// ```swift + /// // SELECT id, IFNULL(name, 'Anonymous') FROM player + /// let defaultName = "Anonymous" + /// let request = Player.all() + /// .select(literal: "id, IFNULL(name, \(defaultName))") + /// ``` /// - /// Any previous selection is replaced: + /// Any previous selection is discarded: /// - /// // SELECT email FROM player - /// request - /// .select(...) - /// .select(literal: "email") + /// ```swift + /// // SELECT IFNULL(name, 'Anonymous') FROM player + /// let request = Player.all() + /// .select(literal: "id") + /// .select(literal: "IFNULL(name, \(defaultName))") + /// ``` public func select(literal sqlLiteral: SQL) -> Self { // NOT TESTED select(sqlLiteral) } - /// Creates a request which appends *selection*. + /// Appends result columns to the selected columns. /// - /// // SELECT id, email, name FROM player - /// var request = Player.all() - /// request = request - /// .select([Column("id"), Column("email")]) - /// .annotated(with: [Column("name")]) + /// For example: + /// + /// ```swift + /// // SELECT *, score + bonus AS totalScore FROM player + /// let totalScore = (Column("score") + Column("bonus")).forKey("totalScore") + /// let request = Player.all().annotated(with: [totalScore]) + /// ``` public func annotated(with selection: [any SQLSelectable]) -> Self { annotatedWhenConnected(with: { _ in selection }) } - /// Creates a request which appends *selection*. + /// Appends result columns to the selected columns. /// - /// // SELECT id, email, name FROM player - /// var request = Player.all() - /// request = request - /// .select([Column("id"), Column("email")]) - /// .annotated(with: Column("name")) + /// For example: + /// + /// ```swift + /// // SELECT *, score + bonus AS totalScore FROM player + /// let totalScore = (Column("score") + Column("bonus")).forKey("totalScore") + /// let request = Player.all().annotated(with: totalScore) + /// ``` public func annotated(with selection: any SQLSelectable...) -> Self { annotated(with: selection) } @@ -138,14 +205,40 @@ extension SelectionRequest { // MARK: - FilteredRequest -/// The protocol for all requests that can be filtered. +/// A request that can filter database rows. +/// +/// The filter applies to the `WHERE` clause, or to the `ON` clause of +/// an SQL join. +/// +/// ## Topics +/// +/// ### The WHERE and JOIN ON Clauses +/// +/// - ``filter(_:)`` +/// - ``filter(literal:)`` +/// - ``filter(sql:arguments:)`` +/// - ``filterWhenConnected(_:)`` +/// - ``none()`` public protocol FilteredRequest { - /// Creates a request with the provided *predicate promise* added to the - /// eventual set of already applied predicates. + /// Filters the fetched rows with a boolean SQL expression. /// - /// // SELECT * FROM player WHERE 1 - /// var request = Player.all() - /// request = request.filterWhenConnected { db in true } + /// The `predicate` parameter is a closure that accepts a database + /// connection and returns a boolean SQL expression. It is evaluated when + /// the request has an access to the database, and can perform database + /// requests in order to build its result. + /// + /// For example: + /// + /// ```swift + /// // SELECT * FROM player WHERE name = 'O''Brien' + /// let name = "O'Brien" + /// let request = Player.all().filterWhenConnected { db in + /// Column("name") == name + /// } + /// ``` + /// + /// - parameter predicate: A closure that accepts a database connection and + /// returns a boolean SQL expression. func filterWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self } @@ -153,46 +246,48 @@ extension FilteredRequest { // Accept SQLSpecificExpressible instead of SQLExpressible, so that we // prevent the `Player.filter(42)` misuse. // See https://github.com/groue/GRDB.swift/pull/864 - /// Creates a request with the provided *predicate* added to the - /// eventual set of already applied predicates. + /// Filters the fetched rows with a boolean SQL expression. /// - /// // SELECT * FROM player WHERE email = 'arthur@example.com' - /// var request = Player.all() - /// request = request.filter(Column("email") == "arthur@example.com") + /// For example: + /// + /// ```swift + /// // SELECT * FROM player WHERE name = 'O''Brien' + /// let name = "O'Brien" + /// let request = Player.all().filter(Column("name") == name) + /// ``` public func filter(_ predicate: some SQLSpecificExpressible) -> Self { filterWhenConnected { _ in predicate } } - /// Creates a request with the provided *predicate* added to the - /// eventual set of already applied predicates. + /// Filters the fetched rows with an SQL string. /// - /// // SELECT * FROM player WHERE email = 'arthur@example.com' - /// var request = Player.all() - /// request = request.filter(sql: "email = ?", arguments: ["arthur@example.com"]) + /// For example: + /// + /// ```swift + /// // SELECT * FROM player WHERE name = 'O''Brien' + /// let name = "O'Brien" + /// let request = Player.all().filter(sql: "name = ?", arguments: [name]) + /// ``` public func filter(sql: String, arguments: StatementArguments = StatementArguments()) -> Self { filter(SQL(sql: sql, arguments: arguments)) } - /// Creates a request with the provided *predicate* added to the - /// eventual set of already applied predicates. + /// Filters the fetched rows with an ``SQL`` literal. /// - /// Literals allow you to safely embed raw values in your SQL, without any - /// risk of syntax errors or SQL injection: + /// ``SQL`` literals allow you to safely embed raw values in your SQL, + /// without any risk of syntax errors or SQL injection: /// - /// // SELECT * FROM player WHERE name = 'O''Brien' - /// let name = "O'Brien" - /// var request = Player.all() - /// request = request.filter(literal: "email = \(email)") + /// ```swift + /// // SELECT * FROM player WHERE name = 'O''Brien' + /// let name = "O'Brien" + /// let request = Player.all().filter(literal: "name = \(name)") + /// ``` public func filter(literal sqlLiteral: SQL) -> Self { // NOT TESTED filter(sqlLiteral) } - /// Creates a request that matches nothing. - /// - /// // SELECT * FROM player WHERE 0 - /// var request = Player.all() - /// request = request.none() + /// Returns an empty request that fetches no row. public func none() -> Self { filterWhenConnected { _ in false } } @@ -200,37 +295,111 @@ extension FilteredRequest { // MARK: - TableRequest -/// The protocol for all requests that feed from a database table +/// A request that feeds from a database table +/// +/// ## Topics +/// +/// ## The Database Table +/// +/// - ``databaseTableName`` +/// +/// ### Instance Methods +/// +/// - ``aliased(_:)`` +/// - ``TableAlias`` +/// +/// ### The WHERE Clause +/// +/// - ``filter(id:)`` +/// - ``filter(ids:)`` +/// - ``filter(key:)-1p9sq`` +/// - ``filter(key:)-2te6v`` +/// - ``filter(keys:)-6ggt1`` +/// - ``filter(keys:)-8fbn9`` +/// - ``matching(_:)`` +/// +/// ### The GROUP BY and HAVING Clauses +/// +/// - ``groupByPrimaryKey()`` +/// +/// ### The ORDER BY Clause +/// +/// - ``orderByPrimaryKey()`` public protocol TableRequest { /// The name of the database table var databaseTableName: String { get } - /// Creates a request that allows you to define expressions that target - /// a specific database table. + /// Returns a request that can be referred to with the provided alias. /// - /// In the example below, the "team.avgScore < player.score" condition in - /// the ON clause could be not achieved without table aliases. + /// Use this method when you need to refer to this request from + /// another request. /// - /// struct Player: TableRecord { - /// static let team = belongsTo(Team.self) - /// } + /// The first example fetches posthumous books: /// - /// // SELECT player.*, team.* - /// // JOIN team ON ... AND team.avgScore < player.score - /// let playerAlias = TableAlias() - /// let request = Player - /// .all() - /// .aliased(playerAlias) - /// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")]) + /// ```swift + /// struct Author: TableRecord, FetchableRecord { } + /// struct Book: TableRecord, FetchableRecord { + /// static let author = belongsTo(Author.self) + /// } + /// + /// // SELECT book.* + /// // FROM book + /// // JOIN author ON author.id = book.authorId + /// // WHERE book.publishDate >= author.deathDate + /// let authorAlias = TableAlias() + /// let posthumousBooks = try Book + /// .joining(required: Book.author.aliased(authorAlias)) + /// .filter(Column("publishDate") >= authorAlias[Column("deathDate")]) + /// .fetchAll(db) + /// ``` + /// + /// The second example sorts books by author name first, and then by title: + /// + /// ```swift + /// // SELECT book.* + /// // FROM book + /// // JOIN author ON author.id = book.authorId + /// // ORDER BY author.name, book.title + /// let authorAlias = TableAlias() + /// let books = try Book + /// .joining(required: Book.author.aliased(authorAlias)) + /// .order(authorAlias[Column("name")], Column("title")) + /// .fetchAll(db) + /// ``` + /// + /// The third example uses named ``TableAlias`` so that SQL snippets can + /// refer to SQL tables with those names: + /// + /// ```swift + /// // SELECT b.* + /// // FROM book b + /// // JOIN author a ON a.id = b.authorId + /// // AND a.countryCode = 'FR' + /// // WHERE b.publishDate >= a.deathDate + /// let bookAlias = TableAlias(name: "b") + /// let authorAlias = TableAlias(name: "a") + /// let posthumousFrenchBooks = try Book.aliased(bookAlias) + /// .joining(required: Book.author.aliased(authorAlias) + /// .filter(sql: "a.countryCode = ?", arguments: ["FR"])) + /// .filter(sql: "b.publishDate >= a.deathDate") + /// .fetchAll(db) + /// ``` func aliased(_ alias: TableAlias) -> Self } extension TableRequest where Self: FilteredRequest, Self: TypedRequest { - /// Creates a request filtered by primary key. + /// Filters by primary key. /// - /// // SELECT * FROM player WHERE ... id = 1 - /// let request = try Player...filter(key: 1) + /// All single-column primary keys are supported: + /// + /// ```swift + /// // SELECT * FROM player WHERE id = 1 + /// let request = Player.all().filter(key: 1) + /// + /// // SELECT * FROM country WHERE code = 'FR' + /// let request = Country.all().filter(key: "FR") + /// ``` /// /// - parameter key: A primary key public func filter(key: some DatabaseValueConvertible) -> Self { @@ -240,10 +409,17 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { return filter(keys: [key]) } - /// Creates a request filtered by primary key. + /// Filters by primary key. /// - /// // SELECT * FROM player WHERE ... id IN (1, 2, 3) - /// let request = try Player...filter(keys: [1, 2, 3]) + /// All single-column primary keys are supported: + /// + /// ```swift + /// // SELECT * FROM player WHERE id = IN (1, 2, 3) + /// let request = Player.all().filter(keys: [1, 2, 3]) + /// + /// // SELECT * FROM country WHERE code = IN ('FR', 'US') + /// let request = Country.all().filter(keys: ["FR", "US"]) + /// ``` /// /// - parameter keys: A collection of primary keys public func filter(keys: Sequence) @@ -301,15 +477,28 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { } } - /// Creates a request filtered by unique key. + /// Filters by primary or unique key. /// - /// // SELECT * FROM player WHERE ... email = 'arthur@example.com' - /// let request = try Player...filter(key: ["email": "arthur@example.com"]) + /// For example: /// - /// When executed, this request raises a fatal error if there is no unique - /// index on the key columns. + /// ```swift + /// // SELECT * FROM player WHERE id = 1 + /// let request = Player.all().filter(key: ["id": 1]) /// - /// - parameter key: A unique key + /// // SELECT * FROM player WHERE email = 'arthur@example.com' + /// let request = Player.all().filter(key: ["email": "arthur@example.com"]) + /// + /// // SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR' + /// let request = Citizenship.all().filter(key: [ + /// "citizenId": 1, + /// "countryCode": "FR", + /// ]) + /// ``` + /// + /// When executed, this request raises a fatal error if no unique index + /// exists on a subset of the key columns. + /// + /// - parameter key: A unique key. public func filter(key: [String: (any DatabaseValueConvertible)?]?) -> Self { guard let key else { return none() @@ -317,13 +506,25 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { return filter(keys: [key]) } - /// Creates a request filtered by unique key. + /// Filters by primary or unique key. /// - /// // SELECT * FROM player WHERE ... email = 'arthur@example.com' AND ... - /// let request = try Player...filter(keys: [["email": "arthur@example.com"], ...]) + /// For example: /// - /// When executed, this request raises a fatal error if there is no unique - /// index on the key columns. + /// ```swift + /// // SELECT * FROM player WHERE id = 1 + /// let request = Player.all().filter(keys: [["id": 1]]) + /// + /// // SELECT * FROM player WHERE email = 'arthur@example.com' + /// let request = Player.all().filter(keys: [["email": "arthur@example.com"]]) + /// + /// // SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR' + /// let request = Citizenship.all().filter(keys: [ + /// ["citizenId": 1, "countryCode": "FR"], + /// ]) + /// ``` + /// + /// When executed, this request raises a fatal error if no unique index + /// exists on a subset of the key columns. /// /// - parameter keys: A collection of unique keys public func filter(keys: [[String: (any DatabaseValueConvertible)?]]) -> Self { @@ -376,20 +577,34 @@ where Self: FilteredRequest, RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible { - /// Creates a request filtered by primary key. + /// Filters by primary key. /// - /// // SELECT * FROM player WHERE ... id = 1 - /// let request = try Player...filter(id: 1) + /// All single-column primary keys are supported: + /// + /// ```swift + /// // SELECT * FROM player WHERE id = 1 + /// let request = Player.all().filter(id: 1) + /// + /// // SELECT * FROM country WHERE code = 'FR' + /// let request = Country.all().filter(id: "FR") + /// ``` /// /// - parameter id: A primary key public func filter(id: RowDecoder.ID) -> Self { filter(key: id) } - /// Creates a request filtered by primary key. + /// Filters by primary key. /// - /// // SELECT * FROM player WHERE ... id IN (1, 2, 3) - /// let request = try Player...filter(ids: [1, 2, 3]) + /// All single-column primary keys are supported: + /// + /// ```swift + /// // SELECT * FROM player WHERE id = IN (1, 2, 3) + /// let request = Player.all().filter(ids: [1, 2, 3]) + /// + /// // SELECT * FROM country WHERE code = IN ('FR', 'US') + /// let request = Country.all().filter(ids: ["FR", "US"]) + /// ``` /// /// - parameter ids: A collection of primary keys public func filter(ids: IDS) -> Self @@ -400,7 +615,22 @@ where Self: FilteredRequest, } extension TableRequest where Self: OrderedRequest { - /// Creates a request ordered by primary key. + /// Sorts the fetched rows according to the primary key. + /// + /// All primary keys are supported: + /// + /// ```swift + /// // SELECT * FROM player ORDER BY id + /// let request = Player.all().orderByPrimaryKey() + /// + /// // SELECT * FROM country ORDER BY code + /// let request = Country.all().orderByPrimaryKey() + /// + /// // SELECT * FROM citizenship ORDER BY citizenId, countryCode + /// let request = Citizenship.all().orderByPrimaryKey() + /// ``` + /// + /// Any previous ordering is discarded. public func orderByPrimaryKey() -> Self { let tableName = self.databaseTableName return orderWhenConnected { db in @@ -410,7 +640,9 @@ extension TableRequest where Self: OrderedRequest { } extension TableRequest where Self: AggregatingRequest { - /// Creates a request grouped by primary key. + /// Returns an aggregate request grouped on the primary key. + /// + /// Any previous grouping is discarded. public func groupByPrimaryKey() -> Self { let tableName = self.databaseTableName return groupWhenConnected { db in @@ -443,52 +675,202 @@ extension TableRequest where Self: AggregatingRequest { // MARK: - AggregatingRequest -/// The protocol for all requests that can aggregate. +/// A request that can aggregate database rows. +/// +/// ## Topics +/// +/// ### The GROUP BY Clause +/// +/// - ``group(_:)-edak`` +/// - ``group(_:)-4216o`` +/// - ``group(literal:)`` +/// - ``group(sql:arguments:)`` +/// - ``groupWhenConnected(_:)`` +/// +/// ### The HAVING Clause +/// +/// - ``having(_:)`` +/// - ``having(literal:)`` +/// - ``having(sql:arguments:)`` +/// - ``havingWhenConnected(_:)`` public protocol AggregatingRequest { - /// Creates a request grouped according to *expressions promise*. + /// Returns an aggregate request grouped on the given SQL expressions. + /// + /// The `expressions` parameter is a closure that accepts a database + /// connection and returns an array of grouping SQL expressions. It is + /// evaluated when the request has an access to the database, and can + /// perform database requests in order to build its result. + /// + /// For example: + /// + /// ```swift + /// // SELECT teamId, MAX(score) + /// // FROM player + /// // GROUP BY teamId + /// let request = Player + /// .select(Column("teamId"), max(Column("score"))) + /// .groupWhenConnected { db in [Column("teamId")] } + /// ``` + /// + /// Any previous grouping is discarded. + /// + /// - parameter expressions: A closure that accepts a database connection + /// and returns an array of SQL expressions. func groupWhenConnected(_ expressions: @escaping (Database) throws -> [any SQLExpressible]) -> Self - /// Creates a request with the provided *predicate promise* added to the - /// eventual set of already applied predicates. + /// Filters the aggregated groups with a boolean SQL expression. + /// + /// The `predicate` parameter is a closure that accepts a database + /// connection and returns a boolean SQL expression. It is evaluated when + /// the request has an access to the database, and can perform database + /// requests in order to build its result. + /// + /// For example: + /// + /// ```swift + /// // SELECT teamId, MAX(score) + /// // FROM player + /// // GROUP BY teamId + /// // HAVING MAX(score) > 1000 + /// let request = Player + /// .select(Column("teamId"), max(Column("score"))) + /// .group(Column("teamId")) + /// .havingWhenConnected { db in max(Column("score")) > 1000 } + /// ``` + /// + /// - parameter predicate: A closure that accepts a database connection and + /// returns a boolean SQL expression. func havingWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self } extension AggregatingRequest { - /// Creates a request grouped according to *expressions*. + /// Returns an aggregate request grouped on the given SQL expressions. + /// + /// For example: + /// + /// ```swift + /// // SELECT teamId, MAX(score) + /// // FROM player + /// // GROUP BY teamId + /// let request = Player + /// .select(Column("teamId"), max(Column("score"))) + /// .group([Column("teamId")]) + /// ``` + /// + /// Any previous grouping is discarded. + /// + /// - parameter expressions: An array of SQL expressions. public func group(_ expressions: [any SQLExpressible]) -> Self { groupWhenConnected { _ in expressions } } - /// Creates a request grouped according to *expressions*. + /// Returns an aggregate request grouped on the given SQL expressions. + /// + /// For example: + /// + /// ```swift + /// // SELECT teamId, MAX(score) + /// // FROM player + /// // GROUP BY teamId + /// let request = Player + /// .select(Column("teamId"), max(Column("score"))) + /// .group(Column("teamId")) + /// ``` + /// + /// Any previous grouping is discarded. + /// + /// - parameter expressions: An array of SQL expressions. public func group(_ expressions: any SQLExpressible...) -> Self { group(expressions) } - /// Creates a request with a new grouping. + /// Returns an aggregate request grouped on an SQL string. + /// + /// For example: + /// + /// ```swift + /// // SELECT teamId, MAX(score) + /// // FROM player + /// // GROUP BY teamId + /// let request = Player + /// .select(Column("teamId"), max(Column("score"))) + /// .group(sql: "teamId") + /// ``` + /// + /// Any previous grouping is discarded. public func group(sql: String, arguments: StatementArguments = StatementArguments()) -> Self { group(SQL(sql: sql, arguments: arguments)) } - /// Creates a request with a new grouping. + /// Returns an aggregate request grouped on an ``SQL`` literal. + /// + /// For example: + /// + /// ```swift + /// // SELECT teamId, MAX(score) + /// // FROM player + /// // GROUP BY teamId + /// let request = Player + /// .select(Column("teamId"), max(Column("score"))) + /// .group(literal: "teamId") + /// ``` + /// + /// Any previous grouping is discarded. public func group(literal sqlLiteral: SQL) -> Self { // NOT TESTED group(sqlLiteral) } - /// Creates a request with the provided *predicate* added to the - /// eventual set of already applied predicates. + /// Filters the aggregated groups with a boolean SQL expression. + /// + /// For example: + /// + /// ```swift + /// // SELECT teamId, MAX(score) + /// // FROM player + /// // GROUP BY teamId + /// // HAVING MAX(score) > 1000 + /// let request = Player + /// .select(Column("teamId"), max(Column("score"))) + /// .group(Column("teamId")) + /// .having(max(Column("score")) > 1000) + /// ``` public func having(_ predicate: some SQLExpressible) -> Self { havingWhenConnected { _ in predicate } } - /// Creates a request with the provided *sql* added to the - /// eventual set of already applied predicates. + /// Filters the aggregated groups with an SQL string. + /// + /// For example: + /// + /// ```swift + /// // SELECT teamId, MAX(score) + /// // FROM player + /// // GROUP BY teamId + /// // HAVING MAX(score) > 1000 + /// let request = Player + /// .select(Column("teamId"), max(Column("score"))) + /// .group(Column("teamId")) + /// .having(sql: "MAX(score) > 1000") + /// ``` public func having(sql: String, arguments: StatementArguments = StatementArguments()) -> Self { having(SQL(sql: sql, arguments: arguments)) } - /// Creates a request with the provided SQL *literal* added to the - /// eventual set of already applied predicates. + /// Filters the aggregated groups with an ``SQL`` literal. + /// + /// For example: + /// + /// ```swift + /// // SELECT teamId, MAX(score) + /// // FROM player + /// // GROUP BY teamId + /// // HAVING MAX(score) > 1000 + /// let request = Player + /// .select(Column("teamId"), max(Column("score"))) + /// .group(Column("teamId")) + /// .having(literal: "MAX(score) > 1000") + /// ``` public func having(literal sqlLiteral: SQL) -> Self { // NOT TESTED having(sqlLiteral) @@ -497,107 +879,152 @@ extension AggregatingRequest { // MARK: - OrderedRequest -/// The protocol for all requests that can be ordered. +/// A request that can sort database rows. +/// +/// ## Topics +/// +/// ### The ORDER BY Clause +/// +/// - ``order(_:)-63rzl`` +/// - ``order(_:)-6co0m`` +/// - ``order(literal:)`` +/// - ``order(sql:arguments:)`` +/// - ``orderWhenConnected(_:)`` +/// - ``reversed()`` +/// - ``unordered()`` public protocol OrderedRequest { - /// Creates a request with the provided *orderings promise*. + /// Sorts the fetched rows according to the given SQL ordering terms. /// - /// // SELECT * FROM player ORDER BY name - /// var request = Player.all() - /// request = request.order { _ in [Column("name")] } + /// The `orderings` parameter is a closure that accepts a database + /// connection and returns an array of SQL ordering terms. It is evaluated + /// when the request has an access to the database, and can perform database + /// requests in order to build its result. /// - /// Any previous ordering is replaced: + /// For example: /// - /// // SELECT * FROM player ORDER BY name - /// request - /// .orderWhenConnected{ _ in [Column("email")] } - /// .reversed() - /// .orderWhenConnected{ _ in [Column("name")] } + /// ```swift + /// // SELECT * FROM player ORDER BY score DESC, name + /// let request = Player.all().orderWhenConnected { db in + /// [Column("score").desc, Column("name")] + /// } + /// ``` + /// + /// Any previous ordering is discarded: + /// + /// ```swift + /// // SELECT * FROM player ORDER BY name + /// let request = Player.all() + /// .orderWhenConnected { db in [Column("score").desc] } + /// .orderWhenConnected { db in [Column("name")] } + /// ``` + /// + /// - parameter orderings: A closure that accepts a database connection and + /// returns an array of SQL ordering terms. func orderWhenConnected(_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) -> Self - /// Creates a request that reverses applied orderings. + /// Returns a request with reversed ordering. /// - /// // SELECT * FROM player ORDER BY name DESC - /// var request = Player.all().order(Column("name")) - /// request = request.reversed() + /// For example: /// - /// If no ordering was applied, the returned request is identical. + /// ```swift + /// // SELECT * FROM player ORDER BY name DESC + /// let request = Player.all() + /// .order(Column("name")) + /// .reversed() + /// ``` /// - /// // SELECT * FROM player - /// var request = Player.all() - /// request = request.reversed() + /// If no ordering was already specified, this method has no effect: + /// + /// ```swift + /// // SELECT * FROM player + /// let request = Player.all().reversed() + /// ``` func reversed() -> Self - /// Creates a request without any ordering. + /// Returns a request without any ordering. /// - /// // SELECT * FROM player - /// var request = Player.all().order(Column("name")) - /// request = request.unordered() + /// For example: + /// + /// ```swift + /// // SELECT * FROM player + /// let request = Player.all() + /// .order(Column("name")) + /// .unordered() + /// ``` func unordered() -> Self } extension OrderedRequest { - /// Creates a request with the provided *orderings*. + /// Sorts the fetched rows according to the given SQL ordering terms. /// - /// // SELECT * FROM player ORDER BY name - /// var request = Player.all() - /// request = request.order(Column("name")) + /// For example: /// - /// Any previous ordering is replaced: + /// ```swift + /// // SELECT * FROM player ORDER BY score DESC, name + /// let request = Player.all() + /// .order(Column("score").desc, Column("name")) + /// ``` /// - /// // SELECT * FROM player ORDER BY name - /// request - /// .order(Column("email")) - /// .reversed() - /// .order(Column("name")) + /// Any previous ordering is discarded: + /// + /// ```swift + /// // SELECT * FROM player ORDER BY name + /// let request = Player.all() + /// .order(Column("score").desc) + /// .order(Column("name")) + /// ``` public func order(_ orderings: any SQLOrderingTerm...) -> Self { orderWhenConnected { _ in orderings } } - /// Creates a request with the provided *orderings*. + /// Sorts the fetched rows according to the given SQL ordering terms. /// - /// // SELECT * FROM player ORDER BY name - /// var request = Player.all() - /// request = request.order(Column("name")) + /// For example: /// - /// Any previous ordering is replaced: + /// ```swift + /// // SELECT * FROM player ORDER BY score DESC, name + /// let request = Player.all() + /// .order([Column("score").desc, Column("name")]) + /// ``` /// - /// // SELECT * FROM player ORDER BY name - /// request - /// .order(Column("email")) - /// .reversed() - /// .order(Column("name")) + /// Any previous ordering is discarded: + /// + /// ```swift + /// // SELECT * FROM player ORDER BY name + /// let request = Player.all() + /// .order([Column("score").desc]) + /// .order([Column("name")]) + /// ``` public func order(_ orderings: [any SQLOrderingTerm]) -> Self { orderWhenConnected { _ in orderings } } - /// Creates a request sorted according to *sql*. + /// Sorts the fetched rows according to the given SQL string. /// - /// // SELECT * FROM player ORDER BY name - /// var request = Player.all() - /// request = request.order(sql: "name") + /// For example: /// - /// Any previous ordering is replaced: + /// ```swift + /// // SELECT * FROM player ORDER BY score DESC, name + /// let request = Player.all() + /// .order(sql: "score DESC, name") + /// ``` /// - /// // SELECT * FROM player ORDER BY name - /// request - /// .order(sql: "email") - /// .order(sql: "name") + /// Any previous ordering is discarded. public func order(sql: String, arguments: StatementArguments = StatementArguments()) -> Self { order(SQL(sql: sql, arguments: arguments)) } - /// Creates a request sorted according to an SQL *literal*. + /// Sorts the fetched rows according to the given ``SQL`` literal. /// - /// // SELECT * FROM player ORDER BY name - /// var request = Player.all() - /// request = request.order(literal: "name") + /// For example: /// - /// Any previous ordering is replaced: + /// ```swift + /// // SELECT * FROM player ORDER BY score DESC, name + /// let request = Player.all() + /// .order(literal: "score DESC, name") + /// ``` /// - /// // SELECT * FROM player ORDER BY name - /// request - /// .order(literal: "email") - /// .order(literal: "name") + /// Any previous ordering is discarded. public func order(literal sqlLiteral: SQL) -> Self { // NOT TESTED order(sqlLiteral) @@ -606,10 +1033,32 @@ extension OrderedRequest { // MARK: - JoinableRequest -/// Implementation details of `JoinableRequest`. +/// A request that can join and prefetch associations. /// -/// :nodoc: -public protocol _JoinableRequest { +/// `JoinableRequest` is adopted by ``QueryInterfaceRequest`` and all +/// types conforming to ``Association``. +/// +/// It provides the methods that build requests involving several tables linked +/// through associations. +/// +/// ## Topics +/// +/// ### Extending the Selection with Columns of Associated Records +/// +/// - ``annotated(withOptional:)`` +/// - ``annotated(withRequired:)`` +/// +/// ### Prefetching Associated Records +/// +/// - ``including(all:)`` +/// - ``including(optional:)`` +/// - ``including(required:)`` +/// +/// ### Joining Associated Records +/// +/// - ``joining(optional:)`` +/// - ``joining(required:)`` +public protocol JoinableRequest: TypedRequest { /// Creates a request that prefetches an association. func _including(all association: _SQLAssociation) -> Self @@ -634,75 +1083,151 @@ public protocol _JoinableRequest { func _joining(required association: _SQLAssociation) -> Self } -/// The protocol for all requests that can be associated. -public protocol JoinableRequest: TypedRequest, _JoinableRequest { } - extension JoinableRequest { - /// Creates a request that prefetches an association. + /// Returns a request that fetches all records associated with each record + /// in this request. + /// + /// For example, we can fetch authors along with their books: + /// + /// ```swift + /// struct Author: TableRecord, FetchableRecord, Decodable { + /// static let books = hasMany(Book.self) + /// } + /// struct Book: TableRecord, FetchableRecord, Decodable { } + /// + /// struct AuthorInfo: FetchableRecord, Decodable { + /// var author: Author + /// var books: [Book] + /// } + /// + /// let authorInfos = try Author.all() + /// .including(all: Author.books) + /// .asRequest(of: AuthorInfo.self) + /// .fetchAll(db) + /// ``` public func including(all association: A) -> Self where A.OriginRowDecoder == RowDecoder { _including(all: association._sqlAssociation) } - /// Creates a request that includes an association. The columns of the - /// associated record are selected. The returned request does not - /// require that the associated database table contains a matching row. + /// Returns a request that fetches the eventual record associated with each + /// record of this request. + /// + /// For example, we can fetch books along with their eventual author: + /// + /// ```swift + /// struct Author: TableRecord, FetchableRecord, Decodable { } + /// struct Book: TableRecord, FetchableRecord, Decodable { + /// static let author = belongsTo(Author.self) + /// } + /// + /// struct BookInfo: FetchableRecord, Decodable { + /// var book: Book + /// var author: Author? + /// } + /// + /// let bookInfos = try Book.all() + /// .including(optional: Book.author) + /// .asRequest(of: BookInfo.self) + /// .fetchAll(db) + /// ``` public func including(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder { _including(optional: association._sqlAssociation) } - /// Creates a request that includes an association. The columns of the - /// associated record are selected. The returned request requires - /// that the associated database table contains a matching row. + /// Returns a request that fetches the record associated with each record in + /// this request. Records that do not have an associated record + /// are discarded. + /// + /// For example, we can fetch books along with their eventual author: + /// + /// ```swift + /// struct Author: TableRecord, FetchableRecord, Decodable { } + /// struct Book: TableRecord, FetchableRecord, Decodable { + /// static let author = belongsTo(Author.self) + /// } + /// + /// struct BookInfo: FetchableRecord, Decodable { + /// var book: Book + /// var author: Author + /// } + /// + /// let bookInfos = try Book.all() + /// .including(required: Book.author) + /// .asRequest(of: BookInfo.self) + /// .fetchAll(db) + /// ``` public func including(required association: A) -> Self where A.OriginRowDecoder == RowDecoder { _including(required: association._sqlAssociation) } - /// Creates a request that joins an association. The columns of the - /// associated record are not selected. The returned request does not - /// require that the associated database table contains a matching row. + /// Returns a request that joins each record of this request to its + /// eventual associated record. public func joining(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder { _joining(optional: association._sqlAssociation) } - /// Creates a request that joins an association. The columns of the - /// associated record are not selected. The returned request requires - /// that the associated database table contains a matching row. + /// Returns a request that joins each record of this request to its + /// associated record. Records that do not have an associated record + /// are discarded. + /// + /// For example, we can fetch only books whose author is French: + /// + /// ```swift + /// struct Author: TableRecord, FetchableRecord, Decodable { } + /// struct Book: TableRecord, FetchableRecord, Decodable { + /// static let author = belongsTo(Author.self) + /// } + /// + /// let frenchAuthors = Book.author.filter(Column("countryCode") == "FR") + /// let bookInfos = try Book.all() + /// .joining(required: frenchAuthors) + /// .fetchAll(db) + /// ``` public func joining(required association: A) -> Self where A.OriginRowDecoder == RowDecoder { _joining(required: association._sqlAssociation) } } extension JoinableRequest where Self: SelectionRequest { - /// Creates a request which appends *columns of an associated record* to - /// the current selection. + /// Appends the columns of the eventual associated record to the + /// selected columns. /// - /// // SELECT player.*, team.color - /// // FROM player LEFT JOIN team ... - /// let teamColor = Player.team.select(Column("color")) - /// let request = Player.all().annotated(withOptional: teamColor) + /// For example: /// - /// This method performs the same SQL request as `including(optional:)`. - /// The difference is in the shape of Decodable records that decode such - /// a request: the associated columns can be decoded at the same level as - /// the main record: + /// ```swift + /// // SELECT player.*, team.color + /// // FROM player LEFT JOIN team ... + /// let teamColor = Player.team.select(Column("color")) + /// let request = Player.all().annotated(withOptional: teamColor) + /// ``` /// - /// struct PlayerWithTeamColor: FetchableRecord, Decodable { - /// var player: Player - /// var color: String? - /// } - /// let players = try dbQueue.read { db in - /// try request - /// .asRequest(of: PlayerWithTeamColor.self) - /// .fetchAll(db) - /// } + /// This method performs the exact same SQL request as + /// ``including(optional:)``. The difference is in the record type that can + /// decode such a request: the columns of the associated record must be + /// decoded at the same level as the main record. For example: /// - /// Note: this is a convenience method. You can build the same request with - /// `TableAlias`, `annotated(with:)`, and `joining(optional:)`: + /// ```swift + /// struct PlayerWithTeamColor: FetchableRecord, Decodable { + /// var player: Player + /// var color: String? + /// } + /// try dbQueue.read { db in + /// let players = try request + /// .asRequest(of: PlayerWithTeamColor.self) + /// .fetchAll(db) + /// } + /// ``` /// - /// let teamAlias = TableAlias() - /// let request = Player.all() - /// .annotated(with: teamAlias[Column("color")]) - /// .joining(optional: Player.team.aliased(teamAlias)) + /// This method is a convenience. You can build the same request with + /// ``TableAlias``, ``SelectionRequest/annotated(with:)-6ehs4``, and + /// ``JoinableRequest/joining(optional:)``: + /// + /// ```swift + /// let teamAlias = TableAlias() + /// let request = Player.all() + /// .annotated(with: teamAlias[Column("color")]) + /// .joining(optional: Player.team.aliased(teamAlias)) + /// ``` public func annotated(withOptional association: A) -> Self where A.OriginRowDecoder == RowDecoder { // TODO: find a way to prefix the selection with the association key let alias = TableAlias() @@ -716,36 +1241,45 @@ extension JoinableRequest where Self: SelectionRequest { }) } - /// Creates a request which appends *columns of an associated record* to - /// the current selection. + /// Appends the columns of the associated record to the selected columns. + /// Records that do not have an associated record are discarded. /// - /// // SELECT player.*, team.color - /// // FROM player JOIN team ... - /// let teamColor = Player.team.select(Column("color")) - /// let request = Player.all().annotated(withRequired: teamColor) + /// For example: /// - /// This method performs the same SQL request as `including(required:)`. - /// The difference is in the shape of Decodable records that decode such - /// a request: the associated columns can be decoded at the same level as - /// the main record: + /// ```swift + /// // SELECT player.*, team.color + /// // FROM player JOIN team ... + /// let teamColor = Player.team.select(Column("color")) + /// let request = Player.all().annotated(withRequired: teamColor) + /// ``` /// - /// struct PlayerWithTeamColor: FetchableRecord, Decodable { - /// var player: Player - /// var color: String - /// } - /// let players = try dbQueue.read { db in - /// try request - /// .asRequest(of: PlayerWithTeamColor.self) - /// .fetchAll(db) - /// } + /// This method performs the exact same SQL request as + /// ``including(required:)``. The difference is in the record type that can + /// decode such a request: the columns of the associated record must be + /// decoded at the same level as the main record. For example: /// - /// Note: this is a convenience method. You can build the same request with - /// `TableAlias`, `annotated(with:)`, and `joining(required:)`: + /// ```swift + /// struct PlayerWithTeamColor: FetchableRecord, Decodable { + /// var player: Player + /// var color: String + /// } + /// try dbQueue.read { db in + /// let players = try request + /// .asRequest(of: PlayerWithTeamColor.self) + /// .fetchAll(db) + /// } + /// ``` /// - /// let teamAlias = TableAlias() - /// let request = Player.all() - /// .annotated(with: teamAlias[Column("color")]) - /// .joining(required: Player.team.aliased(teamAlias)) + /// This method is a convenience. You can build the same request with + /// ``TableAlias``, ``SelectionRequest/annotated(with:)-6ehs4``, and + /// ``JoinableRequest/joining(required:)``: + /// + /// ```swift + /// let teamAlias = TableAlias() + /// let request = Player.all() + /// .annotated(with: teamAlias[Column("color")]) + /// .joining(required: Player.team.aliased(teamAlias)) + /// ``` public func annotated(withRequired association: A) -> Self where A.OriginRowDecoder == RowDecoder { // TODO: find a way to prefix the selection with the association key let selection = association._sqlAssociation.destination.relation.selectionPromise @@ -762,23 +1296,114 @@ extension JoinableRequest where Self: SelectionRequest { // MARK: - DerivableRequest -/// The base protocol for all requests that can be refined. +/// `DerivableRequest` is the base protocol for ``QueryInterfaceRequest`` +/// and ``Association``. +/// +/// Most features of `DerivableRequest` come from the protocols it +/// inherits from. +/// +/// ## Topics +/// +/// ### Instance Methods +/// +/// - ``TableRequest/aliased(_:)`` +/// - ``TableAlias`` +/// +/// ### The WITH Clause +/// +/// - ``with(_:)`` +/// +/// ### The SELECT Clause +/// +/// - ``SelectionRequest/annotated(with:)-4qcem`` +/// - ``SelectionRequest/annotated(with:)-6ehs4`` +/// - ``SelectionRequest/annotatedWhenConnected(with:)`` +/// - ``distinct()`` +/// - ``SelectionRequest/select(_:)-30yzl`` +/// - ``SelectionRequest/select(_:)-7e2y5`` +/// - ``SelectionRequest/select(literal:)`` +/// - ``SelectionRequest/select(sql:arguments:)`` +/// - ``SelectionRequest/selectWhenConnected(_:)`` +/// +/// ### The WHERE Clause +/// +/// - ``FilteredRequest/filter(_:)`` +/// - ``TableRequest/filter(id:)`` +/// - ``TableRequest/filter(ids:)`` +/// - ``TableRequest/filter(key:)-1p9sq`` +/// - ``TableRequest/filter(key:)-2te6v`` +/// - ``TableRequest/filter(keys:)-6ggt1`` +/// - ``TableRequest/filter(keys:)-8fbn9`` +/// - ``FilteredRequest/filter(literal:)`` +/// - ``FilteredRequest/filter(sql:arguments:)`` +/// - ``FilteredRequest/filterWhenConnected(_:)`` +/// - ``TableRequest/matching(_:)`` +/// - ``FilteredRequest/none()`` +/// +/// ### The GROUP BY and HAVING Clauses +/// +/// - ``AggregatingRequest/group(_:)-edak`` +/// - ``AggregatingRequest/group(_:)-4216o`` +/// - ``AggregatingRequest/group(literal:)`` +/// - ``AggregatingRequest/group(sql:arguments:)`` +/// - ``TableRequest/groupByPrimaryKey()`` +/// - ``AggregatingRequest/groupWhenConnected(_:)`` +/// - ``AggregatingRequest/having(_:)`` +/// - ``AggregatingRequest/having(literal:)`` +/// - ``AggregatingRequest/having(sql:arguments:)`` +/// - ``AggregatingRequest/havingWhenConnected(_:)`` +/// +/// ### The ORDER BY Clause +/// +/// - ``OrderedRequest/order(_:)-63rzl`` +/// - ``OrderedRequest/order(_:)-6co0m`` +/// - ``OrderedRequest/order(literal:)`` +/// - ``OrderedRequest/order(sql:arguments:)`` +/// - ``OrderedRequest/orderWhenConnected(_:)`` +/// - ``TableRequest/orderByPrimaryKey()`` +/// - ``OrderedRequest/reversed()`` +/// - ``OrderedRequest/unordered()`` +/// +/// ### Associations +/// +/// - ``JoinableRequest/annotated(withOptional:)`` +/// - ``JoinableRequest/annotated(withRequired:)`` +/// - ``annotated(with:)-74xfs`` +/// - ``annotated(with:)-8snn4`` +/// - ``having(_:)`` +/// - ``JoinableRequest/including(all:)`` +/// - ``JoinableRequest/including(optional:)`` +/// - ``JoinableRequest/including(required:)`` +/// - ``JoinableRequest/joining(optional:)`` +/// - ``JoinableRequest/joining(required:)`` +/// +/// ### Supporting Types +/// +/// - ``AggregatingRequest`` +/// - ``FilteredRequest`` +/// - ``JoinableRequest`` +/// - ``OrderedRequest`` +/// - ``SelectionRequest`` +/// - ``TableRequest`` +/// - ``TypedRequest`` public protocol DerivableRequest: AggregatingRequest, FilteredRequest, JoinableRequest, OrderedRequest, SelectionRequest, TableRequest { - /// Creates a request which returns distinct rows. + /// Returns a request which returns distinct rows. /// - /// // SELECT DISTINCT * FROM player - /// var request = Player.all() - /// request = request.distinct() + /// For example: /// - /// // SELECT DISTINCT name FROM player - /// var request = Player.select(Column("name")) - /// request = request.distinct() + /// ```swift + /// // SELECT DISTINCT * FROM player + /// let request = Player.all().distinct() + /// + /// // SELECT DISTINCT name FROM player + /// let request = Player.select(Column("name")).distinct() + /// ``` func distinct() -> Self - /// Returns a request which embeds the common table expression. + /// Embeds a common table expression. /// /// If a common table expression with the same table name had already been /// embedded, it is replaced by the new one. @@ -786,28 +1411,30 @@ public protocol DerivableRequest: AggregatingRequest, FilteredReques /// For example, you can build a request that fetches all chats with their /// latest message: /// - /// let latestMessageRequest = Message - /// .annotated(with: max(Column("date"))) - /// .group(Column("chatID")) + /// ```swift + /// let latestMessageRequest = Message + /// .annotated(with: max(Column("date"))) + /// .group(Column("chatID")) /// - /// let latestMessageCTE = CommonTableExpression( - /// named: "latestMessage", - /// request: latestMessageRequest) + /// let latestMessageCTE = CommonTableExpression( + /// named: "latestMessage", + /// request: latestMessageRequest) /// - /// let latestMessage = Chat.association( - /// to: latestMessageCTE, - /// on: { chat, latestMessage in - /// chat[Column("id")] == latestMessage[Column("chatID")] - /// }) + /// let latestMessageAssociation = Chat.association( + /// to: latestMessageCTE, + /// on: { chat, latestMessage in + /// chat[Column("id")] == latestMessage[Column("chatID")] + /// }) /// - /// // WITH latestMessage AS - /// // (SELECT *, MAX(date) FROM message GROUP BY chatID) - /// // SELECT chat.*, latestMessage.* - /// // FROM chat - /// // LEFT JOIN latestMessage ON chat.id = latestMessage.chatID - /// let request = Chat.all() - /// .with(latestMessageCTE) - /// .including(optional: latestMessage) + /// // WITH latestMessage AS + /// // (SELECT *, MAX(date) FROM message GROUP BY chatID) + /// // SELECT chat.*, latestMessage.* + /// // FROM chat + /// // LEFT JOIN latestMessage ON chat.id = latestMessage.chatID + /// let request = Chat.all() + /// .with(latestMessageCTE) + /// .including(optional: latestMessageAssociation) + /// ``` func with(_ cte: CommonTableExpression) -> Self } @@ -833,36 +1460,83 @@ extension DerivableRequest { } } - /// Creates a request which appends *aggregates* to the current selection. + /// Appends association aggregates to the selected columns. /// - /// // SELECT team.*, COUNT(DISTINCT player.id) AS playerCount - /// // FROM team LEFT JOIN player ... - /// var request = Team.all() - /// request = request.annotated(with: Team.players.count) + /// For example: + /// + /// ```swift + /// struct Author: TableRecord, FetchableRecord, Decodable { + /// static let books = hasMany(Book.self) + /// } + /// struct Book: TableRecord, FetchableRecord, Decodable { } + /// + /// struct AuthorInfo: FetchableRecord, Decodable { + /// var author: Author + /// var bookCount: Int + /// } + /// + /// // SELECT author.*, COUNT(DISTINCT book.id) AS bookCount + /// // FROM author + /// // LEFT JOIN book ON book.authorId = author.id + /// // GROUP BY author.id + /// let authorInfos = try Author.all() + /// .annotated(with: Author.books.count) + /// .asRequest(of: AuthorInfo.self) + /// .fetchAll(db) + /// ``` public func annotated(with aggregates: AssociationAggregate...) -> Self { annotated(with: aggregates) } - /// Creates a request which appends *aggregates* to the current selection. + /// Appends association aggregates to the selected columns. /// - /// // SELECT team.*, COUNT(DISTINCT player.id) AS playerCount - /// // FROM team LEFT JOIN player ... - /// var request = team.all() - /// request = request.annotated(with: [Team.players.count]) + /// For example: + /// + /// ```swift + /// struct Author: TableRecord, FetchableRecord, Decodable { + /// static let books = hasMany(Book.self) + /// } + /// struct Book: TableRecord, FetchableRecord, Decodable { } + /// + /// struct AuthorInfo: FetchableRecord, Decodable { + /// var author: Author + /// var bookCount: Int + /// } + /// + /// // SELECT author.*, COUNT(DISTINCT book.id) AS bookCount + /// // FROM author + /// // LEFT JOIN book ON book.authorId = author.id + /// // GROUP BY author.id + /// let authorInfos = try Author.all() + /// .annotated(with: [Author.books.count]) + /// .asRequest(of: AuthorInfo.self) + /// .fetchAll(db) + /// ``` public func annotated(with aggregates: [AssociationAggregate]) -> Self { aggregates.reduce(self) { request, aggregate in request.annotated(with: aggregate) } } - /// Creates a request which appends the provided aggregate *predicate* to - /// the eventual set of already applied predicates. + /// Filters the fetched records with an association aggregate. /// - /// // SELECT team.* - /// // FROM team LEFT JOIN player ... - /// // HAVING COUNT(DISTINCT player.id) = 0 - /// var request = Team.all() - /// request = request.having(Team.players.isEmpty) + /// For example: + /// + /// ```swift + /// struct Author: TableRecord, FetchableRecord { + /// static let books = hasMany(Book.self) + /// } + /// struct Book: TableRecord, FetchableRecord { } + /// + /// // SELECT author.* + /// // FROM author + /// // LEFT JOIN book ON book.authorId = author.id + /// // GROUP BY author.id + /// // HAVING COUNT(DISTINCT book.id) > 5 + /// let authors = try Author.all() + /// .having(Author.books.count > 5) + /// .fetchAll(db) + /// ``` public func having(_ predicate: AssociationAggregate) -> Self { var request = self let expression = predicate.prepare(&request) diff --git a/GRDB/QueryInterface/SQL/Column.swift b/GRDB/QueryInterface/SQL/Column.swift index 54a1e8b8b..331789d45 100644 --- a/GRDB/QueryInterface/SQL/Column.swift +++ b/GRDB/QueryInterface/SQL/Column.swift @@ -1,26 +1,27 @@ -/// Adopt the ColumnExpression protocol when you define a column type. +/// A type that represents a column in a database table. /// -/// You can, for example, define a String-based column enum: +/// ## Topics /// -/// enum Columns: String, ColumnExpression { -/// case id, name, score -/// } -/// let arthur = try Player.filter(Columns.name == "Arthur").fetchOne(db) +/// ### Standard Columns /// -/// You can also define a genuine column type: +/// - ``rowID`` /// -/// struct MyColumn: ColumnExpression { -/// var name: String -/// var sqlType: String -/// } -/// let nameColumn = MyColumn(name: "name", sqlType: "VARCHAR") -/// let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db) +/// ### Deriving SQL Expressions /// -/// See +/// - ``detached`` +/// - ``match(_:)`` +/// +/// ### Creating Column Assignments +/// +/// - ``noOverwrite`` +/// - ``set(to:)`` public protocol ColumnExpression: SQLSpecificExpressible { - /// The unqualified name of a database column. + /// The column name. /// - /// "score" is a valid unqualified name. "player.score" is not. + /// The column name is never qualified with a table name. + /// + /// For example, the name of a column can be `"score"`, but + /// not `"player.score"`. var name: String { get } } @@ -29,58 +30,72 @@ extension ColumnExpression { .column(name) } - /// Returns a "detached column", which is never qualified with any table - /// name in the SQL generated by the query interface. A detached column - /// allows you to refer to an aliased column (`expression AS alias`). + /// An SQL expression that refers to an aliased column + /// (`expression AS alias`). + /// + /// Once detached, a column is never qualified with any table name in the + /// SQL generated by the query interface. /// /// For example, see how `Column("total").detached` makes it possible to /// sort this query, when a raw `Column("total")` could not: /// - /// // SELECT player.*, - /// // (player.score + player.bonus) AS total, - /// // team.* - /// // FROM player - /// // JOIN team ON team.id = player.teamID - /// // ORDER BY total, player.name - /// // ~~~~~ - /// let request = Player - /// .annotated(with: (Column("score") + Column("bonus")).forKey("total")) - /// .including(required: Book.team) - /// .order(Column("total").detached, Column("name")) + /// ```swift + /// // SELECT player.*, + /// // (player.score + player.bonus) AS total, + /// // team.* + /// // FROM player + /// // JOIN team ON team.id = player.teamID + /// // ORDER BY total, player.name + /// // ~~~~~ + /// let request = Player + /// .annotated(with: (Column("score") + Column("bonus")).forKey("total")) + /// .including(required: Player.team) + /// .order(Column("total").detached, Column("name")) + /// ``` public var detached: SQLExpression { SQL(sql: name.quotedDatabaseIdentifier).sqlExpression } } extension ColumnExpression where Self == Column { - /// The hidden rowID column + /// The hidden rowID column. public static var rowID: Self { Column.rowID } } /// A column in a database table. /// -/// When you need to introduce your own column type, don't wrap a Column. -/// Instead, adopt the ColumnExpression protocol. +/// ## Topics /// -/// See -public struct Column: ColumnExpression { - /// The hidden rowID column +/// ### Standard Columns +/// +/// - ``rowID-3bn70`` +/// +/// ### Creating A Column +/// +/// - ``init(_:)-5grmu`` +/// - ``init(_:)-7xc4z`` +public struct Column { + /// The hidden rowID column. public static let rowID = Column("rowid") - /// The name of the column public var name: String - /// Creates a column given its name. + /// Creates a `Column` given its name. + /// + /// The name should be unqualified, such as `"score"`. Qualified name such + /// as `"player.score"` are unsupported. public init(_ name: String) { self.name = name } - /// Creates a column given a CodingKey. + /// Creates a `Column` given a `CodingKey`. public init(_ codingKey: some CodingKey) { self.name = codingKey.stringValue } } +extension Column: ColumnExpression { } + /// Support for column enums: /// /// struct Player { diff --git a/GRDB/QueryInterface/SQL/SQLAssociation.swift b/GRDB/QueryInterface/SQL/SQLAssociation.swift index c6d5fb2a2..aa106a319 100644 --- a/GRDB/QueryInterface/SQL/SQLAssociation.swift +++ b/GRDB/QueryInterface/SQL/SQLAssociation.swift @@ -49,8 +49,6 @@ /// through: Pivot1.hasMany(Pivot2.self), /// via: Pivot2.belongsTo(Destination.self))) /// Origin.including(required: association) -/// -/// :nodoc: public struct _SQLAssociation { // All steps, from pivot to destination. Never empty. private(set) var steps: [SQLAssociationStep] diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index bc9de466e..e9de5892d 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -1,5 +1,39 @@ -/// SQLExpression is the type that represents an SQL expression, as -/// described at +/// An SQL expression. +/// +/// `SQLExpression` is an opaque representation of an SQL expression. +/// You generally build `SQLExpression` from other expressions. For example: +/// +/// ```swift +/// // Values +/// 1000.sqlExpression +/// "O'Brien".sqlExpression +/// +/// // Computed expressions +/// Column("score") + Column("bonus") +/// (0...1000).contains(Column("score")) +/// !Column("isBlue") +/// +/// // Literal expression +/// SQL("IFNULL(name, \(defaultName))").sqlExpression +/// +/// // Subquery +/// Player.select(max(Column("score"))).sqlExpression +/// ``` +/// +/// `SQLExpression` is better used as the return type of a function. For +/// function arguments, prefer the ``SQLExpressible`` or +/// ``SQLSpecificExpressible`` protocols. For example: +/// +/// ```swift +/// func date(_ value: some SQLSpecificExpressible) -> SQLExpression { +/// SQL("DATE(\(value))").sqlExpression +/// } +/// +/// // SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23' +/// let request = Player.filter(date(Column("createdAt")) == "2020-01-23") +/// ``` +/// +/// Related SQLite documentation: public struct SQLExpression { private var impl: Impl @@ -160,17 +194,18 @@ public struct SQLExpression { case falsey } - /// `AssociativeBinaryOperator` is an associative binary operator, - /// such as `+`, `*`, `AND`, etc. + /// An associative binary SQL operator, such as `+`, `*`, `AND`, etc. /// /// Use it with the `joined(operator:)` method. For example: /// - /// // SELECT score + bonus + 1000 FROM player - /// let values = [ - /// scoreColumn, - /// bonusColumn, - /// 1000.databaseValue] - /// Player.select(values.joined(operator: .add)) + /// ```swift + /// // SELECT score + bonus + 1000 FROM player + /// let values = [ + /// scoreColumn, + /// bonusColumn, + /// 1000.databaseValue] + /// let request = Player.select(values.joined(operator: .add)) + /// ``` public struct AssociativeBinaryOperator: Hashable { /// The SQL operator let sql: String @@ -202,60 +237,70 @@ public struct SQLExpression { self.isBijective = bijective } - /// The `+` binary operator + /// The `+` binary SQL operator. /// /// For example: /// - /// // score + bonus - /// [Column("score"), Column("bonus")].joined(operator: .add) + /// ```swift + /// // score + bonus + /// [Column("score"), Column("bonus")].joined(operator: .add) + /// ``` public static let add = AssociativeBinaryOperator( sql: "+", neutralValue: 0.databaseValue, strictlyAssociative: false, bijective: false) - /// The `*` binary operator + /// The `*` binary SQL operator. /// /// For example: /// - /// // score * factor - /// [Column("score"), Column("factor")].joined(operator: .multiply) + /// ```swift + /// // score * factor + /// [Column("score"), Column("factor")].joined(operator: .multiply) + /// ``` public static let multiply = AssociativeBinaryOperator( sql: "*", neutralValue: 1.databaseValue, strictlyAssociative: false, bijective: false) - /// The `AND` binary operator + /// The `AND` binary SQL operator. /// /// For example: /// - /// // isBlue AND isTall - /// [Column("isBlue"), Column("isTall")].joined(operator: .and) + /// ```swift + /// // isBlue AND isTall + /// [Column("isBlue"), Column("isTall")].joined(operator: .and) + /// ``` public static let and = AssociativeBinaryOperator( sql: "AND", neutralValue: true.databaseValue, strictlyAssociative: true, bijective: false) - /// The `OR` binary operator + /// The `OR` binary SQL operator. /// /// For example: /// - /// // isBlue OR isTall - /// [Column("isBlue"), Column("isTall")].joined(operator: .or) + /// ```swift + /// // isBlue OR isTall + /// [Column("isBlue"), Column("isTall")].joined(operator: .or) + /// ``` public static let or = AssociativeBinaryOperator( sql: "OR", neutralValue: false.databaseValue, strictlyAssociative: true, bijective: false) - /// The `||` string concatenation operator + /// The `||` string concatenation SQL operator. /// /// For example: /// - /// // firstName || ' ' || lastName - /// [Column("firstName"), " ", Column("lastName")].joined(operator: .concat) + /// ```swift + /// // firstName || ' ' || lastName + /// [Column("firstName"), " ", Column("lastName")].joined(operator: .concat) + /// ``` public static let concat = AssociativeBinaryOperator( sql: "||", neutralValue: "".databaseValue, @@ -1647,13 +1692,15 @@ extension SQLExpression { // MARK: - SQLExpressible -/// `SQLExpressible` is the protocol for all types that can be used as an -/// SQL expression. +/// A type that can be used as an SQL expression. /// -/// It is adopted by protocols like `DatabaseValueConvertible`, and types -/// like `Column`. +/// Related SQLite documentation /// -/// See +/// ## Topics +/// +/// ### Supporting Type +/// +/// - ``SQLExpression`` public protocol SQLExpressible { /// Returns an SQL expression. var sqlExpression: SQLExpression { get } @@ -1664,15 +1711,63 @@ extension SQLExpressible where Self == Column { public static var rowID: Self { Column.rowID } } -/// `SQLSpecificExpressible` is a protocol for all database-specific types that -/// can be turned into an SQL expression. Types whose existence is not purely -/// dedicated to the database should adopt the `SQLExpressible` +/// A database-specific type that can be used as an SQL expression. +/// +/// `SQLSpecificExpressible` is the protocol for all database-specific types +/// that can be turned into an SQL expression. Types whose existence is not purely +/// dedicated to the database should adopt the ``SQLExpressible`` /// protocol instead. /// -/// For example, `Column` is a type that only exists to help you build requests, -/// and it adopts `SQLSpecificExpressible`. +/// For example, ``Column`` is a type that only exists to help you build +/// requests, and it adopts `SQLSpecificExpressible`. /// -/// On the other side, `Int` adopts `SQLExpressible`. +/// On the other side, `Int` adopts ``SQLExpressible``. +/// +/// ## Topics +/// +/// ### Column Expressions +/// +/// - ``Column`` +/// - ``ColumnExpression`` +/// +/// ### Applying a Collation +/// +/// - ``collating(_:)-2mr78`` +/// - ``collating(_:)-10dk1`` +/// +/// ### SQL Functions & Operators +/// +/// - ``abs(_:)-5l6xp`` +/// - ``average(_:)`` +/// - ``capitalized`` +/// - ``count(_:)`` +/// - ``count(distinct:)`` +/// - ``dateTime(_:_:)`` +/// - ``julianDay(_:_:)`` +/// - ``length(_:)-41me0`` +/// - ``like(_:escape:)`` +/// - ``localizedCapitalized`` +/// - ``localizedLowercased`` +/// - ``localizedUppercased`` +/// - ``lowercased`` +/// - ``min(_:)`` +/// - ``max(_:)`` +/// - ``sum(_:)`` +/// - ``total(_:)`` +/// - ``uppercased`` +/// - ``SQLDateModifier`` +/// +/// ### Creating Ordering Terms +/// +/// - ``asc`` +/// - ``ascNullsLast`` +/// - ``desc`` +/// - ``descNullsFirst`` +/// +/// ### Creating Result Columns +/// +/// - ``forKey(_:)-3xk0`` +/// - ``forKey(_:)-3egx6`` public protocol SQLSpecificExpressible: SQLExpressible, SQLSelectable, SQLOrderingTerm { // SQLExpressible can be adopted by Swift standard types, and user // types, through the DatabaseValueConvertible protocol which inherits @@ -1716,19 +1811,26 @@ extension Sequence where Element: SQLSpecificExpressible { /// /// For example: /// - /// // SELECT * FROM player - /// // WHERE (registered - /// // AND (score >= 1000) - /// // AND (name IS NOT NULL)) - /// let conditions = [ - /// Column("registered"), - /// Column("score") >= 1000, - /// Column("name") != nil] - /// Player.filter(conditions.joined(operator: .and)) + /// ```swift + /// // SELECT * FROM player + /// // WHERE (registered + /// // AND (score >= 1000) + /// // AND (name IS NOT NULL)) + /// let conditions = [ + /// Column("registered"), + /// Column("score") >= 1000, + /// Column("name") != nil] + /// Player.filter(conditions.joined(operator: .and)) + /// ``` /// /// When the sequence is empty, `joined(operator:)` returns the neutral - /// value of the operator. It is 0 (zero) for `.add`, 1 for ‘.multiply`, - /// false for `.or`, and true for `.and`. + /// value of the operator. It is: + /// + /// - `0` for ``SQLExpression/AssociativeBinaryOperator/add`` + /// - `1` for ``SQLExpression/AssociativeBinaryOperator/multiply`` + /// - `false` for ``SQLExpression/AssociativeBinaryOperator/or`` + /// - `true` for ``SQLExpression/AssociativeBinaryOperator/and`` + /// - `""` for ``SQLExpression/AssociativeBinaryOperator/concat`` public func joined(operator: SQLExpression.AssociativeBinaryOperator) -> SQLExpression { .associativeBinary(`operator`, map(\.sqlExpression)) } @@ -1740,19 +1842,26 @@ extension Sequence where Element == any SQLSpecificExpressible { /// /// For example: /// - /// // SELECT * FROM player - /// // WHERE (registered - /// // AND (score >= 1000) - /// // AND (name IS NOT NULL)) - /// let conditions = [ - /// Column("registered"), - /// Column("score") >= 1000, - /// Column("name") != nil] - /// Player.filter(conditions.joined(operator: .and)) + /// ``` + /// // SELECT * FROM player + /// // WHERE (registered + /// // AND (score >= 1000) + /// // AND (name IS NOT NULL)) + /// let conditions = [ + /// Column("registered"), + /// Column("score") >= 1000, + /// Column("name") != nil] + /// Player.filter(conditions.joined(operator: .and)) + /// ``` /// /// When the sequence is empty, `joined(operator:)` returns the neutral - /// value of the operator. It is 0 (zero) for `.add`, 1 for ‘.multiply`, - /// false for `.or`, and true for `.and`. + /// value of the operator. It is: + /// + /// - `0` for ``SQLExpression/AssociativeBinaryOperator/add`` + /// - `1` for ``SQLExpression/AssociativeBinaryOperator/multiply`` + /// - `false` for ``SQLExpression/AssociativeBinaryOperator/or`` + /// - `true` for ``SQLExpression/AssociativeBinaryOperator/and`` + /// - `""` for ``SQLExpression/AssociativeBinaryOperator/concat`` public func joined(operator: SQLExpression.AssociativeBinaryOperator) -> SQLExpression { .associativeBinary(`operator`, map(\.sqlExpression)) } @@ -1762,46 +1871,34 @@ extension Sequence where Element == any SQLSpecificExpressible { extension SQLSpecificExpressible { - /// Returns a value that can be used as an argument to QueryInterfaceRequest.order() - /// - /// See + /// An ordering term for ascending order (nulls first). public var asc: SQLOrdering { .asc(sqlExpression) } - /// Returns a value that can be used as an argument to QueryInterfaceRequest.order() - /// - /// See + /// An ordering term for descending order (nulls last). public var desc: SQLOrdering { .desc(sqlExpression) } #if GRDBCUSTOMSQLITE - /// Returns a value that can be used as an argument to QueryInterfaceRequest.order() - /// - /// See + /// An ordering term for ascending order (nulls last). public var ascNullsLast: SQLOrdering { .ascNullsLast(sqlExpression) } - /// Returns a value that can be used as an argument to QueryInterfaceRequest.order() - /// - /// See + /// An ordering term for descending order (nulls first). public var descNullsFirst: SQLOrdering { .descNullsFirst(sqlExpression) } #elseif !GRDBCIPHER - /// Returns a value that can be used as an argument to QueryInterfaceRequest.order() - /// - /// See + /// An ordering term for ascending order (nulls last). @available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) public var ascNullsLast: SQLOrdering { .ascNullsLast(sqlExpression) } - /// Returns a value that can be used as an argument to QueryInterfaceRequest.order() - /// - /// See + /// An ordering term for descending order (nulls first). @available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *) public var descNullsFirst: SQLOrdering { .descNullsFirst(sqlExpression) @@ -1812,53 +1909,34 @@ extension SQLSpecificExpressible { // MARK: - SQL Selection Support extension SQLSpecificExpressible { - /// Returns an aliased column. + /// Returns an aliased result column. /// /// For example: /// - /// // SELECT (width * height) AS area FROM shape - /// let area = (Column("width") * Column("height")).forKey("area") - /// let request = Shape.select(area) - /// if let row = try Row.fetchOne(db, request) { - /// let area: Int = row["area"] - /// } + /// ```swift + /// // SELECT (score + bonus) AS totalScore FROM player + /// let totalScore = (Column("score") * Column("bonus")).forKey("totalScore") + /// let request = Player.select(totalScore) + /// ``` /// /// If you need to refer to the aliased column in another part of a request, - /// use `Column(...).detached`. For example: + /// use ``ColumnExpression/detached``. For example: /// - /// // SELECT (width * height) AS area FROM shape ORDER BY area - /// let area = (Column("width") * Column("height")).forKey("area") - /// let request = Shape - /// .select(area) - /// .order(Column("area").detached) - /// let rows = try Row.fetchCursor(db, request) - /// while let row = try rows.next() { - /// let area: Int = row["area"] - /// } + /// ```swift + /// // SELECT (score + bonus) AS totalScore + /// // FROM player + /// // ORDER BY totalScore + /// let request = Player + /// .select(totalScore) + /// .order(Column("totalScore").detached) + /// ``` public func forKey(_ key: String) -> SQLSelection { .aliasedExpression(sqlExpression, key) } /// Returns an aliased column with the same name as the coding key. /// - /// For example: - /// - /// struct Shape: Decodable, FetchableRecord, TableRecord { - /// let width: Int - /// let height: Int - /// let area: Int - /// - /// static let databaseSelection: [any SQLSelectable] = [ - /// Column(CodingKeys.width), - /// Column(CodingKeys.height), - /// (Column(CodingKeys.width) * Column(CodingKeys.height)).forKey(CodingKeys.area), - /// ] - /// } - /// - /// // SELECT width, height, (width * height) AS area FROM shape - /// let shapes: [Shape] = try Shape.fetchAll(db) - /// - /// See `forKey(_ key: String)` for more information. + /// See ``forKey(_:)-3xk0``. public func forKey(_ key: some CodingKey) -> SQLSelection { forKey(key.stringValue) } @@ -1872,7 +1950,11 @@ extension SQLSpecificExpressible { /// /// For example: /// - /// Player.filter(Column("email").collating(.nocase) == "contact@example.com") + /// ```swift + /// // SELECT * FROM player + /// // WHERE email = 'contact@example.com' COLLATE NOCASE + /// Player.filter(Column("email").collating(.nocase) == "contact@example.com") + /// ``` public func collating(_ collation: Database.CollationName) -> SQLExpression { .collated(sqlExpression, collation) } @@ -1881,7 +1963,9 @@ extension SQLSpecificExpressible { /// /// For example: /// - /// Player.filter(Column("name").collating(.localizedStandardCompare) == "Hervé") + /// ```swift + /// Player.order(Column("name").collating(.localizedStandardCompare)) + /// ``` public func collating(_ collation: DatabaseCollation) -> SQLExpression { .collated(sqlExpression, Database.CollationName(rawValue: collation.name)) } diff --git a/GRDB/QueryInterface/SQL/SQLFunctions.swift b/GRDB/QueryInterface/SQL/SQLFunctions.swift index d5c94b195..9d1796a2d 100644 --- a/GRDB/QueryInterface/SQL/SQLFunctions.swift +++ b/GRDB/QueryInterface/SQL/SQLFunctions.swift @@ -1,184 +1,206 @@ -// MARK: - ABS(...) - -/// Returns an expression that evaluates the `ABS` SQL function. +/// The `ABS` SQL function. /// -/// // ABS(amount) -/// abs(Column("amount")) +/// For example: +/// +/// ```swift +/// // ABS(amount) +/// abs(Column("amount")) +/// ``` public func abs(_ value: some SQLSpecificExpressible) -> SQLExpression { .function("ABS", [value.sqlExpression]) } - -// MARK: - AVG(...) - -/// Returns an expression that evaluates the `AVG` SQL function. +/// The `AVG` SQL function. /// -/// // AVG(length) -/// average(Column("length")) +/// For example: +/// +/// ```swift +/// // AVG(length) +/// average(Column("length")) +/// ``` public func average(_ value: some SQLSpecificExpressible) -> SQLExpression { .aggregate("AVG", [value.sqlExpression]) } - -// MARK: - COUNT(...) - -/// Returns an expression that evaluates the `COUNT` SQL function. +/// The `COUNT` SQL function. /// -/// // COUNT(email) -/// count(Column("email")) +/// For example: +/// +/// ```swift +/// // COUNT(email) +/// count(Column("email")) +/// ``` public func count(_ counted: some SQLSpecificExpressible) -> SQLExpression { .count(counted.sqlExpression) } - -// MARK: - COUNT(DISTINCT ...) - -/// Returns an expression that evaluates the `COUNT(DISTINCT)` SQL function. +/// The `COUNT(DISTINCT)` SQL function. /// -/// // COUNT(DISTINCT email) -/// count(distinct: Column("email")) +/// For example: +/// +/// ```swift +/// // COUNT(DISTINCT email) +/// count(distinct: Column("email")) +/// ``` public func count(distinct value: some SQLSpecificExpressible) -> SQLExpression { .countDistinct(value.sqlExpression) } - -// MARK: - IFNULL(...) - -/// Returns an expression that evaluates the `IFNULL` SQL function. -/// -/// // IFNULL(name, 'Anonymous') -/// Column("name") ?? "Anonymous" -public func ?? (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { - .function("IFNULL", [lhs.sqlExpression, rhs.sqlExpression]) +extension SQLSpecificExpressible { + /// The `IFNULL` SQL function. + /// + /// For example: + /// + /// ```swift + /// // IFNULL(name, 'Anonymous') + /// Column("name") ?? "Anonymous" + /// ``` + public static func ?? (lhs: Self, rhs: some SQLExpressible) -> SQLExpression { + .function("IFNULL", [lhs.sqlExpression, rhs.sqlExpression]) + } } - -// MARK: - LENGTH(...) - -/// Returns an expression that evaluates the `LENGTH` SQL function. +/// The `LENGTH` SQL function. /// -/// // LENGTH(name) -/// length(Column("name")) +/// For example: +/// +/// ```swift +/// // LENGTH(name) +/// length(Column("name")) +/// ``` public func length(_ value: some SQLSpecificExpressible) -> SQLExpression { .function("LENGTH", [value.sqlExpression]) } - -// MARK: - MAX(...) - -/// Returns an expression that evaluates the `MAX` SQL function. +/// The `MAX` SQL function. /// -/// // MAX(score) -/// max(Column("score")) +/// For example: +/// +/// ```swift +/// // MAX(score) +/// max(Column("score")) +/// ``` public func max(_ value: some SQLSpecificExpressible) -> SQLExpression { .aggregate("MAX", [value.sqlExpression]) } - -// MARK: - MIN(...) - -/// Returns an expression that evaluates the `MIN` SQL function. +/// The `MIN` SQL function. /// -/// // MIN(score) -/// min(Column("score")) +/// For example: +/// +/// ```swift +/// // MIN(score) +/// min(Column("score")) +/// ``` public func min(_ value: some SQLSpecificExpressible) -> SQLExpression { .aggregate("MIN", [value.sqlExpression]) } - -// MARK: - SUM(...) - -/// Returns an expression that evaluates the `SUM` SQL function. +/// The `SUM` SQL function. /// -/// See . +/// For example: /// -/// See also `total(_:)`. +/// ```swift +/// // SUM(amount) +/// sum(Column("amount")) +/// ``` /// -/// // SUM(amount) -/// sum(Column("amount")) +/// See also ``total(_:)``. +/// +/// Related SQLite documentation: . public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression { .aggregate("SUM", [value.sqlExpression]) } - -// MARK: - TOTAL(...) - -/// Returns an expression that evaluates the `TOTAL` SQL function. +/// The `TOTAL` SQL function. /// -/// See . +/// For example: /// -/// See also `sum(_:)`. +/// ```swift +/// // TOTAL(amount) +/// total(Column("amount")) +/// ``` /// -/// // TOTAL(amount) -/// total(Column("amount")) +/// See also ``sum(_:)``. +/// +/// Related SQLite documentation: . public func total(_ value: some SQLSpecificExpressible) -> SQLExpression { .aggregate("TOTAL", [value.sqlExpression]) } - // MARK: - String functions -/// :nodoc: extension SQLSpecificExpressible { - /// Returns an SQL expression that applies the Swift's built-in - /// capitalized String property. It is NULL for non-String arguments. + /// An SQL expression that calls the Foundation + /// `String.capitalized` property. /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn.capitalized) - /// let names = try String.fetchAll(dbQueue, request) // [String] + /// For example: + /// + /// ```swift + /// Column("name").capitalized + /// ``` public var capitalized: SQLExpression { DatabaseFunction.capitalize(sqlExpression) } - /// Returns an SQL expression that applies the Swift's built-in - /// lowercased String property. It is NULL for non-String arguments. + /// An SQL expression that calls the Swift + /// `String.lowercased()` method. /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn.lowercased()) - /// let names = try String.fetchAll(dbQueue, request) // [String] + /// For example: + /// + /// ```swift + /// Column("name").lowercased + /// ``` public var lowercased: SQLExpression { DatabaseFunction.lowercase(sqlExpression) } - /// Returns an SQL expression that applies the Swift's built-in - /// uppercased String property. It is NULL for non-String arguments. + /// An SQL expression that calls the Swift + /// `String.uppercased()` method. /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn.uppercased()) - /// let names = try String.fetchAll(dbQueue, request) // [String] + /// For example: + /// + /// ```swift + /// Column("name").uppercased + /// ``` public var uppercased: SQLExpression { DatabaseFunction.uppercase(sqlExpression) } } -/// :nodoc: extension SQLSpecificExpressible { - /// Returns an SQL expression that applies the Swift's built-in - /// localizedCapitalized String property. It is NULL for non-String arguments. + /// An SQL expression that calls the Foundation + /// `String.localizedCapitalized` property. /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn.localizedCapitalized) - /// let names = try String.fetchAll(dbQueue, request) // [String] + /// For example: + /// + /// ```swift + /// Column("name").localizedCapitalized + /// ``` public var localizedCapitalized: SQLExpression { DatabaseFunction.localizedCapitalize(sqlExpression) } - /// Returns an SQL expression that applies the Swift's built-in - /// localizedLowercased String property. It is NULL for non-String arguments. + /// An SQL expression that calls the Foundation + /// `String.localizedLowercase` property. /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn.localizedLowercased) - /// let names = try String.fetchAll(dbQueue, request) // [String] + /// For example: + /// + /// ```swift + /// Column("name").localizedLowercased + /// ``` public var localizedLowercased: SQLExpression { DatabaseFunction.localizedLowercase(sqlExpression) } - /// Returns an SQL expression that applies the Swift's built-in - /// localizedUppercased String property. It is NULL for non-String arguments. + /// An SQL expression that calls the Foundation + /// `String.localizedUppercase` property. /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn.localizedUppercased) - /// let names = try String.fetchAll(dbQueue, request) // [String] + /// For example: + /// + /// ```swift + /// Column("name").localizedUppercased + /// ``` public var localizedUppercased: SQLExpression { DatabaseFunction.localizedUppercase(sqlExpression) } @@ -186,10 +208,9 @@ extension SQLSpecificExpressible { // MARK: - Date functions -/// A date modifier for SQLite date functions such as `julianDay(_:_:)` and -/// `dateTime(_:_:)`. +/// A date modifier for SQLite date functions. /// -/// For more information, see +/// Related SQLite documentation: public enum SQLDateModifier: SQLSpecificExpressible { /// Adds the specified amount of seconds case second(Double) @@ -266,32 +287,38 @@ public enum SQLDateModifier: SQLSpecificExpressible { } } -// MARK: JULIANDAY(...) - -/// Returns an expression that evaluates the `JULIANDAY` SQL function. +/// The `JULIANDAY` SQL function. /// -/// // JULIANDAY(date) -/// julianDay(Column("date")) +/// For example: /// -/// // JULIANDAY(date, '1 days') -/// julianDay(Column("date"), .day(1)) +/// ```swift +/// // JULIANDAY(date) +/// julianDay(Column("date")) /// -/// For more information, see +/// // JULIANDAY(date, '1 days') +/// julianDay(Column("date"), .day(1)) +/// ``` +/// +/// Related SQLite documentation: public func julianDay(_ value: some SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression { .function("JULIANDAY", [value.sqlExpression] + modifiers.map(\.sqlExpression)) } // MARK: DATETIME(...) -/// Returns an expression that evaluates the `DATETIME` SQL function. +/// The `DATETIME` SQL function. /// -/// // DATETIME(date) -/// dateTime(Column("date")) +/// For example: /// -/// // DATETIME(date, '1 days') -/// dateTime(Column("date"), .day(1)) +/// ```swift +/// // DATETIME(date) +/// dateTime(Column("date")) /// -/// For more information, see +/// // DATETIME(date, '1 days') +/// dateTime(Column("date"), .day(1)) +/// ``` +/// +/// Related SQLite documentation: public func dateTime(_ value: some SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression { .function("DATETIME", [value.sqlExpression] + modifiers.map(\.sqlExpression)) } diff --git a/GRDB/QueryInterface/SQL/SQLOperators.swift b/GRDB/QueryInterface/SQL/SQLOperators.swift index e7baeafa2..bf7759f99 100644 --- a/GRDB/QueryInterface/SQL/SQLOperators.swift +++ b/GRDB/QueryInterface/SQL/SQLOperators.swift @@ -1,300 +1,248 @@ -// MARK: - Egality and Identity Operators (=, <>, IS, IS NOT) - -/// An SQL expression that compares two expressions with the `=` SQL operator. -/// -/// // name = 'Arthur' -/// Column("name") == "Arthur" -/// -/// When the right operand is nil, `IS NULL` is used instead. -/// -/// // name IS NULL -/// Column("name") == nil -public func == (lhs: some SQLSpecificExpressible, rhs: (any SQLExpressible)?) -> SQLExpression { - .equal(lhs.sqlExpression, rhs?.sqlExpression ?? .null) -} - -/// An SQL expression that checks the boolean value of an expression. -/// -/// The comparison is done with the built-in boolean evaluation of SQLite: -/// -/// // validated -/// Column("validated") == true -/// -/// // NOT validated -/// Column("validated") == false -public func == (lhs: some SQLSpecificExpressible, rhs: Bool) -> SQLExpression { - if rhs { - return lhs.sqlExpression.is(.true) - } else { - return lhs.sqlExpression.is(.false) +extension SQLSpecificExpressible { + // MARK: - Egality and Identity Operators (=, <>, IS, IS NOT) + + /// Compares two SQL expressions. + /// + /// For example: + /// + /// ```swift + /// // name = 'Arthur' + /// Column("name") == "Arthur" + /// ``` + /// + /// When the right operand is nil, `IS NULL` is used instead of the + /// `=` operator: + /// + /// ```swift + /// // name IS NULL + /// Column("name") == nil + /// ``` + public static func == (lhs: Self, rhs: (any SQLExpressible)?) -> SQLExpression { + .equal(lhs.sqlExpression, rhs?.sqlExpression ?? .null) } -} - -/// An SQL expression that compares two expressions with the `=` SQL operator. -/// -/// // 'Arthur' = name -/// "Arthur" == Column("name") -/// -/// When the left operand is nil, `IS NULL` is used instead. -/// -/// // name IS NULL -/// nil == Column("name") -public func == (lhs: (any SQLExpressible)?, rhs: some SQLSpecificExpressible) -> SQLExpression { - .equal(lhs?.sqlExpression ?? .null, rhs.sqlExpression) -} - -/// An SQL expression that checks the boolean value of an expression. -/// -/// The comparison is done with the built-in boolean evaluation of SQLite: -/// -/// // validated -/// true == Column("validated") -/// -/// // NOT validated -/// false == Column("validated") -public func == (lhs: Bool, rhs: some SQLSpecificExpressible) -> SQLExpression { - if lhs { - return rhs.sqlExpression.is(.true) - } else { - return rhs.sqlExpression.is(.false) + + /// The `=` SQL operator. + public static func == (lhs: Self, rhs: Bool) -> SQLExpression { + if rhs { + return lhs.sqlExpression.is(.true) + } else { + return lhs.sqlExpression.is(.false) + } } -} - -/// An SQL expression that compares two expressions with the `=` SQL operator. -/// -/// // email = login -/// Column("email") == Column("login") -public func == (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { - .equal(lhs.sqlExpression, rhs.sqlExpression) -} - -/// An SQL expression that compares two expressions with the `<>` SQL operator. -/// -/// // name <> 'Arthur' -/// Column("name") != "Arthur" -/// -/// When the right operand is nil, `IS NOT NULL` is used instead. -/// -/// // name IS NOT NULL -/// Column("name") != nil -public func != (lhs: some SQLSpecificExpressible, rhs: (any SQLExpressible)?) -> SQLExpression { - !(lhs == rhs) -} - -/// An SQL expression that checks the boolean value of an expression. -/// -/// The comparison is done with the built-in boolean evaluation of SQLite: -/// -/// // NOT validated -/// Column("validated") != true -/// -/// // validated -/// Column("validated") != false -public func != (lhs: some SQLSpecificExpressible, rhs: Bool) -> SQLExpression { - !(lhs == rhs) -} - -/// An SQL expression that compares two expressions with the `<>` SQL operator. -/// -/// // 'Arthur' <> name -/// "Arthur" != Column("name") -/// -/// When the left operand is nil, `IS NOT NULL` is used instead. -/// -/// // name IS NOT NULL -/// nil != Column("name") -public func != (lhs: (any SQLExpressible)?, rhs: some SQLSpecificExpressible) -> SQLExpression { - !(lhs == rhs) -} - -/// An SQL expression that checks the boolean value of an expression. -/// -/// The comparison is done with the built-in boolean evaluation of SQLite: -/// -/// // NOT validated -/// true != Column("validated") -/// -/// // validated -/// false != Column("validated") -public func != (lhs: Bool, rhs: some SQLSpecificExpressible) -> SQLExpression { - !(lhs == rhs) -} - -/// An SQL expression that compares two expressions with the `<>` SQL operator. -/// -/// // email <> login -/// Column("email") != Column("login") -public func != (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { - !(lhs == rhs) -} - -/// An SQL expression that compares two expressions with the `IS` SQL operator. -/// -/// // name IS 'Arthur' -/// Column("name") === "Arthur" -public func === (lhs: some SQLSpecificExpressible, rhs: (any SQLExpressible)?) -> SQLExpression { - .compare(.is, lhs.sqlExpression, rhs?.sqlExpression ?? .null) -} - -/// An SQL expression that compares two expressions with the `IS` SQL operator. -/// -/// // name IS 'Arthur' -/// "Arthur" === Column("name") -public func === (lhs: (any SQLExpressible)?, rhs: some SQLSpecificExpressible) -> SQLExpression { - if let lhs = lhs { - return .compare(.is, lhs.sqlExpression, rhs.sqlExpression) - } else { - return .compare(.is, rhs.sqlExpression, .null) + + /// Compares two SQL expressions. + /// + /// For example: + /// + /// ```swift + /// // 'Arthur' = name + /// "Arthur" == Column("name") + /// ``` + /// + /// When the left operand is nil, `IS NULL` is used instead of the + /// `=` operator: + /// + /// ```swift + /// // name IS NULL + /// nil == Column("name") + /// ``` + public static func == (lhs: (any SQLExpressible)?, rhs: Self) -> SQLExpression { + .equal(lhs?.sqlExpression ?? .null, rhs.sqlExpression) + } + + /// The `=` SQL operator. + public static func == (lhs: Bool, rhs: Self) -> SQLExpression { + if lhs { + return rhs.sqlExpression.is(.true) + } else { + return rhs.sqlExpression.is(.false) + } + } + + /// The `=` SQL operator. + public static func == (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { + .equal(lhs.sqlExpression, rhs.sqlExpression) + } + + /// Compares two SQL expressions. + /// + /// For example: + /// + /// ```swift + /// // name <> 'Arthur' + /// Column("name") != "Arthur" + /// ``` + /// + /// When the right operand is nil, `IS NOT NULL` is used instead of the + /// `<>` operator: + /// + /// ```swift + /// // name IS NOT NULL + /// Column("name") != nil + /// ``` + public static func != (lhs: Self, rhs: (any SQLExpressible)?) -> SQLExpression { + !(lhs == rhs) + } + + /// The `<>` SQL operator. + public static func != (lhs: Self, rhs: Bool) -> SQLExpression { + !(lhs == rhs) + } + + /// Compares two SQL expressions. + /// + /// For example: + /// + /// ```swift + /// // 'Arthur' <> name + /// "Arthur" != Column("name") + /// ``` + /// + /// When the left operand is nil, `IS NOT NULL` is used instead of the + /// `<>` operator: + /// + /// ```swift + /// // name IS NOT NULL + /// nil != Column("name") + /// ``` + public static func != (lhs: (any SQLExpressible)?, rhs: Self) -> SQLExpression { + !(lhs == rhs) + } + + /// The `<>` SQL operator. + public static func != (lhs: Bool, rhs: Self) -> SQLExpression { + !(lhs == rhs) + } + + /// The `<>` SQL operator. + public static func != (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { + !(lhs == rhs) + } + + /// The `IS` SQL operator. + public static func === (lhs: Self, rhs: (any SQLExpressible)?) -> SQLExpression { + .compare(.is, lhs.sqlExpression, rhs?.sqlExpression ?? .null) + } + + /// The `IS` SQL operator. + public static func === (lhs: (any SQLExpressible)?, rhs: Self) -> SQLExpression { + if let lhs = lhs { + return .compare(.is, lhs.sqlExpression, rhs.sqlExpression) + } else { + return .compare(.is, rhs.sqlExpression, .null) + } + } + + /// The `IS` SQL operator. + public static func === (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { + .compare(.is, lhs.sqlExpression, rhs.sqlExpression) + } + + /// The `IS NOT` SQL operator. + public static func !== (lhs: Self, rhs: (any SQLExpressible)?) -> SQLExpression { + !(lhs === rhs) + } + + /// The `IS NOT` SQL operator. + public static func !== (lhs: (any SQLExpressible)?, rhs: Self) -> SQLExpression { + !(lhs === rhs) + } + + /// The `IS NOT` SQL operator. + public static func !== (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { + !(lhs === rhs) + } + + // MARK: - Comparison Operators (<, >, <=, >=) + + /// The `<` SQL operator. + public static func < (lhs: Self, rhs: some SQLExpressible) -> SQLExpression { + .binary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) + } + + /// The `<` SQL operator. + public static func < (lhs: some SQLExpressible, rhs: Self) -> SQLExpression { + .binary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) + } + + /// The `<` SQL operator. + public static func < (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { + .binary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) + } + + /// The `<=` SQL operator. + public static func <= (lhs: Self, rhs: some SQLExpressible) -> SQLExpression { + .binary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) + } + + /// The `<=` SQL operator. + public static func <= (lhs: some SQLExpressible, rhs: Self) -> SQLExpression { + .binary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) + } + + /// The `<=` SQL operator. + public static func <= (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { + .binary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) + } + + /// The `>` SQL operator. + public static func > (lhs: Self, rhs: some SQLExpressible) -> SQLExpression { + .binary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) + } + + /// The `>` SQL operator. + public static func > (lhs: some SQLExpressible, rhs: Self) -> SQLExpression { + .binary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) + } + + /// The `>` SQL operator. + public static func > (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { + .binary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) + } + + /// The `>=` SQL operator. + public static func >= (lhs: Self, rhs: some SQLExpressible) -> SQLExpression { + .binary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) + } + + /// The `>=` SQL operator. + public static func >= (lhs: some SQLExpressible, rhs: Self) -> SQLExpression { + .binary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) + } + + /// The `>=` SQL operator. + public static func >= (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { + .binary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } -} - -/// An SQL expression that compares two expressions with the `IS` SQL operator. -/// -/// // email IS login -/// Column("email") === Column("login") -public func === (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { - .compare(.is, lhs.sqlExpression, rhs.sqlExpression) -} - -/// An SQL expression that compares two expressions with the `IS NOT` SQL operator. -/// -/// // name IS NOT 'Arthur' -/// Column("name") !== "Arthur" -public func !== (lhs: some SQLSpecificExpressible, rhs: (any SQLExpressible)?) -> SQLExpression { - !(lhs === rhs) -} - -/// An SQL expression that compares two expressions with the `IS NOT` SQL operator. -/// -/// // name IS NOT 'Arthur' -/// "Arthur" !== Column("name") -public func !== (lhs: (any SQLExpressible)?, rhs: some SQLSpecificExpressible) -> SQLExpression { - !(lhs === rhs) -} - -/// An SQL expression that compares two expressions with the `IS NOT` SQL operator. -/// -/// // email IS NOT login -/// Column("email") !== Column("login") -public func !== (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { - !(lhs === rhs) -} - -// MARK: - Comparison Operators (<, >, <=, >=) - -/// An SQL expression that compares two expressions with the `<` SQL operator. -/// -/// // score < 18 -/// Column("score") < 18 -public func < (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { - .binary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) -} - -/// An SQL expression that compares two expressions with the `<` SQL operator. -/// -/// // 18 < score -/// 18 < Column("score") -public func < (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { - .binary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) -} - -/// An SQL expression that compares two expressions with the `<` SQL operator. -/// -/// // width < height -/// Column("width") < Column("height") -public func < (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { - .binary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) -} - -/// An SQL expression that compares two expressions with the `<=` SQL operator. -/// -/// // score <= 18 -/// Column("score") <= 18 -public func <= (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { - .binary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) -} - -/// An SQL expression that compares two expressions with the `<=` SQL operator. -/// -/// // 18 <= score -/// 18 <= Column("score") -public func <= (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { - .binary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) -} - -/// An SQL expression that compares two expressions with the `<=` SQL operator. -/// -/// // width <= height -/// Column("width") <= Column("height") -public func <= (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { - .binary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) -} - -/// An SQL expression that compares two expressions with the `>` SQL operator. -/// -/// // score > 18 -/// Column("score") > 18 -public func > (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { - .binary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) -} - -/// An SQL expression that compares two expressions with the `>` SQL operator. -/// -/// // 18 > score -/// 18 > Column("score") -public func > (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { - .binary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) -} - -/// An SQL expression that compares two expressions with the `>` SQL operator. -/// -/// // width > height -/// Column("width") > Column("height") -public func > (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { - .binary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) -} - -/// An SQL expression that compares two expressions with the `>=` SQL operator. -/// -/// // score >= 18 -/// Column("score") >= 18 -public func >= (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { - .binary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) -} - -/// An SQL expression that compares two expressions with the `>=` SQL operator. -/// -/// // 18 >= score -/// 18 >= Column("score") -public func >= (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { - .binary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) -} - -/// An SQL expression that compares two expressions with the `>=` SQL operator. -/// -/// // width >= height -/// Column("width") >= Column("height") -public func >= (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { - .binary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } // MARK: - Inclusion Operators (BETWEEN, IN) extension Range where Bound: SQLExpressible { - /// An SQL expression that checks the inclusion of an expression in a range. + /// Returns an SQL expression that checks the inclusion of an expression in + /// a range. /// - /// // email >= 'A' AND email < 'B' - /// ("A"..<"B").contains(Column("email")) + /// For example: + /// + /// ```swift + /// // email >= 'A' AND email < 'B' + /// ("A"..<"B").contains(Column("email")) + /// ``` public func contains(_ element: some SQLSpecificExpressible) -> SQLExpression { (element >= lowerBound) && (element < upperBound) } } extension ClosedRange where Bound: SQLExpressible { - /// An SQL expression that checks the inclusion of an expression in a range. + /// Returns an SQL expression that checks the inclusion of an expression in + /// a range. /// - /// // email BETWEEN 'A' AND 'B' - /// ("A"..."B").contains(Column("email")) + /// For example: + /// + /// ```swift + /// // initial BETWEEN 'A' AND 'B' + /// ("A"..."B").contains(Column("initial")) + /// ``` public func contains(_ element: some SQLSpecificExpressible) -> SQLExpression { .between( expression: element.sqlExpression, @@ -304,20 +252,30 @@ extension ClosedRange where Bound: SQLExpressible { } extension CountableRange where Bound: SQLExpressible { - /// An SQL expression that checks the inclusion of an expression in a range. + /// Returns an SQL expression that checks the inclusion of an expression in + /// a range. /// - /// // id BETWEEN 1 AND 9 - /// (1..<10).contains(Column("id")) + /// For example: + /// + /// ```swift + /// // id >= 1 AND id < 10 + /// (1..<10).contains(Column("id")) + /// ``` public func contains(_ element: some SQLSpecificExpressible) -> SQLExpression { (element >= lowerBound) && (element < upperBound) } } extension CountableClosedRange where Bound: SQLExpressible { - /// An SQL expression that checks the inclusion of an expression in a range. + /// Returns an SQL expression that checks the inclusion of an expression in + /// a range. /// - /// // id BETWEEN 1 AND 10 - /// (1...10).contains(Column("id")) + /// For example: + /// + /// ```swift + /// // id BETWEEN 1 AND 10 + /// (1...10).contains(Column("id")) + /// ``` public func contains(_ element: some SQLSpecificExpressible) -> SQLExpression { .between( expression: element.sqlExpression, @@ -327,22 +285,30 @@ extension CountableClosedRange where Bound: SQLExpressible { } extension Sequence where Element: SQLExpressible { - /// An SQL expression that checks the inclusion of an expression in + /// Returns an SQL expression that checks the inclusion of an expression in /// a sequence. /// - /// // id IN (1,2,3) - /// [1, 2, 3].contains(Column("id")) + /// For example: + /// + /// ```swift + /// // id IN (1,2,3) + /// [1, 2, 3].contains(Column("id")) + /// ``` public func contains(_ element: some SQLSpecificExpressible) -> SQLExpression { SQLCollection.array(map(\.sqlExpression)).contains(element.sqlExpression) } } extension Sequence where Element == any SQLExpressible { - /// An SQL expression that checks the inclusion of an expression in + /// Returns an SQL expression that checks the inclusion of an expression in /// a sequence. /// - /// // id IN (1,2,3) - /// [1, 2, 3].contains(Column("id")) + /// For example: + /// + /// ```swift + /// // id IN (1,2,3) + /// [1, 2, 3].contains(Column("id")) + /// ``` public func contains(_ element: some SQLSpecificExpressible) -> SQLExpression { SQLCollection.array(map(\.sqlExpression)).contains(element.sqlExpression) } @@ -351,184 +317,139 @@ extension Sequence where Element == any SQLExpressible { // MARK: - Arithmetic Operators (+, -, *, /) -/// An SQL arithmetic multiplication. -/// -/// // width * 2 -/// Column("width") * 2 -public func * (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { - .associativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) -} - -/// An SQL arithmetic multiplication. -/// -/// // 2 * width -/// 2 * Column("width") -public func * (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { - .associativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) -} - -/// An SQL arithmetic multiplication. -/// -/// // width * height -/// Column("width") * Column("height") -public func * (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { - .associativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) -} - -/// An SQL arithmetic division. -/// -/// // width / 2 -/// Column("width") / 2 -public func / (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { - .binary(.divide, lhs.sqlExpression, rhs.sqlExpression) -} - -/// An SQL arithmetic division. -/// -/// // 2 / width -/// 2 / Column("width") -public func / (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { - .binary(.divide, lhs.sqlExpression, rhs.sqlExpression) -} - -/// An SQL arithmetic division. -/// -/// // width / height -/// Column("width") / Column("height") -public func / (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { - .binary(.divide, lhs.sqlExpression, rhs.sqlExpression) -} - -/// An SQL arithmetic addition. -/// -/// // width + 2 -/// Column("width") + 2 -public func + (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { - .associativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) -} - -/// An SQL arithmetic addition. -/// -/// // 2 + width -/// 2 + Column("width") -public func + (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { - .associativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) -} - -/// An SQL arithmetic addition. -/// -/// // width + height -/// Column("width") + Column("height") -public func + (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { - .associativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) -} - -/// A negated SQL arithmetic expression. -/// -/// // -width -/// -Column("width") -public prefix func - (value: some SQLSpecificExpressible) -> SQLExpression { - .unary(.minus, value.sqlExpression) -} - -/// An SQL arithmetic substraction. -/// -/// // width - 2 -/// Column("width") - 2 -public func - (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { - .binary(.subtract, lhs.sqlExpression, rhs.sqlExpression) -} - -/// An SQL arithmetic substraction. -/// -/// // 2 - width -/// 2 - Column("width") -public func - (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { - .binary(.subtract, lhs.sqlExpression, rhs.sqlExpression) -} - -/// An SQL arithmetic substraction. -/// -/// // width - height -/// Column("width") - Column("height") -public func - (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { - .binary(.subtract, lhs.sqlExpression, rhs.sqlExpression) -} - - -// MARK: - Logical Operators (AND, OR, NOT) - -/// A logical SQL expression with the `AND` SQL operator. -/// -/// // favorite AND 0 -/// Column("favorite") && false -public func && (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { - .associativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) -} - -/// A logical SQL expression with the `AND` SQL operator. -/// -/// // 0 AND favorite -/// false && Column("favorite") -public func && (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { - .associativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) -} - -/// A logical SQL expression with the `AND` SQL operator. -/// -/// // email IS NOT NULL AND favorite -/// Column("email") != nil && Column("favorite") -public func && (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { - .associativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) -} - -/// A logical SQL expression with the `OR` SQL operator. -/// -/// // favorite OR 1 -/// Column("favorite") || true -public func || (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { - .associativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) -} - -/// A logical SQL expression with the `OR` SQL operator. -/// -/// // 0 OR favorite -/// true || Column("favorite") -public func || (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { - .associativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) -} - -/// A logical SQL expression with the `OR` SQL operator. -/// -/// // email IS NULL OR hidden -/// Column("email") == nil || Column("hidden") -public func || (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { - .associativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) -} - -/// A negated logical SQL expression with the `NOT` SQL operator. -/// -/// // NOT hidden -/// !Column("hidden") -/// -/// Some expressions may be negated with specific SQL operators: -/// -/// // id NOT BETWEEN 1 AND 10 -/// !((1...10).contains(Column("id"))) -public prefix func ! (value: some SQLSpecificExpressible) -> SQLExpression { - value.sqlExpression.is(.falsey) +extension SQLSpecificExpressible { + /// The `*` SQL operator. + public static func * (lhs: Self, rhs: some SQLExpressible) -> SQLExpression { + .associativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) + } + + /// The `*` SQL operator. + public static func * (lhs: some SQLExpressible, rhs: Self) -> SQLExpression { + .associativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) + } + + /// The `*` SQL operator. + public static func * (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { + .associativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) + } + + /// The `/` SQL operator. + public static func / (lhs: Self, rhs: some SQLExpressible) -> SQLExpression { + .binary(.divide, lhs.sqlExpression, rhs.sqlExpression) + } + + /// The `/` SQL operator. + public static func / (lhs: some SQLExpressible, rhs: Self) -> SQLExpression { + .binary(.divide, lhs.sqlExpression, rhs.sqlExpression) + } + + /// The `/` SQL operator. + public static func / (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { + .binary(.divide, lhs.sqlExpression, rhs.sqlExpression) + } + + /// The `+` SQL operator. + public static func + (lhs: Self, rhs: some SQLExpressible) -> SQLExpression { + .associativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) + } + + /// The `+` SQL operator. + public static func + (lhs: some SQLExpressible, rhs: Self) -> SQLExpression { + .associativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) + } + + /// The `+` SQL operator. + public static func + (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { + .associativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) + } + + /// The `-` SQL operator. + public static prefix func - (value: Self) -> SQLExpression { + .unary(.minus, value.sqlExpression) + } + + /// The `-` SQL operator. + public static func - (lhs: Self, rhs: some SQLExpressible) -> SQLExpression { + .binary(.subtract, lhs.sqlExpression, rhs.sqlExpression) + } + + /// The `-` SQL operator. + public static func - (lhs: some SQLExpressible, rhs: Self) -> SQLExpression { + .binary(.subtract, lhs.sqlExpression, rhs.sqlExpression) + } + + /// The `-` SQL operator. + public static func - (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { + .binary(.subtract, lhs.sqlExpression, rhs.sqlExpression) + } + + + // MARK: - Logical Operators (AND, OR, NOT) + + /// The `AND` SQL operator. + public static func && (lhs: Self, rhs: some SQLExpressible) -> SQLExpression { + .associativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) + } + + /// The `AND` SQL operator. + public static func && (lhs: some SQLExpressible, rhs: Self) -> SQLExpression { + .associativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) + } + + /// The `AND` SQL operator. + public static func && (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { + .associativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) + } + + /// The `OR` SQL operator. + public static func || (lhs: Self, rhs: some SQLExpressible) -> SQLExpression { + .associativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) + } + + /// The `OR` SQL operator. + public static func || (lhs: some SQLExpressible, rhs: Self) -> SQLExpression { + .associativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) + } + + /// The `OR` SQL operator. + public static func || (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression { + .associativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) + } + + /// A negated logical SQL expression. + /// + /// For example: + /// + /// ```swift + /// // NOT isBlue + /// !Column("isBlue") + /// ``` + /// + /// Some expressions are negated with specific SQL operators: + /// + /// ```swift + /// // id NOT BETWEEN 1 AND 10 + /// !((1...10).contains(Column("id"))) + /// ``` + public static prefix func ! (value: Self) -> SQLExpression { + value.sqlExpression.is(.falsey) + } } // MARK: - Like Operator extension SQLSpecificExpressible { - /// An SQL expression with the `LIKE` SQL operator. + /// The `LIKE` SQL operator. /// - /// // email LIKE '%@example.com" - /// Column("email").like("%@example.com") + /// For example: /// - /// // title LIKE '%10\%%' ESCAPE '\' - /// Column("title").like("%10\\%%", escape: "\\") + /// ```swift + /// // email LIKE '%@example.com" + /// Column("email").like("%@example.com") + /// + /// // title LIKE '%10\%%' ESCAPE '\' + /// Column("title").like("%10\\%%", escape: "\\") + /// ``` public func like(_ pattern: some SQLExpressible, escape: (any SQLExpressible)? = nil) -> SQLExpression { .escapableBinary(.like, sqlExpression, pattern.sqlExpression, escape: escape?.sqlExpression) } diff --git a/GRDB/QueryInterface/SQL/SQLOrdering.swift b/GRDB/QueryInterface/SQL/SQLOrdering.swift index c7d61e574..e7b18f974 100644 --- a/GRDB/QueryInterface/SQL/SQLOrdering.swift +++ b/GRDB/QueryInterface/SQL/SQLOrdering.swift @@ -1,9 +1,17 @@ -/// The type that can be used as an SQL ordering term, as described at -/// +/// An SQL ordering term. /// -/// It is illegal for `SQLOrdering` to represent several ordering terms: +/// `SQLOrdering` is an opaque representation of an SQL ordering term. +/// You generally build `SQLOrdering` from other expressions. For example: /// -/// SQL("score DESC, name").sqlOrdering // illegal +/// ```swift +/// Column("score").desc +/// SQL("score DESC").sqlOrdering +/// ``` +/// +/// `SQLOrdering` is better used as the return type of a function. For +/// function arguments, prefer the ``SQLOrderingTerm`` protocol. +/// +/// Related SQLite documentation: public struct SQLOrdering { private var impl: Impl @@ -121,8 +129,15 @@ extension SQLOrdering { // MARK: - SQLOrderingTerm -/// The protocol for all types that can be used as an SQL ordering term, as -/// described at +/// A type that can be used as an SQL ordering term. +/// +/// Related SQLite documentation +/// +/// ## Topics +/// +/// ### Supporting Type +/// +/// - ``SQLOrdering`` public protocol SQLOrderingTerm { /// Returns an SQL ordering. var sqlOrdering: SQLOrdering { get } diff --git a/GRDB/QueryInterface/SQL/SQLSelection.swift b/GRDB/QueryInterface/SQL/SQLSelection.swift index d546e9682..aec58de09 100644 --- a/GRDB/QueryInterface/SQL/SQLSelection.swift +++ b/GRDB/QueryInterface/SQL/SQLSelection.swift @@ -1,8 +1,20 @@ -/// The type that can be selected, as described at -/// +/// An SQL result column. /// -/// It is legal for `SQLSelection` to represent several columns. The most basic -/// example of such a multi-column selection is the SQL `*`. +/// `SQLSelection` is an opaque representation of an SQL result column. +/// You generally build `SQLSelection` from other expressions. For example: +/// +/// ```swift +/// // Aliased expressions +/// (Column("score") + Column("bonus")).forKey("total") +/// +/// // Literal selection +/// SQL("IFNULL(name, \(defaultName)) AS name").sqlSelection +/// ``` +/// +/// `SQLSelection` is better used as the return type of a function. For +/// function arguments, prefer the ``SQLSelectable`` protocol. +/// +/// Related SQLite documentation: public struct SQLSelection { private var impl: Impl @@ -267,8 +279,16 @@ enum SQLCount { // MARK: - SQLSelectable -/// SQLSelectable is the protocol for types that can be selected, as -/// described at +/// A type that can be used as SQL result columns. +/// +/// Related SQLite documentation +/// +/// ## Topics +/// +/// ### Supporting Types +/// +/// - ``AllColumns`` +/// - ``SQLSelection`` public protocol SQLSelectable { /// Returns an SQL selection. var sqlSelection: SQLSelection { get } @@ -282,29 +302,22 @@ extension SQLSelection: SQLSelectable { // MARK: - AllColumns -/// AllColumns is the `*` in `SELECT *`. -/// -/// You use AllColumns in your custom implementation of -/// TableRecord.databaseSelection. +/// `AllColumns` is the `*` in `SELECT *`. /// /// For example: /// -/// struct Player : TableRecord { -/// static var databaseTableName = "player" -/// static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] -/// } -/// -/// // SELECT *, rowid FROM player -/// let request = Player.all() -public struct AllColumns: SQLSelectable { +/// ```swift +/// try dbQueue.read { db in +/// // SELECT * FROM player +/// let players = try Player.select(AllColumns()).fetchAll(db) +/// } +/// ``` +public struct AllColumns { /// The `*` selection. - /// - /// For example: - /// - /// // SELECT * FROM player - /// Player.select(AllColumns()) public init() { } - +} + +extension AllColumns: SQLSelectable { public var sqlSelection: SQLSelection { .allColumns } diff --git a/GRDB/QueryInterface/SQL/SQLSubquery.swift b/GRDB/QueryInterface/SQL/SQLSubquery.swift index 093b1812d..fb3d59584 100644 --- a/GRDB/QueryInterface/SQL/SQLSubquery.swift +++ b/GRDB/QueryInterface/SQL/SQLSubquery.swift @@ -1,4 +1,6 @@ -/// The type that can be embedded as a subquery. +/// An SQL subquery. +/// +/// `SQLSubquery` is an opaque representation of an SQL subquery. public struct SQLSubquery { private var impl: Impl @@ -85,7 +87,15 @@ extension SQLSubquery { // MARK: - SQLSubqueryable -/// The protocol for types that can be embedded as a subquery. +/// A type that can be used as SQL subquery. +/// +/// Related SQLite documentation +/// +/// ## Topics +/// +/// ### Supporting Types +/// +/// - ``SQLSubquery`` public protocol SQLSubqueryable: SQLSpecificExpressible { var sqlSubquery: SQLSubquery { get } } diff --git a/GRDB/QueryInterface/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift index 4fee7d2ab..6b5b578a6 100644 --- a/GRDB/QueryInterface/SQL/Table.swift +++ b/GRDB/QueryInterface/SQL/Table.swift @@ -1,33 +1,172 @@ -/// `Table` can build query interface requests. +/// A `Table` builds database queries with the Swift language instead of SQL. /// +/// ## Overview +/// +/// A `Table` instance is similar to a ``TableRecord`` type. You will use one +/// when the other is impractical or impossible to use. +/// +/// For example: +/// +/// ```swift +/// let table = Table("player") +/// try dbQueue.read { db in /// // SELECT * FROM player WHERE score >= 1000 -/// let table = Table("player") -/// let rows: [Row] = try dbQueue.read { db in -/// table.all() -/// .filter(Column("score") >= 1000) -/// .fetchAll(db) -/// } +/// let rows: [Row] = table.filter(Column("score") >= 1000).fetchAll(db) +/// } +/// ``` +/// +/// ## Topics +/// +/// ### Creating a Table +/// +/// - ``init(_:)-2iz5y`` +/// - ``init(_:)-3mfb8`` +/// +/// ### Instance Properties +/// +/// - ``tableName`` +/// +/// ### Counting Rows +/// +/// - ``fetchCount(_:)`` +/// +/// ### Testing for Row Existence +/// +/// - ``exists(_:id:)`` +/// - ``exists(_:key:)-4dk7e`` +/// - ``exists(_:key:)-36jtu`` +/// +/// ### Deleting Rows +/// +/// - ``deleteAll(_:)`` +/// - ``deleteAll(_:ids:)`` +/// - ``deleteAll(_:keys:)-5t865`` +/// - ``deleteAll(_:keys:)-28sff`` +/// - ``deleteOne(_:id:)`` +/// - ``deleteOne(_:key:)-404su`` +/// - ``deleteOne(_:key:)-64wmq`` +/// +/// ### Updating Rows +/// +/// - ``updateAll(_:onConflict:_:)-4w9b`` +/// - ``updateAll(_:onConflict:_:)-4cvap`` +/// +/// ### Building Query Interface Requests +/// +/// `Table` provide convenience access to most ``DerivableRequest`` and +/// ``QueryInterfaceRequest`` methods. +/// +/// - ``aliased(_:)`` +/// - ``all()`` +/// - ``annotated(with:)-6i101`` +/// - ``annotated(with:)-6x399`` +/// - ``annotated(with:)-4sbgw`` +/// - ``annotated(with:)-98t4p`` +/// - ``annotated(withOptional:)`` +/// - ``annotated(withRequired:)`` +/// - ``filter(_:)`` +/// - ``filter(id:)`` +/// - ``filter(ids:)`` +/// - ``filter(key:)-tw3i`` +/// - ``filter(key:)-4sun7`` +/// - ``filter(keys:)-85e0v`` +/// - ``filter(keys:)-qqgf`` +/// - ``filter(literal:)`` +/// - ``filter(sql:arguments:)`` +/// - ``having(_:)`` +/// - ``including(all:)`` +/// - ``including(optional:)`` +/// - ``including(required:)`` +/// - ``joining(optional:)`` +/// - ``joining(required:)`` +/// - ``limit(_:offset:)`` +/// - ``none()`` +/// - ``order(_:)-2gvi7`` +/// - ``order(_:)-9o5bb`` +/// - ``order(literal:)`` +/// - ``order(sql:arguments:)`` +/// - ``orderByPrimaryKey()`` +/// - ``select(_:)-1599q`` +/// - ``select(_:)-2cnd1`` +/// - ``select(_:as:)-20ci9`` +/// - ``select(_:as:)-3pr6x`` +/// - ``select(literal:)`` +/// - ``select(literal:as:)`` +/// - ``select(sql:arguments:)`` +/// - ``select(sql:arguments:as:)`` +/// - ``selectPrimaryKey(as:)`` +/// - ``with(_:)`` +/// +/// ### Defining Associations +/// +/// - ``association(to:)`` +/// - ``association(to:on:)`` +/// - ``belongsTo(_:key:using:)-8p5xr`` +/// - ``belongsTo(_:key:using:)-117wr`` +/// - ``hasMany(_:key:using:)-3i6yk`` +/// - ``hasMany(_:key:using:)-57dwf`` +/// - ``hasMany(_:through:using:key:)`` +/// - ``hasOne(_:key:using:)-81vqy`` +/// - ``hasOne(_:key:using:)-3438j`` +/// - ``hasOne(_:through:using:key:)`` +/// +/// ### Fetching Database Rows +/// +/// - ``fetchCursor(_:)-1oqex`` +/// - ``fetchAll(_:)-4s7yn`` +/// - ``fetchSet(_:)-5lp4s`` +/// - ``fetchOne(_:)-3bduz`` +/// +/// ### Fetching Database Values +/// +/// - ``fetchCursor(_:)-65lci`` +/// - ``fetchCursor(_:)-295uw`` +/// - ``fetchAll(_:)-6xr01`` +/// - ``fetchAll(_:)-7tjdp`` +/// - ``fetchSet(_:)-3mchk`` +/// - ``fetchSet(_:)-8k2uk`` +/// - ``fetchOne(_:)-infc`` +/// - ``fetchOne(_:)-71icb`` +/// +/// ### Fetching Records +/// +/// - ``fetchCursor(_:)-81wuu`` +/// - ``fetchAll(_:)-3l7ol`` +/// - ``fetchSet(_:)-ko77`` +/// - ``fetchOne(_:)-8n1q`` +/// +/// ### Database Observation Support +/// +/// - ``databaseRegion(_:)`` public struct Table { - /// The table name + /// The table name. public var tableName: String private init(_ tableName: String, _ type: RowDecoder.Type) { self.tableName = tableName } - /// Create a `Table` + /// Creates a `Table`. /// - /// let table = Table("player") - /// let table = Table("player") + /// For example: + /// + /// ```swift + /// let table = Table("player") + /// let table = Table("player") + /// ``` public init(_ tableName: String) { self.init(tableName, RowDecoder.self) } } extension Table where RowDecoder == Row { - /// Create a `Table` of `Row`. + /// Create a `Table`. /// - /// let table = Table("player") // Table + /// For example: + /// + /// ```swift + /// let table = Table("player") // Table + /// ``` public init(_ tableName: String) { self.init(tableName, Row.self) } @@ -46,49 +185,73 @@ extension Table { .all(fromTable: tableName) } - /// Creates a request for all rows of the table. + /// Returns a request for all rows of the table. /// - /// // Fetch all players - /// let table = Table("player") - /// let request = table.all() - /// let players: [Player] = try request.fetchAll(db) + /// ```swift + /// // Fetch all players + /// let table = Table("player") + /// let request = table.all() + /// let players: [Player] = try request.fetchAll(db) + /// ``` public func all() -> QueryInterfaceRequest { QueryInterfaceRequest(relation: relationForAll) } - /// Creates a request which fetches no row. + /// Returns an empty request that fetches no row. /// - /// // Fetch no players - /// let table = Table("player") - /// let request = table.none() - /// let players: [Player] = try request.fetchAll(db) // Empty array + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let request = Table("player").none() + /// let rows = try request.fetchAll(db) // empty array + /// } public func none() -> QueryInterfaceRequest { all().none() // don't laugh } - /// Creates a request which selects *selection*. + /// Returns a request that selects the provided result columns. /// - /// // SELECT id, email FROM player - /// let table = Table("player") - /// let request = table.select(Column("id"), Column("email")) + /// For example: + /// + /// ```swift + /// let playerTable = Table("player") + /// + /// // SELECT id, score FROM player + /// let request = playerTable.select(Column("id"), Column("score")) + /// ``` public func select(_ selection: any SQLSelectable...) -> QueryInterfaceRequest { all().select(selection) } - /// Creates a request which selects *selection*. + /// Returns a request that selects the provided result columns. /// - /// // SELECT id, email FROM player - /// let table = Table("player") - /// let request = table.select([Column("id"), Column("email")]) + /// For example: + /// + /// ```swift + /// let playerTable = Table("player") + /// + /// // SELECT id, score FROM player + /// let request = playerTable.select([Column("id"), Column("score")]) + /// ``` public func select(_ selection: [any SQLSelectable]) -> QueryInterfaceRequest { all().select(selection) } - /// Creates a request which selects *sql*. + /// Returns a request that selects the provided SQL string. /// - /// // SELECT id, email FROM player - /// let table = Table("player") - /// let request = table.select(sql: "id, email") + /// For example: + /// + /// ```swift + /// let playerTable = Table("player") + /// + /// // SELECT id, name FROM player + /// let request = playerTable.select(sql: "id, name") + /// + /// // SELECT id, IFNULL(name, 'Anonymous') FROM player + /// let defaultName = "Anonymous" + /// let request = playerTable.select(sql: "id, IFNULL(name, ?)", arguments: [defaultName]) + /// ``` public func select( sql: String, arguments: StatementArguments = StatementArguments()) @@ -97,30 +260,44 @@ extension Table { all().select(SQL(sql: sql, arguments: arguments)) } - /// Creates a request which selects an SQL *literal*. + /// Returns a request that selects the provided ``SQL`` literal. /// - /// Literals allow you to safely embed raw values in your SQL, without any - /// risk of syntax errors or SQL injection: + /// ``SQL`` literals allow you to safely embed raw values in your SQL, + /// without any risk of syntax errors or SQL injection: /// - /// // SELECT id, email, score + 1000 FROM player - /// let table = Table("player") - /// let bonus = 1000 - /// let request = table.select(literal: """ - /// id, email, score + \(bonus) - /// """) + /// ```swift + /// let playerTable = Table("player") + /// + /// // SELECT id, IFNULL(name, 'Anonymous') FROM player + /// let defaultName = "Anonymous" + /// let request = playerTable.select(literal: "id, IFNULL(name, \(defaultName))") + /// ``` public func select(literal sqlLiteral: SQL) -> QueryInterfaceRequest { all().select(sqlLiteral) } - /// Creates a request which selects *selection*, and fetches values of - /// type *type*. + /// Returns a request that selects the provided result columns, and defines + /// the type of decoded rows. /// - /// try dbQueue.read { db in - /// // SELECT max(score) FROM player - /// let table = Table("player") - /// let request = table.select([max(Column("score"))], as: Int.self) - /// let maxScore: Int? = try request.fetchOne(db) - /// } + /// For example: + /// + /// ```swift + /// let playerTable = Table("player") + /// + /// let minScore = min(Column("score")) + /// let maxScore = max(Column("score")) + /// + /// // SELECT MAX(score) FROM player + /// let request = playerTable.select([maxScore], as: Int.self) + /// let maxScore = try request.fetchOne(db) // Int? + /// + /// // SELECT MIN(score), MAX(score) FROM player + /// let request = playerTable.select([minScore, maxScore], as: Row.self) + /// if let row = try request.fetchOne(db) { + /// let minScore: Int = row[0] + /// let maxScore: Int = row[1] + /// } + /// ``` public func select( _ selection: [any SQLSelectable], as type: RowDecoder.Type = RowDecoder.self) @@ -129,15 +306,28 @@ extension Table { all().select(selection, as: type) } - /// Creates a request which selects *selection*, and fetches values of - /// type *type*. + /// Returns a request that selects the provided result columns, and defines + /// the type of decoded rows. /// - /// try dbQueue.read { db in - /// // SELECT max(score) FROM player - /// let table = Table("player") - /// let request = table.select(max(Column("score")), as: Int.self) - /// let maxScore: Int? = try request.fetchOne(db) - /// } + /// For example: + /// + /// ```swift + /// let playerTable = Table("player") + /// + /// let minScore = min(Column("score")) + /// let maxScore = max(Column("score")) + /// + /// // SELECT MAX(score) FROM player + /// let request = playerTable.select(maxScore, as: Int.self) + /// let maxScore = try request.fetchOne(db) // Int? + /// + /// // SELECT MIN(score), MAX(score) FROM player + /// let request = playerTable.select(minScore, maxScore, as: Row.self) + /// if let row = try request.fetchOne(db) { + /// let minScore: Int = row[0] + /// let maxScore: Int = row[1] + /// } + /// ``` public func select( _ selection: any SQLSelectable..., as type: RowDecoder.Type = RowDecoder.self) @@ -146,15 +336,23 @@ extension Table { all().select(selection, as: type) } - /// Creates a request which selects *sql*, and fetches values of - /// type *type*. + /// Returns a request that selects the provided SQL string, and defines the + /// type of decoded rows. /// - /// try dbQueue.read { db in - /// // SELECT max(score) FROM player - /// let table = Table("player") - /// let request = table.select(sql: "max(score)", as: Int.self) - /// let maxScore: Int? = try request.fetchOne(db) - /// } + /// For example: + /// + /// ```swift + /// let playerTable = Table("player") + /// + /// // SELECT name FROM player + /// let request = playerTable.select(sql: "name", as: String.self) + /// let names = try request.fetchAll(db) // [String] + /// + /// // SELECT IFNULL(name, 'Anonymous') FROM player + /// let defaultName = "Anonymous" + /// let request = playerTable.select(sql: "IFNULL(name, ?)", arguments: [defaultName], as: String.self) + /// let names = try request.fetchAll(db) // [String] + /// ``` public func select( sql: String, arguments: StatementArguments = StatementArguments(), @@ -164,19 +362,20 @@ extension Table { all().select(SQL(sql: sql, arguments: arguments), as: type) } - /// Creates a request which selects an SQL *literal*, and fetches values of - /// type *type*. + /// Returns a request that selects the provided ``SQL`` literal, and defines + /// the type of decoded rows. /// - /// Literals allow you to safely embed raw values in your SQL, without any - /// risk of syntax errors or SQL injection: + /// ``SQL`` literals allow you to safely embed raw values in your SQL, + /// without any risk of syntax errors or SQL injection: /// - /// // SELECT IFNULL(name, 'Anonymous') FROM player - /// let table = Table("player") - /// let defaultName = "Anonymous" - /// let request = table.select( - /// literal: "IFNULL(name, \(defaultName))", - /// as: String.self) - /// let name: String? = try request.fetchOne(db) + /// ```swift + /// let playerTable = Table("player") + /// + /// // SELECT IFNULL(name, 'Anonymous') FROM player + /// let defaultName = "Anonymous" + /// let request = playerTable.select(literal: "IFNULL(name, \(defaultName))", as: String.self) + /// let names = try request.fetchAll(db) // [String] + /// ``` public func select( literal sqlLiteral: SQL, as type: RowDecoder.Type = RowDecoder.self) @@ -185,51 +384,129 @@ extension Table { all().select(sqlLiteral, as: type) } - /// Creates a request which appends *selection*. + /// Returns a request that selects the primary key. /// - /// // SELECT id, email, name FROM player - /// let table = Table("player") - /// let request = table - /// .select([Column("id"), Column("email")]) - /// .annotated(with: [Column("name")]) + /// All primary keys are supported: + /// + /// ```swift + /// let playerTable = Table("player") + /// let countryTable = Table("country") + /// let citizenshipTable = Table("citizenship") + /// + /// // SELECT id FROM player WHERE ... + /// let request = try playerTable.selectPrimaryKey(as: Int64.self) + /// let ids = try request.fetchAll(db) // [Int64] + /// + /// // SELECT code FROM country WHERE ... + /// let request = try countryTable.selectPrimaryKey(as: String.self) + /// let countryCodes = try request.fetchAll(db) // [String] + /// + /// // SELECT citizenId, countryCode FROM citizenship WHERE ... + /// let request = try citizenshipTable.selectPrimaryKey(as: Row.self) + /// let rows = try request.fetchAll(db) // [Row] + /// ``` + /// + /// For composite primary keys, you can define a ``FetchableRecord`` type: + /// + /// ```swift + /// extension Citizenship { + /// struct ID: Decodable, FetchableRecord { + /// var citizenId: Int64 + /// var countryCode: String + /// } + /// } + /// let request = try citizenshipTable.selectPrimaryKey(as: Citizenship.ID.self) + /// let ids = try request.fetchAll(db) // [Citizenship.ID] + /// ``` + public func selectPrimaryKey(as type: PrimaryKey.Type = PrimaryKey.self) + -> QueryInterfaceRequest + { + all().selectPrimaryKey(as: type) + } + + /// Returns a request with the provided result columns appended to the + /// table columns. + /// + /// For example: + /// + /// ```swift + /// let playerTable = Table("player") + /// + /// // SELECT *, score + bonus AS totalScore FROM player + /// let totalScore = (Column("score") + Column("bonus")).forKey("totalScore") + /// let request = playerTable.annotated(with: [totalScore]) + /// ``` public func annotated(with selection: [any SQLSelectable]) -> QueryInterfaceRequest { all().annotated(with: selection) } - /// Creates a request which appends *selection*. + /// Returns a request with the provided result columns appended to the + /// table columns. /// - /// // SELECT id, email, name FROM player - /// let table = Table("player") - /// let request = table - /// .select([Column("id"), Column("email")]) - /// .annotated(with: Column("name")) + /// For example: + /// + /// ```swift + /// let playerTable = Table("player") + /// + /// // SELECT *, score + bonus AS totalScore FROM player + /// let totalScore = (Column("score") + Column("bonus")).forKey("totalScore") + /// let request = playerTable.annotated(with: totalScore) + /// ``` public func annotated(with selection: any SQLSelectable...) -> QueryInterfaceRequest { all().annotated(with: selection) } - /// Creates a request with the provided *predicate*. + /// Returns a request filtered with a boolean SQL expression. /// - /// // SELECT * FROM player WHERE email = 'arthur@example.com' - /// let table = Table("player") - /// let request = table.filter(Column("email") == "arthur@example.com") + /// For example: + /// + /// ```swift + /// let playerTable = Table("player") + /// + /// // SELECT * FROM player WHERE name = 'O''Brien' + /// let name = "O'Brien" + /// let request = playerTable.filter(Column("name") == name) + /// ``` public func filter(_ predicate: some SQLSpecificExpressible) -> QueryInterfaceRequest { all().filter(predicate) } - /// Creates a request with the provided primary key *predicate*. + /// Returns a request filtered by primary key. /// - /// // SELECT * FROM player WHERE id = 1 - /// let table = Table("player") - /// let request = table.filter(key: 1) + /// All single-column primary keys are supported: + /// + /// ```swift + /// let playerTable = Table("player") + /// let countryTable = Table("country") + /// + /// // SELECT * FROM player WHERE id = 1 + /// let request = playerTable.filter(key: 1) + /// + /// // SELECT * FROM country WHERE code = 'FR' + /// let request = countryTable.filter(key: "FR") + /// ``` + /// + /// - parameter key: A primary key public func filter(key: some DatabaseValueConvertible) -> QueryInterfaceRequest { all().filter(key: key) } - /// Creates a request with the provided primary key *predicate*. + /// Returns a request filtered by primary key. /// - /// // SELECT * FROM player WHERE id IN (1, 2, 3) - /// let table = Table("player") - /// let request = table.filter(keys: [1, 2, 3]) + /// All single-column primary keys are supported: + /// + /// ```swift + /// let playerTable = Table("player") + /// let countryTable = Table("country") + /// + /// // SELECT * FROM player WHERE id = IN (1, 2, 3) + /// let request = playerTable.filter(keys: [1, 2, 3]) + /// + /// // SELECT * FROM country WHERE code = IN ('FR', 'US') + /// let request = countryTable.filter(keys: ["FR", "US"]) + /// ``` + /// + /// - parameter keys: A collection of primary keys public func filter(keys: Keys) -> QueryInterfaceRequest where Keys: Sequence, Keys.Element: DatabaseValueConvertible @@ -237,35 +514,74 @@ extension Table { all().filter(keys: keys) } - /// Creates a request with the provided primary key *predicate*. + /// Returns a request filtered by primary or unique key. /// - /// // SELECT * FROM passport WHERE personId = 1 AND countryCode = 'FR' - /// let table = Table("passport") - /// let request = table.filter(key: ["personId": 1, "countryCode": "FR"]) + /// For example: /// - /// When executed, this request raises a fatal error if there is no unique - /// index on the key columns. + /// ```swift + /// let playerTable = Table("player") + /// let citizenshipTable = Table("citizenship") + /// + /// // SELECT * FROM player WHERE id = 1 + /// let request = playerTable.filter(key: ["id": 1]) + /// + /// // SELECT * FROM player WHERE email = 'arthur@example.com' + /// let request = playerTable.filter(key: ["email": "arthur@example.com"]) + /// + /// // SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR' + /// let request = citizenshipTable.filter(key: [ + /// "citizenId": 1, + /// "countryCode": "FR", + /// ]) + /// ``` + /// + /// When executed, this request raises a fatal error if no unique index + /// exists on a subset of the key columns. + /// + /// - parameter key: A unique key. public func filter(key: [String: (any DatabaseValueConvertible)?]?) -> QueryInterfaceRequest { all().filter(key: key) } - /// Creates a request with the provided primary key *predicate*. + /// Returns a request filtered by primary or unique key. /// - /// // SELECT * FROM passport WHERE (personId = 1 AND countryCode = 'FR') OR ... - /// let table = Table("passport") - /// let request = table.filter(keys: [["personId": 1, "countryCode": "FR"], ...]) + /// For example: /// - /// When executed, this request raises a fatal error if there is no unique - /// index on the key columns. + /// ```swift + /// let playerTable = Table("player") + /// let citizenshipTable = Table("citizenship") + /// + /// // SELECT * FROM player WHERE id = 1 + /// let request = playerTable.filter(keys: [["id": 1]]) + /// + /// // SELECT * FROM player WHERE email = 'arthur@example.com' + /// let request = playerTable.filter(keys: [["email": "arthur@example.com"]]) + /// + /// // SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR' + /// let request = citizenshipTable.filter(keys: [ + /// ["citizenId": 1, "countryCode": "FR"], + /// ]) + /// ``` + /// + /// When executed, this request raises a fatal error if no unique index + /// exists on a subset of the key columns. + /// + /// - parameter keys: A collection of unique keys public func filter(keys: [[String: (any DatabaseValueConvertible)?]]) -> QueryInterfaceRequest { all().filter(keys: keys) } - /// Creates a request with the provided *predicate*. + /// Returns a request filtered with an SQL string. /// - /// // SELECT * FROM player WHERE email = 'arthur@example.com' - /// let table = Table("player") - /// let request = table.filter(sql: "email = ?", arguments: ["arthur@example.com"]) + /// For example: + /// + /// ```swift + /// let playerTable = Table("player") + /// + /// // SELECT * FROM player WHERE name = 'O''Brien' + /// let name = "O'Brien" + /// let request = playerTable.filter(sql: "name = ?", arguments: [name]) + /// ``` public func filter( sql: String, arguments: StatementArguments = StatementArguments()) @@ -274,57 +590,82 @@ extension Table { filter(SQL(sql: sql, arguments: arguments)) } - /// Creates a request with the provided *predicate* added to the - /// eventual set of already applied predicates. + /// Returns a request filtered with an ``SQL`` literal. /// - /// Literals allow you to safely embed raw values in your SQL, without any - /// risk of syntax errors or SQL injection: + /// ``SQL`` literals allow you to safely embed raw values in your SQL, + /// without any risk of syntax errors or SQL injection: /// - /// // SELECT * FROM player WHERE name = 'O''Brien' - /// let table = Table("player") - /// let name = "O'Brien" - /// let request = table.filter(literal: "email = \(email)") + /// ```swift + /// let playerTable = Table("player") + /// + /// // SELECT * FROM player WHERE name = 'O''Brien' + /// let name = "O'Brien" + /// let request = playerTable.filter(literal: "name = \(name)") + /// ``` public func filter(literal sqlLiteral: SQL) -> QueryInterfaceRequest { all().filter(sqlLiteral) } - /// Creates a request sorted according to the - /// provided *orderings*. + /// Returns a request sorted according to the given SQL ordering terms. /// - /// // SELECT * FROM player ORDER BY name - /// let table = Table("player") - /// let request = table.order(Column("name")) + /// For example: + /// + /// ```swift + /// let playerTable = Table("player") + /// + /// // SELECT * FROM player ORDER BY score DESC, name + /// let request = playerTable.order(Column("score").desc, Column("name")) + /// ``` public func order(_ orderings: any SQLOrderingTerm...) -> QueryInterfaceRequest { all().order(orderings) } - /// Creates a request sorted according to the - /// provided *orderings*. + /// Returns a request sorted according to the given SQL ordering terms. /// - /// // SELECT * FROM player ORDER BY name - /// let table = Table("player") - /// let request = table.order([Column("name")]) + /// For example: + /// + /// ```swift + /// let playerTable = Table("player") + /// + /// // SELECT * FROM player ORDER BY score DESC, name + /// let request = playerTable.order([Column("score").desc, Column("name")]) + /// ``` public func order(_ orderings: [any SQLOrderingTerm]) -> QueryInterfaceRequest { all().order(orderings) } - /// Creates a request sorted by primary key. + /// Returns a request sorted by primary key. /// - /// // SELECT * FROM player ORDER BY id - /// let table = Table("player") - /// let request = table.orderByPrimaryKey() + /// All primary keys are supported: /// - /// // SELECT * FROM country ORDER BY code - /// let request = Country.orderByPrimaryKey() + /// ```swift + /// let playerTable = Table("player") + /// let countryTable = Table("country") + /// let citizenshipTable = Table("citizenship") + /// + /// // SELECT * FROM player ORDER BY id + /// let request = playerTable.orderByPrimaryKey() + /// + /// // SELECT * FROM country ORDER BY code + /// let request = countryTable.orderByPrimaryKey() + /// + /// // SELECT * FROM citizenship ORDER BY citizenId, countryCode + /// let request = citizenshipTable.orderByPrimaryKey() + /// ``` public func orderByPrimaryKey() -> QueryInterfaceRequest { all().orderByPrimaryKey() } - /// Creates a request sorted according to *sql*. + /// Returns a request sorted according to the given SQL string. /// - /// // SELECT * FROM player ORDER BY name - /// let table = Table("player") - /// let request = table.order(sql: "name") + /// For example: + /// + /// ```swift + /// let playerTable = Table("player") + /// + /// // SELECT * FROM player ORDER BY score DESC, name + /// let request = playerTable.order(sql: "score DESC, name") + /// ``` public func order( sql: String, arguments: StatementArguments = StatementArguments()) @@ -333,39 +674,50 @@ extension Table { all().order(SQL(sql: sql, arguments: arguments)) } - /// Creates a request sorted according to an SQL *literal*. + /// Returns a request sorted according to the given ``SQL`` literal. /// - /// // SELECT * FROM player ORDER BY name - /// let table = Table("player") - /// let request = table.order(literal: "name") + /// For example: + /// + /// ```swift + /// let playerTable = Table("player") + /// + /// // SELECT * FROM player ORDER BY score DESC, name + /// let request = playerTable.order(literal: "score DESC, name") + /// ``` public func order(literal sqlLiteral: SQL) -> QueryInterfaceRequest { all().order(sqlLiteral) } - /// Creates a request which fetches *limit* rows, starting at - /// *offset*. + /// Returns a limited request. /// - /// // SELECT * FROM player LIMIT 1 - /// let table = Table("player") - /// let request = table.limit(1) + /// The returned request fetches `limit` rows, starting at `offset`. For + /// example: + /// + /// ```swift + /// let playerTable = Table("player") + /// + /// // SELECT * FROM player LIMIT 10 + /// let request = playerTable.limit(10) + /// + /// // SELECT * FROM player LIMIT 10 OFFSET 20 + /// let request = playerTable.limit(10, offset: 20) + /// ``` public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { all().limit(limit, offset: offset) } - /// Creates a request that allows you to define expressions that target - /// a specific database table. + /// Returns a request that can be referred to with the provided alias. /// - /// See `TableRecord.aliased(_:)` for more information. + /// `table.aliased(alias)` is equivalent to `table.all().aliased(alias)`. + /// See ``TableRequest/aliased(_:)`` for more information. public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { all().aliased(alias) } - /// Returns a request which embeds the common table expression. + /// Returns a request that embeds a common table expression. /// - /// See `TableRecord.with(_:)` for more information. - /// - /// - parameter cte: A common table expression. - /// - returns: A request. + /// `table.with(cte)` is equivalent to `table.all().with(cte)`. + /// See ``DerivableRequest/with(_:)`` for more information. public func with(_ cte: CommonTableExpression) -> QueryInterfaceRequest { all().with(cte) } @@ -373,22 +725,54 @@ extension Table { @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible { - /// Creates a request filtered by primary key. + /// Returns a request filtered by primary key. /// - /// // SELECT * FROM player WHERE id = 1 - /// let table = Table("player") - /// let request = table.filter(id: 1) + /// All single-column primary keys are supported: + /// + /// ```swift + /// struct Player: Identifiable { + /// var id: Int64 + /// } + /// struct Country: Identifiable { + /// var id: String + /// } + /// + /// let playerTable = Table("player") + /// let countryTable = Table("country") + /// + /// // SELECT * FROM player WHERE id = 1 + /// let request = playerTable.filter(id: 1) + /// + /// // SELECT * FROM country WHERE code = 'FR' + /// let request = countryTable.filter(id: "FR") + /// ``` /// /// - parameter id: A primary key public func filter(id: RowDecoder.ID) -> QueryInterfaceRequest { all().filter(id: id) } - - /// Creates a request filtered by primary key. + + /// Returns a request filtered by primary key. /// - /// // SELECT * FROM player WHERE id IN (1, 2, 3) - /// let table = Table("player") - /// let request = table.filter(ids: [1, 2, 3]) + /// All single-column primary keys are supported: + /// + /// ```swift + /// struct Player: Identifiable { + /// var id: Int64 + /// } + /// struct Country: Identifiable { + /// var id: String + /// } + /// + /// let playerTable = Table("player") + /// let countryTable = Table("country") + /// + /// // SELECT * FROM player WHERE id = IN (1, 2, 3) + /// let request = playerTable.filter(ids: [1, 2, 3]) + /// + /// // SELECT * FROM country WHERE code = IN ('FR', 'US') + /// let request = countryTable.filter(ids: ["FR", "US"]) + /// ``` /// /// - parameter ids: A collection of primary keys public func filter(ids: IDS) -> QueryInterfaceRequest @@ -399,33 +783,21 @@ extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConv } extension Table { - /// Creates a request which selects the primary key. - /// - /// All primary keys are supported: - /// - /// // SELECT id FROM player - /// let table = Table("player") - /// let request = try table.selectPrimaryKey(as: Int64.self) - /// - /// // SELECT code FROM country - /// let table = Table("country") - /// let request = try table.selectPrimaryKey(as: String.self) - /// - /// // SELECT citizenId, countryCode FROM citizenship - /// let table = Table("citizenship") - /// let request = try table.selectPrimaryKey(as: Row.self) - public func selectPrimaryKey(as type: PrimaryKey.Type = PrimaryKey.self) - -> QueryInterfaceRequest - { - all().selectPrimaryKey(as: type) - } -} -extension Table { - // MARK: - Counting All - - /// The number of rows. + + /// Returns the number of rows in the database table. + /// + /// For example: + /// + /// ```swift + /// let playerTable = Table("player") + /// + /// try dbQueue.read { db in + /// // SELECT COUNT(*) FROM player + /// let count = try playerTable.fetchCount(db) + /// } + /// ``` /// /// - parameter db: A database connection. public func fetchCount(_ db: Database) throws -> Int { @@ -436,63 +808,100 @@ extension Table { // MARK: - Fetching Records from Table extension Table where RowDecoder: FetchableRecord { - /// A cursor over all records fetched from the database. + /// Returns a cursor over all records fetched from the database. /// + /// For example: + /// + /// ```swift + /// struct Player: FetchableRecord { } + /// let playerTable = Table("player") + /// + /// try dbQueue.read { db in /// // SELECT * FROM player - /// let table = Table("player") - /// let players = try table.fetchCursor(db) // Cursor of Player - /// while let player = try players.next() { // Player - /// ... + /// let players = try playerTable.fetchCursor(db) + /// while let player = try players.next() { + /// print(player.name) /// } + /// } + /// ``` /// - /// Records are iterated in the natural ordering of the table. + /// The order in which the records are returned is undefined + /// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)). + /// + /// The returned cursor is valid only during the remaining execution of the + /// database access. Do not store or return the cursor for later use. /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// - /// The cursor must be iterated in a protected dispatch queue. - /// /// - parameter db: A database connection. - /// - returns: A cursor over fetched records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: A ``RecordCursor`` over fetched records. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchCursor(_ db: Database) throws -> RecordCursor { try all().fetchCursor(db) } - - /// An array of all records fetched from the database. + + /// Returns an array of all records fetched from the database. /// + /// For example: + /// + /// ```swift + /// struct Player: FetchableRecord { } + /// let playerTable = Table("player") + /// + /// try dbQueue.read { db in /// // SELECT * FROM player - /// let table = Table("player") - /// let players = try table.fetchAll(db) // [Player] + /// let players = try playerTable.fetchAll(db) + /// } + /// ``` + /// + /// The order in which the records are returned is undefined + /// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)). /// /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchAll(_ db: Database) throws -> [RowDecoder] { try all().fetchAll(db) } - - /// The first found record. + + /// Returns a single record fetched from the database. /// + /// For example: + /// + /// ```swift + /// struct Player: FetchableRecord { } + /// let playerTable = Table("player") + /// + /// try dbQueue.read { db in /// // SELECT * FROM player LIMIT 1 - /// let table = Table("player") - /// let player = try table.fetchOne(db) // Player? + /// let player = try playerTable.fetchOne(db) + /// } + /// ``` /// /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchOne(_ db: Database) throws -> RowDecoder? { try all().fetchOne(db) } } extension Table where RowDecoder: FetchableRecord & Hashable { - /// A set of all records fetched from the database. + /// Returns a set of all records fetched from the database. /// + /// For example: + /// + /// ```swift + /// struct Player: FetchableRecord, Hashable { } + /// let playerTable = Table("player") + /// + /// try dbQueue.read { db in /// // SELECT * FROM player - /// let table = Table("player") - /// let players = try table.fetchSet(db) // Set + /// let players = try playerTable.fetchSet(db) + /// } + /// ``` /// /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchSet(_ db: Database) throws -> Set { try all().fetchSet(db) } @@ -501,61 +910,95 @@ extension Table where RowDecoder: FetchableRecord & Hashable { // MARK: - Fetching Rows from Table extension Table where RowDecoder == Row { - /// A cursor over all rows fetched from the database. + /// Returns a cursor over all rows fetched from the database. /// + /// For example: + /// + /// ```swift + /// let playerTable = Table("player") + /// + /// try dbQueue.read { db in /// // SELECT * FROM player - /// let table = Table("player") - /// let rows = try table.fetchCursor(db) // Cursor of Row - /// while let row = try rows.next() { // Row - /// ... + /// let rows = try playerTable.fetchCursor(db) + /// while let row = try rows.next() { + /// let id: Int64 = row["id"] + /// let name: String = row["name"] /// } + /// } + /// ``` /// - /// Rows are iterated in the natural ordering of the table. + /// The order in which the rows are returned is undefined + /// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)). + /// + /// The returned cursor is valid only during the remaining execution of the + /// database access. Do not store or return the cursor for later use. /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// - /// The cursor must be iterated in a protected dispatch queue. - /// /// - parameter db: A database connection. - /// - returns: A cursor over fetched records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: A ``RowCursor`` over fetched rows. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchCursor(_ db: Database) throws -> RowCursor { try all().fetchCursor(db) } - - /// An array of all rows fetched from the database. + + /// Returns an array of all rows fetched from the database. /// + /// For example: + /// + /// ```swift + /// let playerTable = Table("player") + /// + /// try dbQueue.read { db in /// // SELECT * FROM player - /// let table = Table("player") - /// let players = try table.fetchAll(db) // [Row] + /// let rows = try playerTable.fetchAll(db) + /// } + /// ``` + /// + /// The order in which the rows are returned is undefined + /// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)). /// /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchAll(_ db: Database) throws -> [Row] { try all().fetchAll(db) } - - /// The first found row. + + /// Returns a single row fetched from the database. /// + /// For example: + /// + /// ```swift + /// let playerTable = Table("player") + /// + /// try dbQueue.read { db in /// // SELECT * FROM player LIMIT 1 - /// let table = Table("player") - /// let row = try table.fetchOne(db) // Row? + /// let row = try playerTable.fetchOne(db) + /// } + /// ``` /// /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchOne(_ db: Database) throws -> Row? { try all().fetchOne(db) } - - /// A set of all rows fetched from the database. + + /// Returns a set of all rows fetched from the database. /// + /// For example: + /// + /// ```swift + /// let playerTable = Table("player") + /// + /// try dbQueue.read { db in /// // SELECT * FROM player - /// let table = Table("player") - /// let rows = try table.fetchSet(db) // Set + /// let rows = try playerTable.fetchSet(db) + /// } + /// ``` /// /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchSet(_ db: Database) throws -> Set { try all().fetchSet(db) } @@ -564,63 +1007,60 @@ extension Table where RowDecoder == Row { // MARK: - Fetching Values from Table extension Table where RowDecoder: DatabaseValueConvertible { - /// A cursor over all values fetched from the leftmost column. + /// Returns a cursor over fetched values. /// - /// // SELECT * FROM name - /// let table = Table("name") - /// let names = try table.fetchCursor(db) // Cursor of String - /// while let name = try names.next() { // String - /// ... - /// } + /// The order in which the values are returned is undefined + /// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)). /// - /// Values are iterated in the natural ordering of the table. + /// Values are decoded from the leftmost column. + /// + /// The returned cursor is valid only during the remaining execution of the + /// database access. Do not store or return the cursor for later use. /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// - /// The cursor must be iterated in a protected dispatch queue. - /// /// - parameter db: A database connection. - /// - returns: A cursor over fetched records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: A ``DatabaseValueCursor`` over fetched values. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor { try all().fetchCursor(db) } - - /// An array of all values fetched from the leftmost column. + + /// Returns an array of fetched values. /// - /// // SELECT * FROM name - /// let table = Table("name") - /// let names = try table.fetchAll(db) // [String] + /// Values are decoded from the leftmost column. /// /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: An array of values. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchAll(_ db: Database) throws -> [RowDecoder] { try all().fetchAll(db) } - - /// The value from the leftmost column of the first row. + + /// Returns a single fetched value. /// - /// // SELECT * FROM name LIMIT 1 - /// let table = Table("name") - /// let name = try table.fetchOne(db) // String? + /// The value is decoded from the leftmost column. + /// + /// The result is nil if the request returns no row, or one row with a + /// `NULL` value. /// /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: An optional value. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchOne(_ db: Database) throws -> RowDecoder? { try all().fetchOne(db) } } extension Table where RowDecoder: DatabaseValueConvertible & Hashable { - /// A set of all values fetched from the leftmost column. + /// Returns a set of fetched values. /// - /// // SELECT * FROM name - /// let table = Table("name") - /// let names = try table.fetchSet(db) // Set + /// Values are decoded from the leftmost column. /// /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: A set of values. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchSet(_ db: Database) throws -> Set { try all().fetchSet(db) } @@ -629,63 +1069,60 @@ extension Table where RowDecoder: DatabaseValueConvertible & Hashable { // MARK: - Fetching Fast Values from Table extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible { - /// A cursor over all values fetched from the leftmost column. + /// Returns a cursor over fetched values. /// - /// // SELECT * FROM name - /// let table = Table("name") - /// let names = try table.fetchCursor(db) // Cursor of String - /// while let name = try names.next() { // String - /// ... - /// } + /// The order in which the values are returned is undefined + /// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)). /// - /// Values are iterated in the natural ordering of the table. + /// Values are decoded from the leftmost column. + /// + /// The returned cursor is valid only during the remaining execution of the + /// database access. Do not store or return the cursor for later use. /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// - /// The cursor must be iterated in a protected dispatch queue. - /// /// - parameter db: A database connection. - /// - returns: A cursor over fetched records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: A ``FastDatabaseValueCursor`` over fetched values. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchCursor(_ db: Database) throws -> FastDatabaseValueCursor { try all().fetchCursor(db) } - - /// An array of all values fetched from the leftmost column. + + /// Returns an array of fetched values. /// - /// // SELECT * FROM name - /// let table = Table("name") - /// let names = try table.fetchAll(db) // [String] + /// Values are decoded from the leftmost column. /// /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: An array of values. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchAll(_ db: Database) throws -> [RowDecoder] { try all().fetchAll(db) } - - /// The value from the leftmost column of the first row. + + /// Returns a single fetched value. /// - /// // SELECT * FROM name LIMIT 1 - /// let table = Table("name") - /// let name = try table.fetchOne(db) // String? + /// The value is decoded from the leftmost column. + /// + /// The result is nil if the request returns no row, or one row with a + /// `NULL` value. /// /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: An optional value. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchOne(_ db: Database) throws -> RowDecoder? { try all().fetchOne(db) } } extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible & Hashable { - /// A set of all values fetched from the leftmost column. + /// Returns a set of fetched values. /// - /// // SELECT * FROM name - /// let table = Table("name") - /// let names = try table.fetchSet(db) // Set + /// Values are decoded from the leftmost column. /// /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: A set of values. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchSet(_ db: Database) throws -> Set { try all().fetchSet(db) } @@ -694,20 +1131,18 @@ extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConv // MARK: - Associations to TableRecord extension Table { - /// Creates a "Belongs To" association between Self and the destination - /// type, based on a database foreign key. + /// Creates a ``BelongsToAssociation`` between this table and the + /// destination `TableRecord` type. /// - /// For more information, see `TableRecord.belongsTo(_:key:using:)`. + /// For more information, see ``TableRecord/belongsTo(_:key:using:)-13t5r``. /// /// - parameters: /// - destination: The record type at the other side of the association. - /// - key: An eventual decoding key for the association. By default, it - /// is `destination.databaseTableName`. - /// - foreignKey: An eventual foreign key. You need to provide an - /// explicit foreign key when GRDB can't infer one from the database - /// schema. This happens when the schema does not define any foreign - /// key to the destination table, or when the schema defines several - /// foreign keys to the destination table. + /// - key: The association key. By default, it + /// is `Destination.databaseTableName`. + /// - foreignKey: An eventual foreign key. You need to provide one when + /// no foreign key exists to the destination table, or several foreign + /// keys exist. public func belongsTo( _ destination: Destination.Type, key: String? = nil, @@ -720,21 +1155,19 @@ extension Table { key: key, using: foreignKey) } - - /// Creates a "Has many" association between Self and the destination type, - /// based on a database foreign key. + + /// Creates a ``HasManyAssociation`` between this table and the + /// destination `TableRecord` type. /// - /// For more information, see `TableRecord.hasMany(_:key:using:)`. + /// For more information, see ``TableRecord/hasMany(_:key:using:)-45axo``. /// /// - parameters: /// - destination: The record type at the other side of the association. - /// - key: An eventual decoding key for the association. By default, it - /// is `destination.databaseTableName`. - /// - foreignKey: An eventual foreign key. You need to provide an - /// explicit foreign key when GRDB can't infer one from the database - /// schema. This happens when the schema does not define any foreign - /// key from the destination table, or when the schema defines several - /// foreign keys from the destination table. + /// - key: The association key. By default, it + /// is `Destination.databaseTableName`. + /// - foreignKey: An eventual foreign key. You need to provide one when + /// no foreign key exists to the destination table, or several foreign + /// keys exist. public func hasMany( _ destination: Destination.Type, key: String? = nil, @@ -747,21 +1180,19 @@ extension Table { key: key, using: foreignKey) } - - /// Creates a "Has one" association between Self and the destination type, - /// based on a database foreign key. + + /// Creates a ``HasOneAssociation`` between this table and the + /// destination `TableRecord` type. /// - /// For more information, see `TableRecord.hasOne(_:key:using:)`. + /// For more information, see ``TableRecord/hasOne(_:key:using:)-4g9tm``. /// /// - parameters: /// - destination: The record type at the other side of the association. - /// - key: An eventual decoding key for the association. By default, it - /// is `destination.databaseTableName`. - /// - foreignKey: An eventual foreign key. You need to provide an - /// explicit foreign key when GRDB can't infer one from the database - /// schema. This happens when the schema does not define any foreign - /// key from the destination table, or when the schema defines several - /// foreign keys from the destination table. + /// - key: The association key. By default, it + /// is `Destination.databaseTableName`. + /// - foreignKey: An eventual foreign key. You need to provide one when + /// no foreign key exists to the destination table, or several foreign + /// keys exist. public func hasOne( _ destination: Destination.Type, key: String? = nil, @@ -779,20 +1210,18 @@ extension Table { // MARK: - Associations to Table extension Table { - /// Creates a "Belongs To" association between Self and the destination - /// table, based on a database foreign key. + /// Creates a ``BelongsToAssociation`` between this table and the + /// destination `Table`. /// - /// For more information, see `TableRecord.belongsTo(_:key:using:)`. + /// For more information, see ``TableRecord/belongsTo(_:key:using:)-13t5r``. /// /// - parameters: /// - destination: The table at the other side of the association. - /// - key: An eventual decoding key for the association. By default, it + /// - key: The association key. By default, it /// is `destination.tableName`. - /// - foreignKey: An eventual foreign key. You need to provide an - /// explicit foreign key when GRDB can't infer one from the database - /// schema. This happens when the schema does not define any foreign - /// key to the destination table, or when the schema defines several - /// foreign keys to the destination table. + /// - foreignKey: An eventual foreign key. You need to provide one when + /// no foreign key exists to the destination table, or several foreign + /// keys exist. public func belongsTo( _ destination: Table, key: String? = nil, @@ -804,21 +1233,19 @@ extension Table { key: key, using: foreignKey) } - - /// Creates a "Has many" association between Self and the destination table, - /// based on a database foreign key. + + /// Creates a ``HasManyAssociation`` between this table and the + /// destination `Table`. /// - /// For more information, see `TableRecord.hasMany(_:key:using:)`. + /// For more information, see ``TableRecord/hasMany(_:key:using:)-45axo``. /// /// - parameters: /// - destination: The table at the other side of the association. - /// - key: An eventual decoding key for the association. By default, it + /// - key: The association key. By default, it /// is `destination.tableName`. - /// - foreignKey: An eventual foreign key. You need to provide an - /// explicit foreign key when GRDB can't infer one from the database - /// schema. This happens when the schema does not define any foreign - /// key from the destination table, or when the schema defines several - /// foreign keys from the destination table. + /// - foreignKey: An eventual foreign key. You need to provide one when + /// no foreign key exists to the destination table, or several foreign + /// keys exist. public func hasMany( _ destination: Table, key: String? = nil, @@ -830,21 +1257,19 @@ extension Table { key: key, using: foreignKey) } - - /// Creates a "Has one" association between Self and the destination table, - /// based on a database foreign key. + + /// Creates a ``HasOneAssociation`` between this table and the + /// destination `Table`. /// - /// For more information, see `TableRecord.hasOne(_:key:using:)`. + /// For more information, see ``TableRecord/hasOne(_:key:using:)-4g9tm``. /// /// - parameters: /// - destination: The table at the other side of the association. - /// - key: An eventual decoding key for the association. By default, it - /// is `destination.databaseTableName`. - /// - foreignKey: An eventual foreign key. You need to provide an - /// explicit foreign key when GRDB can't infer one from the database - /// schema. This happens when the schema does not define any foreign - /// key from the destination table, or when the schema defines several - /// foreign keys from the destination table. + /// - key: The association key. By default, it + /// is `destination.tableName`. + /// - foreignKey: An eventual foreign key. You need to provide one when + /// no foreign key exists to the destination table, or several foreign + /// keys exist. public func hasOne( _ destination: Table, key: String? = nil, @@ -861,10 +1286,9 @@ extension Table { // MARK: - Associations to CommonTableExpression extension Table { - /// Creates an association to a common table expression that you can join - /// or include in another request. + /// Creates an association to a common table expression. /// - /// For more information, see `TableRecord.association(to:on:)`. + /// For more information, see ``TableRecord/association(to:on:)``. /// /// - parameter cte: A common table expression. /// - parameter condition: A function that returns the joining clause. @@ -880,12 +1304,10 @@ extension Table { to: cte.relationForAll, condition: .expression { condition($0, $1).sqlExpression }) } - - /// Creates an association to a common table expression that you can join - /// or include in another request. + + /// Creates an association to a common table expression. /// - /// The key of the returned association is the table name of the common - /// table expression. + /// For more information, see ``TableRecord/association(to:)``. /// /// - parameter cte: A common table expression. /// - returns: An association to the common table expression. @@ -900,18 +1322,17 @@ extension Table { // MARK: - "Through" Associations extension Table { - /// Creates a "Has Many Through" association between Self and the + /// Creates a ``HasManyThroughAssociation`` between this table and the /// destination type. /// - /// For more information, see `TableRecord.hasMany(_:through:using:key:)`. + /// For more information, see ``TableRecord/hasMany(_:through:using:key:)``. /// /// - parameters: /// - destination: The record type at the other side of the association. - /// - pivot: An association from Self to the intermediate type. + /// - pivot: An association from `Self` to the intermediate type. /// - target: A target association from the intermediate type to the /// destination type. - /// - key: An eventual decoding key for the association. By default, it - /// is the same key as the target. + /// - key: The association key. By default, it is the key of the target. public func hasMany( _ destination: Target.RowDecoder.Type, through pivot: Pivot, @@ -924,18 +1345,18 @@ extension Table { Pivot.RowDecoder == Target.OriginRowDecoder { let association = HasManyThroughAssociation(through: pivot, using: target) - + if let key = key { return association.forKey(key) } else { return association } } - - /// Creates a "Has One Through" association between Self and the + + /// Creates a ``HasOneThroughAssociation`` between this table and the /// destination type. /// - /// For more information, see `TableRecord.hasOne(_:through:using:key:)`. + /// For more information, see ``TableRecord/hasOne(_:through:using:key:)``. /// /// - parameters: /// - destination: The record type at the other side of the association. @@ -956,7 +1377,7 @@ extension Table { Pivot.RowDecoder == Target.OriginRowDecoder { let association = HasOneThroughAssociation(through: pivot, using: target) - + if let key = key { return association.forKey(key) } else { @@ -968,129 +1389,84 @@ extension Table { // MARK: - Joining Methods extension Table { - /// Creates a request that prefetches an association. + /// Returns a request that fetches all rows associated with each row + /// in this request. + /// + /// See the ``TableRecord`` method ``TableRecord/including(all:)`` + /// for more information. public func including(all association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { all().including(all: association) } - - /// Creates a request that includes an association. The columns of the - /// associated record are selected. The returned association does not - /// require that the associated database table contains a matching row. + + /// Returns a request that fetches the eventual row associated with each + /// row of this request. + /// + /// See the ``TableRecord`` method ``TableRecord/including(optional:)`` + /// for more information. public func including(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { all().including(optional: association) } - - /// Creates a request that includes an association. The columns of the - /// associated record are selected. The returned association requires - /// that the associated database table contains a matching row. + + /// Returns a request that fetches the row associated with each row in + /// this request. Rows that do not have an associated row are discarded. + /// + /// See the ``TableRecord`` method ``TableRecord/including(required:)`` + /// for more information. public func including(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { all().including(required: association) } - - /// Creates a request that includes an association. The columns of the - /// associated record are not selected. The returned association does not - /// require that the associated database table contains a matching row. + + /// Returns a request that joins each row of this request to its + /// eventual associated row. + /// + /// See the ``TableRecord`` method ``TableRecord/including(optional:)`` + /// for more information. public func joining(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { all().joining(optional: association) } - - /// Creates a request that includes an association. The columns of the - /// associated record are not selected. The returned association requires - /// that the associated database table contains a matching row. + + /// Returns a request that joins each row of this request to its + /// associated row. Rows that do not have an associated row are discarded. + /// + /// See the ``TableRecord`` method ``TableRecord/including(required:)`` + /// for more information. public func joining(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { all().joining(required: association) } - - /// Creates a request which appends *columns of an associated record* to - /// the columns of the table. + + /// Returns a request with the columns of the eventual associated row + /// appended to the table columns. /// - /// let playerTable = Table("player") - /// let teamTable = Table("team") - /// let playerTeam = playerTable.belongsTo(teamTable) - /// - /// // SELECT player.*, team.color - /// // FROM player LEFT JOIN team ... - /// let teamColor = playerTeam.select(Column("color") - /// let request = playerTable.annotated(withOptional: teamColor)) - /// - /// This method performs the same SQL request as `including(optional:)`. - /// The difference is in the shape of Decodable records that decode such - /// a request: the associated columns can be decoded at the same level as - /// the main record: - /// - /// struct PlayerWithTeamColor: FetchableRecord, Decodable { - /// var player: Player - /// var color: String? - /// } - /// let players = try dbQueue.read { db in - /// try request - /// .asRequest(of: PlayerWithTeamColor.self) - /// .fetchAll(db) - /// } - /// - /// Note: this is a convenience method. You can build the same request with - /// `TableAlias`, `annotated(with:)`, and `joining(optional:)`: - /// - /// let teamAlias = TableAlias() - /// let request = playerTable - /// .annotated(with: teamAlias[Column("color")]) - /// .joining(optional: playerTeam.aliased(teamAlias)) + /// See the ``TableRecord`` method ``TableRecord/annotated(withOptional:)`` + /// for more information. public func annotated(withOptional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { all().annotated(withOptional: association) } - - /// Creates a request which appends *columns of an associated record* to - /// the columns of the table. + + /// Returns a request with the columns of the associated row appended to + /// the table columns. Rows that do not have an associated row + /// are discarded. /// - /// let playerTable = Table("player") - /// let teamTable = Table("team") - /// let playerTeam = playerTable.belongsTo(teamTable) - /// - /// // SELECT player.*, team.color - /// // FROM player JOIN team ... - /// let teamColor = playerTeam.select(Column("color") - /// let request = playerTable.annotated(withRequired: teamColor)) - /// - /// This method performs the same SQL request as `including(required:)`. - /// The difference is in the shape of Decodable records that decode such - /// a request: the associated columns can be decoded at the same level as - /// the main record: - /// - /// struct PlayerWithTeamColor: FetchableRecord, Decodable { - /// var player: Player - /// var color: String - /// } - /// let players = try dbQueue.read { db in - /// try request - /// .asRequest(of: PlayerWithTeamColor.self) - /// .fetchAll(db) - /// } - /// - /// Note: this is a convenience method. You can build the same request with - /// `TableAlias`, `annotated(with:)`, and `joining(required:)`: - /// - /// let teamAlias = TableAlias() - /// let request = playerTable - /// .annotated(with: teamAlias[Column("color")]) - /// .joining(required: playerTeam.aliased(teamAlias)) + /// See the ``TableRecord`` method ``TableRecord/annotated(withRequired:)`` + /// for more information. public func annotated(withRequired association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder @@ -1102,38 +1478,29 @@ extension Table { // MARK: - Association Aggregates extension Table { - /// Creates a request with *aggregates* appended to the selection. + /// Returns a request with the given association aggregates appended to + /// the table colums. /// - /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount - /// // FROM player LEFT JOIN book ... - /// let table = Table("player") - /// let request = table.annotated(with: Player.books.count) + /// See the ``TableRecord`` method ``TableRecord/annotated(with:)-4xoen`` + /// for more information. public func annotated(with aggregates: AssociationAggregate...) -> QueryInterfaceRequest { all().annotated(with: aggregates) } - - /// Creates a request with *aggregates* appended to the selection. + + /// Returns a request with the given association aggregates appended to + /// the table colums. /// - /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount - /// // FROM player LEFT JOIN book ... - /// let table = Table("player") - /// let request = table.annotated(with: [Player.books.count]) + /// See the ``TableRecord`` method ``TableRecord/annotated(with:)-8ce7u`` + /// for more information. public func annotated(with aggregates: [AssociationAggregate]) -> QueryInterfaceRequest { all().annotated(with: aggregates) } - - /// Creates a request with the provided aggregate *predicate*. + + /// Returns a request filtered according to the provided + /// association aggregate. /// - /// // SELECT player.* - /// // FROM player LEFT JOIN book ... - /// // HAVING COUNT(DISTINCT book.id) = 0 - /// let table = Table("player") - /// var request = table.all() - /// request = request.having(Player.books.isEmpty) - /// - /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableRecord.databaseSelection` property, or - /// for individual requests with the `TableRecord.select` method. + /// See the ``TableRecord`` method ``TableRecord/having(_:)`` + /// for more information. public func having(_ predicate: AssociationAggregate) -> QueryInterfaceRequest { all().having(predicate) } @@ -1146,7 +1513,7 @@ extension Table { /// /// - parameter db: A database connection. /// - returns: The number of deleted rows - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult public func deleteAll(_ db: Database) throws -> Int { try all().deleteAll(db) @@ -1158,13 +1525,17 @@ extension Table { extension Table { /// Returns whether a row exists for this primary key. /// - /// try Table("player").exists(db, key: 123) - /// try Table("country").exists(db, key: "FR") + /// All single-column primary keys are supported: /// - /// When the table has no explicit primary key, GRDB uses the hidden - /// "rowid" column: + /// ```swift + /// let playerTable = Table("player") + /// let countryTable = Table("country") /// - /// try Table("document").exists(db, key: 1) + /// try dbQueue.read { db in + /// let playerExists = try playerTable.exists(db, key: 1) + /// let countryExists = try countryTable.exists(db, key: "FR") + /// } + /// ``` /// /// - parameters: /// - db: A database connection. @@ -1182,13 +1553,24 @@ where RowDecoder: Identifiable, { /// Returns whether a row exists for this primary key. /// - /// try Table("player").exists(db, id: 123) - /// try Table("player").exists(db, id: "FR") + /// All single-column primary keys are supported: /// - /// When the table has no explicit primary key, GRDB uses the hidden - /// "rowid" column: + /// ```swift + /// struct Player: Identifiable { + /// var id: Int64 + /// } + /// struct Country: Identifiable { + /// var id: String + /// } /// - /// try Table("document").exists(db, id: 1) + /// let playerTable = Table("player") + /// let countryTable = Table("country") + /// + /// try dbQueue.read { db in + /// let playerExists = try playerTable.exists(db, id: 1) + /// let countryExists = try countryTable.exists(db, id: "FR") + /// } + /// ``` /// /// - parameters: /// - db: A database connection. @@ -1206,14 +1588,30 @@ where RowDecoder: Identifiable, // MARK: - Check Existence by Key extension Table { - /// Returns whether a row exists for this unique key (primary key or any key - /// with a unique index on it). + /// Returns whether a row exists for this primary or unique key. /// - /// Table("player").exists(db, key: ["name": Arthur"]) + /// For example: + /// + /// ```swift + /// let playerTable = Table("player") + /// let citizenshipTable = Table("citizenship") + /// + /// try dbQueue.read { db in + /// let playerExists = playerTable.exists(db, key: ["id": 1]) + /// let playerExists = playerTable.exists(db, key: ["email": "arthur@example.com"]) + /// let citizenshipExists = citizenshipTable.exists(db, key: [ + /// "citizenId": 1, + /// "countryCode": "FR", + /// ]) + /// } + /// ``` + /// + /// A fatal error is raised if no unique index exists on a subset of the + /// key columns. /// /// - parameters: /// - db: A database connection. - /// - key: A dictionary of values. + /// - key: A unique key. /// - returns: Whether a row exists for this key. public func exists(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool { try !filter(key: key).isEmpty(db) @@ -1223,25 +1621,28 @@ extension Table { // MARK: - Deleting by Single-Column Primary Key extension Table { - /// Delete rows identified by their primary keys, and returns the number of - /// deleted rows. + /// Deletes rows identified by their primary keys, and returns the number + /// of deleted rows. /// + /// All single-column primary keys are supported: + /// + /// ```swift + /// let playerTable = Table("player") + /// let countryTable = Table("country") + /// + /// try dbQueue.write { db in /// // DELETE FROM player WHERE id IN (1, 2, 3) - /// try Table("player").deleteAll(db, keys: [1, 2, 3]) + /// try playerTable.deleteAll(db, keys: [1, 2, 3]) /// - /// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE') - /// try Table("country").deleteAll(db, keys: ["FR", "US", "DE"]) - /// - /// When the table has no explicit primary key, GRDB uses the hidden - /// "rowid" column: - /// - /// // DELETE FROM document WHERE rowid IN (1, 2, 3) - /// try Table("document").deleteAll(db, keys: [1, 2, 3]) + /// // DELETE FROM country WHERE code IN ('FR', 'US') + /// try countryTable.deleteAll(db, keys: ["FR", "US"]) + /// } + /// ``` /// /// - parameters: /// - db: A database connection. /// - keys: A sequence of primary keys. - /// - returns: The number of deleted rows + /// - returns: The number of deleted rows. @discardableResult public func deleteAll(_ db: Database, keys: Keys) throws -> Int @@ -1254,26 +1655,29 @@ extension Table { } return try filter(keys: keys).deleteAll(db) } - - /// Delete a row, identified by its primary key, and returns whether a - /// database row was deleted. + + /// Deletes the row identified by its primary key, and returns whether a + /// row was deleted. /// - /// // DELETE FROM player WHERE id = 123 - /// try Table("player").deleteOne(db, key: 123) + /// All single-column primary keys are supported: + /// + /// ```swift + /// let playerTable = Table("player") + /// let countryTable = Table("country") + /// + /// try dbQueue.write { db in + /// // DELETE FROM player WHERE id = 1 + /// try playerTable.deleteOne(db, key: 1) /// /// // DELETE FROM country WHERE code = 'FR' - /// try Table("country").deleteOne(db, key: "FR") - /// - /// When the table has no explicit primary key, GRDB uses the hidden - /// "rowid" column: - /// - /// // DELETE FROM document WHERE rowid = 1 - /// try Table("document").deleteOne(db, key: 1) + /// try countryTable.deleteOne(db, key: "FR") + /// } + /// ``` /// /// - parameters: /// - db: A database connection. /// - key: A primary key value. - /// - returns: Whether a database row was deleted. + /// - returns: Whether a row was deleted. @discardableResult public func deleteOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Bool { if key.databaseValue.isNull { @@ -1289,25 +1693,35 @@ extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible { - /// Delete rows identified by their primary keys, and returns the number of - /// deleted rows. + /// Deletes rows identified by their primary keys, and returns the number + /// of deleted rows. /// + /// All single-column primary keys are supported: + /// + /// ```swift + /// struct Player: Identifiable { + /// var id: Int64 + /// } + /// struct Country: Identifiable { + /// var id: String + /// } + /// + /// let playerTable = Table("player") + /// let countryTable = Table("country") + /// + /// try dbQueue.write { db in /// // DELETE FROM player WHERE id IN (1, 2, 3) - /// try Table("player").deleteAll(db, ids: [1, 2, 3]) + /// try playerTable.deleteAll(db, ids: [1, 2, 3]) /// - /// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE') - /// try Table("country").deleteAll(db, ids: ["FR", "US", "DE"]) - /// - /// When the table has no explicit primary key, GRDB uses the hidden - /// "rowid" column: - /// - /// // DELETE FROM document WHERE rowid IN (1, 2, 3) - /// try Table("document").deleteAll(db, ids: [1, 2, 3]) + /// // DELETE FROM country WHERE code IN ('FR', 'US') + /// try countryTable.deleteAll(db, ids: ["FR", "US"]) + /// } + /// ``` /// /// - parameters: /// - db: A database connection. /// - ids: A collection of primary keys. - /// - returns: The number of deleted rows + /// - returns: The number of deleted rows. @discardableResult public func deleteAll(_ db: Database, ids: IDS) throws -> Int where IDS: Collection, IDS.Element == RowDecoder.ID @@ -1318,26 +1732,36 @@ where RowDecoder: Identifiable, } return try filter(ids: ids).deleteAll(db) } - - /// Delete a row, identified by its primary key, and returns whether a - /// database row was deleted. + + /// Deletes the row identified by its primary key, and returns whether a + /// row was deleted. /// - /// // DELETE FROM player WHERE id = 123 - /// try Table("player").deleteOne(db, id: 123) + /// All single-column primary keys are supported: + /// + /// ```swift + /// struct Player: Identifiable { + /// var id: Int64 + /// } + /// struct Country: Identifiable { + /// var id: String + /// } + /// + /// let playerTable = Table("player") + /// let countryTable = Table("country") + /// + /// try dbQueue.write { db in + /// // DELETE FROM player WHERE id = 1 + /// try playerTable.deleteOne(db, id: 1) /// /// // DELETE FROM country WHERE code = 'FR' - /// try Table("country").deleteOne(db, id: "FR") - /// - /// When the table has no explicit primary key, GRDB uses the hidden - /// "rowid" column: - /// - /// // DELETE FROM document WHERE rowid = 1 - /// try Table("document").deleteOne(db, id: 1) + /// try countryTable.deleteOne(db, id: "FR") + /// } + /// ``` /// /// - parameters: /// - db: A database connection. /// - id: A primary key value. - /// - returns: Whether a database row was deleted. + /// - returns: Whether a row was deleted. @discardableResult public func deleteOne(_ db: Database, id: RowDecoder.ID) throws -> Bool { if id.databaseValue.isNull { @@ -1351,16 +1775,36 @@ where RowDecoder: Identifiable, // MARK: - Deleting by Key extension Table { - /// Delete rows identified by the provided unique keys (primary key or - /// any key with a unique index on it), and returns the number of - /// deleted rows. + /// Deletes rows identified by their primary or unique keys, and returns + /// the number of deleted rows. /// - /// try Table("player").deleteAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) + /// For example: + /// + /// ```swift + /// let playerTable = Table("player") + /// let citizenshipTable = Table("citizenship") + /// + /// try dbQueue.write { db in + /// // DELETE FROM player WHERE id = 1 + /// try playerTable.deleteAll(db, keys: [["id": 1]]) + /// + /// // DELETE FROM player WHERE email = 'arthur@example.com' + /// try playerTable.deleteAll(db, keys: [["email": "arthur@example.com"]]) + /// + /// // DELETE FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR' + /// try citizenshipTable.deleteAll(db, keys: [ + /// ["citizenId": 1, "countryCode": "FR"], + /// ]) + /// } + /// ``` + /// + /// A fatal error is raised if no unique index exists on a subset of the + /// key columns. /// /// - parameters: /// - db: A database connection. /// - keys: An array of key dictionaries. - /// - returns: The number of deleted rows + /// - returns: The number of deleted rows. @discardableResult public func deleteAll(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> Int { if keys.isEmpty { @@ -1369,17 +1813,37 @@ extension Table { } return try filter(keys: keys).deleteAll(db) } - - /// Delete a row, identified by a unique key (the primary key or any key - /// with a unique index on it), and returns whether a database row - /// was deleted. + + /// Deletes the row identified by its primary or unique keys, and returns + /// whether a row was deleted. /// - /// Table("player").deleteOne(db, key: ["name": Arthur"]) + /// For example: /// + /// ```swift + /// let playerTable = Table("player") + /// let citizenshipTable = Table("citizenship") + /// + /// try dbQueue.write { db in + /// // DELETE FROM player WHERE id = 1 + /// try playerTable.deleteOne(db, key: ["id": 1]) + /// + /// // DELETE FROM player WHERE email = 'arthur@example.com' + /// try playerTable.deleteOne(db, key: ["email": "arthur@example.com"]) + /// + /// // DELETE FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR' + /// try citizenshipTable.deleteOne(db, key: [ + /// "citizenId": 1, + /// "countryCode": "FR", + /// ]) + /// } + /// ``` + /// + /// A fatal error is raised if no unique index exists on a subset of the + /// key columns. /// - parameters: /// - db: A database connection. /// - key: A dictionary of values. - /// - returns: Whether a database row was deleted. + /// - returns: Whether a row was deleted. @discardableResult public func deleteOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool { try deleteAll(db, keys: [key]) > 0 @@ -1389,20 +1853,24 @@ extension Table { // MARK: - Batch Update extension Table { - /// Updates all rows, and returns the number of updated rows.. + /// Updates all rows, and returns the number of updated rows. /// /// For example: /// - /// try dbQueue.write { db in - /// // UPDATE player SET score = 0 - /// try Table("player").updateAll(db, [Column("score").set(to: 0)]) - /// } + /// ```swift + /// let playerTable = Table("player") + /// + /// try dbQueue.write { db in + /// // UPDATE player SET score = 0 + /// try playerTable.updateAll(db, [Column("score").set(to: 0)]) + /// } + /// ``` /// /// - parameter db: A database connection. /// - parameter conflictResolution: A policy for conflict resolution. /// - parameter assignments: An array of column assignments. /// - returns: The number of updated rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult public func updateAll( _ db: Database, @@ -1412,21 +1880,25 @@ extension Table { { try all().updateAll(db, onConflict: conflictResolution, assignments) } - - /// Updates all rows, and returns the number of updated rows.. + + /// Updates all rows, and returns the number of updated rows. /// /// For example: /// - /// try dbQueue.write { db in - /// // UPDATE player SET score = 0 - /// try Table("player").updateAll(db, Column("score").set(to: 0)) - /// } + /// ```swift + /// let playerTable = Table("player") + /// + /// try dbQueue.write { db in + /// // UPDATE player SET score = 0 + /// try playerTable.updateAll(db, Column("score").set(to: 0)) + /// } + /// ``` /// /// - parameter db: A database connection. /// - parameter conflictResolution: A policy for conflict resolution. - /// - parameter assignments: Column assignments. + /// - parameter assignments: An array of column assignments. /// - returns: The number of updated rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult public func updateAll( _ db: Database, diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index 81edac4d0..80131277b 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -1,5 +1,3 @@ -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// /// SQLGenerationContext supports SQL generation: /// /// - It provides a database connection during SQL generation, for any purpose @@ -204,10 +202,12 @@ class StatementArgumentsSink { // MARK: - TableAlias -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// /// A TableAlias identifies a table in a request. -public class TableAlias: Hashable { +/// +/// See ``TableRequest/aliased(_:)`` for more information and examples. +/// +/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) +public class TableAlias { private enum Impl { /// A TableAlias is undefined when it is created by the GRDB user: /// @@ -299,32 +299,16 @@ public class TableAlias: Hashable { } } - /// Creates a TableAlias, suitable for qualifying requests or associations. - /// - /// For example: - /// - /// // The request for all books published after their author has died - /// // - /// // SELECT book.* - /// // FROM book - /// // JOIN author ON author.id = book.authorId - /// // WHERE book.publishDate >= author.deathDate - /// let authorAlias = TableAlias() - /// let request = Book - /// .joining(required: Book.author.aliased(authorAlias)) - /// .filter(Column("publishDate") >= authorAlias[Column("deathDate")]) + /// Creates a TableAlias. /// /// When the alias is given a name, this name is guaranteed to be used as /// the table alias in the SQL query: /// - /// // SELECT book.* - /// // FROM book - /// // JOIN author a ON a.id = book.authorId - /// // WHERE book.publishDate >= a.deathDate - /// let authorAlias = TableAlias(name: "a") - /// let request = Book - /// .joining(required: Book.author.aliased(authorAlias)) - /// .filter(Column("publishDate") >= authorAlias[Column("deathDate")]) + /// ```swift + /// // SELECT p.* FROM player p + /// let alias = TableAlias(name: "p") + /// let request = Player.all().aliased(alias) + /// ``` public init(name: String? = nil) { self.impl = .undefined(userName: name) } @@ -417,60 +401,105 @@ public class TableAlias: Hashable { } } - /// Returns a qualified value that is able to resolve ambiguities in - /// joined queries. + /// Returns a result column that refers to the aliased table. public subscript(_ selectable: some SQLSelectable) -> SQLSelection { + // TODO: test selectable.sqlSelection.qualified(with: self) } - /// Returns a qualified expression that is able to resolve ambiguities in - /// joined queries. + /// Returns an SQL expression that refers to the aliased table. + /// + /// For example, let's sort books by author name first, and then by title: + /// + /// ```swift + /// // SELECT book.* + /// // FROM book + /// // JOIN author ON author.id = book.authorId + /// // ORDER BY author.name, book.title + /// let authorAlias = TableAlias() + /// let request = Book + /// .joining(required: Book.author.aliased(authorAlias)) + /// .order(authorAlias[Column("name")], Column("title")) + /// ``` public subscript(_ expression: some SQLSpecificExpressible & SQLSelectable & SQLOrderingTerm) -> SQLExpression { expression.sqlExpression.qualified(with: self) } - /// Returns a qualified ordering that is able to resolve ambiguities in - /// joined queries. + /// Returns an SQL ordering term that refers to the aliased table. + /// + /// For example, let's sort books by author name first, and then by title: + /// + /// ```swift + /// // SELECT book.* + /// // FROM book + /// // JOIN author ON author.id = book.authorId + /// // ORDER BY author.name ASC, book.title ASC + /// let authorAlias = TableAlias() + /// let request = Book + /// .joining(required: Book.author.aliased(authorAlias)) + /// .order(authorAlias[Column("name").asc], Column("title").asc) + /// ``` public subscript(_ ordering: some SQLOrderingTerm) -> SQLOrdering { ordering.sqlOrdering.qualified(with: self) } - /// Returns a qualified column that is able to resolve ambiguities in - /// joined queries. + /// Returns an SQL column that refers to the aliased table. + /// + /// For example, let's sort books by author name first, and then by title: + /// + /// ```swift + /// // SELECT book.* + /// // FROM book + /// // JOIN author ON author.id = book.authorId + /// // ORDER BY author.name, book.title + /// let authorAlias = TableAlias() + /// let request = Book + /// .joining(required: Book.author.aliased(authorAlias)) + /// .order(authorAlias["name"], Column("title")) + /// ``` public subscript(_ column: String) -> SQLExpression { .qualifiedColumn(column, self) } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// A boolean SQL expression indicating whether this alias refers to some + /// rows, or not. /// - /// An expression that evaluates to true if the record referred by this - /// `TableAlias` exists. + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) /// - /// For example, here is how filter books and only keep those that are not - /// associated to any author: + /// In the example below, we only fetch books that are not associated to + /// any author: /// - /// let books: [Book] = try dbQueue.read { db in - /// let authorAlias = TableAlias() - /// let request = Book - /// .joining(optional: Book.author.aliased(authorAlias)) - /// .filter(!authorAlias.exists) - /// return try request.fetchAll(db) - /// } + /// ```swift + /// struct Author: TableRecord, FetchableRecord { } + /// struct Book: TableRecord, FetchableRecord { + /// static let author = belongsTo(Author.self) + /// } + /// + /// try dbQueue.read { db in + /// let authorAlias = TableAlias() + /// let request = Book + /// .joining(optional: Book.author.aliased(authorAlias)) + /// .filter(!authorAlias.exists) + /// let books = try request.fetchAll(db) + /// } + /// ``` public var exists: SQLExpression { SQLExpression.qualifiedExists(self) } - - /// :nodoc: - public func hash(into hasher: inout Hasher) { - hasher.combine(ObjectIdentifier(root)) - } - - /// :nodoc: +} + +extension TableAlias: Equatable { public static func == (lhs: TableAlias, rhs: TableAlias) -> Bool { ObjectIdentifier(lhs.root) == ObjectIdentifier(rhs.root) } } +extension TableAlias: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(root)) + } +} + extension [TableAlias] { /// Resolve ambiguities in aliases' names. fileprivate var resolvedNames: [TableAlias: String] { diff --git a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift index 6273975a8..0cfca9a21 100644 --- a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift @@ -1,4 +1,3 @@ -/// :nodoc: extension SQLInterpolation { // MARK: - TableRecord @@ -245,7 +244,6 @@ extension SQLInterpolation { // When a value is both an expression and a sequence of expressions, // favor the expression side. Use case: Foundation.Data interpolation. - /// :nodoc: public mutating func appendInterpolation(_ expressible: S) where S: SQLExpressible, S: Sequence, S.Element: SQLExpressible { diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index 7596eaeb8..219aad488 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -5,19 +5,24 @@ extension Database { // TODO: deprecate just before GRDB 6 /// Creates a database table. /// - /// try db.create(table: "place") { t in - /// t.autoIncrementedPrimaryKey("id") - /// t.column("title", .text) - /// t.column("favorite", .boolean).notNull().default(false) - /// t.column("longitude", .double).notNull() - /// t.column("latitude", .double).notNull() - /// } + /// For example: /// - /// See and - /// + /// ```swift + /// try db.create(table: "place") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("title", .text) + /// t.column("favorite", .boolean).notNull().default(false) + /// t.column("longitude", .double).notNull() + /// t.column("latitude", .double).notNull() + /// } + /// ``` + /// + /// Related SQLite documentation: + /// - + /// - /// /// - warning: This method is sunsetted. You should prefer - /// `create(table:options:body:)` instead. + /// ``create(table:options:body:)`` instead. /// /// - parameters: /// - name: The table name. @@ -27,7 +32,7 @@ extension Database { /// already exists. /// - withoutRowID: If true, uses WITHOUT ROWID optimization. /// - body: A closure that defines table columns and constraints. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @_disfavoredOverload public func create( table name: String, @@ -46,22 +51,27 @@ extension Database { /// Creates a database table. /// - /// try db.create(table: "place") { t in - /// t.autoIncrementedPrimaryKey("id") - /// t.column("title", .text) - /// t.column("favorite", .boolean).notNull().default(false) - /// t.column("longitude", .double).notNull() - /// t.column("latitude", .double).notNull() - /// } + /// For example: /// - /// See and - /// + /// ```swift + /// try db.create(table: "place") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("title", .text) + /// t.column("favorite", .boolean).notNull().default(false) + /// t.column("longitude", .double).notNull() + /// t.column("latitude", .double).notNull() + /// } + /// ``` + /// + /// Related SQLite documentation: + /// - + /// - /// /// - parameters: /// - name: The table name. /// - options: Table creation options. /// - body: A closure that defines table columns and constraints. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func create( table name: String, options: TableOptions = [], @@ -78,25 +88,29 @@ extension Database { /// Renames a database table. /// - /// See + /// Related SQLite documentation: /// - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func rename(table name: String, to newName: String) throws { try execute(sql: "ALTER TABLE \(name.quotedDatabaseIdentifier) RENAME TO \(newName.quotedDatabaseIdentifier)") } /// Modifies a database table. /// - /// try db.alter(table: "player") { t in - /// t.add(column: "url", .text) - /// } + /// For example: /// - /// See + /// ```swift + /// try db.alter(table: "player") { t in + /// t.add(column: "url", .text) + /// } + /// ``` + /// + /// Related SQLite documentation: /// /// - parameters: /// - name: The table name. /// - body: A closure that defines table alterations. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func alter(table name: String, body: (TableAlteration) -> Void) throws { let alteration = TableAlteration(name: name) body(alteration) @@ -106,9 +120,9 @@ extension Database { /// Deletes a database table. /// - /// See + /// Related SQLite documentation: /// - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func drop(table name: String) throws { try execute(sql: "DROP TABLE \(name.quotedDatabaseIdentifier)") } @@ -116,18 +130,24 @@ extension Database { // TODO: deprecate just before GRDB 6 /// Creates an index. /// - /// try db.create(index: "playerByEmail", on: "player", columns: ["email"]) + /// For example: /// - /// SQLite can also index expressions (https://www.sqlite.org/expridx.html) + /// ```swift + /// try db.create(index: "playerByEmail", on: "player", columns: ["email"]) + /// ``` + /// + /// SQLite can also index expressions () /// and use specific collations. To create such an index, use a raw SQL - /// query. + /// query: /// - /// try db.execute(sql: "CREATE INDEX ...") + /// ```swift + /// try db.execute(sql: "CREATE INDEX ...") + /// ``` /// - /// See + /// Related SQLite documentation: /// /// - warning: This method is sunsetted. You should prefer - /// `create(index:on:columns:options:condition:)` instead. + /// ``create(index:on:columns:options:condition:)`` instead. /// /// - parameters: /// - name: The index name. @@ -137,6 +157,7 @@ extension Database { /// - ifNotExists: If true, no error is thrown if index already exists. /// - condition: If not nil, creates a partial index /// (see ). + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @_disfavoredOverload public func create( index name: String, @@ -155,15 +176,21 @@ extension Database { /// Creates an index. /// - /// try db.create(index: "playerByEmail", on: "player", columns: ["email"]) + /// For example: /// - /// SQLite can also index expressions (https://www.sqlite.org/expridx.html) + /// ```swift + /// try db.create(index: "playerByEmail", on: "player", columns: ["email"]) + /// ``` + /// + /// SQLite can also index expressions () /// and use specific collations. To create such an index, use a raw SQL - /// query. + /// query: /// - /// try db.execute(sql: "CREATE INDEX ...") + /// ```swift + /// try db.execute(sql: "CREATE INDEX ...") + /// ``` /// - /// See + /// Related SQLite documentation: /// /// - parameters: /// - name: The index name. @@ -172,6 +199,7 @@ extension Database { /// - options: Index creation options. /// - condition: If not nil, creates a partial index /// (see ). + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func create( index name: String, on table: String, @@ -192,33 +220,33 @@ extension Database { /// Deletes a database index. /// - /// See + /// Related SQLite documentation: /// - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func drop(index name: String) throws { try execute(sql: "DROP INDEX \(name.quotedDatabaseIdentifier)") } - /// Delete and recreate from scratch all indices that use this collation. + /// Deletes and recreates from scratch all indices that use this collation. /// /// This method is useful when the definition of a collation sequence /// has changed. /// - /// See + /// Related SQLite documentation: /// - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func reindex(collation: Database.CollationName) throws { try execute(sql: "REINDEX \(collation.rawValue)") } - /// Delete and recreate from scratch all indices that use this collation. + /// Deletes and recreates from scratch all indices that use this collation. /// /// This method is useful when the definition of a collation sequence /// has changed. /// - /// See + /// Related SQLite documentation: /// - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func reindex(collation: DatabaseCollation) throws { try reindex(collation: Database.CollationName(rawValue: collation.name)) } @@ -226,10 +254,8 @@ extension Database { /// Table creation options public struct TableOptions: OptionSet { - /// :nodoc: public let rawValue: Int - /// :nodoc: public init(rawValue: Int) { self.rawValue = rawValue } /// Only creates the table if it does not already exist. @@ -244,27 +270,53 @@ public struct TableOptions: OptionSet { #if GRDBCUSTOMSQLITE || GRDBCIPHER /// Creates a STRICT table /// - /// See + /// Related SQLite documentation: public static let strict = TableOptions(rawValue: 1 << 3) #else /// Creates a STRICT table /// - /// See + /// Related SQLite documentation: @available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) // SQLite 3.37+ public static let strict = TableOptions(rawValue: 1 << 3) #endif } -/// The TableDefinition class lets you define table columns and constraints. +/// A `TableDefinition` lets you define the components of a database table. /// -/// You don't create instances of this class. Instead, you use the Database -/// `create(table:)` method: +/// You don't create instances of this class. Instead, you use the `Database` +/// ``Database/create(table:options:body:)`` method: /// -/// try db.create(table: "player") { t in // t is TableDefinition -/// t.column(...) -/// } +/// ```swift +/// try db.create(table: "player") { t in // t is TableDefinition +/// t.autoIncrementedPrimaryKey("id") +/// t.column("name", .text).notNull() +/// } +/// ``` /// -/// See +/// ## Topics +/// +/// ### Define Columns +/// +/// - ``column(_:_:)`` +/// - ``column(literal:)`` +/// - ``column(sql:)`` +/// - ``ColumnDefinition`` +/// +/// ### Define Keys +/// +/// - ``autoIncrementedPrimaryKey(_:onConflict:)`` +/// - ``foreignKey(_:references:columns:onDelete:onUpdate:deferred:)`` +/// - ``primaryKey(_:onConflict:)`` +/// - ``uniqueKey(_:onConflict:)`` +/// +/// ### Define Others Constraints +/// +/// - ``check(_:)`` +/// - ``check(sql:)`` +/// - ``constraint(literal:)`` +/// - ``constraint(sql:)`` +/// +/// Related SQLite documentation: public final class TableDefinition { private typealias KeyConstraint = ( columns: [String], @@ -317,31 +369,29 @@ public final class TableDefinition { /// Defines the auto-incremented primary key. /// - /// try db.create(table: "player") { t in - /// t.autoIncrementedPrimaryKey("id") - /// } + /// For example: + /// + /// ```swift + /// // CREATE TABLE player ( + /// // id INTEGER PRIMARY KEY AUTOINCREMENT + /// // ) + /// try db.create(table: "player") { t in + /// t.autoIncrementedPrimaryKey("id") + /// } + /// ``` /// /// The auto-incremented primary key is an integer primary key that /// automatically generates unused values when you do not explicitly /// provide one, and prevents the reuse of ids over the lifetime of /// the database. /// - /// **It is the preferred way to define a numeric primary key**. - /// - /// The fact that an auto-incremented primary key prevents the reuse of - /// ids is an excellent guard against data races that could happen when your - /// application processes ids in an asynchronous way. The auto-incremented - /// primary key provides the guarantee that a given id can't reference a row - /// that is different from the one it used to be at the beginning of the - /// asynchronous process, even if this row gets deleted and a new one is - /// inserted in between. - /// - /// See and - /// + /// Related SQLite documentation: + /// - + /// - /// /// - parameter conflictResolution: An optional conflict resolution /// (see ). - /// - returns: Self so that you can further refine the column definition. + /// - returns: `self` so that you can further refine the column definition. @discardableResult public func autoIncrementedPrimaryKey( _ name: String, @@ -353,15 +403,22 @@ public final class TableDefinition { /// Appends a table column. /// - /// try db.create(table: "player") { t in - /// t.column("name", .text) - /// } + /// For example: /// - /// See + /// ```swift + /// // CREATE TABLE player ( + /// // name TEXT + /// // ) + /// try db.create(table: "player") { t in + /// t.column("name", .text) + /// } + /// ``` + /// + /// Related SQLite documentation: /// /// - parameter name: the column name. /// - parameter type: the eventual column type. - /// - returns: An ColumnDefinition that allows you to refine the + /// - returns: An ``ColumnDefinition`` that allows you to refine the /// column definition. @discardableResult public func column(_ name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition { @@ -370,41 +427,60 @@ public final class TableDefinition { return column } - /// Appends a table column defined with raw SQL. + /// Appends a table column. /// - /// try db.create(table: "player") { t in - /// t.column(sql: "name TEXT") - /// } + /// For example: + /// + /// ```swift + /// // CREATE TABLE player ( + /// // name TEXT + /// // ) + /// try db.create(table: "player") { t in + /// t.column(sql: "name TEXT") + /// } + /// ``` public func column(sql: String) { columns.append(.literal(SQL(sql: sql))) } - /// Appends a table column defined with an SQL *literal*. + /// Appends a table column. /// - /// Literals allow you to safely embed raw values in your SQL, without any - /// risk of syntax errors or SQL injection: + /// ``SQL`` literals allow you to safely embed raw values in your SQL, + /// without any risk of syntax errors or SQL injection: /// - /// // CREATE TABLE player ( - /// // name TEXT DEFAULT 'Anonymous' - /// // ) - /// let defaultName = "Anonymous" - /// try db.create(table: "player") { t in - /// t.column(literal: "name TEXT DEFAULT \(defaultName)") - /// } + /// ```swift + /// // CREATE TABLE player ( + /// // name TEXT DEFAULT 'Anonymous' + /// // ) + /// let defaultName = "Anonymous" + /// try db.create(table: "player") { t in + /// t.column(literal: "name TEXT DEFAULT \(defaultName)") + /// } + /// ``` public func column(literal: SQL) { columns.append(.literal(literal)) } - /// Defines the table primary key. + /// Defines the primary key. /// - /// try db.create(table: "citizenship") { t in - /// t.column("citizenID", .integer) - /// t.column("countryCode", .text) - /// t.primaryKey(["citizenID", "countryCode"]) - /// } + /// For example: /// - /// See and - /// + /// ```swift + /// // CREATE TABLE citizenship ( + /// // citizenID INTEGER NOT NULL, + /// // countryCode TEXT NOT NULL, + /// // PRIMARY KEY (citizenID, countryCode) + /// // ) + /// try db.create(table: "citizenship") { t in + /// t.column("citizenID", .integer).notNull() + /// t.column("countryCode", .text).notNull() + /// t.primaryKey(["citizenID", "countryCode"]) + /// } + /// ``` + /// + /// Related SQLite documentation: + /// - + /// - /// /// - parameter columns: The primary key columns. /// - parameter conflictResolution: An optional conflict resolution @@ -417,15 +493,24 @@ public final class TableDefinition { primaryKeyConstraint = (columns: columns, conflictResolution: conflictResolution) } - /// Adds a unique key. + /// Adds a unique constraint. /// - /// try db.create(table: "place") { t in - /// t.column("latitude", .double) - /// t.column("longitude", .double) - /// t.uniqueKey(["latitude", "longitude"]) - /// } + /// For example: /// - /// See + /// ```swift + /// // CREATE TABLE place ( + /// // latitude DOUBLE, + /// // longitude DOUBLE, + /// // UNIQUE (latitude, longitude) + /// // ) + /// try db.create(table: "place") { t in + /// t.column("latitude", .double) + /// t.column("longitude", .double) + /// t.uniqueKey(["latitude", "longitude"]) + /// } + /// ``` + /// + /// Related SQLite documentation: /// /// - parameter columns: The unique key columns. /// - parameter conflictResolution: An optional conflict resolution @@ -436,14 +521,26 @@ public final class TableDefinition { /// Adds a foreign key. /// - /// try db.create(table: "passport") { t in - /// t.column("issueDate", .date) - /// t.column("citizenID", .integer) - /// t.column("countryCode", .text) - /// t.foreignKey(["citizenID", "countryCode"], references: "citizenship", onDelete: .cascade) - /// } + /// For example: /// - /// See + /// ```swift + /// // CREATE TABLE passport ( + /// // issueDate DATE NOT NULL, + /// // citizenID INTEGER NOT NULL, + /// // countryCode INTEGER NOT NULL, + /// // FOREIGN KEY (citizenID, countryCode) + /// // REFERENCES citizenship(citizenID, countryCode) + /// // ON DELETE CASCADE + /// // ) + /// try db.create(table: "passport") { t in + /// t.column("issueDate", .date).notNull() + /// t.column("citizenID", .integer).notNull() + /// t.column("countryCode", .text).notNull() + /// t.foreignKey(["citizenID", "countryCode"], references: "citizenship", onDelete: .cascade) + /// } + /// ``` + /// + /// Related SQLite documentation: /// /// - parameters: /// - columns: The foreign key columns. @@ -472,66 +569,90 @@ public final class TableDefinition { deferred: deferred)) } - /// Adds a CHECK constraint. + /// Adds a check constraint. /// - /// try db.create(table: "player") { t in - /// t.column("personalPhone", .text) - /// t.column("workPhone", .text) - /// let personalPhone = Column("personalPhone") - /// let workPhone = Column("workPhone") - /// t.check(personalPhone != nil || workPhone != nil) - /// } + /// For example: /// - /// See + /// ```swift + /// // CREATE TABLE player ( + /// // personalPhone TEXT, + /// // workPhone TEXT, + /// // CHECK personalPhone IS NOT NULL OR workPhone IS NOT NULL + /// // ) + /// try db.create(table: "player") { t in + /// t.column("personalPhone", .text) + /// t.column("workPhone", .text) + /// let personalPhone = Column("personalPhone") + /// let workPhone = Column("workPhone") + /// t.check(personalPhone != nil || workPhone != nil) + /// } + /// ``` /// - /// - parameter condition: The checked condition + /// Related SQLite documentation: + /// + /// - parameter condition: The checked condition. public func check(_ condition: some SQLExpressible) { checkConstraints.append(condition.sqlExpression) } - /// Adds a CHECK constraint. + /// Adds a check constraint. /// - /// try db.create(table: "player") { t in - /// t.column("personalPhone", .text) - /// t.column("workPhone", .text) - /// t.check(sql: "personalPhone IS NOT NULL OR workPhone IS NOT NULL") - /// } + /// For example: /// - /// See + /// ```swift + /// // CREATE TABLE player ( + /// // personalPhone TEXT, + /// // workPhone TEXT, + /// // CHECK personalPhone IS NOT NULL OR workPhone IS NOT NULL + /// // ) + /// try db.create(table: "player") { t in + /// t.column("personalPhone", .text) + /// t.column("workPhone", .text) + /// t.check(sql: "personalPhone IS NOT NULL OR workPhone IS NOT NULL") + /// } + /// ``` + /// + /// Related SQLite documentation: /// /// - parameter sql: An SQL snippet public func check(sql: String) { checkConstraints.append(SQL(sql: sql).sqlExpression) } - /// Appends a table constraint defined with raw SQL. + /// Appends a table constraint. /// - /// // CREATE TABLE player ( - /// // ... - /// // CHECK (score >= 0) - /// // ) - /// try db.create(table: "player") { t in - /// ... - /// t.constraint(sql: "CHECK (score >= 0)") - /// } + /// For example: + /// + /// ```swift + /// // CREATE TABLE player ( + /// // score INTEGER, + /// // CHECK (score >= 0) + /// // ) + /// try db.create(table: "player") { t in + /// t.column("score", .integer) + /// t.constraint(sql: "CHECK (score >= 0)") + /// } + /// ``` public func constraint(sql: String) { literalConstraints.append(SQL(sql: sql)) } - /// Appends a table constraint defined with an SQL *literal*. + /// Appends a table constraint. /// - /// Literals allow you to safely embed raw values in your SQL, without any - /// risk of syntax errors or SQL injection: + /// ``SQL`` literals allow you to safely embed raw values in your SQL, + /// without any risk of syntax errors or SQL injection: /// /// // CREATE TABLE player ( - /// // ... - /// // CHECK (score >= 0) - /// // ) - /// let minScore = 0 - /// try db.create(table: "player") { t in - /// ... - /// t.constraint(literal: "CHECK (score >= \(minScore))") - /// } + /// ```swift + /// // score INTEGER, + /// // CHECK (score >= 0) + /// // ) + /// let minScore = 0 + /// try db.create(table: "player") { t in + /// t.column("score", .integer) + /// t.constraint(literal: "CHECK (score >= \(minScore))") + /// } + /// ``` public func constraint(literal: SQL) { literalConstraints.append(literal) } @@ -681,16 +802,18 @@ public final class TableDefinition { } } -/// The TableAlteration class lets you alter database tables. +/// A `TableDefinition` lets you modify the components of a database table. /// -/// You don't create instances of this class. Instead, you use the Database -/// `alter(table:)` method: +/// You don't create instances of this class. Instead, you use the `Database` +/// ``Database/alter(table:body:)`` method: /// -/// try db.alter(table: "player") { t in // t is TableAlteration -/// t.add(column: ...) -/// } +/// ```swift +/// try db.alter(table: "player") { t in // t is TableAlteration +/// t.add(column: "bonus", .integer) +/// } +/// ``` /// -/// See +/// Related SQLite documentation: public final class TableAlteration { private let name: String @@ -707,13 +830,18 @@ public final class TableAlteration { self.name = name } - /// Appends a column to the table. + /// Appends a column. /// - /// try db.alter(table: "player") { t in - /// t.add(column: "url", .text) - /// } + /// For example: /// - /// See + /// ```swift + /// // ALTER TABLE player ADD COLUMN bonus integer + /// try db.alter(table: "player") { t in + /// t.add(column: "bonus", .integer) + /// } + /// ``` + /// + /// Related SQLite documentation: /// /// - parameter name: the column name. /// - parameter type: the column type. @@ -726,82 +854,103 @@ public final class TableAlteration { return column } - /// Appends a table column defined with raw SQL. + /// Appends a column. /// - /// // ALTER TABLE player ADD COLUMN name TEXT - /// try db.alter(table: "player") { t in - /// t.addColumn(sql: "name TEXT") - /// } + /// For example: + /// + /// ```swift + /// // ALTER TABLE player ADD COLUMN bonus integer + /// try db.alter(table: "player") { t in + /// t.addColumn(sql: "bonus integer") + /// } + /// ``` public func addColumn(sql: String) { alterations.append(.addColumnLiteral(SQL(sql: sql))) } - /// Appends a table column defined with an SQL *literal*. + /// Appends a column. /// - /// Literals allow you to safely embed raw values in your SQL, without any - /// risk of syntax errors or SQL injection: + /// ``SQL`` literals allow you to safely embed raw values in your SQL, + /// without any risk of syntax errors or SQL injection: /// - /// // ALTER TABLE player ADD COLUMN name TEXT DEFAULT 'Anonymous' - /// let defaultName = "Anonymous" - /// try db.alter(table: "player") { t in - /// t.addColumn(literal: "name TEXT DEFAULT \(defaultName)") - /// } + /// ```swift + /// // ALTER TABLE player ADD COLUMN name TEXT DEFAULT 'Anonymous' + /// try db.alter(table: "player") { t in + /// t.addColumn(literal: "name TEXT DEFAULT \(defaultName)") + /// } + /// ``` public func addColumn(literal: SQL) { alterations.append(.addColumnLiteral(literal)) } #if GRDBCUSTOMSQLITE || GRDBCIPHER - /// Renames a column in a table. + /// Renames a column. /// - /// try db.alter(table: "player") { t in - /// t.rename(column: "url", to: "homeURL") - /// } + /// For example: /// - /// See + /// ```swift + /// try db.alter(table: "player") { t in + /// t.rename(column: "url", to: "homeURL") + /// } + /// ``` /// - /// - parameter name: the column name to rename. + /// Related SQLite documentation: + /// + /// - parameter name: the old name of the column. /// - parameter newName: the new name of the column. public func rename(column name: String, to newName: String) { _rename(column: name, to: newName) } - /// Drops a column from the table. + /// Drops a column. /// - /// try db.alter(table: "player") { t in - /// t.drop(column: "age") - /// } + /// For example: /// - /// See + /// ```swift + /// try db.alter(table: "player") { t in + /// t.drop(column: "age") + /// } + /// ``` /// - /// - Parameter name: the column name to drop. + /// Related SQLite documentation: + /// + /// - Parameter name: the name of the column to drop. public func drop(column name: String) { _drop(column: name) } #else - /// Renames a column in a table. + /// Renames a column. /// - /// try db.alter(table: "player") { t in - /// t.rename(column: "url", to: "homeURL") - /// } + /// For example: /// - /// See + /// ```swift + /// try db.alter(table: "player") { t in + /// t.rename(column: "url", to: "homeURL") + /// } + /// ``` /// - /// - parameter name: the column name to rename. + /// Related SQLite documentation: + /// + /// - parameter name: the old name of the column. /// - parameter newName: the new name of the column. @available(iOS 13.0, tvOS 13.0, watchOS 6.0, *) public func rename(column name: String, to newName: String) { _rename(column: name, to: newName) } - /// Drops a column from the table. + /// Drops a column. /// - /// try db.alter(table: "player") { t in - /// t.drop(column: "age") - /// } + /// For example: /// - /// See + /// ```swift + /// try db.alter(table: "player") { t in + /// t.drop(column: "age") + /// } + /// ``` /// - /// - Parameter name: the column name to drop. + /// Related SQLite documentation: + /// + /// - Parameter name: the name of the column to drop. @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public func drop(column name: String) { _drop(column: name) @@ -870,20 +1019,55 @@ public final class TableAlteration { } } -/// The ColumnDefinition class lets you refine a table column. +/// Describes a database column. /// -/// You get instances of this class when you create or alter a database table: +/// You get instances of `ColumnDefinition` when you create or alter a database +/// tables. For example: /// -/// try db.create(table: "player") { t in -/// t.column(...) // ColumnDefinition -/// } +/// ```swift +/// try db.create(table: "player") { t in +/// t.column("name", .text) // ColumnDefinition +/// } /// -/// try db.alter(table: "player") { t in -/// t.add(column: ...) // ColumnDefinition -/// } +/// try db.alter(table: "player") { t in +/// t.add(column: "score", .integer) // ColumnDefinition +/// } +/// ``` /// -/// See and -/// +/// See ``TableDefinition/column(_:_:)`` and ``TableAlteration/add(column:_:)``. +/// +/// Related SQLite documentation: +/// +/// - +/// - +/// +/// ## Topics +/// +/// ### Keys +/// +/// - ``primaryKey(onConflict:autoincrement:)`` +/// - ``references(_:column:onDelete:onUpdate:deferred:)`` +/// +/// ### Indexes +/// +/// - ``indexed()`` +/// - ``unique(onConflict:)`` +/// +/// ### Default value +/// +/// - ``defaults(to:)`` +/// - ``defaults(sql:)`` +/// +/// ### Collations +/// +/// - ``collate(_:)-4dljx`` +/// - ``collate(_:)-9ywza`` +/// +/// ### Other Constraints +/// +/// - ``check(_:)`` +/// - ``check(sql:)`` +/// - ``notNull(onConflict:)`` public final class ColumnDefinition { enum Index { case none @@ -902,7 +1086,7 @@ public final class ColumnDefinition { /// The `GeneratedColumnQualification` enum defines whether a generated /// column sis virtual or stored. /// - /// See + /// Related SQLite documentation: public enum GeneratedColumnQualification { case virtual case stored @@ -929,20 +1113,35 @@ public final class ColumnDefinition { self.type = type } - /// Adds a primary key constraint on the column. + /// Adds a primary key constraint. /// - /// try db.create(table: "player") { t in - /// t.column("id", .integer).primaryKey() - /// } + /// For example: /// - /// See and - /// + /// ```swift + /// // CREATE TABLE player( + /// // id TEXT NOT NULL PRIMARY KEY + /// // ) + /// try db.create(table: "player") { t in + /// t.column("id", .text).notNull().primaryKey() + /// } + /// ``` + /// + /// - warning: Make sure you add a not null constraint on your primary key + /// column, as in the above example, or SQLite will allow null values. + /// See + /// for more information. + /// + /// When you want to define a primary key on multiple columns, do not use + /// this method. Use ``TableDefinition/primaryKey(_:onConflict:)`` instead. + /// + /// Related SQLite documentation: + /// - + /// - /// /// - parameters: - /// - conflictResolution: An optional conflict resolution - /// (see ). + /// - conflictResolution: An optional ``Database/ConflictResolution``. /// - autoincrement: If true, the primary key is autoincremented. - /// - returns: Self so that you can further refine the column definition. + /// - returns: `self` so that you can further refine the column definition. @discardableResult public func primaryKey( onConflict conflictResolution: Database.ConflictResolution? = nil, @@ -953,49 +1152,71 @@ public final class ColumnDefinition { return self } - /// Adds a NOT NULL constraint on the column. + /// Adds a not null constraint. /// - /// try db.create(table: "player") { t in - /// t.column("name", .text).notNull() - /// } + /// For example: /// - /// See + /// ```swift + /// // CREATE TABLE player( + /// // name TEXT NOT NULL + /// // ) + /// try db.create(table: "player") { t in + /// t.column("name", .text).notNull() + /// } + /// ``` /// - /// - parameter conflictResolution: An optional conflict resolution - /// (see ). - /// - returns: Self so that you can further refine the column definition. + /// Related SQLite documentation: + /// + /// - parameter conflictResolution: An optional ``Database/ConflictResolution``. + /// - returns: `self` so that you can further refine the column definition. @discardableResult public func notNull(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self { notNullConflictResolution = conflictResolution ?? .abort return self } - /// Adds a UNIQUE constraint on the column. + /// Adds a unique constraint. /// - /// try db.create(table: "player") { t in - /// t.column("email", .text).unique() - /// } + /// For example: /// - /// See + /// ```swift + /// // CREATE TABLE player( + /// // email TEXT UNIQUE + /// // ) + /// try db.create(table: "player") { t in + /// t.column("email", .text).unique() + /// } + /// ``` /// - /// - parameter conflictResolution: An optional conflict resolution - /// (see ). - /// - returns: Self so that you can further refine the column definition. + /// Related SQLite documentation: + /// + /// - parameter conflictResolution: An optional ``Database/ConflictResolution``. + /// - returns: `self` so that you can further refine the column definition. @discardableResult public func unique(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self { index = .unique(conflictResolution ?? .abort) return self } - /// Adds an index of the column. + /// Adds an index. /// - /// try db.create(table: "player") { t in - /// t.column("email", .text).indexed() - /// } + /// For example: /// - /// See + /// ```swift + /// // CREATE TABLE player(email TEXT); + /// // CREATE INDEX player_on_email ON player(email); + /// try db.create(table: "player") { t in + /// t.column("email", .text).indexed() + /// } + /// ``` /// - /// - returns: Self so that you can further refine the column definition. + /// The name of the created index is `_on_`, where `table` + /// and `column` are the names of the table and the column. See the + /// example above. + /// + /// See also ``unique(onConflict:)``. + /// + /// - returns: `self` so that you can further refine the column definition. @discardableResult public func indexed() -> Self { if case .none = index { @@ -1004,97 +1225,136 @@ public final class ColumnDefinition { return self } - /// Adds a CHECK constraint on the column. + /// Adds a check constraint. /// - /// try db.create(table: "player") { t in - /// t.column("name", .text).check { length($0) > 0 } - /// } + /// For example: /// - /// See + /// ```swift + /// // CREATE TABLE player( + /// // name TEXT CHECK (LENGTH(name) > 0) + /// // ) + /// try db.create(table: "player") { t in + /// t.column("name", .text).check { length($0) > 0 } + /// } + /// ``` /// - /// - parameter condition: A closure whose argument is an Column that + /// Related SQLite documentation: + /// + /// - parameter condition: A closure whose argument is a ``Column`` that /// represents the defined column, and returns the expression to check. - /// - returns: Self so that you can further refine the column definition. + /// - returns: `self` so that you can further refine the column definition. @discardableResult public func check(_ condition: (Column) -> any SQLExpressible) -> Self { checkConstraints.append(condition(Column(name)).sqlExpression) return self } - /// Adds a CHECK constraint on the column. + /// Adds a check constraint. /// - /// try db.create(table: "player") { t in - /// t.column("name", .text).check(sql: "LENGTH(name) > 0") - /// } + /// For example: /// - /// See + /// ```swift + /// // CREATE TABLE player( + /// // name TEXT CHECK (LENGTH(name) > 0) + /// // ) + /// try db.create(table: "player") { t in + /// t.column("name", .text).check(sql: "LENGTH(name) > 0") + /// } + /// ``` + /// + /// Related SQLite documentation: /// /// - parameter sql: An SQL snippet. - /// - returns: Self so that you can further refine the column definition. + /// - returns: `self` so that you can further refine the column definition. @discardableResult public func check(sql: String) -> Self { checkConstraints.append(SQL(sql: sql).sqlExpression) return self } - /// Defines the default column value. + /// Defines the default value. /// - /// try db.create(table: "player") { t in - /// t.column("name", .text).defaults(to: "Anonymous") - /// } + /// For example: /// - /// See + /// ```swift + /// // CREATE TABLE player( + /// // email TEXT DEFAULT 'Anonymous' + /// // ) + /// try db.create(table: "player") { t in + /// t.column("name", .text).defaults(to: "Anonymous") + /// } + /// ``` /// - /// - parameter value: A DatabaseValueConvertible value. - /// - returns: Self so that you can further refine the column definition. + /// Related SQLite documentation: + /// + /// - parameter value: A ``DatabaseValueConvertible`` value. + /// - returns: `self` so that you can further refine the column definition. @discardableResult public func defaults(to value: some DatabaseValueConvertible) -> Self { defaultExpression = value.sqlExpression return self } - /// Defines the default column value. + /// Defines the default value. /// - /// try db.create(table: "player") { t in - /// t.column("creationDate", .DateTime).defaults(sql: "CURRENT_TIMESTAMP") - /// } + /// For example: /// - /// See + /// ```swift + /// // CREATE TABLE player( + /// // creationDate DATETIME DEFAULT CURRENT_TIMESTAMP + /// // ) + /// try db.create(table: "player") { t in + /// t.column("creationDate", .DateTime).defaults(sql: "CURRENT_TIMESTAMP") + /// } + /// ``` + /// + /// Related SQLite documentation: /// /// - parameter sql: An SQL snippet. - /// - returns: Self so that you can further refine the column definition. + /// - returns: `self` so that you can further refine the column definition. @discardableResult public func defaults(sql: String) -> Self { defaultExpression = SQL(sql: sql).sqlExpression return self } - /// Defines the default column collation. + /// Defines the default collation. /// - /// try db.create(table: "player") { t in - /// t.column("email", .text).collate(.nocase) - /// } + /// For example: /// - /// See + /// ```swift + /// // CREATE TABLE player( + /// // email TEXT COLLATE NOCASE + /// // ) + /// try db.create(table: "player") { t in + /// t.column("email", .text).collate(.nocase) + /// } + /// ``` /// - /// - parameter collation: An Database.CollationName. - /// - returns: Self so that you can further refine the column definition. + /// Related SQLite documentation: + /// + /// - parameter collation: A ``Database/CollationName``. + /// - returns: `self` so that you can further refine the column definition. @discardableResult public func collate(_ collation: Database.CollationName) -> Self { collationName = collation.rawValue return self } - /// Defines the default column collation. + /// Defines the default collation. /// - /// try db.create(table: "player") { t in - /// t.column("name", .text).collate(.localizedCaseInsensitiveCompare) - /// } + /// For example: /// - /// See + /// ```swift + /// try db.create(table: "player") { t in + /// t.column("name", .text).collate(.localizedCaseInsensitiveCompare) + /// } + /// ``` /// - /// - parameter collation: A custom DatabaseCollation. - /// - returns: Self so that you can further refine the column definition. + /// Related SQLite documentation: + /// + /// - parameter collation: A ``DatabaseCollation``. + /// - returns: `self` so that you can further refine the column definition. @discardableResult public func collate(_ collation: DatabaseCollation) -> Self { collationName = collation.name @@ -1104,21 +1364,30 @@ public final class ColumnDefinition { #if GRDBCUSTOMSQLITE /// Defines the column as a generated column. /// - /// try db.create(table: "player") { t in - /// t.column("id", .integer).primaryKey() - /// t.column("score", .integer).notNull() - /// t.column("bonus", .integer).notNull() - /// t.column("totalScore", .integer).generatedAs(sql: "score + bonus", .stored) - /// } + /// For example: /// - /// See . Note particularly the limitations of - /// generated columns, e.g. they may not have a default value. + /// ```swift + /// // CREATE TABLE player( + /// // id INTEGER PRIMARY KEY AUTOINCREMENT, + /// // score INTEGER NOT NULL, + /// // bonus INTEGER NOT NULL, + /// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) STORED + /// // ) + /// try db.create(table: "player") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("score", .integer).notNull() + /// t.column("bonus", .integer).notNull() + /// t.column("totalScore", .integer).generatedAs(sql: "score + bonus", .stored) + /// } + /// ``` + /// + /// Related SQLite documentation: /// /// - parameters: /// - sql: An SQL expression. /// - qualification: The generated column's qualification, which - /// defaults to `.virtual`. - /// - returns: Self so that you can further refine the column definition. + /// defaults to ``GeneratedColumnQualification/virtual``. + /// - returns: `self` so that you can further refine the column definition. @discardableResult public func generatedAs( sql: String, @@ -1134,21 +1403,30 @@ public final class ColumnDefinition { /// Defines the column as a generated column. /// - /// try db.create(table: "player") { t in - /// t.column("id", .integer).primaryKey() - /// t.column("score", .integer).notNull() - /// t.column("bonus", .integer).notNull() - /// t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus"), .stored) - /// } + /// For example: /// - /// See . Note particularly the limitations of - /// generated columns, e.g. they may not have a default value. + /// ```swift + /// // CREATE TABLE player( + /// // id INTEGER PRIMARY KEY AUTOINCREMENT, + /// // score INTEGER NOT NULL, + /// // bonus INTEGER NOT NULL, + /// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) STORED + /// // ) + /// try db.create(table: "player") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("score", .integer).notNull() + /// t.column("bonus", .integer).notNull() + /// t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus"), .stored) + /// } + /// ``` + /// + /// Related SQLite documentation: /// /// - parameters: /// - expression: The generated expression. /// - qualification: The generated column's qualification, which - /// defaults to `.virtual`. - /// - returns: Self so that you can further refine the column definition. + /// defaults to ``GeneratedColumnQualification/virtual``. + /// - returns: `self` so that you can further refine the column definition. @discardableResult public func generatedAs( _ expression: some SQLExpressible, @@ -1162,23 +1440,31 @@ public final class ColumnDefinition { } #endif - /// Defines a foreign key. + /// Adds a foreign key constraint. /// - /// try db.create(table: "book") { t in - /// t.column("authorId", .integer).references("author", onDelete: .cascade) - /// } + /// For example: /// - /// See + /// ```swift + /// // CREATE TABLE book( + /// // authorId INTEGER REFERENCES author(id) ON DELETE CASCADE + /// // ) + /// try db.create(table: "book") { t in + /// t.column("authorId", .integer).references("author", onDelete: .cascade) + /// } + /// ``` /// - /// - parameters + /// Related SQLite documentation: + /// + /// - parameters: /// - table: The referenced table. - /// - column: The column in the referenced table. If not specified, the - /// column of the primary key of the referenced table is used. + /// - column: The referenced column in the referenced table. If not + /// specified, the column of the primary key of the referenced table + /// is used. /// - deleteAction: Optional action when the referenced row is deleted. /// - updateAction: Optional action when the referenced row is updated. /// - deferred: If true, defines a deferred foreign key constraint. /// See . - /// - returns: Self so that you can further refine the column definition. + /// - returns: `self` so that you can further refine the column definition. @discardableResult public func references( _ table: String, @@ -1319,10 +1605,8 @@ public final class ColumnDefinition { /// Table creation options public struct IndexOptions: OptionSet { - /// :nodoc: public let rawValue: Int - /// :nodoc: public init(rawValue: Int) { self.rawValue = rawValue } /// Only creates the index if it does not already exist. diff --git a/GRDB/QueryInterface/Schema/VirtualTableModule.swift b/GRDB/QueryInterface/Schema/VirtualTableModule.swift index 3b34dc29d..9aba55308 100644 --- a/GRDB/QueryInterface/Schema/VirtualTableModule.swift +++ b/GRDB/QueryInterface/Schema/VirtualTableModule.swift @@ -1,32 +1,49 @@ -/// The protocol for SQLite virtual table modules. It lets you define a DSL for -/// the `Database.create(virtualTable:using:)` method: +/// The protocol for SQLite virtual table modules. /// -/// let module = ... -/// try db.create(virtualTable: "item", using: module) { t in -/// ... -/// } +/// The protocol can define a DSL for the +/// ``Database/create(virtualTable:ifNotExists:using:_:)`` `Database` method: /// -/// GRDB ships with three concrete classes that implement this protocol: FTS3, -/// FTS4 and FTS5. +/// ```swift +/// let module = ... +/// try db.create(virtualTable: "item", using: module) { t in +/// ... +/// } +/// ``` +/// +/// GRDB ships with three concrete classes that implement this protocol: +/// ``FTS3``, ``FTS4`` and `FTS5`. +/// +/// ## Topics +/// +/// ### Configuration Virtual Table Creation +/// +/// - ``VirtualTableConfiguration`` public protocol VirtualTableModule { - - /// The type of the closure argument in the - /// `Database.create(virtualTable:using:)` method: + /// The type of the argument in the + /// ``Database/create(virtualTable:ifNotExists:using:_:)`` closure. /// - /// try db.create(virtualTable: "item", using: module) { t in - /// // t is TableDefinition - /// } + /// For example: + /// + /// ```swift + /// try db.create(virtualTable: "item", using: module) { t in + /// // t is TableDefinition + /// } + /// ``` associatedtype TableDefinition /// The name of the module. var moduleName: String { get } - /// Returns a table definition that is passed as the closure argument in the - /// `Database.create(virtualTable:using:)` method: + /// Returns a table definition that is passed as the argument in the + /// ``Database/create(virtualTable:ifNotExists:using:_:)`` closure. /// - /// try db.create(virtualTable: "item", using: module) { t in - /// // t is the result of makeTableDefinition(configuration:) - /// } + /// For example: + /// + /// ```swift + /// try db.create(virtualTable: "item", using: module) { t in + /// // t is the result of makeTableDefinition(configuration:) + /// } + /// ``` func makeTableDefinition(configuration: VirtualTableConfiguration) -> TableDefinition /// Returns the module arguments for the `CREATE VIRTUAL TABLE` query. @@ -49,9 +66,14 @@ extension Database { /// Creates a virtual database table. /// - /// try db.create(virtualTable: "vocabulary", using: "spellfix1") + /// For example: /// - /// See + /// ```swift + /// // CREATE VIRTUAL TABLE vocabulary USING spellfix1 + /// try db.create(virtualTable: "vocabulary", using: "spellfix1") + /// ``` + /// + /// Related SQLite documentation: /// /// - parameters: /// - name: The table name. @@ -59,7 +81,7 @@ extension Database { /// table already exists. Otherwise, the table is created unless it /// already exists. /// - module: The name of an SQLite virtual table module. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func create(virtualTable name: String, ifNotExists: Bool = false, using module: String) throws { var chunks: [String] = [] chunks.append("CREATE VIRTUAL TABLE") @@ -75,33 +97,29 @@ extension Database { /// Creates a virtual database table. /// - /// let module = ... - /// try db.create(virtualTable: "book", using: module) { t in - /// ... - /// } + /// The type of the argument of the `body` function depends on the type of + /// the `module` argument: refer to this module's documentation. /// - /// The type of the closure argument `t` depends on the type of the module - /// argument: refer to this module's documentation. + /// You can use this method to create full-text virtual tables: /// - /// Use this method to create full-text tables using the FTS3, FTS4, or - /// FTS5 modules: + /// ```swift + /// try db.create(virtualTable: "book", using: FTS4()) { t in + /// t.column("title") + /// t.column("author") + /// t.column("body") + /// } + /// ``` /// - /// try db.create(virtualTable: "book", using: FTS4()) { t in - /// t.column("title") - /// t.column("author") - /// t.column("body") - /// } - /// - /// See + /// Related SQLite documentation: /// /// - parameters: /// - name: The table name. /// - ifNotExists: If false (the default), an error is thrown if the /// table already exists. Otherwise, the table is created unless it /// already exists. - /// - module: a VirtualTableModule + /// - module: a virtual module. /// - body: An optional closure that defines the virtual table. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func create( virtualTable tableName: String, ifNotExists: Bool = false, diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index c2769d583..766d06ffa 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -1,62 +1,64 @@ // MARK: - Associations to TableRecord extension TableRecord { - /// Creates a "Belongs To" association between Self and the destination - /// type, based on a database foreign key. + /// Creates a ``BelongsToAssociation`` between `Self` and the + /// destination `TableRecord` type. /// - /// struct Author: TableRecord { ... } - /// struct Book: TableRecord { - /// static let author = belongsTo(Author.self) - /// } + /// For example: /// - /// The association will let you define requests that load both the source - /// and the destination type: + /// ```swift + /// struct Author: TableRecord { } + /// struct Book: TableRecord { + /// static let author = belongsTo(Author.self) + /// } + /// ``` /// - /// // A request for all books with their authors: - /// let request = Book.including(optional: Book.author) + /// The association lets you define requests that involve both the source + /// and the destination type. /// - /// To consume those requests, define a type that adopts both the - /// FetchableRecord and Decodable protocols: + /// For example, we can fetch all books with their author: /// - /// struct BookInfo: FetchableRecord, Decodable { - /// var book: Book - /// var author: Author? - /// } + /// ```swift + /// struct BookInfo: FetchableRecord, Decodable { + /// var book: Book + /// var author: Author + /// } /// - /// let bookInfos = try dbQueue.read { db in - /// return try BookInfo.fetchAll(db, request) - /// } + /// try dbQueue.read { db in + /// let request = Book + /// .including(required: Book.author) + /// .asRequest(of: BookInfo.self) + /// let bookInfos = try request.fetchAll(db) /// for bookInfo in bookInfos { /// print("\(bookInfo.book.title) by \(bookInfo.author.name)") /// } + /// } + /// ``` /// - /// It is recommended that you define, alongside the static association, a - /// property with the same name: + /// The association can also help fetching associated records: /// - /// struct Book: TableRecord, EncodableRecord { - /// static let author = belongsTo(Author.self) - /// var author: QueryInterfaceRequest { - /// return request(for: Book.author) - /// } - /// } + /// ```swift + /// try dbQueue.read { db in + /// let book: Book = ... + /// let author: Author? = book + /// .request(for: Book.author) + /// .fetchOne(db) + /// } + /// ``` /// - /// This property will let you navigate from the source type to the - /// destination type: + /// For more information about this association, + /// see ``BelongsToAssociation``. /// - /// try dbQueue.read { db in - /// let book: Book = ... - /// let author = try book.author.fetchOne(db) // Author? - /// } + /// Methods that build requests involving associations are defined in the + /// ``JoinableRequest`` protocol. /// /// - parameters: /// - destination: The record type at the other side of the association. - /// - key: An eventual decoding key for the association. By default, it - /// is `destination.databaseTableName`. - /// - foreignKey: An eventual foreign key. You need to provide an - /// explicit foreign key when GRDB can't infer one from the database - /// schema. This happens when the schema does not define any foreign - /// key to the destination table, or when the schema defines several - /// foreign keys to the destination table. + /// - key: The association key. By default, it + /// is `Destination.databaseTableName`. + /// - foreignKey: An eventual foreign key. You need to provide one when + /// no foreign key exists to the destination table, or several foreign + /// keys exist. public static func belongsTo( _ destination: Destination.Type, key: String? = nil, @@ -70,62 +72,64 @@ extension TableRecord { using: foreignKey) } - /// Creates a "Has many" association between Self and the destination type, - /// based on a database foreign key. + /// Creates a ``HasManyAssociation`` between `Self` and the + /// destination `TableRecord` type. /// - /// struct Book: TableRecord { ... } - /// struct Author: TableRecord { - /// static let books = hasMany(Book.self) + /// For example: + /// + /// ```swift + /// struct Book: TableRecord { } + /// struct Author: TableRecord { + /// static let books = hasMany(Book.self) + /// } + /// ``` + /// + /// The association lets you define requests that involve both the source + /// and the destination type. + /// + /// For example, we can fetch all authors with all their books: + /// + /// ```swift + /// struct AuthorInfo: FetchableRecord, Decodable { + /// var author: Author + /// var books: [Book] + /// } + /// + /// try dbQueue.read { db in + /// let request = Author + /// .including(all: Author.books) + /// .asRequest(of: AuthorInfo.self) + /// let authorInfos = try request.fetchAll(db) + /// for authorInfo in authorInfos { + /// print("\(authorInfo.author.name) wrote \(authorInfo.books.count) books") /// } + /// } + /// ``` /// - /// The association will let you define requests that load both the source - /// and the destination type: + /// The association can also help fetching associated records: /// - /// // A request for all (author, book) pairs: - /// let request = Author.including(required: Author.books) + /// ```swift + /// try dbQueue.read { db in + /// let author: Author = ... + /// let books: [Book] = author + /// .request(for: Author.books) + /// .fetchAll(db) + /// } + /// ``` /// - /// To consume those requests, define a type that adopts both the - /// FetchableRecord and Decodable protocols: + /// For more information about this association, + /// see ``HasManyAssociation``. /// - /// struct Authorship: FetchableRecord, Decodable { - /// var author: Author - /// var book: Book - /// } - /// - /// let authorships = try dbQueue.read { db in - /// return try Authorship.fetchAll(db, request) - /// } - /// for authorship in authorships { - /// print("\(authorship.author.name) wrote \(authorship.book.title)") - /// } - /// - /// It is recommended that you define, alongside the static association, a - /// property with the same name: - /// - /// struct Author: TableRecord, EncodableRecord { - /// static let books = hasMany(Book.self) - /// var books: QueryInterfaceRequest { - /// return request(for: Author.books) - /// } - /// } - /// - /// This property will let you navigate from the source type to the - /// destination type: - /// - /// try dbQueue.read { db in - /// let author: Author = ... - /// let books = try author.books.fetchAll(db) // [Book] - /// } + /// Methods that build requests involving associations are defined in the + /// ``JoinableRequest`` protocol. /// /// - parameters: /// - destination: The record type at the other side of the association. - /// - key: An eventual decoding key for the association. By default, it - /// is `destination.databaseTableName`. - /// - foreignKey: An eventual foreign key. You need to provide an - /// explicit foreign key when GRDB can't infer one from the database - /// schema. This happens when the schema does not define any foreign - /// key from the destination table, or when the schema defines several - /// foreign keys from the destination table. + /// - key: The association key. By default, it + /// is `Destination.databaseTableName`. + /// - foreignKey: An eventual foreign key. You need to provide one when + /// no foreign key exists to the destination table, or several foreign + /// keys exist. public static func hasMany( _ destination: Destination.Type, key: String? = nil, @@ -139,62 +143,69 @@ extension TableRecord { using: foreignKey) } - /// Creates a "Has one" association between Self and the destination type, - /// based on a database foreign key. + /// Creates a ``HasOneAssociation`` between `Self` and the + /// destination `TableRecord` type. /// - /// struct Demographics: TableRecord { ... } - /// struct Country: TableRecord { - /// static let demographics = hasOne(Demographics.self) - /// } + /// For example: /// - /// The association will let you define requests that load both the source - /// and the destination type: + /// ```swift + /// struct Demographics: TableRecord { } + /// struct Country: TableRecord { + /// static let demographics = hasOne(Demographics.self) + /// } + /// ``` /// - /// // A request for all countries with their demographic profile: - /// let request = Country.including(optional: Country.demographics) + /// The association lets you define requests that involve both the source + /// and the destination type. /// - /// To consume those requests, define a type that adopts both the - /// FetchableRecord and Decodable protocols: + /// For example, we can fetch all countries with their eventual demographics: /// - /// struct CountryInfo: FetchableRecord, Decodable { - /// var country: Country - /// var demographics: Demographics? - /// } + /// ```swift + /// struct CountryInfo: FetchableRecord, Decodable { + /// var country: Country + /// var demographics: Demographics? + /// } /// - /// let countryInfos = try dbQueue.read { db in - /// return try CountryInfo.fetchAll(db, request) - /// } + /// try dbQueue.read { db in + /// let request = Country + /// .including(optional: Country.demographics) + /// .asRequest(of: CountryInfo.self) + /// let countryInfos = try request.fetchAll(db) /// for countryInfo in countryInfos { - /// print("\(countryInfo.country.name) has \(countryInfo.demographics.population) citizens") - /// } - /// - /// It is recommended that you define, alongside the static association, a - /// property with the same name: - /// - /// struct Country: TableRecord, EncodableRecord { - /// static let demographics = hasOne(Demographics.self) - /// var demographics: QueryInterfaceRequest { - /// return request(for: Country.demographics) + /// if let demographics = countryInfo.demographics { + /// print(""" + /// \(countryInfo.country.name) has \ + /// \(demographics.population) citizens. + /// """) /// } /// } + /// } + /// ``` /// - /// This property will let you navigate from the source type to the - /// destination type: + /// The association can also help fetching associated records: /// - /// try dbQueue.read { db in - /// let country: Country = ... - /// let demographics = try country.demographics.fetchOne(db) // Demographics? - /// } + /// ```swift + /// try dbQueue.read { db in + /// let country: Country = ... + /// let demographics: Demographics? = country + /// .request(for: Country.demographics) + /// .fetchOne(db) + /// } + /// ``` + /// + /// For more information about this association, + /// see ``HasOneAssociation``. + /// + /// Methods that build requests involving associations are defined in the + /// ``JoinableRequest`` protocol. /// /// - parameters: /// - destination: The record type at the other side of the association. - /// - key: An eventual decoding key for the association. By default, it - /// is `destination.databaseTableName`. - /// - foreignKey: An eventual foreign key. You need to provide an - /// explicit foreign key when GRDB can't infer one from the database - /// schema. This happens when the schema does not define any foreign - /// key from the destination table, or when the schema defines several - /// foreign keys from the destination table. + /// - key: The association key. By default, it + /// is `Destination.databaseTableName`. + /// - foreignKey: An eventual foreign key. You need to provide one when + /// no foreign key exists to the destination table, or several foreign + /// keys exist. public static func hasOne( _ destination: Destination.Type, key: String? = nil, @@ -212,21 +223,18 @@ extension TableRecord { // MARK: - Associations to Table extension TableRecord { - /// Creates a "Belongs To" association between Self and the destination - /// table, based on a database foreign key. + /// Creates a ``BelongsToAssociation`` between `Self` and the + /// destination `Table`. /// - /// For more information, see `TableRecord.belongsTo(_:key:using:)` where - /// the first argument is `TableRecord`. + /// For more information, see ``TableRecord/belongsTo(_:key:using:)-13t5r``. /// /// - parameters: /// - destination: The table at the other side of the association. - /// - key: An eventual decoding key for the association. By default, it + /// - key: The association key. By default, it /// is `destination.tableName`. - /// - foreignKey: An eventual foreign key. You need to provide an - /// explicit foreign key when GRDB can't infer one from the database - /// schema. This happens when the schema does not define any foreign - /// key to the destination table, or when the schema defines several - /// foreign keys to the destination table. + /// - foreignKey: An eventual foreign key. You need to provide one when + /// no foreign key exists to the destination table, or several foreign + /// keys exist. public static func belongsTo( _ destination: Table, key: String? = nil, @@ -239,21 +247,18 @@ extension TableRecord { using: foreignKey) } - /// Creates a "Has many" association between Self and the destination table, - /// based on a database foreign key. + /// Creates a ``HasManyAssociation`` between `Self` and the + /// destination `Table`. /// - /// For more information, see `TableRecord.hasMany(_:key:using:)` where - /// the first argument is `TableRecord`. + /// For more information, see ``TableRecord/hasMany(_:key:using:)-45axo``. /// /// - parameters: /// - destination: The table at the other side of the association. - /// - key: An eventual decoding key for the association. By default, it + /// - key: The association key. By default, it /// is `destination.tableName`. - /// - foreignKey: An eventual foreign key. You need to provide an - /// explicit foreign key when GRDB can't infer one from the database - /// schema. This happens when the schema does not define any foreign - /// key from the destination table, or when the schema defines several - /// foreign keys from the destination table. + /// - foreignKey: An eventual foreign key. You need to provide one when + /// no foreign key exists to the destination table, or several foreign + /// keys exist. public static func hasMany( _ destination: Table, key: String? = nil, @@ -266,21 +271,18 @@ extension TableRecord { using: foreignKey) } - /// Creates a "Has one" association between Self and the destination table, - /// based on a database foreign key. + /// Creates a ``HasOneAssociation`` between `Self` and the + /// destination `Table`. /// - /// For more information, see `TableRecord.hasOne(_:key:using:)` where - /// the first argument is `TableRecord`. + /// For more information, see ``TableRecord/hasOne(_:key:using:)-4g9tm``. /// /// - parameters: /// - destination: The table at the other side of the association. - /// - key: An eventual decoding key for the association. By default, it - /// is `destination.databaseTableName`. - /// - foreignKey: An eventual foreign key. You need to provide an - /// explicit foreign key when GRDB can't infer one from the database - /// schema. This happens when the schema does not define any foreign - /// key from the destination table, or when the schema defines several - /// foreign keys from the destination table. + /// - key: The association key. By default, it + /// is `destination.tableName`. + /// - foreignKey: An eventual foreign key. You need to provide one when + /// no foreign key exists to the destination table, or several foreign + /// keys exist. public static func hasOne( _ destination: Table, key: String? = nil, @@ -297,8 +299,7 @@ extension TableRecord { // MARK: - Associations to CommonTableExpression extension TableRecord { - /// Creates an association to a common table expression that you can join - /// or include in another request. + /// Creates an association to a common table expression. /// /// The key of the returned association is the table name of the common /// table expression. @@ -306,28 +307,30 @@ extension TableRecord { /// For example, you can build a request that fetches all chats with their /// latest message: /// - /// let latestMessageRequest = Message - /// .annotated(with: max(Column("date"))) - /// .group(Column("chatID")) + /// ```swift + /// let latestMessageRequest = Message + /// .annotated(with: max(Column("date"))) + /// .group(Column("chatID")) /// - /// let latestMessageCTE = CommonTableExpression( - /// named: "latestMessage", - /// request: latestMessageRequest) + /// let latestMessageCTE = CommonTableExpression( + /// named: "latestMessage", + /// request: latestMessageRequest) /// - /// let latestMessage = Chat.association( - /// to: latestMessageCTE, - /// on: { chat, latestMessage in - /// chat[Column("id")] == latestMessage[Column("chatID")] - /// }) + /// let latestMessageAssociation = Chat.association( + /// to: latestMessageCTE, + /// on: { chat, latestMessage in + /// chat[Column("id")] == latestMessage[Column("chatID")] + /// }) /// - /// // WITH latestMessage AS - /// // (SELECT *, MAX(date) FROM message GROUP BY chatID) - /// // SELECT chat.*, latestMessage.* - /// // FROM chat - /// // LEFT JOIN latestMessage ON chat.id = latestMessage.chatID - /// let request = Chat - /// .with(latestMessageCTE) - /// .including(optional: latestMessage) + /// // WITH latestMessage AS + /// // (SELECT *, MAX(date) FROM message GROUP BY chatID) + /// // SELECT chat.*, latestMessage.* + /// // FROM chat + /// // LEFT JOIN latestMessage ON chat.id = latestMessage.chatID + /// let request = Chat + /// .with(latestMessageCTE) + /// .including(optional: latestMessageAssociation) + /// ``` /// /// - parameter cte: A common table expression. /// - parameter condition: A function that returns the joining clause. @@ -344,8 +347,7 @@ extension TableRecord { condition: .expression { condition($0, $1).sqlExpression }) } - /// Creates an association to a common table expression that you can join - /// or include in another request. + /// Creates an association to a common table expression. /// /// The key of the returned association is the table name of the common /// table expression. @@ -363,67 +365,71 @@ extension TableRecord { // MARK: - "Through" Associations extension TableRecord { - /// Creates a "Has Many Through" association between Self and the - /// destination type. + /// Creates a ``HasManyThroughAssociation`` between `Self` and the + /// destination `TableRecord` type. /// - /// struct Country: TableRecord { - /// static let passports = hasMany(Passport.self) - /// static let citizens = hasMany(Citizen.self, through: passports, using: Passport.citizen) + /// For example: + /// + /// ```swift + /// struct Citizen: TableRecord { } + /// + /// struct Passport: TableRecord { + /// static let citizen = belongsTo(Citizen.self) + /// } + /// + /// struct Country: TableRecord { + /// static let passports = hasMany(Passport.self) + /// static let citizens = hasMany(Citizen.self, + /// through: passports, + /// using: Passport.citizen) + /// } + /// ``` + /// + /// The association lets you define requests that involve both the source + /// and the destination type. + /// + /// For example, we can fetch all countries with all their citizens: + /// + /// ```swift + /// struct CountryInfo: FetchableRecord, Decodable { + /// var country: Country + /// var citizens: [Citizen] + /// } + /// + /// try dbQueue.read { db in + /// let request = Country + /// .including(all: Country.citizens) + /// .asRequest(of: CountryInfo.self) + /// let countryInfos = try request.fetchAll(db) + /// for countryInfo in countryInfos { + /// print("\(countryInfo.country.name) has \(countryInfo.citizens.count) citizens") /// } + /// } + /// ``` /// - /// struct Passport: TableRecord { - /// static let citizen = belongsTo(Citizen.self) - /// } + /// The association can also help fetching associated records: /// - /// struct Citizen: TableRecord { } + /// ```swift + /// try dbQueue.read { db in + /// let country: Country = ... + /// let citizens: [Citizen] = country + /// .request(for: Country.citizens) + /// .fetchAll(db) + /// } + /// ``` /// - /// The association will let you define requests that load both the source - /// and the destination type: + /// For more information about this association, + /// see ``HasManyThroughAssociation``. /// - /// // A request for all (country, citizen) pairs: - /// let request = Country.including(required: Coutry.citizens) - /// - /// To consume those requests, define a type that adopts both the - /// FetchableRecord and Decodable protocols: - /// - /// struct Citizenship: FetchableRecord, Decodable { - /// var country: Country - /// var citizen: Citizen - /// } - /// - /// let citizenships = try dbQueue.read { db in - /// return try Citizenship.fetchAll(db, request) - /// } - /// for citizenship in citizenships { - /// print("\(citizenship.citizen.name) is a citizen of \(citizenship.country.name)") - /// } - /// - /// It is recommended that you define, alongside the static association, a - /// property with the same name: - /// - /// struct Country: TableRecord, EncodableRecord { - /// static let passports = hasMany(Passport.self) - /// static let citizens = hasMany(Citizen.self, through: passports, using: Passport.citizen) - /// var citizens: QueryInterfaceRequest { - /// return request(for: Country.citizens) - /// } - /// } - /// - /// This property will let you navigate from the source type to the - /// destination type: - /// - /// try dbQueue.read { db in - /// let country: Country = ... - /// let citizens = try country.citizens.fetchAll(db) // [Country] - /// } + /// Methods that build requests involving associations are defined in the + /// ``JoinableRequest`` protocol. /// /// - parameters: /// - destination: The record type at the other side of the association. - /// - pivot: An association from Self to the intermediate type. + /// - pivot: An association from `Self` to the intermediate type. /// - target: A target association from the intermediate type to the /// destination type. - /// - key: An eventual decoding key for the association. By default, it - /// is the same key as the target. + /// - key: The association key. By default, it is the key of the target. public static func hasMany( _ destination: Target.RowDecoder.Type, through pivot: Pivot, @@ -444,67 +450,72 @@ extension TableRecord { } } - /// Creates a "Has One Through" association between Self and the - /// destination type. + /// Creates a ``HasOneThroughAssociation`` between `Self` and the + /// destination `TableRecord` type. /// - /// struct Book: TableRecord { - /// static let library = belongsTo(Library.self) - /// static let returnAddress = hasOne(Address.self, through: library, using: Library.address) + /// For example: + /// + /// ```swift + /// struct Address: TableRecord { } + /// + /// struct Library: TableRecord { + /// static let address = hasOne(Address.self) + /// } + /// + /// struct Book: TableRecord { + /// static let library = belongsTo(Library.self) + /// static let returnAddress = hasOne(Address.self, + /// through: library, + /// using: Library.address, + /// key: "returnAddress") + /// } + /// ``` + /// + /// The association lets you define requests that involve both the source + /// and the destination type. + /// + /// For example, we can fetch all books with their return address: + /// + /// ```swift + /// struct BookInfo: FetchableRecord, Decodable { + /// var book: Book + /// var returnAddress: Address + /// } + /// + /// try dbQueue.read { db in + /// let request = Book + /// .including(required: Book.returnAddress) + /// .asRequest(of: BookInfo.self) + /// let bookInfos = try request.fetchAll(db) + /// for bookInfo in bookInfos { + /// print("\(bookInfo.book.title) must return to \(bookInfo.returnAddress)") /// } + /// } + /// ``` /// - /// struct Library: TableRecord { - /// static let address = hasOne(Address.self) - /// } + /// The association can also help fetching associated records: /// - /// struct Address: TableRecord { ... } + /// ```swift + /// try dbQueue.read { db in + /// let book: Book = ... + /// let returnAddress: Address? = book + /// .request(for: Book.returnAddress) + /// .fetchOne(db) + /// } + /// ``` /// - /// The association will let you define requests that load both the source - /// and the destination type: + /// For more information about this association, + /// see ``HasOneThroughAssociation``. /// - /// // A request for all (book, returnAddress) pairs: - /// let request = Book.including(required: Book.returnAddress) - /// - /// To consume those requests, define a type that adopts both the - /// FetchableRecord and Decodable protocols: - /// - /// struct Todo: FetchableRecord, Decodable { - /// var book: Book - /// var address: Address - /// } - /// - /// let todos = try dbQueue.read { db in - /// return try Todo.fetchAll(db, request) - /// } - /// for todo in todos { - /// print("Please return \(todo.book) to \(todo.address)") - /// } - /// - /// It is recommended that you define, alongside the static association, a - /// property with the same name: - /// - /// struct Book: TableRecord, EncodableRecord { - /// static let library = belongsTo(Library.self) - /// static let returnAddress = hasOne(Address.self, through: library, using: library.address) - /// var returnAddress: QueryInterfaceRequest
{ - /// return request(for: Book.returnAddress) - /// } - /// } - /// - /// This property will let you navigate from the source type to the - /// destination type: - /// - /// try dbQueue.read { db in - /// let book: Book = ... - /// let address = try book.returnAddress.fetchOne(db) // Address? - /// } + /// Methods that build requests involving associations are defined in the + /// ``JoinableRequest`` protocol. /// /// - parameters: /// - destination: The record type at the other side of the association. /// - pivot: An association from Self to the intermediate type. /// - target: A target association from the intermediate type to the /// destination type. - /// - key: An eventual decoding key for the association. By default, it - /// is the same key as the target. + /// - key: The association key. By default, it is the key of the target. public static func hasOne( _ destination: Target.RowDecoder.Type, through pivot: Pivot, @@ -529,19 +540,23 @@ extension TableRecord { // MARK: - Request for associated records extension TableRecord where Self: EncodableRecord { - /// Creates a request that fetches the associated record(s). + /// Returns a request for the associated record(s). /// /// For example: /// - /// struct Team: TableRecord, EncodableRecord { - /// static let players = hasMany(Player.self) - /// var players: QueryInterfaceRequest { - /// return request(for: Team.players) - /// } - /// } + /// ```swift + /// struct Player: TableRecord, FetchableRecord { } + /// struct Team: TableRecord, EncodableRecord { + /// static let players = hasMany(Player.self) + /// } /// + /// try dbQueue.read { db in /// let team: Team = ... - /// let players = try team.players.fetchAll(db) // [Player] + /// let players: [Player] = try team + /// .request(for: Team.players) + /// .fetchAll(db) + /// } + /// ``` public func request(for association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self @@ -571,7 +586,27 @@ extension TableRecord where Self: EncodableRecord { // MARK: - Joining Methods extension TableRecord { - /// Creates a request that prefetches an association. + /// Returns a request that fetches all records associated with each record + /// in this request. + /// + /// For example, we can fetch authors along with their books: + /// + /// ```swift + /// struct Author: TableRecord, FetchableRecord, Decodable { + /// static let books = hasMany(Book.self) + /// } + /// struct Book: TableRecord, FetchableRecord, Decodable { } + /// + /// struct AuthorInfo: FetchableRecord, Decodable { + /// var author: Author + /// var books: [Book] + /// } + /// + /// let authorInfos = try Author + /// .including(all: Author.books) + /// .asRequest(of: AuthorInfo.self) + /// .fetchAll(db) + /// ``` public static func including(all association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self @@ -579,9 +614,27 @@ extension TableRecord { all().including(all: association) } - /// Creates a request that includes an association. The columns of the - /// associated record are selected. The returned association does not - /// require that the associated database table contains a matching row. + /// Returns a request that fetches the eventual record associated with each + /// record of this request. + /// + /// For example, we can fetch books along with their eventual author: + /// + /// ```swift + /// struct Author: TableRecord, FetchableRecord, Decodable { } + /// struct Book: TableRecord, FetchableRecord, Decodable { + /// static let author = belongsTo(Author.self) + /// } + /// + /// struct BookInfo: FetchableRecord, Decodable { + /// var book: Book + /// var author: Author? + /// } + /// + /// let bookInfos = try Book + /// .including(optional: Book.author) + /// .asRequest(of: BookInfo.self) + /// .fetchAll(db) + /// ``` public static func including(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self @@ -589,9 +642,28 @@ extension TableRecord { all().including(optional: association) } - /// Creates a request that includes an association. The columns of the - /// associated record are selected. The returned association requires - /// that the associated database table contains a matching row. + /// Returns a request that fetches the record associated with each record in + /// this request. Records that do not have an associated record + /// are discarded. + /// + /// For example, we can fetch books along with their eventual author: + /// + /// ```swift + /// struct Author: TableRecord, FetchableRecord, Decodable { } + /// struct Book: TableRecord, FetchableRecord, Decodable { + /// static let author = belongsTo(Author.self) + /// } + /// + /// struct BookInfo: FetchableRecord, Decodable { + /// var book: Book + /// var author: Author + /// } + /// + /// let bookInfos = try Book + /// .including(required: Book.author) + /// .asRequest(of: BookInfo.self) + /// .fetchAll(db) + /// ``` public static func including(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self @@ -599,9 +671,8 @@ extension TableRecord { all().including(required: association) } - /// Creates a request that includes an association. The columns of the - /// associated record are not selected. The returned association does not - /// require that the associated database table contains a matching row. + /// Returns a request that joins each record of this request to its + /// eventual associated record. public static func joining(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self @@ -609,9 +680,23 @@ extension TableRecord { all().joining(optional: association) } - /// Creates a request that includes an association. The columns of the - /// associated record are not selected. The returned association requires - /// that the associated database table contains a matching row. + /// Returns a request that joins each record of this request to its + /// associated record. Records that do not have an associated record + /// are discarded. + /// + /// For example, we can fetch only books whose author is French: + /// + /// ```swift + /// struct Author: TableRecord, FetchableRecord, Decodable { } + /// struct Book: TableRecord, FetchableRecord, Decodable { + /// static let author = belongsTo(Author.self) + /// } + /// + /// let frenchAuthors = Book.author.filter(Column("countryCode") == "FR") + /// let bookInfos = try Book + /// .joining(required: frenchAuthors) + /// .fetchAll(db) + /// ``` public static func joining(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self @@ -619,36 +704,22 @@ extension TableRecord { all().joining(required: association) } - /// Creates a request which appends *columns of an associated record* to - /// the selection. + /// Returns a request with the columns of the eventual associated record + /// appended to the record selection. /// - /// // SELECT player.*, team.color - /// // FROM player LEFT JOIN team ... - /// let teamColor = Player.team.select(Column("color")) - /// let request = Player.annotated(withOptional: teamColor) + /// The record selection is determined by + /// ``TableRecord/databaseSelection-7iphs``, which defaults to all columns. /// - /// This method performs the same SQL request as `including(optional:)`. - /// The difference is in the shape of Decodable records that decode such - /// a request: the associated columns can be decoded at the same level as - /// the main record: + /// For example: /// - /// struct PlayerWithTeamColor: FetchableRecord, Decodable { - /// var player: Player - /// var color: String? - /// } - /// let players = try dbQueue.read { db in - /// try request - /// .asRequest(of: PlayerWithTeamColor.self) - /// .fetchAll(db) - /// } + /// ```swift + /// // SELECT player.*, team.color + /// // FROM player LEFT JOIN team ... + /// let teamColor = Player.team.select(Column("color")) + /// let request = Player.annotated(withOptional: teamColor) + /// ``` /// - /// Note: this is a convenience method. You can build the same request with - /// `TableAlias`, `annotated(with:)`, and `joining(optional:)`: - /// - /// let teamAlias = TableAlias() - /// let request = Player - /// .annotated(with: teamAlias[Column("color")]) - /// .joining(optional: Player.team.aliased(teamAlias)) + /// See ``JoinableRequest/annotated(withOptional:)`` for more information. public static func annotated(withOptional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self @@ -656,36 +727,23 @@ extension TableRecord { all().annotated(withOptional: association) } - /// Creates a request which appends *columns of an associated record* to - /// the selection. + /// Returns a request with the columns of the associated record appended to + /// the record selection. Records that do not have an associated record + /// are discarded. /// - /// // SELECT player.*, team.color - /// // FROM player JOIN team ... - /// let teamColor = Player.team.select(Column("color")) - /// let request = Player.annotated(withRequired: teamColor) + /// The record selection is determined by + /// ``TableRecord/databaseSelection-7iphs``, which defaults to all columns. /// - /// This method performs the same SQL request as `including(required:)`. - /// The difference is in the shape of Decodable records that decode such - /// a request: the associated columns can be decoded at the same level as - /// the main record: + /// For example: /// - /// struct PlayerWithTeamColor: FetchableRecord, Decodable { - /// var player: Player - /// var color: String - /// } - /// let players = try dbQueue.read { db in - /// try request - /// .asRequest(of: PlayerWithTeamColor.self) - /// .fetchAll(db) - /// } + /// ```swift + /// // SELECT player.*, team.color + /// // FROM player JOIN team ... + /// let teamColor = Player.team.select(Column("color")) + /// let request = Player.annotated(withRequired: teamColor) + /// ``` /// - /// Note: this is a convenience method. You can build the same request with - /// `TableAlias`, `annotated(with:)`, and `joining(required:)`: - /// - /// let teamAlias = TableAlias() - /// let request = Player - /// .annotated(with: teamAlias[Column("color")]) - /// .joining(required: Player.team.aliased(teamAlias)) + /// See ``JoinableRequest/annotated(withRequired:)`` for more information. public static func annotated(withRequired association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self @@ -697,35 +755,90 @@ extension TableRecord { // MARK: - Aggregates extension TableRecord { - /// Creates a request with *aggregates* appended to the selection. + /// Returns a request with the given association aggregates appended to + /// the record selection. /// - /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount - /// // FROM player LEFT JOIN book ... - /// let request = Player.annotated(with: Player.books.count) + /// The record selection is determined by + /// ``TableRecord/databaseSelection-7iphs``, which defaults to all columns. + /// + /// For example: + /// + /// ```swift + /// struct Author: TableRecord, FetchableRecord, Decodable { + /// static let books = hasMany(Book.self) + /// } + /// struct Book: TableRecord, FetchableRecord, Decodable { } + /// + /// struct AuthorInfo: FetchableRecord, Decodable { + /// var author: Author + /// var bookCount: Int + /// } + /// + /// // SELECT author.*, COUNT(DISTINCT book.id) AS bookCount + /// // FROM author + /// // LEFT JOIN book ON book.authorId = author.id + /// // GROUP BY author.id + /// let authorInfos = try Author + /// .annotated(with: Author.books.count) + /// .asRequest(of: AuthorInfo.self) + /// .fetchAll(db) + /// ``` public static func annotated(with aggregates: AssociationAggregate...) -> QueryInterfaceRequest { all().annotated(with: aggregates) } - /// Creates a request with *aggregates* appended to the selection. + /// Returns a request with the given association aggregates appended to + /// the record selection. /// - /// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount - /// // FROM player LEFT JOIN book ... - /// let request = Player.annotated(with: [Player.books.count]) + /// The record selection is determined by + /// ``TableRecord/databaseSelection-7iphs``, which defaults to all columns. + /// + /// For example: + /// + /// ```swift + /// struct Author: TableRecord, FetchableRecord, Decodable { + /// static let books = hasMany(Book.self) + /// } + /// struct Book: TableRecord, FetchableRecord, Decodable { } + /// + /// struct AuthorInfo: FetchableRecord, Decodable { + /// var author: Author + /// var bookCount: Int + /// } + /// + /// // SELECT author.*, COUNT(DISTINCT book.id) AS bookCount + /// // FROM author + /// // LEFT JOIN book ON book.authorId = author.id + /// // GROUP BY author.id + /// let authorInfos = try Author + /// .annotated(with: [Author.books.count]) + /// .asRequest(of: AuthorInfo.self) + /// .fetchAll(db) + /// ``` public static func annotated(with aggregates: [AssociationAggregate]) -> QueryInterfaceRequest { all().annotated(with: aggregates) } - /// Creates a request with the provided aggregate *predicate*. + /// Returns a request filtered according to the provided + /// association aggregate. /// - /// // SELECT player.* - /// // FROM player LEFT JOIN book ... - /// // HAVING COUNT(DISTINCT book.id) = 0 - /// var request = Player.all() - /// request = request.having(Player.books.isEmpty) + /// For example: /// - /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableRecord.databaseSelection` property, or - /// for individual requests with the `TableRecord.select` method. + /// ```swift + /// struct Author: TableRecord, FetchableRecord { + /// static let books = hasMany(Book.self) + /// } + /// struct Book: TableRecord, FetchableRecord { } + /// + /// // SELECT author.* + /// // FROM author + /// // LEFT JOIN book ON book.authorId = author.id + /// // GROUP BY author.id + /// // HAVING COUNT(DISTINCT book.id) > 5 + /// let authors = try Author + /// .having(Author.books.count > 5) + /// .fetchAll(db) + /// ``` public static func having(_ predicate: AssociationAggregate) -> QueryInterfaceRequest { all().having(predicate) } diff --git a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift index be9e3ad51..21af9630b 100644 --- a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift @@ -6,39 +6,81 @@ extension TableRecord { .all(fromTable: databaseTableName, selection: { _ in databaseSelection.map(\.sqlSelection) }) } - /// Creates a request which fetches all records. + /// Returns a request for all records in the table. /// + /// The record selection is determined by + /// ``TableRecord/databaseSelection-7iphs``, which defaults to all columns. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// try dbQueue.read { db in /// // SELECT * FROM player /// let request = Player.all() + /// } public static func all() -> QueryInterfaceRequest { QueryInterfaceRequest(relation: relationForAll) } - /// Creates a request which fetches no record. + /// Returns an empty request that fetches no record. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord, FetchableRecord { } + /// + /// try dbQueue.read { db in + /// let request = Player.none() + /// let players = try request.fetchAll(db) // empty array + /// } public static func none() -> QueryInterfaceRequest { all().none() // don't laugh } - /// Creates a request which selects *selection*. + /// Returns a request that selects the provided result columns. /// - /// // SELECT id, email FROM player - /// let request = Player.select(Column("id"), Column("email")) + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT id, score FROM player + /// let request = Player.select(Column("id"), Column("score")) + /// ``` public static func select(_ selection: any SQLSelectable...) -> QueryInterfaceRequest { all().select(selection) } - /// Creates a request which selects *selection*. + /// Returns a request that selects the provided result columns. /// - /// // SELECT id, email FROM player - /// let request = Player.select([Column("id"), Column("email")]) + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT id, score FROM player + /// let request = Player.select([Column("id"), Column("score")]) + /// ``` public static func select(_ selection: [any SQLSelectable]) -> QueryInterfaceRequest { all().select(selection) } - /// Creates a request which selects *sql*. + /// Returns a request that selects the provided SQL string. /// - /// // SELECT id, email FROM player - /// let request = Player.select(sql: "id, email") + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT id, name FROM player + /// let request = Player.select(sql: "id, name") + /// + /// // SELECT id, IFNULL(name, 'Anonymous') FROM player + /// let defaultName = "Anonymous" + /// let request = Player.select(sql: "id, IFNULL(name, ?)", arguments: [defaultName]) + /// ``` public static func select( sql: String, arguments: StatementArguments = StatementArguments()) @@ -47,28 +89,43 @@ extension TableRecord { all().select(SQL(sql: sql, arguments: arguments)) } - /// Creates a request which selects an SQL *literal*. + /// Returns a request that selects the provided ``SQL`` literal. /// - /// Literals allow you to safely embed raw values in your SQL, without any - /// risk of syntax errors or SQL injection: + /// ``SQL`` literals allow you to safely embed raw values in your SQL, + /// without any risk of syntax errors or SQL injection: /// - /// // SELECT id, email, score + 1000 FROM player - /// let bonus = 1000 - /// let request = Player.select(literal: """ - /// id, email, score + \(bonus) - /// """) + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT id, IFNULL(name, 'Anonymous') FROM player + /// let defaultName = "Anonymous" + /// let request = Player.select(literal: "id, IFNULL(name, \(defaultName))") + /// ``` public static func select(literal sqlLiteral: SQL) -> QueryInterfaceRequest { all().select(sqlLiteral) } - /// Creates a request which selects *selection*, and fetches values of - /// type *type*. + /// Returns a request that selects the provided result columns, and defines + /// the type of decoded rows. /// - /// try dbQueue.read { db in - /// // SELECT max(score) FROM player - /// let request = Player.select([max(Column("score"))], as: Int.self) - /// let maxScore: Int? = try request.fetchOne(db) - /// } + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// let minScore = min(Column("score")) + /// let maxScore = max(Column("score")) + /// + /// // SELECT MAX(score) FROM player + /// let request = Player.select([maxScore], as: Int.self) + /// let maxScore = try request.fetchOne(db) // Int? + /// + /// // SELECT MIN(score), MAX(score) FROM player + /// let request = Player.select([minScore, maxScore], as: Row.self) + /// if let row = try request.fetchOne(db) { + /// let minScore: Int = row[0] + /// let maxScore: Int = row[1] + /// } + /// ``` public static func select( _ selection: [any SQLSelectable], as type: RowDecoder.Type = RowDecoder.self) @@ -77,14 +134,27 @@ extension TableRecord { all().select(selection, as: type) } - /// Creates a request which selects *selection*, and fetches values of - /// type *type*. + /// Returns a request that selects the provided result columns, and defines + /// the type of decoded rows. /// - /// try dbQueue.read { db in - /// // SELECT max(score) FROM player - /// let request = Player.select(max(Column("score")), as: Int.self) - /// let maxScore: Int? = try request.fetchOne(db) - /// } + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// let minScore = min(Column("score")) + /// let maxScore = max(Column("score")) + /// + /// // SELECT MAX(score) FROM player + /// let request = Player.select(maxScore, as: Int.self) + /// let maxScore = try request.fetchOne(db) // Int? + /// + /// // SELECT MIN(score), MAX(score) FROM player + /// let request = Player.select(minScore, maxScore, as: Row.self) + /// if let row = try request.fetchOne(db) { + /// let minScore: Int = row[0] + /// let maxScore: Int = row[1] + /// } + /// ``` public static func select( _ selection: any SQLSelectable..., as type: RowDecoder.Type = RowDecoder.self) @@ -93,14 +163,23 @@ extension TableRecord { all().select(selection, as: type) } - /// Creates a request which selects *sql*, and fetches values of - /// type *type*. + /// Returns a request that selects the provided SQL string, and defines the + /// type of decoded rows. /// - /// try dbQueue.read { db in - /// // SELECT max(score) FROM player - /// let request = Player.select(sql: "max(score)", as: Int.self) - /// let maxScore: Int? = try request.fetchOne(db) - /// } + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT name FROM player + /// let request = Player.select(sql: "name", as: String.self) + /// let names = try request.fetchAll(db) // [String] + /// + /// // SELECT IFNULL(name, 'Anonymous') FROM player + /// let defaultName = "Anonymous" + /// let request = Player.select(sql: "IFNULL(name, ?)", arguments: [defaultName], as: String.self) + /// let names = try request.fetchAll(db) // [String] + /// ``` public static func select( sql: String, arguments: StatementArguments = StatementArguments(), @@ -110,18 +189,20 @@ extension TableRecord { all().select(SQL(sql: sql, arguments: arguments), as: type) } - /// Creates a request which selects an SQL *literal*, and fetches values of - /// type *type*. + /// Returns a request that selects the provided ``SQL`` literal, and defines + /// the type of decoded rows. /// - /// Literals allow you to safely embed raw values in your SQL, without any - /// risk of syntax errors or SQL injection: + /// ``SQL`` literals allow you to safely embed raw values in your SQL, + /// without any risk of syntax errors or SQL injection: /// - /// // SELECT IFNULL(name, 'Anonymous') FROM player - /// let defaultName = "Anonymous" - /// let request = Player.select( - /// literal: "IFNULL(name, \(defaultName))", - /// as: String.self) - /// let name: String? = try request.fetchOne(db) + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT IFNULL(name, 'Anonymous') FROM player + /// let defaultName = "Anonymous" + /// let request = Player.select(literal: "IFNULL(name, \(defaultName))", as: String.self) + /// let names = try request.fetchAll(db) // [String] + /// ``` public static func select( literal sqlLiteral: SQL, as type: RowDecoder.Type = RowDecoder.self) @@ -130,40 +211,80 @@ extension TableRecord { all().select(sqlLiteral, as: type) } - /// Creates a request which selects the primary key. + /// Returns a request that selects the primary key. /// /// All primary keys are supported: /// - /// // SELECT id FROM player - /// let request = try Player.selectPrimaryKey(as: Int64.self) + /// ```swift + /// struct Player: TableRecord { } + /// struct Country: TableRecord { } + /// struct Citizenship: TableRecord { } /// - /// // SELECT code FROM country - /// let request = try Country.selectPrimaryKey(as: String.self) + /// // SELECT id FROM player WHERE ... + /// let request = try Player.selectPrimaryKey(as: Int64.self) + /// let ids = try request.fetchAll(db) // [Int64] /// - /// // SELECT citizenId, countryCode FROM citizenship - /// let request = try Citizenship.selectPrimaryKey(as: Row.self) + /// // SELECT code FROM country WHERE ... + /// let request = try Country.selectPrimaryKey(as: String.self) + /// let countryCodes = try request.fetchAll(db) // [String] + /// + /// // SELECT citizenId, countryCode FROM citizenship WHERE ... + /// let request = try Citizenship.selectPrimaryKey(as: Row.self) + /// let rows = try request.fetchAll(db) // [Row] + /// ``` + /// + /// For composite primary keys, you can define a ``FetchableRecord`` type: + /// + /// ```swift + /// extension Citizenship { + /// struct ID: Decodable, FetchableRecord { + /// var citizenId: Int64 + /// var countryCode: String + /// } + /// } + /// let request = try Citizenship.selectPrimaryKey(as: Citizenship.ID.self) + /// let ids = try request.fetchAll(db) // [Citizenship.ID] + /// ``` public static func selectPrimaryKey(as type: PrimaryKey.Type = PrimaryKey.self) -> QueryInterfaceRequest { all().selectPrimaryKey(as: type) } - /// Creates a request which appends *selection*. + /// Returns a request with the provided result columns appended to the + /// record selection. /// - /// // SELECT id, email, name FROM player - /// let request = Player - /// .select([Column("id"), Column("email")]) - /// .annotated(with: [Column("name")]) + /// The record selection is determined by + /// ``TableRecord/databaseSelection-7iphs``, which defaults to all columns. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT *, score + bonus AS totalScore FROM player + /// let totalScore = (Column("score") + Column("bonus")).forKey("totalScore") + /// let request = Player.annotated(with: [totalScore]) + /// ``` public static func annotated(with selection: [any SQLSelectable]) -> QueryInterfaceRequest { all().annotated(with: selection) } - /// Creates a request which appends *selection*. + /// Returns a request with the provided result columns appended to the + /// record selection. /// - /// // SELECT id, email, name FROM player - /// let request = Player - /// .select([Column("id"), Column("email")]) - /// .annotated(with: Column("name")) + /// The record selection is determined by + /// ``TableRecord/databaseSelection-7iphs``, which defaults to all columns. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT *, score + bonus AS totalScore FROM player + /// let totalScore = (Column("score") + Column("bonus")).forKey("totalScore") + /// let request = Player.annotated(with: totalScore) + /// ``` public static func annotated(with selection: any SQLSelectable...) -> QueryInterfaceRequest { all().annotated(with: selection) } @@ -171,26 +292,57 @@ extension TableRecord { // Accept SQLSpecificExpressible instead of SQLExpressible, so that we // prevent the `Player.filter(42)` misuse. // See https://github.com/groue/GRDB.swift/pull/864 - /// Creates a request with the provided *predicate*. + /// Returns a request filtered with a boolean SQL expression. /// - /// // SELECT * FROM player WHERE email = 'arthur@example.com' - /// let request = Player.filter(Column("email") == "arthur@example.com") + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT * FROM player WHERE name = 'O''Brien' + /// let name = "O'Brien" + /// let request = Player.filter(Column("name") == name) + /// ``` public static func filter(_ predicate: some SQLSpecificExpressible) -> QueryInterfaceRequest { all().filter(predicate) } - /// Creates a request with the provided primary key *predicate*. + /// Returns a request filtered by primary key. /// - /// // SELECT * FROM player WHERE id = 1 - /// let request = Player.filter(key: 1) + /// All single-column primary keys are supported: + /// + /// ```swift + /// struct Player: TableRecord { } + /// struct Country: TableRecord { } + /// + /// // SELECT * FROM player WHERE id = 1 + /// let request = Player.filter(key: 1) + /// + /// // SELECT * FROM country WHERE code = 'FR' + /// let request = Country.filter(key: "FR") + /// ``` + /// + /// - parameter key: A primary key public static func filter(key: some DatabaseValueConvertible) -> QueryInterfaceRequest { all().filter(key: key) } - /// Creates a request with the provided primary key *predicate*. + /// Returns a request filtered by primary key. /// - /// // SELECT * FROM player WHERE id IN (1, 2, 3) - /// let request = Player.filter(keys: [1, 2, 3]) + /// All single-column primary keys are supported: + /// + /// ```swift + /// struct Player: TableRecord { } + /// struct Country: TableRecord { } + /// + /// // SELECT * FROM player WHERE id = IN (1, 2, 3) + /// let request = Player.filter(keys: [1, 2, 3]) + /// + /// // SELECT * FROM country WHERE code = IN ('FR', 'US') + /// let request = Country.filter(keys: ["FR", "US"]) + /// ``` + /// + /// - parameter keys: A collection of primary keys public static func filter(keys: Keys) -> QueryInterfaceRequest where Keys: Sequence, Keys.Element: DatabaseValueConvertible @@ -198,32 +350,74 @@ extension TableRecord { all().filter(keys: keys) } - /// Creates a request with the provided primary key *predicate*. + /// Returns a request filtered by primary or unique key. /// - /// // SELECT * FROM passport WHERE personId = 1 AND countryCode = 'FR' - /// let request = Passport.filter(key: ["personId": 1, "countryCode": "FR"]) + /// For example: /// - /// When executed, this request raises a fatal error if there is no unique - /// index on the key columns. + /// ```swift + /// struct Player: TableRecord { } + /// struct Citizenship: TableRecord { } + /// + /// // SELECT * FROM player WHERE id = 1 + /// let request = Player.filter(key: ["id": 1]) + /// + /// // SELECT * FROM player WHERE email = 'arthur@example.com' + /// let request = Player.filter(key: ["email": "arthur@example.com"]) + /// + /// // SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR' + /// let request = Citizenship.filter(key: [ + /// "citizenId": 1, + /// "countryCode": "FR", + /// ]) + /// ``` + /// + /// When executed, this request raises a fatal error if no unique index + /// exists on a subset of the key columns. + /// + /// - parameter key: A unique key. public static func filter(key: [String: (any DatabaseValueConvertible)?]?) -> QueryInterfaceRequest { all().filter(key: key) } - /// Creates a request with the provided primary key *predicate*. + /// Returns a request filtered by primary or unique key. /// - /// // SELECT * FROM passport WHERE (personId = 1 AND countryCode = 'FR') OR ... - /// let request = Passport.filter(keys: [["personId": 1, "countryCode": "FR"], ...]) + /// For example: /// - /// When executed, this request raises a fatal error if there is no unique - /// index on the key columns. + /// ```swift + /// struct Player: TableRecord { } + /// struct Citizenship: TableRecord { } + /// + /// // SELECT * FROM player WHERE id = 1 + /// let request = Player.filter(keys: [["id": 1]]) + /// + /// // SELECT * FROM player WHERE email = 'arthur@example.com' + /// let request = Player.filter(keys: [["email": "arthur@example.com"]]) + /// + /// // SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR' + /// let request = Citizenship.filter(keys: [ + /// ["citizenId": 1, "countryCode": "FR"], + /// ]) + /// ``` + /// + /// When executed, this request raises a fatal error if no unique index + /// exists on a subset of the key columns. + /// + /// - parameter keys: A collection of unique keys public static func filter(keys: [[String: (any DatabaseValueConvertible)?]]) -> QueryInterfaceRequest { all().filter(keys: keys) } - /// Creates a request with the provided *predicate*. + /// Returns a request filtered with an SQL string. /// - /// // SELECT * FROM player WHERE email = 'arthur@example.com' - /// let request = Player.filter(sql: "email = ?", arguments: ["arthur@example.com"]) + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT * FROM player WHERE name = 'O''Brien' + /// let name = "O'Brien" + /// let request = Player.filter(sql: "name = ?", arguments: [name]) + /// ``` public static func filter( sql: String, arguments: StatementArguments = StatementArguments()) @@ -232,53 +426,83 @@ extension TableRecord { filter(SQL(sql: sql, arguments: arguments)) } - /// Creates a request with the provided *predicate* added to the - /// eventual set of already applied predicates. + /// Returns a request filtered with an ``SQL`` literal. /// - /// Literals allow you to safely embed raw values in your SQL, without any - /// risk of syntax errors or SQL injection: + /// ``SQL`` literals allow you to safely embed raw values in your SQL, + /// without any risk of syntax errors or SQL injection: /// - /// // SELECT * FROM player WHERE name = 'O''Brien' - /// let name = "O'Brien" - /// let request = Player.filter(literal: "email = \(email)") + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT * FROM player WHERE name = 'O''Brien' + /// let name = "O'Brien" + /// let request = Player.filter(literal: "name = \(name)") + /// ``` public static func filter(literal sqlLiteral: SQL) -> QueryInterfaceRequest { // NOT TESTED all().filter(sqlLiteral) } - /// Creates a request sorted according to the - /// provided *orderings*. + /// Returns a request sorted according to the given SQL ordering terms. /// - /// // SELECT * FROM player ORDER BY name - /// let request = Player.order(Column("name")) + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT * FROM player ORDER BY score DESC, name + /// let request = Player.order(Column("score").desc, Column("name")) + /// ``` public static func order(_ orderings: any SQLOrderingTerm...) -> QueryInterfaceRequest { all().order(orderings) } - /// Creates a request sorted according to the - /// provided *orderings*. + /// Returns a request sorted according to the given SQL ordering terms. /// - /// // SELECT * FROM player ORDER BY name - /// let request = Player.order([Column("name")]) + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT * FROM player ORDER BY score DESC, name + /// let request = Player.order([Column("score").desc, Column("name")]) + /// ``` public static func order(_ orderings: [any SQLOrderingTerm]) -> QueryInterfaceRequest { all().order(orderings) } - /// Creates a request sorted by primary key. + /// Returns a request sorted by primary key. /// - /// // SELECT * FROM player ORDER BY id - /// let request = Player.orderByPrimaryKey() + /// All primary keys are supported: /// - /// // SELECT * FROM country ORDER BY code - /// let request = Country.orderByPrimaryKey() + /// ```swift + /// struct Player: TableRecord { } + /// struct Country: TableRecord { } + /// struct Citizenship: TableRecord { } + /// + /// // SELECT * FROM player ORDER BY id + /// let request = Player.orderByPrimaryKey() + /// + /// // SELECT * FROM country ORDER BY code + /// let request = Country.orderByPrimaryKey() + /// + /// // SELECT * FROM citizenship ORDER BY citizenId, countryCode + /// let request = Citizenship.orderByPrimaryKey() + /// ``` public static func orderByPrimaryKey() -> QueryInterfaceRequest { all().orderByPrimaryKey() } - /// Creates a request sorted according to *sql*. + /// Returns a request sorted according to the given SQL string. /// - /// // SELECT * FROM player ORDER BY name - /// let request = Player.order(sql: "name") + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT * FROM player ORDER BY score DESC, name + /// let request = Player.order(sql: "score DESC, name") + /// ``` public static func order( sql: String, arguments: StatementArguments = StatementArguments()) @@ -287,76 +511,95 @@ extension TableRecord { all().order(SQL(sql: sql, arguments: arguments)) } - /// Creates a request sorted according to an SQL *literal*. + /// Returns a request sorted according to the given ``SQL`` literal. /// - /// // SELECT * FROM player ORDER BY name - /// let request = Player.order(literal: "name") + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT * FROM player ORDER BY score DESC, name + /// let request = Player.order(literal: "score DESC, name") + /// ``` public static func order(literal sqlLiteral: SQL) -> QueryInterfaceRequest { all().order(sqlLiteral) } - /// Creates a request which fetches *limit* rows, starting at - /// *offset*. + /// Returns a limited request. /// - /// // SELECT * FROM player LIMIT 1 - /// let request = Player.limit(1) + /// The returned request fetches `limit` rows, starting at `offset`. For + /// example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT * FROM player LIMIT 10 + /// let request = Player.limit(10) + /// + /// // SELECT * FROM player LIMIT 10 OFFSET 20 + /// let request = Player.limit(10, offset: 20) + /// ``` public static func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { all().limit(limit, offset: offset) } - /// Creates a request that allows you to define expressions that target - /// a specific database table. + /// Returns a request that can be referred to with the provided alias. /// - /// In the example below, the "team.avgScore < player.score" condition in - /// the ON clause could be not achieved without table aliases. + /// Use this method when you need to refer to this table from + /// another request. /// - /// struct Player: TableRecord { - /// static let team = belongsTo(Team.self) - /// } + /// For example, the request below fetches posthumous books: /// - /// // SELECT player.*, team.* - /// // JOIN team ON ... AND team.avgScore < player.score - /// let playerAlias = TableAlias() - /// let request = Player - /// .aliased(playerAlias) - /// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")]) + /// ```swift + /// struct Author: TableRecord { } + /// struct Book: TableRecord { + /// static let author = belongsTo(Author.self) + /// } + /// + /// // SELECT book.* + /// // FROM book + /// // JOIN author ON author.id = book.authorId + /// // AND author.deathDate <= book.publishDate + /// let bookAlias = TableAlias() + /// let request = Book + /// .aliased(bookAlias) + /// .joining(required: Book.author.filter(Column("deathDate") <= bookAlias[Column("publishDate")]) + /// ``` + /// + /// See ``TableRequest/aliased(_:)`` for more information. public static func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { all().aliased(alias) } - /// Returns a request which embeds the common table expression. - /// - /// If a common table expression with the same table name had already been - /// embedded, it is replaced by the new one. + /// Returns a request that embeds a common table expression. /// /// For example, you can build a request that fetches all chats with their - /// latest post: + /// latest message: /// - /// let latestMessageRequest = Message - /// .annotated(with: max(Column("date"))) - /// .group(Column("chatID")) + /// ```swift + /// let latestMessageRequest = Message + /// .annotated(with: max(Column("date"))) + /// .group(Column("chatID")) /// - /// let latestMessageCTE = CommonTableExpression( - /// named: "latestMessage", - /// request: latestMessageRequest) + /// let latestMessageCTE = CommonTableExpression( + /// named: "latestMessage", + /// request: latestMessageRequest) /// - /// let latestMessage = Chat.association( - /// to: latestMessageCTE, - /// on: { chat, latestMessage in - /// chat[Column("id")] == latestMessage[Column("chatID")] - /// }) + /// let latestMessageAssociation = Chat.association( + /// to: latestMessageCTE, + /// on: { chat, latestMessage in + /// chat[Column("id")] == latestMessage[Column("chatID")] + /// }) /// - /// // WITH latestMessage AS - /// // (SELECT *, MAX(date) FROM message GROUP BY chatID) - /// // SELECT chat.*, latestMessage.* - /// // FROM chat - /// // LEFT JOIN latestMessage ON chat.id = latestMessage.chatID - /// let request = Chat - /// .with(latestMessageCTE) - /// .including(optional: latestMessage) - /// - /// - parameter cte: A common table expression. - /// - returns: A request. + /// // WITH latestMessage AS + /// // (SELECT *, MAX(date) FROM message GROUP BY chatID) + /// // SELECT chat.*, latestMessage.* + /// // FROM chat + /// // LEFT JOIN latestMessage ON chat.id = latestMessage.chatID + /// let request = Chat + /// .with(latestMessageCTE) + /// .including(optional: latestMessageAssociation) + /// ``` public static func with(_ cte: CommonTableExpression) -> QueryInterfaceRequest { all().with(cte) } @@ -364,20 +607,48 @@ extension TableRecord { @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { - /// Creates a request filtered by primary key. + /// Returns a request filtered by primary key. /// - /// // SELECT * FROM player WHERE id = 1 - /// let request = Player.filter(id: 1) + /// All single-column primary keys are supported: + /// + /// ```swift + /// struct Player: TableRecord, Identifiable { + /// var id: Int64 + /// } + /// struct Country: TableRecord, Identifiable { + /// var id: String + /// } + /// + /// // SELECT * FROM player WHERE id = 1 + /// let request = Player.filter(id: 1) + /// + /// // SELECT * FROM country WHERE code = 'FR' + /// let request = Country.filter(id: "FR") + /// ``` /// /// - parameter id: A primary key public static func filter(id: ID) -> QueryInterfaceRequest { all().filter(id: id) } - /// Creates a request filtered by primary key. + /// Returns a request filtered by primary key. /// - /// // SELECT * FROM player WHERE id IN (1, 2, 3) - /// let request = Player.filter(ids: [1, 2, 3]) + /// All single-column primary keys are supported: + /// + /// ```swift + /// struct Player: TableRecord, Identifiable { + /// var id: Int64 + /// } + /// struct Country: TableRecord, Identifiable { + /// var id: String + /// } + /// + /// // SELECT * FROM player WHERE id = IN (1, 2, 3) + /// let request = Player.filter(ids: [1, 2, 3]) + /// + /// // SELECT * FROM country WHERE code = IN ('FR', 'US') + /// let request = Country.filter(ids: ["FR", "US"]) + /// ``` /// /// - parameter ids: A collection of primary keys public static func filter(ids: IDS) -> QueryInterfaceRequest diff --git a/GRDB/Record/EncodableRecord+Encodable.swift b/GRDB/Record/EncodableRecord+Encodable.swift index a73d7bdf1..2d6e5dba4 100644 --- a/GRDB/Record/EncodableRecord+Encodable.swift +++ b/GRDB/Record/EncodableRecord+Encodable.swift @@ -1,6 +1,8 @@ import Foundation extension EncodableRecord where Self: Encodable { + /// Encodes the record into the provided persistence container, using the + /// `Encodable` conformance. public func encode(to container: inout PersistenceContainer) throws { let encoder = RecordEncoder(persistenceContainer: container) try encode(to: encoder) diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index 72c2d6784..336cae571 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -1,23 +1,62 @@ import Foundation // For JSONEncoder -/// Types that adopt `EncodableRecord` can be encoded into the database. +/// A type that can encode itself in a database row. +/// +/// To conform to `EncodableRecord`, provide an implementation for the +/// ``encode(to:)-k9pf`` method. This implementation is ready-made for +/// `Encodable` types. +/// +/// Most of the time, your record types will get `EncodableRecord` conformance +/// through the ``MutablePersistableRecord`` or ``PersistableRecord`` protocols, +/// which provide persistence methods. +/// +/// ## Topics +/// +/// ### Encoding a Database Row +/// +/// - ``encode(to:)-k9pf`` +/// - ``PersistenceContainer`` +/// +/// ### Configuring Persistence for the Standard Encodable Protocol +/// +/// - ``databaseColumnEncodingStrategy-5sx4v`` +/// - ``databaseDateEncodingStrategy-2gtc1`` +/// - ``databaseEncodingUserInfo-8upii`` +/// - ``databaseJSONEncoder(for:)-6x62c`` +/// - ``databaseUUIDEncodingStrategy-2t96q`` +/// - ``DatabaseColumnEncodingStrategy`` +/// - ``DatabaseDateEncodingStrategy`` +/// - ``DatabaseUUIDEncodingStrategy`` +/// +/// ### Converting a Record to a Dictionary +/// +/// - ``databaseDictionary`` +/// +/// ### Comparing Records +/// +/// - ``databaseChanges(from:)`` +/// - ``databaseEquals(_:)`` public protocol EncodableRecord { - /// Encodes the record into database values. + /// Encodes the record into the provided persistence container. /// - /// Store in the *container* argument all values that should be stored in - /// the columns of the database table (see databaseTableName()). + /// In your implementation of this method, store in the `container` argument + /// all values that should be stored in database columns. /// /// Primary key columns, if any, must be included. /// - /// struct Player: EncodableRecord { - /// var id: Int64? - /// var name: String? + /// For example: /// - /// func encode(to container: inout PersistenceContainer) { - /// container["id"] = id - /// container["name"] = name - /// } + /// ```swift + /// struct Player: EncodableRecord { + /// var id: Int64? + /// var name: String? + /// + /// func encode(to container: inout PersistenceContainer) { + /// container["id"] = id + /// container["name"] = name /// } + /// } + /// ``` /// /// It is undefined behavior to set different values for the same column. /// Column names are case insensitive, so defining both "name" and "NAME" @@ -29,119 +68,125 @@ public protocol EncodableRecord { // MARK: - Customizing the Format of Database Columns - /// When the EncodableRecord type also adopts the standard Encodable - /// protocol, you can use this dictionary to customize the encoding process - /// into database rows. + /// Contextual information made available to the + /// `Encodable.encode(to:)` method. + /// + /// This property is dedicated to ``EncodableRecord`` types that also + /// conform to the standard `Encodable` protocol and use the default + /// ``encode(to:)-1mrt`` implementation. + /// + /// The returned dictionary is returned by `Encoder.userInfo` when the + /// record is encoded. /// /// For example: /// - /// // A key that holds a encoder's name - /// let encoderName = CodingUserInfoKey(rawValue: "encoderName")! + /// ```swift + /// // A key that holds a encoder's name + /// let encoderName = CodingUserInfoKey(rawValue: "encoderName")! /// - /// struct Player: PersistableRecord, Encodable { - /// // Customize the encoder name when encoding a database row - /// static let databaseEncodingUserInfo: [CodingUserInfoKey: Any] = [encoderName: "Database"] + /// struct Player: PersistableRecord, Encodable { + /// // Customize the encoder name when encoding a database row + /// static let databaseEncodingUserInfo: [CodingUserInfoKey: Any] = [encoderName: "Database"] /// - /// func encode(to encoder: Encoder) throws { - /// // Print the encoder name - /// print(encoder.userInfo[encoderName]) - /// ... - /// } + /// func encode(to encoder: Encoder) throws { + /// // Print the encoder name + /// print(encoder.userInfo[encoderName]) + /// ... /// } + /// } /// - /// let player = Player(...) + /// let player = Player(...) /// - /// // prints "Database" - /// try player.insert(db) + /// // prints "Database" + /// try player.insert(db) /// - /// // prints "JSON" - /// let encoder = JSONEncoder() - /// encoder.userInfo = [encoderName: "JSON"] - /// let data = try encoder.encode(player) + /// // prints "JSON" + /// let encoder = JSONEncoder() + /// encoder.userInfo = [encoderName: "JSON"] + /// let data = try encoder.encode(player) + /// ``` static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] { get } - /// When the EncodableRecord type also adopts the standard Encodable - /// protocol, this method controls the encoding process of nested properties - /// into JSON database columns. + /// Returns the `JSONEncoder` that encodes the value for a given column. /// - /// The default implementation returns a JSONEncoder with the - /// following properties: - /// - /// - dataEncodingStrategy: .base64 - /// - dateEncodingStrategy: .millisecondsSince1970 - /// - nonConformingFloatEncodingStrategy: .throw - /// - outputFormatting: .sortedKeys - /// - /// You can override those defaults: - /// - /// struct Achievement: Encodable { - /// var name: String - /// var date: Date - /// } - /// - /// struct Player: Encodable, PersistableRecord { - /// // stored in a JSON column - /// var achievements: [Achievement] - /// - /// static func databaseJSONEncoder(for column: String) -> JSONEncoder { - /// let encoder = JSONEncoder() - /// encoder.dateEncodingStrategy = .iso8601 - /// return encoder - /// } - /// } + /// This method is dedicated to ``EncodableRecord`` types that also conform + /// to the standard `Encodable` protocol and use the default + /// ``encode(to:)-1mrt`` implementation. static func databaseJSONEncoder(for column: String) -> JSONEncoder - /// When the EncodableRecord type also adopts the standard Encodable - /// protocol, this property controls the encoding of date properties. + /// The strategy for encoding `Date` columns. /// - /// Default value is .deferredToDate + /// This property is dedicated to ``EncodableRecord`` types that also + /// conform to the standard `Encodable` protocol and use the default + /// ``encode(to:)-1mrt`` implementation. /// /// For example: /// - /// struct Player: PersistableRecord, Encodable { - /// static let databaseDateEncodingStrategy: DatabaseDateEncodingStrategy = .timeIntervalSince1970 + /// ```swift + /// struct Player: EncodableRecord, Encodable { + /// static let databaseDateEncodingStrategy = DatabaseDateEncodingStrategy.timeIntervalSince1970 /// - /// var name: String - /// var registrationDate: Date // encoded as an epoch timestamp - /// } + /// // Encoded as an epoch timestamp + /// var creationDate: Date + /// } + /// ``` static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { get } - /// When the EncodableRecord type also adopts the standard Encodable - /// protocol, this property controls the encoding of UUID properties. + /// The strategy for encoding `UUID` columns. /// - /// Default value is .deferredToUUID + /// This property is dedicated to ``EncodableRecord`` types that also + /// conform to the standard `Encodable` protocol and use the default + /// ``encode(to:)-1mrt`` implementation. /// /// For example: /// - /// struct Player: PersistableProtocol, Encodable { - /// static let databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy = .uppercaseString + /// ```swift + /// struct Player: EncodableRecord, Encodable { + /// static let databaseUUIDEncodingStrategy = DatabaseUUIDEncodingStrategy.uppercaseString /// - /// // encoded in a string like "E621E1F8-C36C-495A-93FC-0C247A3E6E5F" - /// var uuid: UUID - /// } + /// // Encoded in a string like "E621E1F8-C36C-495A-93FC-0C247A3E6E5F" + /// var uuid: UUID + /// } + /// ``` static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { get } - /// When the EncodableRecord type also adopts the standard Encodable - /// protocol, this property controls the key encoding strategy. + /// The strategy for converting coding keys to column names. /// - /// Default value is .useDefaultKeys + /// This property is dedicated to ``EncodableRecord`` types that also + /// conform to the standard `Encodable` protocol and use the default + /// ``encode(to:)-1mrt`` implementation. /// /// For example: /// - /// struct Player: PersistableProtocol, Encodable { - /// static let databaseColumnEncodingStrategy: DatabaseColumnEncodingStrategy = .convertToSnakeCase + /// ```swift + /// struct Player: EncodableProtocol, Encodable { + /// static let databaseColumnEncodingStrategy = DatabaseColumnEncodingStrategy.convertToSnakeCase /// - /// // encoded as player_id - /// var playerID: String - /// } + /// // Encoded in the 'player_id' column + /// var playerID: String + /// } + /// ``` static var databaseColumnEncodingStrategy: DatabaseColumnEncodingStrategy { get } } extension EncodableRecord { + /// Contextual information made available to the + /// `Encodable.encode(to:)` method. + /// + /// The default implementation returns an empty dictionary. public static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] { [:] } + /// Returns the `JSONEncoder` that encodes the value for a given column. + /// + /// The default implementation returns a `JSONEncoder` with the + /// following properties: + /// + /// - `dataEncodingStrategy`: `.base64` + /// - `dateEncodingStrategy`: `.millisecondsSince1970` + /// - `nonConformingFloatEncodingStrategy`: `.throw` + /// - `outputFormatting`: `.sortedKeys` public static func databaseJSONEncoder(for column: String) -> JSONEncoder { let encoder = JSONEncoder() encoder.dataEncodingStrategy = .base64 @@ -153,21 +198,28 @@ extension EncodableRecord { return encoder } + /// Returns the default strategy for encoding `Date` columns: + /// ``DatabaseDateEncodingStrategy/deferredToDate``. public static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { .deferredToDate } + /// Returns the default strategy for encoding `UUID` columns: + /// ``DatabaseUUIDEncodingStrategy/deferredToUUID``. public static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { .deferredToUUID } + /// Returns the default strategy for converting coding keys to column names: + /// ``DatabaseColumnEncodingStrategy/useDefaultKeys``. public static var databaseColumnEncodingStrategy: DatabaseColumnEncodingStrategy { .useDefaultKeys } } extension EncodableRecord { - /// A dictionary whose keys are the columns encoded in the `encode(to:)` method. + /// A dictionary whose keys are the columns encoded in the + /// method. /// /// - throws: An error is thrown if the record can't be encoded to its /// database representation. @@ -193,18 +245,20 @@ extension EncodableRecord { } } - /// A dictionary of values changed from the other record. + /// Returns a dictionary of values changed from the other record. /// - /// Its keys are column names. Its values come from the other record. + /// The keys of the dictionary are the column names for which record do not + /// share the same value. Values are the database values from the + /// `other` record. /// - /// Note that this method is not symmetrical, not only in terms of values, - /// but also in terms of columns. When the two records don't define the - /// same set of columns in their `encode(to:)` method, only the columns - /// defined by the receiver record are considered. + /// Note that the `other` record does not have to have the same type of the + /// receiver record. When the two records don't define the same set of + /// columns in their + /// method, only the columns defined by the receiver are considered. /// /// - throws: An error is thrown if one record can't be encoded to its /// database representation. - public func databaseChanges(from record: Record) + public func databaseChanges(from record: some EncodableRecord) throws -> [String: DatabaseValue] { let changes = try PersistenceContainer(self).changesIterator(from: PersistenceContainer(record)) @@ -214,39 +268,23 @@ extension EncodableRecord { // MARK: - PersistenceContainer -/// Use persistence containers in the `encode(to:)` method of your -/// encodable records: +/// A container for database values to store in a database row. /// -/// struct Player: EncodableRecord { -/// var id: Int64? -/// var name: String? -/// -/// func encode(to container: inout PersistenceContainer) { -/// container["id"] = id -/// container["name"] = name -/// } -/// } +/// `PersistenceContainer` is the argument of the +/// ``EncodableRecord/encode(to:)-k9pf`` method. public struct PersistenceContainer { // fileprivate for Row(_:PersistenceContainer) // The ordering of the OrderedDictionary helps generating always the same // SQL queries, and hit the statement cache. fileprivate var storage: OrderedDictionary - /// Accesses the value associated with the given column. - /// - /// It is undefined behavior to set different values for the same column. - /// Column names are case insensitive, so defining both "name" and "NAME" - /// is considered undefined behavior. + /// The value associated with the given column. public subscript(_ column: String) -> (any DatabaseValueConvertible)? { get { self[caseInsensitive: column] } set { storage.updateValue(newValue, forKey: column) } } - /// Accesses the value associated with the given column. - /// - /// It is undefined behavior to set different values for the same column. - /// Column names are case insensitive, so defining both "name" and "NAME" - /// is considered undefined behavior. + /// The value associated with the given column. public subscript(_ column: some ColumnExpression) -> (any DatabaseValueConvertible)? { get { self[column.name] } set { self[column.name] = newValue } @@ -283,8 +321,6 @@ public struct PersistenceContainer { /// Accesses the value associated with the given column, in a /// case-insensitive fashion. - /// - /// :nodoc: subscript(caseInsensitive column: String) -> (any DatabaseValueConvertible)? { get { if let value = storage[column] { @@ -358,16 +394,20 @@ extension Row { // MARK: - DatabaseDateEncodingStrategy /// `DatabaseDateEncodingStrategy` specifies how `EncodableRecord` types that -/// also adopt the standard `Encodable` protocol encode their `Date` properties. +/// also adopt the standard `Encodable` protocol encode their `Date` properties +/// in the default +/// implementation. /// /// For example: /// -/// struct Player: EncodableRecord, Encodable { -/// static let databaseDateEncodingStrategy = DatabaseDateEncodingStrategy.timeIntervalSince1970 +/// ```swift +/// struct Player: EncodableRecord, Encodable { +/// static let databaseDateEncodingStrategy = DatabaseDateEncodingStrategy.timeIntervalSince1970 /// -/// var name: String -/// var registrationDate: Date // encoded as an epoch timestamp -/// } +/// // Encoded as an epoch timestamp +/// var creationDate: Date +/// } +/// ``` public enum DatabaseDateEncodingStrategy { /// The strategy that uses formatting from the Date structure. /// @@ -431,16 +471,20 @@ public enum DatabaseDateEncodingStrategy { // MARK: - DatabaseUUIDEncodingStrategy /// `DatabaseUUIDEncodingStrategy` specifies how `EncodableRecord` types that -/// also adopt the standard `Encodable` protocol encode their `UUID` properties. +/// also adopt the standard `Encodable` protocol encode their `UUID` properties +/// in the default +/// implementation. /// /// For example: /// -/// struct Player: EncodableProtocol, Encodable { -/// static let databaseUUIDEncodingStrategy = DatabaseUUIDEncodingStrategy.uppercaseString +/// ```swift +/// struct Player: EncodableRecord, Encodable { +/// static let databaseUUIDEncodingStrategy = DatabaseUUIDEncodingStrategy.uppercaseString /// -/// // encoded in a string like "E621E1F8-C36C-495A-93FC-0C247A3E6E5F" -/// var uuid: UUID -/// } +/// // Encoded in a string like "E621E1F8-C36C-495A-93FC-0C247A3E6E5F" +/// var uuid: UUID +/// } +/// ``` public enum DatabaseUUIDEncodingStrategy { /// The strategy that uses formatting from the UUID type. /// @@ -469,16 +513,19 @@ public enum DatabaseUUIDEncodingStrategy { /// `DatabaseColumnEncodingStrategy` specifies how `EncodableRecord` types that /// also adopt the standard `Encodable` protocol encode their coding keys into -/// database columns. +/// database columns in the default +/// implementation. /// /// For example: /// -/// struct Player: EncodableProtocol, Encodable { -/// static let databaseColumnEncodingStrategy = DatabaseColumnEncodingStrategy.convertToSnakeCase +/// ```swift +/// struct Player: EncodableProtocol, Encodable { +/// static let databaseColumnEncodingStrategy = DatabaseColumnEncodingStrategy.convertToSnakeCase /// -/// // Encoded in the player_id column -/// var playerID: String -/// } +/// // Encoded in the 'player_id' column +/// var playerID: String +/// } +/// ``` public enum DatabaseColumnEncodingStrategy { /// A key encoding strategy that doesn’t change key names during encoding. case useDefaultKeys diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index 9be222aec..d74a49c05 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -1,6 +1,7 @@ import Foundation extension FetchableRecord where Self: Decodable { + /// Creates a record from `row`, using the `Decodable` conformance. public init(row: Row) throws { self = try RowDecoder().decode(from: row) } @@ -367,10 +368,16 @@ private struct _RowDecoder: Decoder { return try T(from: columnDecoder) } catch is JSONRequiredError { // Decode from JSON - let data = try row.decodeDataNoCopy(atIndex: index) - return try R - .databaseJSONDecoder(for: key.stringValue) - .decode(type.self, from: data) + return try row.withUnsafeData(atIndex: index) { data in + guard let data = data else { + throw DecodingError.valueNotFound(Data.self, DecodingError.Context( + codingPath: codingPath + [key], + debugDescription: "Missing Data")) + } + return try R + .databaseJSONDecoder(for: key.stringValue) + .decode(type.self, from: data) + } } } } diff --git a/GRDB/Record/FetchableRecord+TableRecord.swift b/GRDB/Record/FetchableRecord+TableRecord.swift index 43e4b59b8..ceb76c048 100644 --- a/GRDB/Record/FetchableRecord+TableRecord.swift +++ b/GRDB/Record/FetchableRecord+TableRecord.swift @@ -2,75 +2,96 @@ extension FetchableRecord where Self: TableRecord { // MARK: Fetching All - /// A cursor over all records fetched from the database. + /// Returns a cursor over all records fetched from the database. /// + /// For example: + /// + /// ```swift + /// struct Player: FetchableRecord, TableRecord { } + /// + /// try dbQueue.read { db in /// // SELECT * FROM player - /// let players = try Player.fetchCursor(db) // Cursor of Player - /// while let player = try players.next() { // Player - /// ... + /// let players = try Player.fetchCursor(db) + /// while let player = try players.next() { + /// print(player.name) /// } + /// } + /// ``` /// - /// Records are iterated in the natural ordering of the table. + /// The order in which the records are returned is undefined + /// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)). + /// + /// The returned cursor is valid only during the remaining execution of the + /// database access. Do not store or return the cursor for later use. /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// - /// The cursor must be iterated in a protected dispatch queue. - /// - /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableRecord.databaseSelection` property, or - /// for individual requests with the `TableRecord.select` method. - /// /// - parameter db: A database connection. - /// - returns: A cursor over fetched records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: A ``RecordCursor`` over fetched records. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor(_ db: Database) throws -> RecordCursor { try all().fetchCursor(db) } - /// An array of all records fetched from the database. + /// Returns an array of all records fetched from the database. /// + /// For example: + /// + /// ```swift + /// struct Player: FetchableRecord, TableRecord { } + /// + /// try dbQueue.read { db in /// // SELECT * FROM player - /// let players = try Player.fetchAll(db) // [Player] + /// let players = try Player.fetchAll(db) + /// } + /// ``` /// - /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableRecord.databaseSelection` property, or - /// for individual requests with the `TableRecord.select` method. + /// The order in which the records are returned is undefined + /// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)). /// /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll(_ db: Database) throws -> [Self] { try all().fetchAll(db) } - /// The first found record. + /// Returns a single record fetched from the database. /// + /// For example: + /// + /// ```swift + /// struct Player: FetchableRecord, TableRecord { } + /// + /// try dbQueue.read { db in /// // SELECT * FROM player LIMIT 1 - /// let player = try Player.fetchOne(db) // Player? - /// - /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableRecord.databaseSelection` property, or - /// for individual requests with the `TableRecord.select` method. + /// let player = try Player.fetchOne(db) + /// } + /// ``` /// /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne(_ db: Database) throws -> Self? { try all().fetchOne(db) } } extension FetchableRecord where Self: TableRecord & Hashable { - /// A set of all records fetched from the database. + /// Returns a set of all records fetched from the database. /// + /// For example: + /// + /// ```swift + /// struct Player: FetchableRecord, TableRecord, Hashable { } + /// + /// try dbQueue.read { db in /// // SELECT * FROM player - /// let players = try Player.fetchSet(db) // Set - /// - /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableRecord.databaseSelection` property, or - /// for individual requests with the `TableRecord.select` method. + /// let players = try Player.fetchSet(db) + /// } + /// ``` /// /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet(_ db: Database) throws -> Set { try all().fetchSet(db) } @@ -80,20 +101,33 @@ extension FetchableRecord where Self: TableRecord { // MARK: Fetching by Single-Column Primary Key - /// Returns a cursor over records, given their primary keys. + /// Returns a cursor over records identified by their primary keys. /// - /// let players = try Player.fetchCursor(db, keys: [1, 2, 3]) // Cursor of Player - /// while let player = try players.next() { // Player - /// ... + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let players = try Player.fetchCursor(db, keys: [1, 2, 3]) + /// while let player = try players.next() { + /// print(player.name) /// } + /// } + /// ``` /// - /// Records are iterated in unspecified order. + /// The order in which the records are returned is undefined + /// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)). + /// + /// The returned cursor is valid only during the remaining execution of the + /// database access. Do not store or return the cursor for later use. + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. /// /// - parameters: /// - db: A database connection. /// - keys: A sequence of primary keys. - /// - returns: A cursor over fetched records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: A ``RecordCursor`` over fetched records. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, keys: Keys) throws -> RecordCursor where Keys: Sequence, Keys.Element: DatabaseValueConvertible @@ -101,17 +135,25 @@ extension FetchableRecord where Self: TableRecord { try filter(keys: keys).fetchCursor(db) } - /// Returns an array of records, given their primary keys. + /// Returns an array of records identified by their primary keys. /// - /// let players = try Player.fetchAll(db, keys: [1, 2, 3]) // [Player] + /// For example: /// - /// The order of records in the returned array is undefined. + /// ```swift + /// try dbQueue.read { db in + /// let players = try Player.fetchAll(db, keys: [1, 2, 3]) + /// let countries = try Country.fetchAll(db, keys: ["FR", "US"]) + /// } + /// ``` + /// + /// The order in which the records are returned is undefined + /// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)). /// /// - parameters: /// - db: A database connection. /// - keys: A sequence of primary keys. /// - returns: An array of records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll(_ db: Database, keys: Keys) throws -> [Self] where Keys: Sequence, Keys.Element: DatabaseValueConvertible @@ -124,15 +166,22 @@ extension FetchableRecord where Self: TableRecord { return try filter(keys: keys).fetchAll(db) } - /// Returns a single record given its primary key. + /// Returns the record identified by a primary key. /// - /// let player = try Player.fetchOne(db, key: 123) // Player? + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let player = try Player.fetchOne(db, key: 123) + /// let country = try Country.fetchOne(db, key: "FR") + /// } + /// ``` /// /// - parameters: /// - db: A database connection. /// - key: A primary key value. /// - returns: An optional record. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Self? { if key.databaseValue.isNull { // Don't hit the database @@ -147,20 +196,33 @@ extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseVa // MARK: Fetching by Single-Column Primary Key - /// Returns a cursor over records, given their primary keys. + /// Returns a cursor over records identified by their primary keys. /// - /// let players = try Player.fetchCursor(db, ids: [1, 2, 3]) // Cursor of Player - /// while let player = try players.next() { // Player - /// ... + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let players = try Player.fetchCursor(db, ids: [1, 2, 3]) + /// while let player = try players.next() { + /// print(player.name) /// } + /// } + /// ``` /// - /// Records are iterated in unspecified order. + /// The order in which the records are returned is undefined + /// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)). + /// + /// The returned cursor is valid only during the remaining execution of the + /// database access. Do not store or return the cursor for later use. + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. /// /// - parameters: /// - db: A database connection. /// - ids: A collection of primary keys. - /// - returns: A cursor over fetched records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: A ``RecordCursor`` over fetched records. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, ids: IDS) throws -> RecordCursor where IDS: Collection, IDS.Element == ID @@ -168,17 +230,25 @@ extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseVa try filter(ids: ids).fetchCursor(db) } - /// Returns an array of records, given their primary keys. + /// Returns an array of records identified by their primary keys. /// - /// let players = try Player.fetchAll(db, ids: [1, 2, 3]) // [Player] + /// For example: /// - /// The order of records in the returned array is undefined. + /// ```swift + /// try dbQueue.read { db in + /// let players = try Player.fetchAll(db, ids: [1, 2, 3]) + /// let players = try Country.fetchAll(db, ids: ["FR", "US"]) + /// } + /// ``` + /// + /// The order in which the records are returned is undefined + /// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)). /// /// - parameters: /// - db: A database connection. /// - ids: A collection of primary keys. /// - returns: An array of records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll(_ db: Database, ids: IDS) throws -> [Self] where IDS: Collection, IDS.Element == ID { @@ -189,30 +259,44 @@ extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseVa return try filter(ids: ids).fetchAll(db) } - /// Returns a single record given its primary key. + /// Returns the record identified by a primary key. /// - /// let player = try Player.fetchOne(db, id: 123) // Player? + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let player = try Player.fetchOne(db, id: 123) + /// let country = try Country.fetchOne(db, key: "FR") + /// } + /// ``` /// /// - parameters: /// - db: A database connection. /// - id: A primary key value. /// - returns: An optional record. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne(_ db: Database, id: ID) throws -> Self? { try filter(id: id).fetchOne(db) } } extension FetchableRecord where Self: TableRecord & Hashable { - /// Returns a set of records, given their primary keys. + /// Returns a set of records identified by their primary keys. /// - /// let players = try Player.fetchSet(db, keys: [1, 2, 3]) // Set + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let players = try Player.fetchSet(db, keys: [1, 2, 3]) + /// let countries = try Country.fetchSet(db, keys: ["FR", "US"]) + /// } + /// ``` /// /// - parameters: /// - db: A database connection. /// - keys: A sequence of primary keys. /// - returns: A set of records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet(_ db: Database, keys: Keys) throws -> Set where Keys: Sequence, Keys.Element: DatabaseValueConvertible @@ -228,15 +312,22 @@ extension FetchableRecord where Self: TableRecord & Hashable { @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) extension FetchableRecord where Self: TableRecord & Hashable & Identifiable, ID: DatabaseValueConvertible { - /// Returns a set of records, given their primary keys. + /// Returns a set of records identified by their primary keys. /// - /// let players = try Player.fetchSet(db, ids: [1, 2, 3]) // Set + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let players = try Player.fetchSet(db, ids: [1, 2, 3]) + /// let countries = try Country.fetchSet(db, ids: ["FR", "US"]) + /// } + /// ``` /// /// - parameters: /// - db: A database connection. /// - ids: A collection of primary keys. /// - returns: A set of records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet(_ db: Database, ids: IDS) throws -> Set where IDS: Collection, IDS.Element == ID { @@ -255,21 +346,33 @@ extension FetchableRecord where Self: TableRecord { /// Returns a cursor over records identified by the provided unique keys /// (primary key or any key with a unique index on it). /// - /// // Cursor of Player + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in /// let players = try Player.fetchCursor(db, keys: [ /// ["email": "a@example.com"], /// ["email": "b@example.com"]]) - /// while let player = try players.next() { // Player - /// ... + /// while let player = try players.next() { + /// print(player.name) /// } + /// } + /// ``` /// - /// Records are iterated in unspecified order. + /// The order in which the records are returned is undefined + /// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)). + /// + /// The returned cursor is valid only during the remaining execution of the + /// database access. Do not store or return the cursor for later use. + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. /// /// - parameters: /// - db: A database connection. /// - keys: An array of key dictionaries. - /// - returns: A cursor over fetched records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: A ``RecordCursor`` over fetched records. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> RecordCursor { @@ -279,18 +382,24 @@ extension FetchableRecord where Self: TableRecord { /// Returns an array of records identified by the provided unique keys /// (primary key or any key with a unique index on it). /// - /// // [Player] + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in /// let players = try Player.fetchAll(db, keys: [ /// ["email": "a@example.com"], /// ["email": "b@example.com"]]) + /// } + /// ``` /// - /// The order of records in the returned array is undefined. + /// The order in which the records are returned is undefined + /// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)). /// /// - parameters: /// - db: A database connection. /// - keys: An array of key dictionaries. /// - returns: An array of records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> [Self] { if keys.isEmpty { // Avoid hitting the database @@ -299,16 +408,22 @@ extension FetchableRecord where Self: TableRecord { return try filter(keys: keys).fetchAll(db) } - /// Returns a single record identified by a unique key (the primary key or + /// Returns the record identified by a unique key (the primary key or /// any key with a unique index on it). /// - /// let player = try Player.fetchOne(db, key: ["name": Arthur"]) // Player? + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let player = try Player.fetchOne(db, key: ["name": "Arthur"]) + /// } + /// ``` /// /// - parameters: /// - db: A database connection. /// - key: A dictionary of values. /// - returns: An optional record. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]?) throws -> Self? { guard let key else { // Avoid hitting the database @@ -322,16 +437,21 @@ extension FetchableRecord where Self: TableRecord & Hashable { /// Returns a set of records identified by the provided unique keys /// (primary key or any key with a unique index on it). /// - /// // Set + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in /// let players = try Player.fetchSet(db, keys: [ /// ["email": "a@example.com"], /// ["email": "b@example.com"]]) + /// } + /// ``` /// /// - parameters: /// - db: A database connection. /// - keys: An array of key dictionaries. /// - returns: A set of records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> Set { if keys.isEmpty { // Avoid hitting the database diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 453f49f9d..424664eeb 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -1,134 +1,208 @@ import Foundation -/// Types that adopt `FetchableRecord` can be initialized from a database Row. +/// A type that can decode itself from a database row. /// -/// let row = try Row.fetchOne(db, sql: "SELECT ...")! -/// let player = Player(row) +/// To conform to `FetchableRecord`, provide an implementation for the +/// ``init(row:)-9w9yp`` initializer. This implementation is ready-made for +/// `Decodable` types. /// -/// The protocol comes with built-in methods that allow to fetch cursors, -/// arrays, or single records: +/// For example: /// -/// try Player.fetchCursor(db, sql: "SELECT ...", arguments:...) // Cursor of Player -/// try Player.fetchAll(db, sql: "SELECT ...", arguments:...) // [Player] -/// try Player.fetchOne(db, sql: "SELECT ...", arguments:...) // Player? +/// ```swift +/// struct Player: FetchableRecord, Decodable { +/// var name: String +/// var score: Int +/// } /// -/// let statement = try db.makeStatement(sql: "SELECT ...") -/// try Player.fetchCursor(statement, arguments:...) // Cursor of Player -/// try Player.fetchAll(statement, arguments:...) // [Player] -/// try Player.fetchOne(statement, arguments:...) // Player? +/// if let row = try Row.fetchOne(db, sql: "SELECT * FROM player") { +/// let player = try Player(row: row) +/// } +/// ``` +/// +/// If you add conformance to ``TableRecord``, the record type can generate +/// SQL queries for you: +/// +/// ```swift +/// struct Player: FetchableRecord, TableRecord, Decodable { +/// var name: String +/// var score: Int +/// } +/// +/// let players = try Player.fetchAll(db) +/// let players = try Player.order(Column("score")).fetchAll(db) +/// ``` +/// +/// ## Topics +/// +/// ### Initializers +/// +/// - ``init(row:)-9w9yp`` +/// +/// ### Fetching Records +/// - ``fetchCursor(_:)`` +/// - ``fetchAll(_:)`` +/// - ``fetchSet(_:)`` +/// - ``fetchOne(_:)`` +/// +/// ### Fetching Records from Raw SQL +/// +/// - ``fetchCursor(_:sql:arguments:adapter:)`` +/// - ``fetchAll(_:sql:arguments:adapter:)`` +/// - ``fetchSet(_:sql:arguments:adapter:)`` +/// - ``fetchOne(_:sql:arguments:adapter:)`` +/// +/// ### Fetching Records from a Prepared Statement +/// +/// - ``fetchCursor(_:arguments:adapter:)`` +/// - ``fetchAll(_:arguments:adapter:)`` +/// - ``fetchSet(_:arguments:adapter:)`` +/// - ``fetchOne(_:arguments:adapter:)`` +/// +/// ### Fetching Records from a Request +/// +/// - ``fetchCursor(_:_:)`` +/// - ``fetchAll(_:_:)`` +/// - ``fetchSet(_:_:)`` +/// - ``fetchOne(_:_:)`` +/// +/// ### Fetching Records by Primary Key +/// +/// - ``fetchCursor(_:ids:)`` +/// - ``fetchAll(_:ids:)`` +/// - ``fetchSet(_:ids:)`` +/// - ``fetchOne(_:id:)`` +/// - ``fetchCursor(_:keys:)-2jrm1`` +/// - ``fetchAll(_:keys:)-4c8no`` +/// - ``fetchSet(_:keys:)-e6uy`` +/// - ``fetchOne(_:key:)-3f3hc`` +/// +/// ### Fetching Record by Key +/// +/// - ``fetchCursor(_:keys:)-5u9hu`` +/// - ``fetchAll(_:keys:)-2addp`` +/// - ``fetchSet(_:keys:)-8no3x`` +/// - ``fetchOne(_:key:)-92b9m`` +/// +/// ### Configuring Row Decoding for the Standard Decodable Protocol +/// +/// - ``databaseColumnDecodingStrategy-6uefz`` +/// - ``databaseDateDecodingStrategy-78y03`` +/// - ``databaseDecodingUserInfo-77jim`` +/// - ``databaseJSONDecoder(for:)-7lmxd`` +/// - ``DatabaseColumnDecodingStrategy`` +/// - ``DatabaseDateDecodingStrategy`` +/// +/// ### Supporting Types +/// +/// - ``RecordCursor`` public protocol FetchableRecord { // MARK: - Row Decoding /// Creates a record from `row`. /// - /// For performance reasons, the row argument may be reused during the - /// iteration of a fetch query. If you want to keep the row for later use, - /// make sure to store a copy: `self.row = row.copy()`. + /// The row argument may be reused during the iteration of database results. + /// If you want to keep the row for later use, make sure to store a copy: + /// `row.copy()`. + /// + /// - throws: An error is thrown if the record can't be decoded from the + /// database row. init(row: Row) throws // MARK: - Customizing the Format of Database Columns - /// When the FetchableRecord type also adopts the standard Decodable - /// protocol, you can use this dictionary to customize the decoding process - /// from database rows. + /// Contextual information made available to the + /// `Decodable.init(from:)` initializer. /// /// For example: /// - /// // A key that holds a decoder's name - /// let decoderName = CodingUserInfoKey(rawValue: "decoderName")! + /// ```swift + /// // A key that holds a decoder's name + /// let decoderName = CodingUserInfoKey(rawValue: "decoderName")! /// - /// // A FetchableRecord + Decodable record - /// struct Player: FetchableRecord, Decodable { - /// // Customize the decoder name when decoding a database row - /// static let databaseDecodingUserInfo: [CodingUserInfoKey: Any] = [decoderName: "Database"] + /// // A FetchableRecord + Decodable record + /// struct Player: FetchableRecord, Decodable { + /// // Customize the decoder name when decoding a database row + /// static let databaseDecodingUserInfo: [CodingUserInfoKey: Any] = [decoderName: "Database"] /// - /// init(from decoder: Decoder) throws { - /// // Print the decoder name - /// print(decoder.userInfo[decoderName]) - /// ... - /// } + /// init(from decoder: Decoder) throws { + /// // Print the decoder name + /// print(decoder.userInfo[decoderName]) + /// ... /// } + /// } /// - /// // prints "Database" - /// let player = try Player.fetchOne(db, ...) + /// // prints "Database" + /// let player = try Player.fetchOne(db, ...) /// - /// // prints "JSON" - /// let decoder = JSONDecoder() - /// decoder.userInfo = [decoderName: "JSON"] - /// let player = try decoder.decode(Player.self, from: ...) + /// // prints "JSON" + /// let decoder = JSONDecoder() + /// decoder.userInfo = [decoderName: "JSON"] + /// let player = try decoder.decode(Player.self, from: ...) + /// ``` static var databaseDecodingUserInfo: [CodingUserInfoKey: Any] { get } - /// When the FetchableRecord type also adopts the standard Decodable - /// protocol, this method controls the decoding process of nested properties - /// from JSON database columns. + /// Returns the `JSONDecoder` that decodes the value for a given column. /// - /// The default implementation returns a JSONDecoder with the - /// following properties: - /// - /// - dataDecodingStrategy: .base64 - /// - dateDecodingStrategy: .millisecondsSince1970 - /// - nonConformingFloatDecodingStrategy: .throw - /// - /// You can override those defaults: - /// - /// struct Achievement: Decodable { - /// var name: String - /// var date: Date - /// } - /// - /// struct Player: Decodable, FetchableRecord { - /// // stored in a JSON column - /// var achievements: [Achievement] - /// - /// static func databaseJSONDecoder(for column: String) -> JSONDecoder { - /// let decoder = JSONDecoder() - /// decoder.dateDecodingStrategy = .iso8601 - /// return decoder - /// } - /// } + /// This method is dedicated to ``FetchableRecord`` types that also conform + /// to the standard `Decodable` protocol and use the default + /// ``init(row:)-4ptlh`` implementation. static func databaseJSONDecoder(for column: String) -> JSONDecoder - /// When the FetchableRecord type also adopts the standard Decodable - /// protocol, this property controls the decoding of date properties. + /// The strategy for decoding `Date` columns. /// - /// Default value is .deferredToDate + /// This property is dedicated to ``FetchableRecord`` types that also + /// conform to the standard `Decodable` protocol and use the default + /// ``init(row:)-4ptlh`` implementation. /// /// For example: /// - /// struct Player: FetchableRecord, Decodable { - /// static let databaseDateDecodingStrategy: DatabaseDateDecodingStrategy = .timeIntervalSince1970 + /// ```swift + /// struct Player: FetchableRecord, Decodable { + /// static let databaseDateDecodingStrategy = DatabaseDateDecodingStrategy.timeIntervalSince1970 /// - /// var name: String - /// var registrationDate: Date // decoded from epoch timestamp - /// } + /// // Decoded from an epoch timestamp + /// var creationDate: Date + /// } + /// ``` static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { get } - /// When the FetchableRecord type also adopts the standard Decodable - /// protocol, this property controls the key decoding strategy. + /// The strategy for converting column names to coding keys. /// - /// Default value is .useDefaultKeys + /// This property is dedicated to ``FetchableRecord`` types that also + /// conform to the standard `Decodable` protocol and use the default + /// ``init(row:)-4ptlh`` implementation. /// /// For example: /// - /// struct Player: FetchableRecord, Decodable { - /// static let databaseDateDecodingStrategy: DatabaseColumnDecodingStrategy = .convertFromSnakeCase + /// ```swift + /// struct Player: FetchableRecord, Decodable { + /// static let databaseColumnDecodingStrategy = DatabaseColumnDecodingStrategy.convertFromSnakeCase /// - /// var playerID: String // decoded from player_id - /// } + /// // Decoded from the 'player_id' column + /// var playerID: String + /// } + /// ``` static var databaseColumnDecodingStrategy: DatabaseColumnDecodingStrategy { get } } extension FetchableRecord { + /// Contextual information made available to the + /// `Decodable.init(from:)` initializer. + /// + /// The default implementation returns an empty dictionary. public static var databaseDecodingUserInfo: [CodingUserInfoKey: Any] { [:] } - /// Returns a JSONDecoder with the following properties: + /// Returns the `JSONDecoder` that decodes the value for a given column. /// - /// - dataDecodingStrategy: .base64 - /// - dateDecodingStrategy: .millisecondsSince1970 - /// - nonConformingFloatDecodingStrategy: .throw + /// The default implementation returns a `JSONDecoder` with the + /// following properties: + /// + /// - `dataDecodingStrategy`: `.base64` + /// - `dateDecodingStrategy`: `.millisecondsSince1970` + /// - `nonConformingFloatDecodingStrategy`: `.throw` public static func databaseJSONDecoder(for column: String) -> JSONDecoder { let decoder = JSONDecoder() decoder.dataDecodingStrategy = .base64 @@ -138,10 +212,14 @@ extension FetchableRecord { return decoder } + /// The default strategy for decoding `Date` columns is + /// ``DatabaseDateDecodingStrategy/deferredToDate``. public static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { .deferredToDate } + /// The default strategy for converting column names to coding keys is + /// ``DatabaseColumnDecodingStrategy/useDefaultKeys``. public static var databaseColumnDecodingStrategy: DatabaseColumnDecodingStrategy { .useDefaultKeys } @@ -151,25 +229,34 @@ extension FetchableRecord { // MARK: Fetching From Prepared Statement - /// A cursor over records fetched from a prepared statement. + /// Returns a cursor over records fetched from a prepared statement. /// - /// let statement = try db.makeStatement(sql: "SELECT * FROM player") - /// let players = try Player.fetchCursor(statement) // Cursor of Player - /// while let player = try players.next() { // Player - /// ... + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT * FROM player WHERE lastName = ?" + /// let statement = try db.makeStatement(sql: sql) + /// let players = try Player.fetchCursor(statement, arguments: [lastName]) + /// while let player = try players.next() { + /// print(player.name) /// } + /// } + /// ``` + /// + /// The returned cursor is valid only during the remaining execution of the + /// database access. Do not store or return the cursor for later use. /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// - /// The cursor must be iterated in a protected dispatch queue. - /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter - /// - returns: A cursor over fetched records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: A ``RecordCursor`` over fetched records. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor( _ statement: Statement, arguments: StatementArguments? = nil, @@ -181,15 +268,23 @@ extension FetchableRecord { /// Returns an array of records fetched from a prepared statement. /// - /// let statement = try db.makeStatement(sql: "SELECT * FROM player") - /// let players = try Player.fetchAll(statement) // [Player] + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT * FROM player WHERE lastName = ?" + /// let statement = try db.makeStatement(sql: sql) + /// let players = try Player.fetchAll(statement, arguments: [lastName]) + /// } + /// ``` /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: An array of records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll( _ statement: Statement, arguments: StatementArguments? = nil, @@ -201,15 +296,23 @@ extension FetchableRecord { /// Returns a single record fetched from a prepared statement. /// - /// let statement = try db.makeStatement(sql: "SELECT * FROM player") - /// let player = try Player.fetchOne(statement) // Player? + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT * FROM player WHERE lastName = ? LIMIT 1" + /// let statement = try db.makeStatement(sql: sql) + /// let player = try Player.fetchOne(statement, arguments: [lastName]) + /// } + /// ``` /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: An optional record. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne( _ statement: Statement, arguments: StatementArguments? = nil, @@ -223,15 +326,23 @@ extension FetchableRecord { extension FetchableRecord where Self: Hashable { /// Returns a set of records fetched from a prepared statement. /// - /// let statement = try db.makeStatement(sql: "SELECT * FROM player") - /// let players = try Player.fetchSet(statement) // Set + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT * FROM player WHERE lastName = ?" + /// let statement = try db.makeStatement(sql: sql) + /// let players = try Player.fetchSet(statement, arguments: [lastName]) + /// } + /// ``` /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: A set of records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet( _ statement: Statement, arguments: StatementArguments? = nil, @@ -248,23 +359,32 @@ extension FetchableRecord { /// Returns a cursor over records fetched from an SQL query. /// - /// let players = try Player.fetchCursor(db, sql: "SELECT * FROM player") // Cursor of Player - /// while let player = try players.next() { // Player - /// ... + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT * FROM player WHERE lastName = ?" + /// let players = try Player.fetchCursor(db, sql: sql, arguments: [lastName]) + /// while let player = try players.next() { + /// print(player.name) /// } + /// } + /// ``` + /// + /// The returned cursor is valid only during the remaining execution of the + /// database access. Do not store or return the cursor for later use. /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// - /// The cursor must be iterated in a protected dispatch queue. - /// /// - parameters: /// - db: A database connection. - /// - sql: An SQL query. + /// - sql: An SQL string. /// - arguments: Statement arguments. /// - adapter: Optional RowAdapter - /// - returns: A cursor over fetched records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: A ``RecordCursor`` over fetched records. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor( _ db: Database, sql: String, @@ -277,15 +397,23 @@ extension FetchableRecord { /// Returns an array of records fetched from an SQL query. /// - /// let players = try Player.fetchAll(db, sql: "SELECT * FROM player") // [Player] + /// For example: + /// + /// ```swift + /// let players = try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT * FROM player WHERE lastName = ?" + /// return try Player.fetchAll(db, sql: sql, arguments: [lastName]) + /// } + /// ``` /// /// - parameters: /// - db: A database connection. - /// - sql: An SQL query. + /// - sql: An SQL string. /// - arguments: Statement arguments. /// - adapter: Optional RowAdapter /// - returns: An array of records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll( _ db: Database, sql: String, @@ -298,15 +426,23 @@ extension FetchableRecord { /// Returns a single record fetched from an SQL query. /// - /// let player = try Player.fetchOne(db, sql: "SELECT * FROM player") // Player? + /// For example: + /// + /// ```swift + /// let player = try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT * FROM player WHERE lastName = ? LIMIT 1" + /// return try Player.fetchOne(db, sql: sql, arguments: [lastName]) + /// } + /// ``` /// /// - parameters: /// - db: A database connection. - /// - sql: An SQL query. + /// - sql: An SQL string. /// - arguments: Statement arguments. /// - adapter: Optional RowAdapter /// - returns: An optional record. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne( _ db: Database, sql: String, @@ -321,15 +457,23 @@ extension FetchableRecord { extension FetchableRecord where Self: Hashable { /// Returns a set of records fetched from an SQL query. /// - /// let players = try Player.fetchSet(db, sql: "SELECT * FROM player") // Set + /// For example: + /// + /// ```swift + /// let players = try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// let sql = "SELECT * FROM player WHERE lastName = ?" + /// return try Player.fetchSet(db, sql: sql, arguments: [lastName]) + /// } + /// ``` /// /// - parameters: /// - db: A database connection. - /// - sql: An SQL query. + /// - sql: An SQL string. /// - arguments: Statement arguments. /// - adapter: Optional RowAdapter /// - returns: A set of records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet( _ db: Database, sql: String, @@ -347,23 +491,39 @@ extension FetchableRecord { /// Returns a cursor over records fetched from a fetch request. /// - /// let request = try Player.all() - /// let players = try Player.fetchCursor(db, request) // Cursor of Player - /// while let player = try players.next() { // Player - /// ... + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player.filter(Column("lastName") == lastName) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT * FROM player WHERE lastName = \(lastName) + /// """ + /// + /// let players = try Player.fetchCursor(db, request) + /// while let player = try players.next() { + /// print(player.name) /// } + /// } + /// ``` + /// + /// The returned cursor is valid only during the remaining execution of the + /// database access. Do not store or return the cursor for later use. /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// - /// The cursor must be iterated in a protected dispatch queue. - /// /// - parameters: /// - db: A database connection. /// - sql: a FetchRequest. - /// - returns: A cursor over fetched records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: R) throws -> RecordCursor { + /// - returns: A ``RecordCursor`` over fetched records. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public static func fetchCursor(_ db: Database, _ request: some FetchRequest) throws -> RecordCursor { let request = try request.makePreparedRequest(db, forSingleResult: false) precondition(request.supplementaryFetch == nil, "Not implemented: fetchCursor with supplementary fetch") return try fetchCursor(request.statement, adapter: request.adapter) @@ -371,15 +531,30 @@ extension FetchableRecord { /// Returns an array of records fetched from a fetch request. /// - /// let request = try Player.all() - /// let players = try Player.fetchAll(db, request) // [Player] + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player.filter(Column("lastName") == lastName) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT * FROM player WHERE lastName = \(lastName) + /// """ + /// + /// let players = try Player.fetchAll(db, request) + /// } + /// ``` /// /// - parameters: /// - db: A database connection. /// - sql: a FetchRequest. /// - returns: An array of records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: R) throws -> [Self] { + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] { let request = try request.makePreparedRequest(db, forSingleResult: false) if let supplementaryFetch = request.supplementaryFetch { let rows = try Row.fetchAll(request.statement, adapter: request.adapter) @@ -392,15 +567,29 @@ extension FetchableRecord { /// Returns a single record fetched from a fetch request. /// - /// let request = try Player.filter(key: 1) - /// let player = try Player.fetchOne(db, request) // Player? + /// For example: /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player.filter(Column("lastName") == lastName) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT * FROM player WHERE lastName = \(lastName) LIMIT 1 + /// """ + /// + /// let player = try Player.fetchOne(db, request) + /// } + /// ``` /// - parameters: /// - db: A database connection. /// - sql: a FetchRequest. /// - returns: An optional record. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, _ request: R) throws -> Self? { + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? { let request = try request.makePreparedRequest(db, forSingleResult: true) if let supplementaryFetch = request.supplementaryFetch { guard let row = try Row.fetchOne(request.statement, adapter: request.adapter) else { @@ -417,15 +606,30 @@ extension FetchableRecord { extension FetchableRecord where Self: Hashable { /// Returns a set of records fetched from a fetch request. /// - /// let request = try Player.all() - /// let players = try Player.fetchSet(db, request) // Set + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player.filter(Column("lastName") == lastName) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT * FROM player WHERE lastName = \(lastName) + /// """ + /// + /// let players = try Player.fetchSet(db, request) + /// } + /// ``` /// /// - parameters: /// - db: A database connection. /// - sql: a FetchRequest. /// - returns: A set of records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, _ request: R) throws -> Set { + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set { let request = try request.makePreparedRequest(db, forSingleResult: false) if let supplementaryFetch = request.supplementaryFetch { let rows = try Row.fetchAll(request.statement, adapter: request.adapter) @@ -444,64 +648,128 @@ extension FetchRequest where RowDecoder: FetchableRecord { // MARK: Fetching Records - /// A cursor over fetched records. + /// Returns a cursor over fetched records. /// - /// struct Player: FetchableRecord { ... } - /// let request: some FetchRequest = ... - /// let players = try request.fetchCursor(db) // Cursor of Player - /// while let player = try players.next() { // Player - /// ... + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player.filter(Column("lastName") == lastName) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT * FROM player WHERE lastName = \(lastName) + /// """ + /// + /// let players = try request.fetchCursor(db) + /// while let player = try players.next() { + /// print(player.name) /// } + /// } + /// ``` + /// + /// The returned cursor is valid only during the remaining execution of the + /// database access. Do not store or return the cursor for later use. /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// - /// The cursor must be iterated in a protected dispatch queue. - /// - /// - parameter db: A database connection. - /// - returns: A cursor over fetched records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - parameters: + /// - db: A database connection. + /// - sql: a FetchRequest. + /// - returns: A ``RecordCursor`` over fetched records. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchCursor(_ db: Database) throws -> RecordCursor { try RowDecoder.fetchCursor(db, self) } - /// An array of fetched records. + /// Returns an array of fetched records. /// - /// struct Player: FetchableRecord { ... } - /// let request: some FetchRequest = ... - /// let players = try request.fetchAll(db) // [Player] + /// For example: /// - /// - parameter db: A database connection. + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player.filter(Column("lastName") == lastName) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT * FROM player WHERE lastName = \(lastName) + /// """ + /// + /// let players = try request.fetchAll(db) + /// } + /// ``` + /// + /// - parameters: + /// - db: A database connection. + /// - sql: a FetchRequest. /// - returns: An array of records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchAll(_ db: Database) throws -> [RowDecoder] { try RowDecoder.fetchAll(db, self) } - /// The first fetched record. + /// Returns a single record. /// - /// struct Player: FetchableRecord { ... } - /// let request: some FetchRequest = ... - /// let player = try request.fetchOne(db) // Player? + /// For example: /// - /// - parameter db: A database connection. + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player.filter(Column("lastName") == lastName) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT * FROM player WHERE lastName = \(lastName) LIMIT 1 + /// """ + /// + /// let player = try request.fetchOne(db) + /// } + /// ``` + /// - parameters: + /// - db: A database connection. + /// - sql: a FetchRequest. /// - returns: An optional record. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchOne(_ db: Database) throws -> RowDecoder? { try RowDecoder.fetchOne(db, self) } } extension FetchRequest where RowDecoder: FetchableRecord & Hashable { - /// A set of fetched records. + /// Returns a set of fetched records. /// - /// struct Player: FetchableRecord, Hashable { ... } - /// let request: some FetchRequest = ... - /// let players = try request.fetchSet(db) // Set + /// For example: /// - /// - parameter db: A database connection. + /// ```swift + /// try dbQueue.read { db in + /// let lastName = "O'Reilly" + /// + /// // Query interface request + /// let request = Player.filter(Column("lastName") == lastName) + /// + /// // SQL request + /// let request: SQLRequest = """ + /// SELECT * FROM player WHERE lastName = \(lastName) + /// """ + /// + /// let players = try request.fetchSet(db) + /// } + /// ``` + /// + /// - parameters: + /// - db: A database connection. + /// - sql: a FetchRequest. /// - returns: A set of records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchSet(_ db: Database) throws -> Set { try RowDecoder.fetchSet(db, self) } @@ -509,17 +777,24 @@ extension FetchRequest where RowDecoder: FetchableRecord & Hashable { // MARK: - RecordCursor -/// A cursor of records. For example: +/// A cursor of records. /// -/// struct Player : FetchableRecord { ... } -/// try dbQueue.read { db in -/// let players: RecordCursor = try Player.fetchCursor(db, sql: "SELECT * FROM player") +/// A `RecordCursor` iterates all rows from a database request. Its +/// elements are the records decoded from each fetched row. +/// +/// For example: +/// +/// ```swift +/// try dbQueue.read { db in +/// let players: RecordCursor = try Player.fetchCursor(db, sql: "SELECT * FROM player") +/// while let player = try players.next() { +/// print(player.name) /// } +/// } +/// ``` public final class RecordCursor: DatabaseCursor { public typealias Element = Record - /// :nodoc: public let _statement: Statement - /// :nodoc: public var _isDone = false @usableFromInline let _row: Row // Instantiated once, reused for performance @@ -536,7 +811,6 @@ public final class RecordCursor: DatabaseCursor { try? _statement.reset() } - /// :nodoc: @inlinable public func _element(sqliteStatement: SQLiteStatement) throws -> Record { try Record(row: _row) diff --git a/GRDB/Record/MutablePersistableRecord+Delete.swift b/GRDB/Record/MutablePersistableRecord+Delete.swift index 2df6cb315..f800ab244 100644 --- a/GRDB/Record/MutablePersistableRecord+Delete.swift +++ b/GRDB/Record/MutablePersistableRecord+Delete.swift @@ -23,7 +23,7 @@ extension MutablePersistableRecord { /// /// - parameter db: A database connection. /// - returns: Whether a database row was deleted. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult @inlinable // allow specialization so that empty callbacks are removed public func delete(_ db: Database) throws -> Bool { diff --git a/GRDB/Record/MutablePersistableRecord+Insert.swift b/GRDB/Record/MutablePersistableRecord+Insert.swift index 956cda11c..83e61018e 100644 --- a/GRDB/Record/MutablePersistableRecord+Insert.swift +++ b/GRDB/Record/MutablePersistableRecord+Insert.swift @@ -21,9 +21,21 @@ extension MutablePersistableRecord { extension MutablePersistableRecord { /// Executes an `INSERT` statement. /// + /// For example: + /// + /// ```swift + /// try dbQueue.write { db in + /// var player = Player(name: "Arthur") + /// try player.insert(db) + /// } + /// ``` + /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public mutating func insert( _ db: Database, @@ -47,19 +59,22 @@ extension MutablePersistableRecord { /// Executes an `INSERT` statement, and returns the inserted record. /// - /// Usage: + /// For example: /// - /// let player = Player(id: nil, name: "Arthur") - /// let insertedPlayer = try dbQueue.write { db in - /// try player.inserted(db) - /// } - /// print(player.id) // nil - /// print(insertedPlayer.id) // some id + /// ```swift + /// let player = Player(name: "Arthur") + /// let insertedPlayer = try await dbQueue.write { [player] db in + /// try player.inserted(db) + /// } + /// ``` /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - returns: The inserted record. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public func inserted( _ db: Database, @@ -76,22 +91,26 @@ extension MutablePersistableRecord { extension MutablePersistableRecord { #if GRDBCUSTOMSQLITE || GRDBCIPHER - /// Executes an `INSERT ... RETURNING ...` statement, and returns the - /// inserted record. + /// Executes an `INSERT RETURNING` statement, and returns a new record built + /// from the inserted row. /// - /// This method helps dealing with default column values and - /// generated columns. + /// This method is equivalent to ``insertAndFetch(_:onConflict:as:)``, + /// with `Self` as the `returnedType` argument: /// - /// For example: - /// - /// let player: Player = ... - /// let insertedPlayer = player.insertAndFetch(db) + /// ```swift + /// // Equivalent + /// let insertedPlayer = try player.insertAndFetch(db) + /// let insertedPlayer = try player.insertAndFetch(db, as: Player.self) + /// ``` /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - returns: The inserted record, if any. The result can be nil when the /// conflict policy is `IGNORE`. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public func insertAndFetch( _ db: Database, @@ -103,55 +122,60 @@ extension MutablePersistableRecord { return try result.insertAndFetch(db, onConflict: conflictResolution, as: Self.self) } - /// Executes an `INSERT ... RETURNING ...` statement, and returns a new - /// record built from the inserted row. + /// Executes an `INSERT RETURNING` statement, and returns a new record built + /// from the inserted row. /// /// This method helps dealing with default column values and /// generated columns. /// /// For example: /// - /// // A table with an auto-incremented primary key and a default value - /// try dbQueue.write { db in - /// try db.execute(sql: """ - /// CREATE TABLE player( - /// id INTEGER PRIMARY KEY AUTOINCREMENT, - /// name TEXT, - /// score INTEGER DEFAULT 1000) - /// """) - /// } + /// ```swift + /// // A table with an auto-incremented primary key and a default value + /// try dbQueue.write { db in + /// try db.execute(sql: """ + /// CREATE TABLE player( + /// id INTEGER PRIMARY KEY AUTOINCREMENT, + /// name TEXT, + /// score INTEGER DEFAULT 1000) + /// """) + /// } /// - /// // A player with partial database information - /// struct PartialPlayer: MutablePersistableRecord { - /// static let databaseTableName = "player" - /// var name: String - /// } + /// // A player with partial database information + /// struct PartialPlayer: MutablePersistableRecord { + /// static let databaseTableName = "player" + /// var name: String + /// } /// - /// // A full player, with all database information - /// struct Player: TableRecord, FetchableRecord { - /// var id: Int64 - /// var name: String - /// var score: Int - /// } + /// // A full player, with all database information + /// struct Player: TableRecord, FetchableRecord { + /// var id: Int64 + /// var name: String + /// var score: Int + /// } /// - /// // Insert a base player, get a full one - /// try dbQueue.write { db in - /// var partialPlayer = PartialPlayer(name: "Alice") + /// // Insert a partial player, get a full one + /// try dbQueue.write { db in + /// var partialPlayer = PartialPlayer(name: "Alice") /// - /// // INSERT INTO player (name) VALUES ('Alice') RETURNING * - /// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) { - /// print(player.id) // The inserted id - /// print(player.name) // The inserted name - /// print(player.score) // The default score - /// } + /// // INSERT INTO player (name) VALUES ('Alice') RETURNING * + /// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) { + /// print(player.id) // The inserted id + /// print(player.name) // The inserted name + /// print(player.score) // The default score /// } + /// } + /// ``` /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter returnedType: The type of the returned record. /// - returns: A record of type `returnedType`, if any. The result can be /// nil when the conflict policy is `IGNORE`. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public mutating func insertAndFetch( _ db: Database, @@ -164,47 +188,53 @@ extension MutablePersistableRecord { } } - /// Executes an `INSERT ... RETURNING ...` statement, and returns the - /// selected columns from the inserted row. + /// Executes an `INSERT RETURNING` statement, and returns the selected + /// columns from the inserted row. /// /// This method helps dealing with default column values and /// generated columns. /// /// For example: /// - /// // A table with an auto-incremented primary key and a default value - /// try dbQueue.write { db in - /// try db.execute(sql: """ - /// CREATE TABLE player( - /// id INTEGER PRIMARY KEY AUTOINCREMENT, - /// name TEXT, - /// score INTEGER DEFAULT 1000) - /// """) - /// } + /// ```swift + /// // A table with an auto-incremented primary key and a default value + /// try dbQueue.write { db in + /// try db.execute(sql: """ + /// CREATE TABLE player( + /// id INTEGER PRIMARY KEY AUTOINCREMENT, + /// name TEXT, + /// score INTEGER DEFAULT 1000) + /// """) + /// } /// - /// // A player with partial database information - /// struct PartialPlayer: MutablePersistableRecord { - /// static let databaseTableName = "player" - /// var name: String - /// } + /// // A player with partial database information + /// struct PartialPlayer: MutablePersistableRecord { + /// static let databaseTableName = "player" + /// var name: String + /// } /// - /// // Insert a base player, get the inserted score - /// try dbQueue.write { db in - /// var partialPlayer = PartialPlayer(name: "Alice") + /// // Insert a partial player, get the inserted score + /// try dbQueue.write { db in + /// var partialPlayer = PartialPlayer(name: "Alice") /// - /// // INSERT INTO player (name) VALUES ('Alice') RETURNING score - /// let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { statement in - /// try Int.fetchOne(statement) - /// } - /// print(score) // The inserted score + /// // INSERT INTO player (name) VALUES ('Alice') RETURNING score + /// let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { statement in + /// try Int.fetchOne(statement) /// } + /// print(score) // The inserted score + /// } + /// ``` /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter selection: The returned columns (must not be empty). - /// - parameter fetch: A function that executes its ``Statement`` argument. + /// - parameter fetch: A closure that executes its ``Statement`` argument. + /// If the conflict policy is `IGNORE`, the statement may return no row. /// - returns: The result of the `fetch` function. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed public mutating func insertAndFetch( @@ -234,22 +264,26 @@ extension MutablePersistableRecord { return success.returned } #else - /// Executes an `INSERT ... RETURNING ...` statement, and returns the - /// inserted record. + /// Executes an `INSERT RETURNING` statement, and returns a new record built + /// from the inserted row. /// - /// This method helps dealing with default column values and - /// generated columns. + /// This method is equivalent to ``insertAndFetch(_:onConflict:as:)``, + /// with `Self` as the `returnedType` argument: /// - /// For example: - /// - /// let player: Player = ... - /// let insertedPlayer = player.insertAndFetch(db) + /// ```swift + /// // Equivalent + /// let insertedPlayer = try player.insertAndFetch(db) + /// let insertedPlayer = try player.insertAndFetch(db, as: Player.self) + /// ``` /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - returns: The inserted record, if any. The result can be nil when the /// conflict policy is `IGNORE`. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public func insertAndFetch( @@ -262,55 +296,60 @@ extension MutablePersistableRecord { return try result.insertAndFetch(db, onConflict: conflictResolution, as: Self.self) } - /// Executes an `INSERT ... RETURNING ...` statement, and returns a new - /// record built from the inserted row. + /// Executes an `INSERT RETURNING` statement, and returns a new record built + /// from the inserted row. /// /// This method helps dealing with default column values and /// generated columns. /// /// For example: /// - /// // A table with an auto-incremented primary key and a default value - /// try dbQueue.write { db in - /// try db.execute(sql: """ - /// CREATE TABLE player( - /// id INTEGER PRIMARY KEY AUTOINCREMENT, - /// name TEXT, - /// score INTEGER DEFAULT 1000) - /// """) - /// } + /// ```swift + /// // A table with an auto-incremented primary key and a default value + /// try dbQueue.write { db in + /// try db.execute(sql: """ + /// CREATE TABLE player( + /// id INTEGER PRIMARY KEY AUTOINCREMENT, + /// name TEXT, + /// score INTEGER DEFAULT 1000) + /// """) + /// } /// - /// // A player with partial database information - /// struct PartialPlayer: MutablePersistableRecord { - /// static let databaseTableName = "player" - /// var name: String - /// } + /// // A player with partial database information + /// struct PartialPlayer: MutablePersistableRecord { + /// static let databaseTableName = "player" + /// var name: String + /// } /// - /// // A full player, with all database information - /// struct Player: TableRecord, FetchableRecord { - /// var id: Int64 - /// var name: String - /// var score: Int - /// } + /// // A full player, with all database information + /// struct Player: TableRecord, FetchableRecord { + /// var id: Int64 + /// var name: String + /// var score: Int + /// } /// - /// // Insert a base player, get a full one - /// try dbQueue.write { db in - /// var partialPlayer = PartialPlayer(name: "Alice") + /// // Insert a partial player, get a full one + /// try dbQueue.write { db in + /// var partialPlayer = PartialPlayer(name: "Alice") /// - /// // INSERT INTO player (name) VALUES ('Alice') RETURNING * - /// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) { - /// print(player.id) // The inserted id - /// print(player.name) // The inserted name - /// print(player.score) // The default score - /// } + /// // INSERT INTO player (name) VALUES ('Alice') RETURNING * + /// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) { + /// print(player.id) // The inserted id + /// print(player.name) // The inserted name + /// print(player.score) // The default score /// } + /// } + /// ``` /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter returnedType: The type of the returned record. /// - returns: A record of type `returnedType`, if any. The result can be /// nil when the conflict policy is `IGNORE`. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public mutating func insertAndFetch( @@ -324,47 +363,53 @@ extension MutablePersistableRecord { } } - /// Executes an `INSERT ... RETURNING ...` statement, and returns the - /// selected columns from the inserted row. + /// Executes an `INSERT RETURNING` statement, and returns the selected + /// columns from the inserted row. /// /// This method helps dealing with default column values and /// generated columns. /// /// For example: /// - /// // A table with an auto-incremented primary key and a default value - /// try dbQueue.write { db in - /// try db.execute(sql: """ - /// CREATE TABLE player( - /// id INTEGER PRIMARY KEY AUTOINCREMENT, - /// name TEXT, - /// score INTEGER DEFAULT 1000) - /// """) - /// } + /// ```swift + /// // A table with an auto-incremented primary key and a default value + /// try dbQueue.write { db in + /// try db.execute(sql: """ + /// CREATE TABLE player( + /// id INTEGER PRIMARY KEY AUTOINCREMENT, + /// name TEXT, + /// score INTEGER DEFAULT 1000) + /// """) + /// } /// - /// // A player with partial database information - /// struct PartialPlayer: MutablePersistableRecord { - /// static let databaseTableName = "player" - /// var name: String - /// } + /// // A player with partial database information + /// struct PartialPlayer: MutablePersistableRecord { + /// static let databaseTableName = "player" + /// var name: String + /// } /// - /// // Insert a base player, get the inserted score - /// try dbQueue.write { db in - /// var partialPlayer = PartialPlayer(name: "Alice") + /// // Insert a partial player, get the inserted score + /// try dbQueue.write { db in + /// var partialPlayer = PartialPlayer(name: "Alice") /// - /// // INSERT INTO player (name) VALUES ('Alice') RETURNING score - /// let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { statement in - /// try Int.fetchOne(statement) - /// } - /// print(score) // The inserted score + /// // INSERT INTO player (name) VALUES ('Alice') RETURNING score + /// let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { statement in + /// try Int.fetchOne(statement) /// } + /// print(score) // The inserted score + /// } + /// ``` /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter selection: The returned columns (must not be empty). - /// - parameter fetch: A function that executes its ``Statement`` argument. + /// - parameter fetch: A closure that executes its ``Statement`` argument. + /// If the conflict policy is `IGNORE`, the statement may return no row. /// - returns: The result of the `fetch` function. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ diff --git a/GRDB/Record/MutablePersistableRecord+Save.swift b/GRDB/Record/MutablePersistableRecord+Save.swift index cfe50308c..65daefc17 100644 --- a/GRDB/Record/MutablePersistableRecord+Save.swift +++ b/GRDB/Record/MutablePersistableRecord+Save.swift @@ -27,8 +27,11 @@ extension MutablePersistableRecord { /// Otherwise, performs an insert. /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public mutating func save( _ db: Database, @@ -62,9 +65,12 @@ extension MutablePersistableRecord { /// print(savedPlayer.id) // some id /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - returns: The saved record. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public func saved( _ db: Database, @@ -81,8 +87,8 @@ extension MutablePersistableRecord { extension MutablePersistableRecord { #if GRDBCUSTOMSQLITE || GRDBCIPHER - /// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...` - /// statement, and returns the saved row. + /// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and + /// returns a new record built from the saved row. /// /// If the receiver has a non-nil primary key and a matching row in the /// database, this method performs an update. Otherwise, it performs @@ -97,10 +103,13 @@ extension MutablePersistableRecord { /// let savedPlayer = player.saveAndFetch(db) /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - returns: The saved record. The result can be nil when the /// conflict policy is `IGNORE`. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public func saveAndFetch( _ db: Database, @@ -112,19 +121,22 @@ extension MutablePersistableRecord { return try result.saveAndFetch(db, onConflict: conflictResolution, as: Self.self) } - /// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...` - /// statement, and returns a new record built from the saved row. + /// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and + /// returns a new record built from the saved row. /// /// If the receiver has a non-nil primary key and a matching row in the /// database, this method performs an update. Otherwise, it performs /// an insert. /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter returnedType: The type of the returned record. /// - returns: A record of type `returnedType`. The result can be nil when /// the conflict policy is `IGNORE`. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public mutating func saveAndFetch( _ db: Database, @@ -152,19 +164,22 @@ extension MutablePersistableRecord { return success.returned } - /// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...` - /// statement, and returns the selected columns from the saved row. + /// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and + /// returns the selected columns from the saved row. /// /// If the receiver has a non-nil primary key and a matching row in the /// database, this method performs an update. Otherwise, it performs /// an insert. /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter selection: The returned columns (must not be empty). /// - parameter fetch: A function that executes it ``Statement`` argument. /// - returns: The result of the `fetch` function. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed public mutating func saveAndFetch( @@ -194,8 +209,8 @@ extension MutablePersistableRecord { return success.returned } #else - /// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...` - /// statement, and returns the saved row. + /// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and + /// returns a new record built from the saved row. /// /// If the receiver has a non-nil primary key and a matching row in the /// database, this method performs an update. Otherwise, it performs @@ -210,10 +225,13 @@ extension MutablePersistableRecord { /// let savedPlayer = player.saveAndFetch(db) /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - returns: The saved record. The result can be nil when the /// conflict policy is `IGNORE`. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public func saveAndFetch( @@ -226,19 +244,22 @@ extension MutablePersistableRecord { return try result.saveAndFetch(db, onConflict: conflictResolution, as: Self.self) } - /// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...` - /// statement, and returns a new record built from the saved row. + /// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and + /// returns a new record built from the saved row. /// /// If the receiver has a non-nil primary key and a matching row in the /// database, this method performs an update. Otherwise, it performs /// an insert. /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter returnedType: The type of the returned record. /// - returns: A record of type `returnedType`. The result can be nil when /// the conflict policy is `IGNORE`. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public mutating func saveAndFetch( @@ -267,19 +288,22 @@ extension MutablePersistableRecord { return success.returned } - /// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...` - /// statement, and returns the selected columns from the saved row. + /// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and + /// returns the selected columns from the saved row. /// /// If the receiver has a non-nil primary key and a matching row in the /// database, this method performs an update. Otherwise, it performs /// an insert. /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter selection: The returned columns (must not be empty). /// - parameter fetch: A function that executes it ``Statement`` argument. /// - returns: The result of the `fetch` function. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ diff --git a/GRDB/Record/MutablePersistableRecord+Update.swift b/GRDB/Record/MutablePersistableRecord+Update.swift index cce51cfcb..9f9479993 100644 --- a/GRDB/Record/MutablePersistableRecord+Update.swift +++ b/GRDB/Record/MutablePersistableRecord+Update.swift @@ -21,12 +21,26 @@ extension MutablePersistableRecord { extension MutablePersistableRecord { /// Executes an `UPDATE` statement on the provided columns. /// + /// For example: + /// + /// ```swift + /// try dbQueue.write { db in + /// if var player = Player.fetchOne(db, id: 1) { + /// player.score += 10 + /// try player.update(db, columns: ["score"]) + /// } + /// } + /// ``` + /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter columns: The columns to update. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type, + /// or ``PersistenceError/recordNotFound(databaseTableName:key:)`` if the + /// primary key does not match any row in the database. @inlinable // allow specialization so that empty callbacks are removed public func update( _ db: Database, @@ -51,12 +65,26 @@ extension MutablePersistableRecord { /// Executes an `UPDATE` statement on the provided columns. /// + /// For example: + /// + /// ```swift + /// try dbQueue.write { db in + /// if var player = Player.fetchOne(db, id: 1) { + /// player.score += 10 + /// try player.update(db, columns: [Column("score")]) + /// } + /// } + /// ``` + /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter columns: The columns to update. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type, + /// or ``PersistenceError/recordNotFound(databaseTableName:key:)`` if the + /// primary key does not match any row in the database. @inlinable // allow specialization so that empty callbacks are removed public func update( _ db: Database, @@ -70,11 +98,25 @@ extension MutablePersistableRecord { /// Executes an `UPDATE` statement on all columns. /// + /// For example: + /// + /// ```swift + /// try dbQueue.write { db in + /// if var player = Player.fetchOne(db, id: 1) { + /// player.score += 10 + /// try player.update(db) + /// } + /// } + /// ``` + /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type, + /// or ``PersistenceError/recordNotFound(databaseTableName:key:)`` if the + /// primary key does not match any row in the database. @inlinable // allow specialization so that empty callbacks are removed public func update( _ db: Database, @@ -92,20 +134,32 @@ extension MutablePersistableRecord { /// /// For example: /// - /// if let oldPlayer = try Player.fetchOne(db, key: 42) { + /// ```swift + /// try dbQueue.write { db in + /// if let oldPlayer = Player.fetchOne(db, id: 1) { /// var newPlayer = oldPlayer - /// newPlayer.score += 10 + /// newPlayer.score = 1000 /// newPlayer.hasAward = true - /// try newPlayer.updateChanges(db, from: oldRecord) + /// let modified = try newPlayer.updateChanges(db, from: oldPlayer) + /// if modified { + /// print("player was modified") + /// } else { + /// print("player was not modified") + /// } /// } + /// } + /// ``` /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter record: The comparison record. /// - returns: Whether the record had changes. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database and record could not be updated. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type, + /// or ``PersistenceError/recordNotFound(databaseTableName:key:)`` if the + /// primary key does not match any row in the database. /// - SeeAlso: updateChanges(_:with:) @discardableResult @inlinable // allow specialization so that empty callbacks are removed @@ -124,20 +178,32 @@ extension MutablePersistableRecord { /// /// For example: /// - /// if var player = try Player.fetchOne(db, key: 42) { - /// try player.updateChanges(db) { - /// $0.score += 10 + /// ```swift + /// try dbQueue.write { db in + /// if var player = Player.fetchOne(db, id: 1) { + /// let modified = try player.updateChanges(db) { + /// $0.score = 1000 /// $0.hasAward = true /// } + /// if modified { + /// print("player was modified") + /// } else { + /// print("player was not modified") + /// } /// } + /// } + /// ``` /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter modify: A closure that modifies the record. /// - returns: Whether the record had changes. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database and record could not be updated. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type, + /// or ``PersistenceError/recordNotFound(databaseTableName:key:)`` if the + /// primary key does not match any row in the database. @discardableResult @inlinable // allow specialization so that empty callbacks are removed public mutating func updateChanges( @@ -156,22 +222,19 @@ extension MutablePersistableRecord { extension MutablePersistableRecord { #if GRDBCUSTOMSQLITE || GRDBCIPHER - /// Executes an `UPDATE ... RETURNING ...` statement, and returns the - /// updated record. - /// - /// This method helps dealing with default column values and - /// generated columns. - /// - /// For example: - /// - /// let player: Player = ... - /// let updatedPlayer = player.updateAndFetch(db) + /// Executes an `UPDATE RETURNING` statement on all columns, and returns a + /// new record built from the updated row. /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - returns: The updated record. The result can be nil when the /// conflict policy is `IGNORE`. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type, + /// or ``PersistenceError/recordNotFound(databaseTableName:key:)`` if the + /// primary key does not match any row in the database. @inlinable // allow specialization so that empty callbacks are removed public func updateAndFetch( _ db: Database, @@ -182,17 +245,20 @@ extension MutablePersistableRecord { try updateAndFetch(db, onConflict: conflictResolution, as: Self.self) } - /// Executes an `UPDATE ... RETURNING ...` statement on all columns, and - /// returns a new record built from the updated row. + /// Executes an `UPDATE RETURNING` statement on all columns, and returns a + /// new record built from the updated row. /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter returnedType: The type of the returned record. /// - returns: A record of type `returnedType`. The result can be nil when /// the conflict policy is `IGNORE`. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type, + /// or ``PersistenceError/recordNotFound(databaseTableName:key:)`` if the + /// primary key does not match any row in the database. @inlinable // allow specialization so that empty callbacks are removed public func updateAndFetch( _ db: Database, @@ -206,18 +272,21 @@ extension MutablePersistableRecord { } /// Modifies the record according to the provided `modify` closure, and - /// executes an `UPDATE ... RETURNING ...` statement that updates the - /// modified columns, if and only the record was modified. The method - /// returns a new record built from the updated row. + /// executes an `UPDATE RETURNING` statement that updates the modified + /// columns, if and only the record was modified. The method returns a new + /// record built from the updated row. /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter modify: A closure that modifies the record. /// - returns: An updated record, or nil if the record has no change, or /// in case of a failed update due to the `IGNORE` conflict policy. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database and record could not be updated. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type, + /// or ``PersistenceError/recordNotFound(databaseTableName:key:)`` if the + /// primary key does not match any row in the database. @inlinable // allow specialization so that empty callbacks are removed public mutating func updateChangesAndFetch( _ db: Database, @@ -230,20 +299,23 @@ extension MutablePersistableRecord { } /// Modifies the record according to the provided `modify` closure, and - /// executes an `UPDATE ... RETURNING ...` statement that updates the - /// modified columns, if and only the record was modified. The method - /// returns a new record built from the updated row. + /// executes an `UPDATE RETURNING` statement that updates the modified + /// columns, if and only the record was modified. The method returns a new + /// record built from the updated row. /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter returnedType: The type of the returned record. /// - parameter modify: A closure that modifies the record. /// - returns: A record of type `returnedType`, or nil if the record has /// no change, or in case of a failed update due to the `IGNORE` /// conflict policy. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database and record could not be updated. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type, + /// or ``PersistenceError/recordNotFound(databaseTableName:key:)`` if the + /// primary key does not match any row in the database. @inlinable // allow specialization so that empty callbacks are removed public mutating func updateChangesAndFetch( _ db: Database, @@ -259,30 +331,35 @@ extension MutablePersistableRecord { modify: modify) } - /// Executes an `UPDATE ... RETURNING ...` statement on the provided - /// columns, and returns the selected columns from the updated row. + /// Executes an `UPDATE RETURNING` statement on the provided columns, and + /// returns the selected columns from the updated row. /// /// For example: /// - /// try dbQueue.write { db in - /// // UPDATE player SET score = ... RETURNING totalScore - /// let totalScore = try player.updateAndFetch( - /// db, columns: ["Score"], - /// selection: [Column("totalScore")], - /// fetch: { statement in - /// try Int.fetchOne(statement) - /// }) - /// } + /// ```swift + /// try dbQueue.write { db in + /// // UPDATE player SET score = ... RETURNING totalScore + /// let totalScore = try player.updateAndFetch( + /// db, columns: ["Score"], + /// selection: [Column("totalScore")], + /// fetch: { statement in + /// try Int.fetchOne(statement) + /// }) + /// } + /// ``` /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter columns: The columns to update. /// - parameter selection: The returned columns (must not be empty). /// - parameter fetch: A function that executes it ``Statement`` argument. /// - returns: The result of the `fetch` function. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type, + /// or ``PersistenceError/recordNotFound(databaseTableName:key:)`` if the + /// primary key does not match any row in the database. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed public func updateAndFetch( @@ -315,30 +392,35 @@ extension MutablePersistableRecord { return success.returned } - /// Executes an `UPDATE ... RETURNING ...` statement on the provided - /// columns, and returns the selected columns from the updated row. + /// Executes an `UPDATE RETURNING` statement on the provided columns, and + /// returns the selected columns from the updated row. /// /// For example: /// - /// try dbQueue.write { db in - /// // UPDATE player SET score = ... RETURNING totalScore - /// let totalScore = try player.updateAndFetch( - /// db, columns: [Column("Score")], - /// selection: [Column("totalScore")], - /// fetch: { statement in - /// try Int.fetchOne(statement) - /// }) - /// } + /// ```swift + /// try dbQueue.write { db in + /// // UPDATE player SET score = ... RETURNING totalScore + /// let totalScore = try player.updateAndFetch( + /// db, columns: [Column("Score")], + /// selection: [Column("totalScore")], + /// fetch: { statement in + /// try Int.fetchOne(statement) + /// }) + /// } + /// ``` /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter columns: The columns to update. /// - parameter selection: The returned columns (must not be empty). /// - parameter fetch: A function that executes it ``Statement`` argument. /// - returns: The result of the `fetch` function. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type, + /// or ``PersistenceError/recordNotFound(databaseTableName:key:)`` if the + /// primary key does not match any row in the database. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed public func updateAndFetch( @@ -357,26 +439,31 @@ extension MutablePersistableRecord { fetch: fetch) } - /// Executes an `UPDATE ... RETURNING ...` statement on all columns, and - /// returns the selected columns from the updated row. + /// Executes an `UPDATE RETURNING` statement on all columns, and returns the + /// selected columns from the updated row. /// /// For example: /// - /// try dbQueue.write { db in - /// // UPDATE player SET ... RETURNING totalScore - /// let totalScore = try player.updateAndFetch(db, selection: [Column("totalScore")]) { statement in - /// try Int.fetchOne(statement) - /// } + /// ```swift + /// try dbQueue.write { db in + /// // UPDATE player SET ... RETURNING totalScore + /// let totalScore = try player.updateAndFetch(db, selection: [Column("totalScore")]) { statement in + /// try Int.fetchOne(statement) /// } + /// } + /// ``` /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter selection: The returned columns (must not be empty). /// - parameter fetch: A function that executes it ``Statement`` argument. /// - returns: The result of the `fetch` function. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type, + /// or ``PersistenceError/recordNotFound(databaseTableName:key:)`` if the + /// primary key does not match any row in the database. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed public func updateAndFetch( @@ -396,19 +483,22 @@ extension MutablePersistableRecord { } /// Modifies the record according to the provided `modify` closure, and - /// executes an `UPDATE ... RETURNING ...` statement that updates the - /// modified columns, if and only the record was modified. The method - /// returns a new record built from the updated row. + /// executes an `UPDATE RETURNING` statement that updates the modified + /// columns, if and only the record was modified. The method returns a new + /// record built from the updated row. /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter selection: The returned columns (must not be empty). /// - parameter fetch: A function that executes it ``Statement`` argument. /// - parameter modify: A closure that modifies the record. /// - returns: The result of the `fetch` function. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database and record could not be updated. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type, + /// or ``PersistenceError/recordNotFound(databaseTableName:key:)`` if the + /// primary key does not match any row in the database. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed public mutating func updateChangesAndFetch( @@ -428,22 +518,19 @@ extension MutablePersistableRecord { fetch: fetch) } #else - /// Executes an `UPDATE ... RETURNING ...` statement, and returns the - /// updated record. - /// - /// This method helps dealing with default column values and - /// generated columns. - /// - /// For example: - /// - /// let player: Player = ... - /// let updatedPlayer = player.updateAndFetch(db) + /// Executes an `UPDATE RETURNING` statement on all columns, and returns a + /// new record built from the updated row. /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - returns: The updated record. The result can be nil when the /// conflict policy is `IGNORE`. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type, + /// or ``PersistenceError/recordNotFound(databaseTableName:key:)`` if the + /// primary key does not match any row in the database. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public func updateAndFetch( @@ -455,17 +542,20 @@ extension MutablePersistableRecord { try updateAndFetch(db, onConflict: conflictResolution, as: Self.self) } - /// Executes an `UPDATE ... RETURNING ...` statement on all columns, and - /// returns a new record built from the updated row. + /// Executes an `UPDATE RETURNING` statement on all columns, and returns a + /// new record built from the updated row. /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter returnedType: The type of the returned record. /// - returns: A record of type `returnedType`. The result can be nil when /// the conflict policy is `IGNORE`. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type, + /// or ``PersistenceError/recordNotFound(databaseTableName:key:)`` if the + /// primary key does not match any row in the database. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public func updateAndFetch( @@ -480,18 +570,21 @@ extension MutablePersistableRecord { } /// Modifies the record according to the provided `modify` closure, and - /// executes an `UPDATE ... RETURNING ...` statement that updates the - /// modified columns, if and only the record was modified. The method - /// returns a new record built from the updated row. + /// executes an `UPDATE RETURNING` statement that updates the modified + /// columns, if and only the record was modified. The method returns a new + /// record built from the updated row. /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter modify: A closure that modifies the record. /// - returns: An updated record, or nil if the record has no change, or /// in case of a failed update due to the `IGNORE` conflict policy. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database and record could not be updated. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type, + /// or ``PersistenceError/recordNotFound(databaseTableName:key:)`` if the + /// primary key does not match any row in the database. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public mutating func updateChangesAndFetch( @@ -505,20 +598,23 @@ extension MutablePersistableRecord { } /// Modifies the record according to the provided `modify` closure, and - /// executes an `UPDATE ... RETURNING ...` statement that updates the - /// modified columns, if and only the record was modified. The method - /// returns a new record built from the updated row. + /// executes an `UPDATE RETURNING` statement that updates the modified + /// columns, if and only the record was modified. The method returns a new + /// record built from the updated row. /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter returnedType: The type of the returned record. /// - parameter modify: A closure that modifies the record. /// - returns: A record of type `returnedType`, or nil if the record has /// no change, or in case of a failed update due to the `IGNORE` /// conflict policy. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database and record could not be updated. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type, + /// or ``PersistenceError/recordNotFound(databaseTableName:key:)`` if the + /// primary key does not match any row in the database. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public mutating func updateChangesAndFetch( @@ -535,30 +631,35 @@ extension MutablePersistableRecord { modify: modify) } - /// Executes an `UPDATE ... RETURNING ...` statement on the provided - /// columns, and returns the selected columns from the updated row. + /// Executes an `UPDATE RETURNING` statement on the provided columns, and + /// returns the selected columns from the updated row. /// /// For example: /// - /// try dbQueue.write { db in - /// // UPDATE player SET score = ... RETURNING totalScore - /// let totalScore = try player.updateAndFetch( - /// db, columns: ["Score"], - /// selection: [Column("totalScore")], - /// fetch: { statement in - /// try Int.fetchOne(statement) - /// }) - /// } + /// ```swift + /// try dbQueue.write { db in + /// // UPDATE player SET score = ... RETURNING totalScore + /// let totalScore = try player.updateAndFetch( + /// db, columns: ["Score"], + /// selection: [Column("totalScore")], + /// fetch: { statement in + /// try Int.fetchOne(statement) + /// }) + /// } + /// ``` /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter columns: The columns to update. /// - parameter selection: The returned columns (must not be empty). /// - parameter fetch: A function that executes it ``Statement`` argument. /// - returns: The result of the `fetch` function. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type, + /// or ``PersistenceError/recordNotFound(databaseTableName:key:)`` if the + /// primary key does not match any row in the database. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ @@ -592,30 +693,35 @@ extension MutablePersistableRecord { return success.returned } - /// Executes an `UPDATE ... RETURNING ...` statement on the provided - /// columns, and returns the selected columns from the updated row. + /// Executes an `UPDATE RETURNING` statement on the provided columns, and + /// returns the selected columns from the updated row. /// /// For example: /// - /// try dbQueue.write { db in - /// // UPDATE player SET score = ... RETURNING totalScore - /// let totalScore = try player.updateAndFetch( - /// db, columns: [Column("Score")], - /// selection: [Column("totalScore")], - /// fetch: { statement in - /// try Int.fetchOne(statement) - /// }) - /// } + /// ```swift + /// try dbQueue.write { db in + /// // UPDATE player SET score = ... RETURNING totalScore + /// let totalScore = try player.updateAndFetch( + /// db, columns: [Column("Score")], + /// selection: [Column("totalScore")], + /// fetch: { statement in + /// try Int.fetchOne(statement) + /// }) + /// } + /// ``` /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter columns: The columns to update. /// - parameter selection: The returned columns (must not be empty). /// - parameter fetch: A function that executes it ``Statement`` argument. /// - returns: The result of the `fetch` function. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type, + /// or ``PersistenceError/recordNotFound(databaseTableName:key:)`` if the + /// primary key does not match any row in the database. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ @@ -635,26 +741,31 @@ extension MutablePersistableRecord { fetch: fetch) } - /// Executes an `UPDATE ... RETURNING ...` statement on all columns, and - /// returns the selected columns from the updated row. + /// Executes an `UPDATE RETURNING` statement on all columns, and returns the + /// selected columns from the updated row. /// /// For example: /// - /// try dbQueue.write { db in - /// // UPDATE player SET ... RETURNING totalScore - /// let totalScore = try player.updateAndFetch(db, selection: [Column("totalScore")]) { statement in - /// try Int.fetchOne(statement) - /// } + /// ```swift + /// try dbQueue.write { db in + /// // UPDATE player SET ... RETURNING totalScore + /// let totalScore = try player.updateAndFetch(db, selection: [Column("totalScore")]) { statement in + /// try Int.fetchOne(statement) /// } + /// } + /// ``` /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter selection: The returned columns (must not be empty). /// - parameter fetch: A function that executes it ``Statement`` argument. /// - returns: The result of the `fetch` function. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type, + /// or ``PersistenceError/recordNotFound(databaseTableName:key:)`` if the + /// primary key does not match any row in the database. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ @@ -675,19 +786,22 @@ extension MutablePersistableRecord { } /// Modifies the record according to the provided `modify` closure, and - /// executes an `UPDATE ... RETURNING ...` statement that updates the - /// modified columns, if and only the record was modified. The method - /// returns a new record built from the updated row. + /// executes an `UPDATE RETURNING` statement that updates the modified + /// columns, if and only the record was modified. The method returns a new + /// record built from the updated row. /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter selection: The returned columns (must not be empty). /// - parameter fetch: A function that executes it ``Statement`` argument. /// - parameter modify: A closure that modifies the record. /// - returns: The result of the `fetch` function. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database and record could not be updated. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type, + /// or ``PersistenceError/recordNotFound(databaseTableName:key:)`` if the + /// primary key does not match any row in the database. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ diff --git a/GRDB/Record/MutablePersistableRecord+Upsert.swift b/GRDB/Record/MutablePersistableRecord+Upsert.swift index 09979d0cf..38f4e41eb 100644 --- a/GRDB/Record/MutablePersistableRecord+Upsert.swift +++ b/GRDB/Record/MutablePersistableRecord+Upsert.swift @@ -2,26 +2,34 @@ extension MutablePersistableRecord { #if GRDBCUSTOMSQLITE || GRDBCIPHER - /// Executes an `INSERT ... ON CONFLICT DO UPDATE` statement. + /// Executes an `INSERT ON CONFLICT DO UPDATE` statement. /// /// The upsert behavior is triggered by a violation of any uniqueness /// constraint on the table (primary key or unique index). In case of /// violation, all columns but the primary key are overwritten with the - /// inserted values: + /// inserted values. /// - /// struct Player: Encodable, MutablePersistableRecord { - /// var id: Int64 - /// var name: String - /// var score: Int - /// } + /// For example: /// - /// // INSERT INTO player (id, name, score) - /// // VALUES (1, 'Arthur', 1000) - /// // ON CONFLICT DO UPDATE SET - /// // name = excluded.name, - /// // score = excluded.score - /// var player = Player(id: 1, name: "Arthur", score: 1000) - /// try player.upsert(db) + /// ```swift + /// struct Player: Encodable, MutablePersistableRecord { + /// var id: Int64 + /// var name: String + /// var score: Int + /// } + /// + /// // INSERT INTO player (id, name, score) + /// // VALUES (1, 'Arthur', 1000) + /// // ON CONFLICT DO UPDATE SET + /// // name = excluded.name, + /// // score = excluded.score + /// var player = Player(id: 1, name: "Arthur", score: 1000) + /// try player.upsert(db) + /// ``` + /// + /// - parameter db: A database connection. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public mutating func upsert(_ db: Database) throws { try willSave(db) @@ -39,28 +47,30 @@ extension MutablePersistableRecord { didSave(saved) } - /// Executes an `INSERT ... ON CONFLICT DO UPDATE ... RETURNING ...` - /// statement, and returns the upserted record. + /// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and + /// returns the upserted record. /// /// With default parameters (`upsertAndFetch(db)`), the upsert behavior is /// triggered by a violation of any uniqueness constraint on the table /// (primary key or unique index). In case of violation, all columns but the /// primary key are overwritten with the inserted values: /// - /// struct Player: Encodable, MutablePersistableRecord { - /// var id: Int64 - /// var name: String - /// var score: Int - /// } + /// ```swift + /// struct Player: Encodable, MutablePersistableRecord { + /// var id: Int64 + /// var name: String + /// var score: Int + /// } /// - /// // INSERT INTO player (id, name, score) - /// // VALUES (1, 'Arthur', 1000) - /// // ON CONFLICT DO UPDATE SET - /// // name = excluded.name, - /// // score = excluded.score - /// // RETURNING * - /// var player = Player(id: 1, name: "Arthur", score: 1000) - /// let upsertedPlayer = try player.upsertAndFetch(db) + /// // INSERT INTO player (id, name, score) + /// // VALUES (1, 'Arthur', 1000) + /// // ON CONFLICT DO UPDATE SET + /// // name = excluded.name, + /// // score = excluded.score + /// // RETURNING * + /// var player = Player(id: 1, name: "Arthur", score: 1000) + /// let upsertedPlayer = try player.upsertAndFetch(db) + /// ``` /// /// With `conflictTarget` and `assignments` arguments, you can further /// control the upsert behavior. Make sure you check @@ -77,31 +87,33 @@ extension MutablePersistableRecord { /// does not overwrite the tainted flag, and overwrites the /// remaining columns: /// - /// // CREATE TABLE vocabulary( - /// // word TEXT PRIMARY KEY, - /// // kind TEXT NOT NULL, - /// // isTainted BOOLEAN DEFAULT 0, - /// // count INT DEFAULT 1)) - /// struct Vocabulary: Encodable, MutablePersistableRecord { - /// var word: String - /// var kind: String - /// var isTainted: Bool - /// } + /// ```swift + /// // CREATE TABLE vocabulary( + /// // word TEXT PRIMARY KEY, + /// // kind TEXT NOT NULL, + /// // isTainted BOOLEAN DEFAULT 0, + /// // count INT DEFAULT 1)) + /// struct Vocabulary: Encodable, MutablePersistableRecord { + /// var word: String + /// var kind: String + /// var isTainted: Bool + /// } /// - /// // INSERT INTO vocabulary(word, kind, isTainted) - /// // VALUES('jovial', 'adjective', 0) - /// // ON CONFLICT(word) DO UPDATE SET \ - /// // count = count + 1, - /// // kind = excluded.kind - /// // RETURNING * - /// var vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false) - /// let upserted = try vocabulary.upsertAndFetch( - /// db, - /// onConflict: ["word"], - /// doUpdate: { _ in - /// [Column("count") += 1, - /// Column("isTainted").noOverwrite] - /// }) + /// // INSERT INTO vocabulary(word, kind, isTainted) + /// // VALUES('jovial', 'adjective', 0) + /// // ON CONFLICT(word) DO UPDATE SET \ + /// // count = count + 1, + /// // kind = excluded.kind + /// // RETURNING * + /// var vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false) + /// let upserted = try vocabulary.upsertAndFetch( + /// db, + /// onConflict: ["word"], + /// doUpdate: { _ in + /// [Column("count") += 1, + /// Column("isTainted").noOverwrite] + /// }) + /// ``` /// /// - parameter db: A database connection. /// - parameter conflictTarget: The conflict target. @@ -110,7 +122,8 @@ extension MutablePersistableRecord { /// constraints, these assignments are performed, and remaining columns /// are overwritten by inserted values. /// - returns: The upserted record. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public mutating func upsertAndFetch( _ db: Database, @@ -122,8 +135,8 @@ extension MutablePersistableRecord { try upsertAndFetch(db, as: Self.self, onConflict: conflictTarget, doUpdate: assignments) } - /// Executes an `INSERT ... ON CONFLICT DO UPDATE ... RETURNING ...` - /// statement, and returns the upserted record. + /// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and + /// returns the upserted record. /// /// See `upsertAndFetch(_:onConflict:doUpdate:)` for more information about /// the `conflictTarget` and `assignments` parameters. @@ -136,7 +149,8 @@ extension MutablePersistableRecord { /// constraints, these assignments are performed, and remaining columns /// are overwritten by inserted values. /// - returns: A record of type `returnedType`. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public mutating func upsertAndFetch( _ db: Database, @@ -164,26 +178,34 @@ extension MutablePersistableRecord { return success.returned } #else - /// Executes an `INSERT ... ON CONFLICT DO UPDATE` statement. + /// Executes an `INSERT ON CONFLICT DO UPDATE` statement. /// /// The upsert behavior is triggered by a violation of any uniqueness /// constraint on the table (primary key or unique index). In case of /// violation, all columns but the primary key are overwritten with the - /// inserted values: + /// inserted values. /// - /// struct Player: Encodable, MutablePersistableRecord { - /// var id: Int64 - /// var name: String - /// var score: Int - /// } + /// For example: /// - /// // INSERT INTO player (id, name, score) - /// // VALUES (1, 'Arthur', 1000) - /// // ON CONFLICT DO UPDATE SET - /// // name = excluded.name, - /// // score = excluded.score - /// var player = Player(id: 1, name: "Arthur", score: 1000) - /// try player.upsert(db) + /// ```swift + /// struct Player: Encodable, MutablePersistableRecord { + /// var id: Int64 + /// var name: String + /// var score: Int + /// } + /// + /// // INSERT INTO player (id, name, score) + /// // VALUES (1, 'Arthur', 1000) + /// // ON CONFLICT DO UPDATE SET + /// // name = excluded.name, + /// // score = excluded.score + /// var player = Player(id: 1, name: "Arthur", score: 1000) + /// try player.upsert(db) + /// ``` + /// + /// - parameter db: A database connection. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public mutating func upsert(_ db: Database) throws { @@ -202,28 +224,30 @@ extension MutablePersistableRecord { didSave(saved) } - /// Executes an `INSERT ... ON CONFLICT DO UPDATE ... RETURNING ...` - /// statement, and returns the upserted record. + /// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and + /// returns the upserted record. /// /// With default parameters (`upsertAndFetch(db)`), the upsert behavior is /// triggered by a violation of any uniqueness constraint on the table /// (primary key or unique index). In case of violation, all columns but the /// primary key are overwritten with the inserted values: /// - /// struct Player: Encodable, MutablePersistableRecord { - /// var id: Int64 - /// var name: String - /// var score: Int - /// } + /// ```swift + /// struct Player: Encodable, MutablePersistableRecord { + /// var id: Int64 + /// var name: String + /// var score: Int + /// } /// - /// // INSERT INTO player (id, name, score) - /// // VALUES (1, 'Arthur', 1000) - /// // ON CONFLICT DO UPDATE SET - /// // name = excluded.name, - /// // score = excluded.score - /// // RETURNING * - /// var player = Player(id: 1, name: "Arthur", score: 1000) - /// let upsertedPlayer = try player.upsertAndFetch(db) + /// // INSERT INTO player (id, name, score) + /// // VALUES (1, 'Arthur', 1000) + /// // ON CONFLICT DO UPDATE SET + /// // name = excluded.name, + /// // score = excluded.score + /// // RETURNING * + /// var player = Player(id: 1, name: "Arthur", score: 1000) + /// let upsertedPlayer = try player.upsertAndFetch(db) + /// ``` /// /// With `conflictTarget` and `assignments` arguments, you can further /// control the upsert behavior. Make sure you check @@ -240,31 +264,33 @@ extension MutablePersistableRecord { /// does not overwrite the tainted flag, and overwrites the /// remaining columns: /// - /// // CREATE TABLE vocabulary( - /// // word TEXT PRIMARY KEY, - /// // kind TEXT NOT NULL, - /// // isTainted BOOLEAN DEFAULT 0, - /// // count INT DEFAULT 1)) - /// struct Vocabulary: Encodable, MutablePersistableRecord { - /// var word: String - /// var kind: String - /// var isTainted: Bool - /// } + /// ```swift + /// // CREATE TABLE vocabulary( + /// // word TEXT PRIMARY KEY, + /// // kind TEXT NOT NULL, + /// // isTainted BOOLEAN DEFAULT 0, + /// // count INT DEFAULT 1)) + /// struct Vocabulary: Encodable, MutablePersistableRecord { + /// var word: String + /// var kind: String + /// var isTainted: Bool + /// } /// - /// // INSERT INTO vocabulary(word, kind, isTainted) - /// // VALUES('jovial', 'adjective', 0) - /// // ON CONFLICT(word) DO UPDATE SET \ - /// // count = count + 1, - /// // kind = excluded.kind - /// // RETURNING * - /// var vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false) - /// let upserted = try vocabulary.upsertAndFetch( - /// db, - /// onConflict: ["word"], - /// doUpdate: { _ in - /// [Column("count") += 1, - /// Column("isTainted").noOverwrite] - /// }) + /// // INSERT INTO vocabulary(word, kind, isTainted) + /// // VALUES('jovial', 'adjective', 0) + /// // ON CONFLICT(word) DO UPDATE SET \ + /// // count = count + 1, + /// // kind = excluded.kind + /// // RETURNING * + /// var vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false) + /// let upserted = try vocabulary.upsertAndFetch( + /// db, + /// onConflict: ["word"], + /// doUpdate: { _ in + /// [Column("count") += 1, + /// Column("isTainted").noOverwrite] + /// }) + /// ``` /// /// - parameter db: A database connection. /// - parameter conflictTarget: The conflict target. @@ -273,7 +299,8 @@ extension MutablePersistableRecord { /// constraints, these assignments are performed, and remaining columns /// are overwritten by inserted values. /// - returns: The upserted record. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public mutating func upsertAndFetch( @@ -286,11 +313,11 @@ extension MutablePersistableRecord { try upsertAndFetch(db, as: Self.self, onConflict: conflictTarget, doUpdate: assignments) } - /// Executes an `INSERT ... ON CONFLICT DO UPDATE ... RETURNING ...` - /// statement, and returns the upserted record. + /// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and + /// returns the upserted record. /// - /// See `upsertAndFetch(_:onConflict:doUpdate:)` for more information about - /// the `conflictTarget` and `assignments` parameters. + /// See ``upsertAndFetch(_:onConflict:doUpdate:)`` for more information + /// about the `conflictTarget` and `assignments` parameters. /// /// - parameter db: A database connection. /// - parameter returnedType: The type of the returned record. @@ -300,7 +327,8 @@ extension MutablePersistableRecord { /// constraints, these assignments are performed, and remaining columns /// are overwritten by inserted values. /// - returns: A record of type `returnedType`. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public mutating func upsertAndFetch( @@ -374,7 +402,7 @@ extension MutablePersistableRecord { return success } - /// Executes an `INSERT ... RETURNING` statement, and DOES NOT run + /// Executes an `INSERT RETURNING` statement, and DOES NOT run /// insertion callbacks. @usableFromInline func upsertAndFetchWithoutCallbacks( diff --git a/GRDB/Record/MutablePersistableRecord.swift b/GRDB/Record/MutablePersistableRecord.swift index 6e3d44e46..b69c2eaec 100644 --- a/GRDB/Record/MutablePersistableRecord.swift +++ b/GRDB/Record/MutablePersistableRecord.swift @@ -1,5 +1,128 @@ -/// Types that adopt `MutablePersistableRecord` can be inserted, updated, -/// and deleted. +/// A type that can be persisted in the database, and mutates on insertion. +/// +/// ## Overview +/// +/// A `MutablePersistableRecord` instance mutates on insertion. This protocol +/// is suited for record types that are a `struct`, and target a database table +/// where ids are generated on insertion. Such records implement the +/// ``didInsert(_:)-109jm`` callback in order to grab this id. For example: +/// +/// ```swift +/// // CREATE TABLE player ( +/// // id INTEGER PRIMARY KEY AUTOINCREMENT, +/// // name TEXT NOT NULL, +/// // score INTEGER NOT NULL +/// // ) +/// struct Player: Encodable { +/// var id: Int64? +/// var name: String +/// var score: Int +/// } +/// +/// extension Player: MutablePersistableRecord { +/// mutating func didInsert(_ inserted: InsertionSuccess) { +/// id = inserted.rowID +/// } +/// } +/// +/// try dbQueue.write { db in +/// var player = Player(id: nil, name:: "Arthur", score: 1000) +/// try player.insert(db) +/// print(player.id) // Some id that is not nil +/// } +/// ``` +/// +/// Other record types (classes, and generally records that do not mutate on +/// insertion) should prefer the ``PersistableRecord`` protocol instead. +/// +/// ## Conforming to the MutablePersistableRecord Protocol +/// +/// To conform to `MutablePersistableRecord`, provide an implementation for the +/// ``EncodableRecord/encode(to:)-k9pf`` method. This implementation is +/// ready-made for `Encodable` types. +/// +/// You configure the database table where records are persisted with the +/// ``TableRecord`` inherited protocol. +/// +/// ## Topics +/// +/// ### Testing if a Record Exists in the Database +/// +/// - ``exists(_:)`` +/// +/// ### Inserting a Record +/// +/// - ``insert(_:onConflict:)`` +/// - ``inserted(_:onConflict:)`` +/// - ``upsert(_:)`` +/// +/// ### Inserting a Record and Fetching the Inserted Row +/// +/// - ``insertAndFetch(_:onConflict:)`` +/// - ``insertAndFetch(_:onConflict:as:)`` +/// - ``insertAndFetch(_:onConflict:selection:fetch:)`` +/// - ``upsertAndFetch(_:onConflict:doUpdate:)`` +/// - ``upsertAndFetch(_:as:onConflict:doUpdate:)`` +/// +/// ### Updating a Record +/// +/// See inherited ``TableRecord`` methods for batch updates. +/// +/// - ``update(_:onConflict:)`` +/// - ``update(_:onConflict:columns:)-4foo1`` +/// - ``update(_:onConflict:columns:)-5hxyx`` +/// - ``updateChanges(_:onConflict:from:)`` +/// - ``updateChanges(_:onConflict:modify:)`` +/// +/// ### Updating a Record and Fetching the Updated Row +/// +/// - ``updateAndFetch(_:onConflict:)`` +/// - ``updateAndFetch(_:onConflict:as:)`` +/// - ``updateAndFetch(_:onConflict:columns:selection:fetch:)-7s7y1`` +/// - ``updateAndFetch(_:onConflict:columns:selection:fetch:)-30d2v`` +/// - ``updateAndFetch(_:onConflict:selection:fetch:)`` +/// - ``updateChangesAndFetch(_:onConflict:modify:)`` +/// - ``updateChangesAndFetch(_:onConflict:as:modify:)`` +/// - ``updateChangesAndFetch(_:onConflict:selection:fetch:modify:)`` +/// +/// ### Saving a Record +/// +/// - ``save(_:onConflict:)`` +/// - ``saved(_:onConflict:)`` +/// +/// ### Saving a Record and Fetching the Saved Row +/// +/// - ``saveAndFetch(_:onConflict:)`` +/// - ``saveAndFetch(_:onConflict:as:)`` +/// - ``saveAndFetch(_:onConflict:selection:fetch:)`` +/// +/// ### Deleting a Record +/// +/// See inherited ``TableRecord`` methods for batch deletes. +/// +/// - ``delete(_:)`` +/// +/// ### Persistence Callbacks +/// +/// - ``willDelete(_:)-7rmqk`` +/// - ``willInsert(_:)-1xfwo`` +/// - ``willSave(_:)-6jitc`` +/// - ``willUpdate(_:columns:)-3oko4`` +/// - ``didDelete(deleted:)-7sq9c`` +/// - ``didInsert(_:)-109jm`` +/// - ``didSave(_:)-177yz`` +/// - ``didUpdate(_:)-1oql8`` +/// - ``aroundDelete(_:delete:)-8w9ei`` +/// - ``aroundInsert(_:insert:)-67r8o`` +/// - ``aroundSave(_:save:)-5o9jz`` +/// - ``aroundUpdate(_:columns:update:)-ka41`` +/// - ``InsertionSuccess`` +/// - ``PersistenceSuccess`` +/// +/// ### Configuring Persistence +/// +/// - ``persistenceConflictPolicy-1isyv`` +/// - ``PersistenceConflictPolicy`` public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// The policy that handles SQLite conflicts when records are inserted /// or updated. @@ -27,13 +150,15 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// /// For example: /// - /// struct Player: MutablePersistableRecord { - /// func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { - /// print("Player will insert") - /// _ = try insert() - /// print("Player did insert") - /// } + /// ```swift + /// struct Player: MutablePersistableRecord { + /// func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + /// print("Player will insert") + /// _ = try insert() + /// print("Player did insert") /// } + /// } + /// ``` /// /// - parameter db: A database connection. /// - parameter insert: A function that inserts the record, and returns @@ -47,14 +172,16 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// You can provide a custom implementation in order to grab the /// auto-incremented id: /// - /// struct Player: MutablePersistableRecord { - /// var id: Int64? - /// var name: String + /// ```swift + /// struct Player: MutablePersistableRecord { + /// var id: Int64? + /// var name: String /// - /// mutating func didInsert(_ inserted: InsertionSuccess) { - /// id = inserted.rowID - /// } + /// mutating func didInsert(_ inserted: InsertionSuccess) { + /// id = inserted.rowID /// } + /// } + /// ``` /// /// - parameter inserted: Information about the inserted row. mutating func didInsert(_ inserted: InsertionSuccess) @@ -68,7 +195,6 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// - parameter db: A database connection. func willUpdate(_ db: Database, columns: Set) throws - // swiftlint:disable line_length /// Persistence callback called around the record update. /// /// If you provide a custom implementation of this method, you must call @@ -77,20 +203,20 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// /// For example: /// - /// struct Player: MutablePersistableRecord { - /// func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { - /// print("Player will update") - /// _ = try update() - /// print("Player did update") - /// } + /// ```swift + /// struct Player: MutablePersistableRecord { + /// func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + /// print("Player will update") + /// _ = try update() + /// print("Player did update") /// } + /// ``` /// /// - parameter db: A database connection. /// - parameter columns: The updated columns. /// - parameter update: A function that updates the record. Its result is /// reserved for GRDB usage. func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws - // swiftlint:enable line_length /// Persistence callback called upon successful update. /// @@ -116,13 +242,15 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// /// For example: /// - /// struct Player: MutablePersistableRecord { - /// func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { - /// print("Player will save") - /// _ = try save() - /// print("Player did save") - /// } + /// ```swift + /// struct Player: MutablePersistableRecord { + /// func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + /// print("Player will save") + /// _ = try save() + /// print("Player did save") /// } + /// } + /// ``` /// /// - parameter db: A database connection. /// - parameter update: A function that updates the record. Its result is @@ -153,13 +281,15 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// /// For example: /// - /// struct Player: MutablePersistableRecord { - /// func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { - /// print("Player will delete") - /// _ = try delete() - /// print("Player did delete") - /// } + /// ```swift + /// struct Player: MutablePersistableRecord { + /// func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + /// print("Player will delete") + /// _ = try delete() + /// print("Player did delete") /// } + /// } + /// ``` /// /// - parameter db: A database connection. /// - parameter delete: A function that deletes the record and returns @@ -198,12 +328,11 @@ extension MutablePersistableRecord { // MARK: - Existence Check extension MutablePersistableRecord { - /// Returns true if and only if the primary key matches a row in + /// Returns whether the primary key of the record matches a row in /// the database. /// /// - parameter db: A database connection. - /// - returns: Whether the primary key matches a row in the database. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func exists(_ db: Database) throws -> Bool { guard let statement = try DAO(db, self).existsStatement() else { // Nil primary key @@ -213,19 +342,19 @@ extension MutablePersistableRecord { } } -/// An error thrown by a type that adopts `MutablePersistableRecord`. +/// An error thrown by persistence methods of the +/// ``MutablePersistableRecord`` protocol. public enum PersistenceError: Error { - - /// Thrown by `MutablePersistableRecord.update(_:)` methods when no matching - /// row could be found in the database. + /// Thrown by ``MutablePersistableRecord`` updating methods, when no + /// matching row could be found and updated. /// - /// - `databaseTableName`: the table of the unfound record - /// - `key`: the key of the unfound record (column and values) + /// - parameters: + /// - databaseTableName: The table of the unfound record. + /// - key: The key of the unfound record (column and values). case recordNotFound(databaseTableName: String, key: [String: DatabaseValue]) } extension PersistenceError: CustomStringConvertible { - /// :nodoc: public var description: String { switch self { case let .recordNotFound(databaseTableName: databaseTableName, key: key): @@ -258,35 +387,39 @@ public struct PersistenceConflictPolicy { /// The result of a successful record insertion. /// /// `InsertionSuccess` gives the auto-incremented id after a successful -/// record insertion: +/// record insertion. For example: /// -/// struct Player: Encodable, MutablePersistableRecord { -/// var id: Int64? -/// var name: String +/// ```swift +/// struct Player: Encodable, MutablePersistableRecord { +/// var id: Int64? +/// var name: String /// -/// mutating func didInsert(_ inserted: InsertionSuccess) { -/// id = inserted.rowID -/// } +/// mutating func didInsert(_ inserted: InsertionSuccess) { +/// id = inserted.rowID /// } +/// } /// -/// try dbQueue.write { db in -/// var player = Player(id: nil, name: "Alice") -/// try player.insert(db) -/// print(player.id) // The inserted id -/// } +/// try dbQueue.write { db in +/// var player = Player(id: nil, name: "Alice") +/// try player.insert(db) +/// print(player.id) // The inserted id +/// } +/// ``` public struct InsertionSuccess { /// The rowid of the inserted record. /// /// For example: /// - /// struct Player: Encodable, MutablePersistableRecord { - /// var id: Int64? - /// var name: String + /// ```swift + /// struct Player: Encodable, MutablePersistableRecord { + /// var id: Int64? + /// var name: String /// - /// mutating func didInsert(_ inserted: InsertionSuccess) { - /// id = inserted.rowID - /// } + /// mutating func didInsert(_ inserted: InsertionSuccess) { + /// id = inserted.rowID /// } + /// } + /// ``` /// /// To learn about rowids, see . public var rowID: Int64 diff --git a/GRDB/Record/PersistableRecord+Insert.swift b/GRDB/Record/PersistableRecord+Insert.swift index e88d00ce2..112029d51 100644 --- a/GRDB/Record/PersistableRecord+Insert.swift +++ b/GRDB/Record/PersistableRecord+Insert.swift @@ -1,8 +1,12 @@ // MARK: - Insert Callbacks extension PersistableRecord { + @inline(__always) + @inlinable public func willInsert(_ db: Database) throws { } + @inline(__always) + @inlinable public func didInsert(_ inserted: InsertionSuccess) { } } @@ -11,9 +15,21 @@ extension PersistableRecord { extension PersistableRecord { /// Executes an `INSERT` statement. /// + /// For example: + /// + /// ```swift + /// try dbQueue.write { db in + /// let player = Player(name: "Arthur") + /// try player.insert(db) + /// } + /// ``` + /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public func insert( _ db: Database, @@ -40,55 +56,60 @@ extension PersistableRecord { extension PersistableRecord { #if GRDBCUSTOMSQLITE || GRDBCIPHER - /// Executes an `INSERT ... RETURNING ...` statement, and returns a new - /// record built from the inserted row. + /// Executes an `INSERT RETURNING` statement, and returns a new record built + /// from the inserted row. /// /// This method helps dealing with default column values and /// generated columns. /// /// For example: /// - /// // A table with an auto-incremented primary key and a default value - /// try dbQueue.write { db in - /// try db.execute(sql: """ - /// CREATE TABLE player( - /// id INTEGER PRIMARY KEY AUTOINCREMENT, - /// name TEXT, - /// score INTEGER DEFAULT 1000) - /// """) - /// } + /// ```swift + /// // A table with an auto-incremented primary key and a default value + /// try dbQueue.write { db in + /// try db.execute(sql: """ + /// CREATE TABLE player( + /// id INTEGER PRIMARY KEY AUTOINCREMENT, + /// name TEXT, + /// score INTEGER DEFAULT 1000) + /// """) + /// } /// - /// // A player with partial database information - /// struct PartialPlayer: PersistableRecord { - /// static let databaseTableName = "player" - /// var name: String - /// } + /// // A player with partial database information + /// struct PartialPlayer: PersistableRecord { + /// static let databaseTableName = "player" + /// var name: String + /// } /// - /// // A full player, with all database information - /// struct Player: TableRecord, FetchableRecord { - /// var id: Int64 - /// var name: String - /// var score: Int - /// } + /// // A full player, with all database information + /// struct Player: TableRecord, FetchableRecord { + /// var id: Int64 + /// var name: String + /// var score: Int + /// } /// - /// // Insert a base player, get a full one - /// try dbQueue.write { db in - /// let partialPlayer = PartialPlayer(name: "Alice") + /// // Insert a partial player, get a full one + /// try dbQueue.write { db in + /// let partialPlayer = PartialPlayer(name: "Alice") /// - /// // INSERT INTO player (name) VALUES ('Alice') RETURNING * - /// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) { - /// print(player.id) // The inserted id - /// print(player.name) // The inserted name - /// print(player.score) // The default score - /// } + /// // INSERT INTO player (name) VALUES ('Alice') RETURNING * + /// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) { + /// print(player.id) // The inserted id + /// print(player.name) // The inserted name + /// print(player.score) // The default score /// } + /// } + /// ``` /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter returnedType: The type of the returned record. - /// - returns: A record of type `returnedType`. The result can be + /// - returns: A record of type `returnedType`, if any. The result can be /// nil when the conflict policy is `IGNORE`. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public func insertAndFetch( _ db: Database, @@ -101,47 +122,53 @@ extension PersistableRecord { } } - /// Executes an `INSERT ... RETURNING ...` statement, and returns the - /// selected columns from the inserted row. + /// Executes an `INSERT RETURNING` statement, and returns the selected + /// columns from the inserted row. /// /// This method helps dealing with default column values and /// generated columns. /// /// For example: /// - /// // A table with an auto-incremented primary key and a default value - /// try dbQueue.write { db in - /// try db.execute(sql: """ - /// CREATE TABLE player( - /// id INTEGER PRIMARY KEY AUTOINCREMENT, - /// name TEXT, - /// score INTEGER DEFAULT 1000) - /// """) - /// } + /// ```swift + /// // A table with an auto-incremented primary key and a default value + /// try dbQueue.write { db in + /// try db.execute(sql: """ + /// CREATE TABLE player( + /// id INTEGER PRIMARY KEY AUTOINCREMENT, + /// name TEXT, + /// score INTEGER DEFAULT 1000) + /// """) + /// } /// - /// // A player with partial database information - /// struct PartialPlayer: PersistableRecord { - /// static let databaseTableName = "player" - /// var name: String - /// } + /// // A player with partial database information + /// struct PartialPlayer: PersistableRecord { + /// static let databaseTableName = "player" + /// var name: String + /// } /// - /// // Insert a base player, get the inserted score - /// try dbQueue.write { db in - /// let partialPlayer = PartialPlayer(name: "Alice") + /// // Insert a partial player, get the inserted score + /// try dbQueue.write { db in + /// let partialPlayer = PartialPlayer(name: "Alice") /// - /// // INSERT INTO player (name) VALUES ('Alice') RETURNING score - /// let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { statement in - /// try Int.fetchOne(statement) - /// } - /// print(score) // The inserted score + /// // INSERT INTO player (name) VALUES ('Alice') RETURNING score + /// let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { statement in + /// try Int.fetchOne(statement) /// } + /// print(score) // The inserted score + /// } + /// ``` /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter selection: The returned columns (must not be empty). - /// - parameter fetch: A function that executes its ``Statement`` argument. + /// - parameter fetch: A closure that executes its ``Statement`` argument. + /// If the conflict policy is `IGNORE`, the statement may return no row. /// - returns: The result of the `fetch` function. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed public func insertAndFetch( @@ -171,55 +198,60 @@ extension PersistableRecord { return success.returned } #else - /// Executes an `INSERT ... RETURNING ...` statement, and returns a new - /// record built from the inserted row. + /// Executes an `INSERT RETURNING` statement, and returns a new record built + /// from the inserted row. /// /// This method helps dealing with default column values and /// generated columns. /// /// For example: /// - /// // A table with an auto-incremented primary key and a default value - /// try dbQueue.write { db in - /// try db.execute(sql: """ - /// CREATE TABLE player( - /// id INTEGER PRIMARY KEY AUTOINCREMENT, - /// name TEXT, - /// score INTEGER DEFAULT 1000) - /// """) - /// } + /// ```swift + /// // A table with an auto-incremented primary key and a default value + /// try dbQueue.write { db in + /// try db.execute(sql: """ + /// CREATE TABLE player( + /// id INTEGER PRIMARY KEY AUTOINCREMENT, + /// name TEXT, + /// score INTEGER DEFAULT 1000) + /// """) + /// } /// - /// // A player with partial database information - /// struct PartialPlayer: PersistableRecord { - /// static let databaseTableName = "player" - /// var name: String - /// } + /// // A player with partial database information + /// struct PartialPlayer: PersistableRecord { + /// static let databaseTableName = "player" + /// var name: String + /// } /// - /// // A full player, with all database information - /// struct Player: TableRecord, FetchableRecord { - /// var id: Int64 - /// var name: String - /// var score: Int - /// } + /// // A full player, with all database information + /// struct Player: TableRecord, FetchableRecord { + /// var id: Int64 + /// var name: String + /// var score: Int + /// } /// - /// // Insert a base player, get a full one - /// try dbQueue.write { db in - /// let partialPlayer = PartialPlayer(name: "Alice") + /// // Insert a partial player, get a full one + /// try dbQueue.write { db in + /// let partialPlayer = PartialPlayer(name: "Alice") /// - /// // INSERT INTO player (name) VALUES ('Alice') RETURNING * - /// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) { - /// print(player.id) // The inserted id - /// print(player.name) // The inserted name - /// print(player.score) // The default score - /// } + /// // INSERT INTO player (name) VALUES ('Alice') RETURNING * + /// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) { + /// print(player.id) // The inserted id + /// print(player.name) // The inserted name + /// print(player.score) // The default score /// } + /// } + /// ``` /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter returnedType: The type of the returned record. - /// - returns: A record of type `returnedType`. The result can be + /// - returns: A record of type `returnedType`, if any. The result can be /// nil when the conflict policy is `IGNORE`. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public func insertAndFetch( @@ -233,47 +265,53 @@ extension PersistableRecord { } } - /// Executes an `INSERT ... RETURNING ...` statement, and returns the - /// selected columns from the inserted row. + /// Executes an `INSERT RETURNING` statement, and returns the selected + /// columns from the inserted row. /// /// This method helps dealing with default column values and /// generated columns. /// /// For example: /// - /// // A table with an auto-incremented primary key and a default value - /// try dbQueue.write { db in - /// try db.execute(sql: """ - /// CREATE TABLE player( - /// id INTEGER PRIMARY KEY AUTOINCREMENT, - /// name TEXT, - /// score INTEGER DEFAULT 1000) - /// """) - /// } + /// ```swift + /// // A table with an auto-incremented primary key and a default value + /// try dbQueue.write { db in + /// try db.execute(sql: """ + /// CREATE TABLE player( + /// id INTEGER PRIMARY KEY AUTOINCREMENT, + /// name TEXT, + /// score INTEGER DEFAULT 1000) + /// """) + /// } /// - /// // A player with partial database information - /// struct PartialPlayer: PersistableRecord { - /// static let databaseTableName = "player" - /// var name: String - /// } + /// // A player with partial database information + /// struct PartialPlayer: PersistableRecord { + /// static let databaseTableName = "player" + /// var name: String + /// } /// - /// // Insert a base player, get the inserted score - /// try dbQueue.write { db in - /// let partialPlayer = PartialPlayer(name: "Alice") + /// // Insert a partial player, get the inserted score + /// try dbQueue.write { db in + /// let partialPlayer = PartialPlayer(name: "Alice") /// - /// // INSERT INTO player (name) VALUES ('Alice') RETURNING score - /// let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { statement in - /// try Int.fetchOne(statement) - /// } - /// print(score) // The inserted score + /// // INSERT INTO player (name) VALUES ('Alice') RETURNING score + /// let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { statement in + /// try Int.fetchOne(statement) /// } + /// print(score) // The inserted score + /// } + /// ``` /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter selection: The returned columns (must not be empty). - /// - parameter fetch: A function that executes its ``Statement`` argument. + /// - parameter fetch: A closure that executes its ``Statement`` argument. + /// If the conflict policy is `IGNORE`, the statement may return no row. /// - returns: The result of the `fetch` function. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ diff --git a/GRDB/Record/PersistableRecord+Save.swift b/GRDB/Record/PersistableRecord+Save.swift index 355202414..ea5b06796 100644 --- a/GRDB/Record/PersistableRecord+Save.swift +++ b/GRDB/Record/PersistableRecord+Save.swift @@ -9,8 +9,11 @@ extension PersistableRecord { /// Otherwise, performs an insert. /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public func save( _ db: Database, @@ -36,19 +39,22 @@ extension PersistableRecord { extension PersistableRecord { #if GRDBCUSTOMSQLITE || GRDBCIPHER - /// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...` - /// statement, and returns a new record built from the saved row. + /// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and + /// returns a new record built from the saved row. /// /// If the receiver has a non-nil primary key and a matching row in the /// database, this method performs an update. Otherwise, it performs /// an insert. /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter returnedType: The type of the returned record. /// - returns: A record of type `returnedType`. The result can be nil when /// the conflict policy is `IGNORE`. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public func saveAndFetch( _ db: Database, @@ -76,19 +82,22 @@ extension PersistableRecord { return success.returned } - /// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...` - /// statement, and returns the selected columns from the saved row. + /// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and + /// returns the selected columns from the saved row. /// /// If the receiver has a non-nil primary key and a matching row in the /// database, this method performs an update. Otherwise, it performs /// an insert. /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter selection: The returned columns (must not be empty). /// - parameter fetch: A function that executes it ``Statement`` argument. /// - returns: The result of the `fetch` function. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed public func saveAndFetch( @@ -118,19 +127,22 @@ extension PersistableRecord { return success.returned } #else - /// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...` - /// statement, and returns a new record built from the saved row. + /// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and + /// returns a new record built from the saved row. /// /// If the receiver has a non-nil primary key and a matching row in the /// database, this method performs an update. Otherwise, it performs /// an insert. /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter returnedType: The type of the returned record. /// - returns: A record of type `returnedType`. The result can be nil when /// the conflict policy is `IGNORE`. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public func saveAndFetch( @@ -159,19 +171,22 @@ extension PersistableRecord { return success.returned } - /// Executes an `INSERT ... RETURNING ...` or `UPDATE ... RETURNING ...` - /// statement, and returns the selected columns from the saved row. + /// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and + /// returns the selected columns from the saved row. /// /// If the receiver has a non-nil primary key and a matching row in the /// database, this method performs an update. Otherwise, it performs /// an insert. /// /// - parameter db: A database connection. - /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. /// - parameter selection: The returned columns (must not be empty). /// - parameter fetch: A function that executes it ``Statement`` argument. /// - returns: The result of the `fetch` function. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ @@ -204,7 +219,7 @@ extension PersistableRecord { #endif } -// MARK: - Internals +// MARK: - Internal extension PersistableRecord { /// Executes an `UPDATE` or `INSERT` statement, and runs insertion or diff --git a/GRDB/Record/PersistableRecord+Upsert.swift b/GRDB/Record/PersistableRecord+Upsert.swift index 8b34ae6e8..df5df0d3c 100644 --- a/GRDB/Record/PersistableRecord+Upsert.swift +++ b/GRDB/Record/PersistableRecord+Upsert.swift @@ -2,26 +2,34 @@ extension PersistableRecord { #if GRDBCUSTOMSQLITE || GRDBCIPHER - /// Executes an `INSERT ... ON CONFLICT DO UPDATE` statement. + /// Executes an `INSERT ON CONFLICT DO UPDATE` statement. /// /// The upsert behavior is triggered by a violation of any uniqueness /// constraint on the table (primary key or unique index). In case of /// violation, all columns but the primary key are overwritten with the - /// inserted values: + /// inserted values. /// - /// struct Player: Encodable, PersistableRecord { - /// var id: Int64 - /// var name: String - /// var score: Int - /// } + /// For example: /// - /// // INSERT INTO player (id, name, score) - /// // VALUES (1, 'Arthur', 1000) - /// // ON CONFLICT DO UPDATE SET - /// // name = excluded.name, - /// // score = excluded.score - /// let player = Player(id: 1, name: "Arthur", score: 1000) - /// try player.upsert(db) + /// ```swift + /// struct Player: Encodable, PersistableRecord { + /// var id: Int64 + /// var name: String + /// var score: Int + /// } + /// + /// // INSERT INTO player (id, name, score) + /// // VALUES (1, 'Arthur', 1000) + /// // ON CONFLICT DO UPDATE SET + /// // name = excluded.name, + /// // score = excluded.score + /// let player = Player(id: 1, name: "Arthur", score: 1000) + /// try player.upsert(db) + /// ``` + /// + /// - parameter db: A database connection. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public func upsert(_ db: Database) throws { try willSave(db) @@ -39,28 +47,30 @@ extension PersistableRecord { didSave(saved) } - /// Executes an `INSERT ... ON CONFLICT DO UPDATE ... RETURNING ...` - /// statement, and returns the upserted record. + /// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and + /// returns the upserted record. /// /// With default parameters (`upsertAndFetch(db)`), the upsert behavior is /// triggered by a violation of any uniqueness constraint on the table /// (primary key or unique index). In case of violation, all columns but the /// primary key are overwritten with the inserted values: /// - /// struct Player: Encodable, PersistableRecord { - /// var id: Int64 - /// var name: String - /// var score: Int - /// } + /// ```swift + /// struct Player: Encodable, PersistableRecord { + /// var id: Int64 + /// var name: String + /// var score: Int + /// } /// - /// // INSERT INTO player (id, name, score) - /// // VALUES (1, 'Arthur', 1000) - /// // ON CONFLICT DO UPDATE SET - /// // name = excluded.name, - /// // score = excluded.score - /// // RETURNING * - /// let player = Player(id: 1, name: "Arthur", score: 1000) - /// let upsertedPlayer = try player.upsertAndFetch(db) + /// // INSERT INTO player (id, name, score) + /// // VALUES (1, 'Arthur', 1000) + /// // ON CONFLICT DO UPDATE SET + /// // name = excluded.name, + /// // score = excluded.score + /// // RETURNING * + /// let player = Player(id: 1, name: "Arthur", score: 1000) + /// let upsertedPlayer = try player.upsertAndFetch(db) + /// ``` /// /// With `conflictTarget` and `assignments` arguments, you can further /// control the upsert behavior. Make sure you check @@ -77,31 +87,33 @@ extension PersistableRecord { /// does not overwrite the tainted flag, and overwrites the /// remaining columns: /// - /// // CREATE TABLE vocabulary( - /// // word TEXT PRIMARY KEY, - /// // kind TEXT NOT NULL, - /// // isTainted BOOLEAN DEFAULT 0, - /// // count INT DEFAULT 1)) - /// struct Vocabulary: Encodable, PersistableRecord { - /// var word: String - /// var kind: String - /// var isTainted: Bool - /// } + /// ```swift + /// // CREATE TABLE vocabulary( + /// // word TEXT PRIMARY KEY, + /// // kind TEXT NOT NULL, + /// // isTainted BOOLEAN DEFAULT 0, + /// // count INT DEFAULT 1)) + /// struct Vocabulary: Encodable, PersistableRecord { + /// var word: String + /// var kind: String + /// var isTainted: Bool + /// } /// - /// // INSERT INTO vocabulary(word, kind, isTainted) - /// // VALUES('jovial', 'adjective', 0) - /// // ON CONFLICT(word) DO UPDATE SET \ - /// // count = count + 1, - /// // kind = excluded.kind - /// // RETURNING * - /// let vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false) - /// let upserted = try vocabulary.upsertAndFetch( - /// db, - /// onConflict: ["word"], - /// doUpdate: { _ in - /// [Column("count") += 1, - /// Column("isTainted").noOverwrite] - /// }) + /// // INSERT INTO vocabulary(word, kind, isTainted) + /// // VALUES('jovial', 'adjective', 0) + /// // ON CONFLICT(word) DO UPDATE SET \ + /// // count = count + 1, + /// // kind = excluded.kind + /// // RETURNING * + /// let vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false) + /// let upserted = try vocabulary.upsertAndFetch( + /// db, + /// onConflict: ["word"], + /// doUpdate: { _ in + /// [Column("count") += 1, + /// Column("isTainted").noOverwrite] + /// }) + /// ``` /// /// - parameter db: A database connection. /// - parameter conflictTarget: The conflict target. @@ -110,7 +122,8 @@ extension PersistableRecord { /// constraints, these assignments are performed, and remaining columns /// are overwritten by inserted values. /// - returns: The upserted record. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public func upsertAndFetch( _ db: Database, @@ -122,8 +135,8 @@ extension PersistableRecord { try upsertAndFetch(db, as: Self.self, onConflict: conflictTarget, doUpdate: assignments) } - /// Executes an `INSERT ... ON CONFLICT DO UPDATE ... RETURNING ...` - /// statement, and returns the upserted record. + /// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and + /// returns the upserted record. /// /// See `upsertAndFetch(_:onConflict:doUpdate:)` for more information about /// the `conflictTarget` and `assignments` parameters. @@ -136,7 +149,8 @@ extension PersistableRecord { /// constraints, these assignments are performed, and remaining columns /// are overwritten by inserted values. /// - returns: A record of type `returnedType`. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public func upsertAndFetch( _ db: Database, @@ -164,26 +178,34 @@ extension PersistableRecord { return success.returned } #else - /// Executes an `INSERT ... ON CONFLICT DO UPDATE` statement. + /// Executes an `INSERT ON CONFLICT DO UPDATE` statement. /// /// The upsert behavior is triggered by a violation of any uniqueness /// constraint on the table (primary key or unique index). In case of /// violation, all columns but the primary key are overwritten with the - /// inserted values: + /// inserted values. /// - /// struct Player: Encodable, PersistableRecord { - /// var id: Int64 - /// var name: String - /// var score: Int - /// } + /// For example: /// - /// // INSERT INTO player (id, name, score) - /// // VALUES (1, 'Arthur', 1000) - /// // ON CONFLICT DO UPDATE SET - /// // name = excluded.name, - /// // score = excluded.score - /// let player = Player(id: 1, name: "Arthur", score: 1000) - /// try player.upsert(db) + /// ```swift + /// struct Player: Encodable, PersistableRecord { + /// var id: Int64 + /// var name: String + /// var score: Int + /// } + /// + /// // INSERT INTO player (id, name, score) + /// // VALUES (1, 'Arthur', 1000) + /// // ON CONFLICT DO UPDATE SET + /// // name = excluded.name, + /// // score = excluded.score + /// let player = Player(id: 1, name: "Arthur", score: 1000) + /// try player.upsert(db) + /// ``` + /// + /// - parameter db: A database connection. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public func upsert(_ db: Database) throws { @@ -202,28 +224,30 @@ extension PersistableRecord { didSave(saved) } - /// Executes an `INSERT ... ON CONFLICT DO UPDATE ... RETURNING ...` - /// statement, and returns the upserted record. + /// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and + /// returns the upserted record. /// /// With default parameters (`upsertAndFetch(db)`), the upsert behavior is /// triggered by a violation of any uniqueness constraint on the table /// (primary key or unique index). In case of violation, all columns but the /// primary key are overwritten with the inserted values: /// - /// struct Player: Encodable, PersistableRecord { - /// var id: Int64 - /// var name: String - /// var score: Int - /// } + /// ```swift + /// struct Player: Encodable, PersistableRecord { + /// var id: Int64 + /// var name: String + /// var score: Int + /// } /// - /// // INSERT INTO player (id, name, score) - /// // VALUES (1, 'Arthur', 1000) - /// // ON CONFLICT DO UPDATE SET - /// // name = excluded.name, - /// // score = excluded.score - /// // RETURNING * - /// let player = Player(id: 1, name: "Arthur", score: 1000) - /// let upsertedPlayer = try player.upsertAndFetch(db) + /// // INSERT INTO player (id, name, score) + /// // VALUES (1, 'Arthur', 1000) + /// // ON CONFLICT DO UPDATE SET + /// // name = excluded.name, + /// // score = excluded.score + /// // RETURNING * + /// let player = Player(id: 1, name: "Arthur", score: 1000) + /// let upsertedPlayer = try player.upsertAndFetch(db) + /// ``` /// /// With `conflictTarget` and `assignments` arguments, you can further /// control the upsert behavior. Make sure you check @@ -240,31 +264,33 @@ extension PersistableRecord { /// does not overwrite the tainted flag, and overwrites the /// remaining columns: /// - /// // CREATE TABLE vocabulary( - /// // word TEXT PRIMARY KEY, - /// // kind TEXT NOT NULL, - /// // isTainted BOOLEAN DEFAULT 0, - /// // count INT DEFAULT 1)) - /// struct Vocabulary: Encodable, PersistableRecord { - /// var word: String - /// var kind: String - /// var isTainted: Bool - /// } + /// ```swift + /// // CREATE TABLE vocabulary( + /// // word TEXT PRIMARY KEY, + /// // kind TEXT NOT NULL, + /// // isTainted BOOLEAN DEFAULT 0, + /// // count INT DEFAULT 1)) + /// struct Vocabulary: Encodable, PersistableRecord { + /// var word: String + /// var kind: String + /// var isTainted: Bool + /// } /// - /// // INSERT INTO vocabulary(word, kind, isTainted) - /// // VALUES('jovial', 'adjective', 0) - /// // ON CONFLICT(word) DO UPDATE SET \ - /// // count = count + 1, - /// // kind = excluded.kind - /// // RETURNING * - /// let vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false) - /// let upserted = try vocabulary.upsertAndFetch( - /// db, - /// onConflict: ["word"], - /// doUpdate: { _ in - /// [Column("count") += 1, - /// Column("isTainted").noOverwrite] - /// }) + /// // INSERT INTO vocabulary(word, kind, isTainted) + /// // VALUES('jovial', 'adjective', 0) + /// // ON CONFLICT(word) DO UPDATE SET \ + /// // count = count + 1, + /// // kind = excluded.kind + /// // RETURNING * + /// let vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false) + /// let upserted = try vocabulary.upsertAndFetch( + /// db, + /// onConflict: ["word"], + /// doUpdate: { _ in + /// [Column("count") += 1, + /// Column("isTainted").noOverwrite] + /// }) + /// ``` /// /// - parameter db: A database connection. /// - parameter conflictTarget: The conflict target. @@ -273,7 +299,8 @@ extension PersistableRecord { /// constraints, these assignments are performed, and remaining columns /// are overwritten by inserted values. /// - returns: The upserted record. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public func upsertAndFetch( @@ -286,11 +313,11 @@ extension PersistableRecord { try upsertAndFetch(db, as: Self.self, onConflict: conflictTarget, doUpdate: assignments) } - /// Executes an `INSERT ... ON CONFLICT DO UPDATE ... RETURNING ...` - /// statement, and returns the upserted record. + /// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and + /// returns the upserted record. /// - /// See `upsertAndFetch(_:onConflict:doUpdate:)` for more information about - /// the `conflictTarget` and `assignments` parameters. + /// See ``upsertAndFetch(_:onConflict:doUpdate:)`` for more information + /// about the `conflictTarget` and `assignments` parameters. /// /// - parameter db: A database connection. /// - parameter returnedType: The type of the returned record. @@ -300,7 +327,8 @@ extension PersistableRecord { /// constraints, these assignments are performed, and remaining columns /// are overwritten by inserted values. /// - returns: A record of type `returnedType`. - /// - throws: A DatabaseError whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ public func upsertAndFetch( diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index a5c6b3119..d41535b5d 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -1,7 +1,44 @@ -/// Types that adopt `PersistableRecord` can be inserted, updated, and deleted. +/// A type that can be persisted in the database. /// -/// `PersistableRecord` has non-mutating variants of -/// `MutablePersistableRecord` methods. +/// ``PersistableRecord`` has non-mutating variants of +/// ``MutablePersistableRecord`` methods. +/// +/// ## Conforming to the PersistableRecord Protocol +/// +/// To conform to `PersistableRecord`, provide an implementation for the +/// ``EncodableRecord/encode(to:)-k9pf`` method. This implementation is +/// ready-made for `Encodable` types. +/// +/// You configure the database table where records are persisted with the +/// ``TableRecord`` inherited protocol. +/// +/// ## Topics +/// +/// ### Inserting a Record +/// +/// - ``insert(_:onConflict:)`` +/// - ``upsert(_:)`` +/// +/// ### Inserting a Record and Fetching the Inserted Row +/// +/// - ``insertAndFetch(_:onConflict:as:)`` +/// - ``insertAndFetch(_:onConflict:selection:fetch:)`` +/// - ``upsertAndFetch(_:onConflict:doUpdate:)`` +/// - ``upsertAndFetch(_:as:onConflict:doUpdate:)`` +/// +/// ### Saving a Record +/// +/// - ``save(_:onConflict:)`` +/// +/// ### Saving a Record and Fetching the Saved Row +/// +/// - ``saveAndFetch(_:onConflict:as:)`` +/// - ``saveAndFetch(_:onConflict:selection:fetch:)`` +/// +/// ### Persistence Callbacks +/// +/// - ``willInsert(_:)-5x6sh`` +/// - ``didInsert(_:)-9jpoy`` public protocol PersistableRecord: MutablePersistableRecord { // MARK: Insertion Callbacks @@ -21,14 +58,16 @@ public protocol PersistableRecord: MutablePersistableRecord { /// You can provide a custom implementation in order to grab the /// auto-incremented id: /// - /// class Player: PersistableRecord { - /// var id: Int64? - /// var name: String? + /// ```swift + /// class Player: PersistableRecord { + /// var id: Int64? + /// var name: String? /// - /// func didInsert(_ inserted: InsertionSuccess) { - /// id = inserted.rowID - /// } + /// func didInsert(_ inserted: InsertionSuccess) { + /// id = inserted.rowID /// } + /// } + /// ``` /// /// - note: If you need a mutating variant of this method, adopt the /// ``MutablePersistableRecord`` protocol instead. diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index be2b873bb..c66d38812 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -1,14 +1,44 @@ // MARK: - Record -/// Record is a class that wraps a table row, or the result of any query. It is -/// designed to be subclassed. -open class Record: FetchableRecord, TableRecord, PersistableRecord { +/// A base class for types that can be fetched and persisted in the database. +/// +/// ## Topics +/// +/// ### Creating Record Instances +/// +/// - ``init()`` +/// - ``init(row:)`` +/// +/// ### Encoding a Database Row +/// +/// - ``encode(to:)`` +/// +/// ### Changes Tracking +/// +/// - ``databaseChanges`` +/// - ``hasDatabaseChanges`` +/// - ``updateChanges(_:)`` +/// +/// ### Persistence Callbacks +/// +/// - ``willSave(_:)`` +/// - ``willInsert(_:)`` +/// - ``willUpdate(_:columns:)`` +/// - ``willDelete(_:)`` +/// - ``didSave(_:)`` +/// - ``didInsert(_:)`` +/// - ``didUpdate(_:)`` +/// - ``didDelete(deleted:)`` +/// - ``aroundSave(_:save:)`` +/// - ``aroundInsert(_:insert:)`` +/// - ``aroundUpdate(_:columns:update:)`` +/// - ``aroundDelete(_:delete:)`` +open class Record { // MARK: - Initializers /// Creates a Record. - public init() { - } + public init() { } /// Creates a Record from a row. public required init(row: Row) throws { @@ -22,21 +52,19 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { } } - // MARK: - Core methods - /// The name of a database table. + /// The name of the database table used to build SQL queries. /// - /// This table name is required by the insert, update, save, delete, - /// and exists methods. + /// Subclasses must override this method. For example: /// - /// class Player : Record { - /// override class var databaseTableName: String { - /// return "player" - /// } + /// ```swift + /// class Player: Record { + /// override class var databaseTableName: String { + /// return "player" /// } - /// - /// The implementation of the base class Record raises a fatal error. + /// } + /// ``` /// /// - returns: The name of a database table. open class var databaseTableName: String { @@ -44,88 +72,83 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { fatalError("subclass must override") } - /// The policy that handles SQLite conflicts when records are inserted - /// or updated. - /// - /// The default implementation uses the ABORT policy for both insertions and - /// updates, and has GRDB generate regular INSERT and UPDATE queries. - /// - /// See open class var persistenceConflictPolicy: PersistenceConflictPolicy { PersistenceConflictPolicy(insert: .abort, update: .abort) } - /// The default request selection. + /// The columns selected by the record. /// - /// Unless this method is overridden, requests select all columns: + /// By default, all columns are selected: /// - /// // SELECT * FROM player - /// try Player.fetchAll(db) + /// ```swift + /// class Player: Record { } /// - /// You can override this property and provide an explicit list - /// of columns: + /// // SELECT * FROM player + /// try Player.fetchAll(db) + /// ``` /// - /// class RestrictedPlayer : Record { - /// override static var databaseSelection: [any SQLSelectable] { - /// return [Column("id"), Column("name")] - /// } + /// You can override this property and provide an explicit selection. + /// For example: + /// + /// ```swift + /// class PartialPlayer: Record { + /// override static var databaseSelection: [any SQLSelectable] { + /// [Column("id"), Column("name")] /// } + /// } /// - /// // SELECT id, name FROM player - /// try RestrictedPlayer.fetchAll(db) - /// - /// You can also add extra columns such as the `rowid` column: - /// - /// class ExtendedPlayer : Player { - /// override static var databaseSelection: [any SQLSelectable] { - /// return [AllColumns(), Column.rowID] - /// } - /// } - /// - /// // SELECT *, rowid FROM player - /// try ExtendedPlayer.fetchAll(db) + /// // SELECT id, name FROM player + /// try PartialPlayer.fetchAll(db) + /// ``` open class var databaseSelection: [any SQLSelectable] { [AllColumns()] } - - /// Defines the values persisted in the database. + /// Encodes the record into the provided persistence container. /// - /// Store in the *container* parameter all values that should be stored in - /// the columns of the database table (see Record.databaseTableName()). + /// In your implementation of this method, store in the `container` argument + /// all values that should be stored in database columns. /// /// Primary key columns, if any, must be included. /// - /// class Player : Record { - /// var id: Int64? - /// var name: String? + /// For example: /// - /// override func encode(to container: inout PersistenceContainer) throws { - /// container["id"] = id - /// container["name"] = name - /// } + /// ```swift + /// class Player: Record { + /// var id: Int64? + /// var name: String? + /// + /// override func encode(to container: inout PersistenceContainer) { + /// container["id"] = id + /// container["name"] = name /// } + /// } + /// ``` /// - /// The implementation of the base class Record does not store any value in - /// the container. + /// It is undefined behavior to set different values for the same column. + /// Column names are case insensitive, so defining both "name" and "NAME" + /// is considered undefined behavior. + /// + /// - throws: An error is thrown if the record can't be encoded to its + /// database representation. open func encode(to container: inout PersistenceContainer) throws { } // MARK: - Compare with Previous Versions - /// A boolean that indicates whether the record has changes that have not + /// A boolean value indicating whether the record has changes that have not /// been saved. /// - /// This flag is purely informative, and does not prevent insert(), - /// update(), and save() from performing their database queries. + /// This flag is purely informative, and does not prevent insertions and + /// updates from performing their database queries. /// /// A record is *edited* if has been changed since last database - /// synchronization (fetch, update, insert). Comparison - /// is performed between *values* (values stored in the `encode(to:)` - /// method, and values loaded from the database). Property setters do not + /// synchronization (fetch, update, or insert). Comparison + /// is performed between *values* (values stored in the ``encode(to:)`` + /// method, and values decoded from ``init(row:)``). Property setters do not /// trigger this flag. /// - /// You can rely on the Record base class to compute this flag for you, or - /// you may set it to true or false when you know better. Setting it to + /// You can rely on the ``Record`` base class to compute this flag for you, + /// or you may set it to true or false when you know better. Setting it to /// false does not prevent it from turning true on subsequent modifications /// of the record. public var hasDatabaseChanges: Bool { @@ -139,13 +162,14 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// A dictionary of changes that have not been saved. /// - /// Its keys are column names, and values the old values that have been - /// changed since last fetching or saving of the record. + /// The keys of the dictionary are column names, and values are the old + /// values that have been changed since last fetching or saving of + /// the record. /// /// Unless the record has actually been fetched or saved, the old values /// are nil. /// - /// See `hasDatabaseChanges` for more information. + /// See ``hasDatabaseChanges`` for more information. /// /// - throws: An error is thrown if the record can't be encoded to its /// database representation. @@ -211,13 +235,15 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// /// For example: /// - /// class Player: Record { - /// func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { - /// print("Player will insert") - /// try super.aroundInsert(db, insert: insert) - /// print("Player did insert") - /// } + /// ```swift + /// class Player: Record { + /// func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + /// print("Player will insert") + /// try super.aroundInsert(db, insert: insert) + /// print("Player did insert") /// } + /// } + /// ``` /// /// - parameter db: A database connection. /// - parameter insert: A function that inserts the record, and returns @@ -231,15 +257,17 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// /// You can override this method in order to grab the auto-incremented id: /// - /// class Player: Record { - /// var id: Int64? - /// var name: String + /// ```swift + /// class Player: Record { + /// var id: Int64? + /// var name: String /// - /// override func didInsert(_ inserted: InsertionSuccess) { - /// super.didInsert(inserted) - /// id = inserted.rowID - /// } + /// override func didInsert(_ inserted: InsertionSuccess) { + /// super.didInsert(inserted) + /// id = inserted.rowID /// } + /// } + /// ``` /// /// If you override this method, you must call `super` at some point in /// your implementation. @@ -255,7 +283,6 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// - parameter db: A database connection. open func willUpdate(_ db: Database, columns: Set) throws { } - // swiftlint:disable line_length /// Called around the record update. /// /// If you override this method, you must call `super` at some point in @@ -263,13 +290,20 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// /// For example: /// - /// class Player: Record { - /// override func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { - /// print("Player will update") - /// try super.aroundUpdate(db, columns: columns, update: update) - /// print("Player did update") - /// } + /// ```swift + /// class Player: Record { + /// override func aroundUpdate( + /// _ db: Database, + /// columns: Set, + /// update: () throws -> PersistenceSuccess) + /// throws + /// { + /// print("Player will update") + /// try super.aroundUpdate(db, columns: columns, update: update) + /// print("Player did update") /// } + /// } + /// ``` /// /// - parameter db: A database connection. /// - parameter columns: The updated columns. @@ -279,7 +313,6 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { let updated = try update() resetDatabaseChanges(with: updated.persistenceContainer) } - // swiftlint:enable line_length /// Called upon successful update. /// @@ -304,13 +337,15 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// /// For example: /// - /// class Player: Record { - /// override func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { - /// print("Player will save") - /// try super.aroundSave(db, save: save) - /// print("Player did save") - /// } + /// ```swift + /// class Player: Record { + /// override func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + /// print("Player will save") + /// try super.aroundSave(db, save: save) + /// print("Player did save") /// } + /// } + /// ``` /// /// - parameter db: A database connection. /// - parameter update: A function that updates the record. Its result is @@ -342,13 +377,15 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// /// For example: /// - /// class Player: Record { - /// override func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { - /// print("Player will delete") - /// try super.aroundDelete(db, delete: delete) - /// print("Player did delete") - /// } + /// ```swift + /// class Player: Record { + /// override func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + /// print("Player will delete") + /// try super.aroundDelete(db, delete: delete) + /// print("Player did delete") /// } + /// } + /// ``` /// /// - parameter db: A database connection. /// - parameter delete: A function that deletes the record and returns @@ -368,20 +405,17 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { // MARK: - CRUD - /// If the record has been changed, executes an UPDATE statement so that + /// If the record has been changed, executes an `UPDATE` statement so that /// those changes and only those changes are saved in the database. /// - /// On success, this method sets the *hasDatabaseChanges* flag to false. - /// - /// This method is guaranteed to have saved the eventual changes in the - /// database if it returns without error. + /// On success, this method sets the `hasDatabaseChanges` flag to false. /// /// - parameter db: A database connection. - /// - parameter columns: The columns to update. /// - returns: Whether the record had changes. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - /// PersistenceError.recordNotFound is thrown if the primary key does not - /// match any row in the database and record could not be updated. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + /// ``PersistenceError/recordNotFound(databaseTableName:key:)`` is thrown + /// if the primary key does not match any row in the database and record + /// could not be updated. @discardableResult public final func updateChanges(_ db: Database) throws -> Bool { let changedColumns = try Set(databaseChanges.keys) @@ -393,3 +427,7 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { } } } + +extension Record: TableRecord { } +extension Record: PersistableRecord { } +extension Record: FetchableRecord { } diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index b6d42354c..cb3f26c74 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -1,51 +1,145 @@ import Foundation -/// Types that adopt `TableRecord` declare a particular relationship with -/// a database table. +/// A type that builds database queries with the Swift language instead of SQL. /// -/// Types that adopt both `TableRecord` and `FetchableRecord` are granted with -/// built-in methods that allow to fetch instances identified by key: +/// A `TableRecord` type is tied to one database table, and can build SQL +/// queries on that table. /// -/// try Player.fetchOne(db, key: 123) // Player? -/// try Citizenship.fetchOne(db, key: ["citizenId": 12, "countryId": 45]) // Citizenship? +/// To build SQL queries that involve several tables, define some ``Association`` +/// between two `TableRecord` types. +/// +/// Most of the time, your record types will get `TableRecord` conformance +/// through the ``MutablePersistableRecord`` or ``PersistableRecord`` protocols, +/// which provide persistence methods. +/// +/// ## Topics +/// +/// ### Configuring the Generated SQL +/// +/// - ``databaseTableName-3tcw2`` +/// - ``databaseSelection-7iphs`` +/// - ``numberOfSelectedColumns(_:)`` +/// +/// ### Counting Records +/// +/// - ``fetchCount(_:)`` +/// +/// ### Testing for Record Existence +/// +/// - ``exists(_:id:)`` +/// - ``exists(_:key:)-60hf2`` +/// - ``exists(_:key:)-6ha6`` +/// +/// ### Deleting Records +/// +/// - ``deleteAll(_:)`` +/// - ``deleteAll(_:ids:)`` +/// - ``deleteAll(_:keys:)-jbkm`` +/// - ``deleteAll(_:keys:)-5s1jg`` +/// - ``deleteOne(_:id:)`` +/// - ``deleteOne(_:key:)-413u8`` +/// - ``deleteOne(_:key:)-5pdh5`` +/// +/// ### Updating Records +/// +/// - ``updateAll(_:onConflict:_:)-7vv9x`` +/// - ``updateAll(_:onConflict:_:)-7atfw`` +/// +/// ### Building Query Interface Requests +/// +/// `TableRecord` provide convenience access to most ``DerivableRequest`` and +/// ``QueryInterfaceRequest`` methods as static methods on the type itself. +/// +/// - ``aliased(_:)`` +/// - ``all()`` +/// - ``annotated(with:)-3zi1n`` +/// - ``annotated(with:)-4xoen`` +/// - ``annotated(with:)-8ce7u`` +/// - ``annotated(with:)-79389`` +/// - ``annotated(withOptional:)`` +/// - ``annotated(withRequired:)`` +/// - ``filter(_:)`` +/// - ``filter(id:)`` +/// - ``filter(ids:)`` +/// - ``filter(key:)-9ey53`` +/// - ``filter(key:)-34lau`` +/// - ``filter(keys:)-4hq8y`` +/// - ``filter(keys:)-7skw1`` +/// - ``filter(literal:)`` +/// - ``filter(sql:arguments:)`` +/// - ``having(_:)`` +/// - ``including(all:)`` +/// - ``including(optional:)`` +/// - ``including(required:)`` +/// - ``joining(optional:)`` +/// - ``joining(required:)`` +/// - ``limit(_:offset:)`` +/// - ``matching(_:)`` +/// - ``none()`` +/// - ``order(_:)-9rc11`` +/// - ``order(_:)-2033k`` +/// - ``order(literal:)`` +/// - ``order(sql:arguments:)`` +/// - ``orderByPrimaryKey()`` +/// - ``request(for:)`` +/// - ``select(_:)-1gvtj`` +/// - ``select(_:)-5oylt`` +/// - ``select(_:as:)-1puz3`` +/// - ``select(_:as:)-tjh0`` +/// - ``select(literal:)`` +/// - ``select(literal:as:)`` +/// - ``select(sql:arguments:)`` +/// - ``select(sql:arguments:as:)`` +/// - ``selectPrimaryKey(as:)`` +/// - ``with(_:)`` +/// +/// ### Defining Associations +/// +/// - ``association(to:)`` +/// - ``association(to:on:)`` +/// - ``belongsTo(_:key:using:)-13t5r`` +/// - ``belongsTo(_:key:using:)-81six`` +/// - ``hasMany(_:key:using:)-45axo`` +/// - ``hasMany(_:key:using:)-10d4k`` +/// - ``hasMany(_:through:using:key:)`` +/// - ``hasOne(_:key:using:)-4g9tm`` +/// - ``hasOne(_:key:using:)-4v5xa`` +/// - ``hasOne(_:through:using:key:)`` public protocol TableRecord { - /// The name of the database table used to build requests. + /// The name of the database table used to build SQL queries. /// - /// struct Player : TableRecord { - /// static var databaseTableName = "player" - /// } + /// For example: /// - /// // SELECT * FROM player - /// try Player.fetchAll(db) + /// ```swift + /// struct Player: TableRecord { + /// static var databaseTableName = "player" + /// } + /// + /// // SELECT * FROM player + /// try Player.fetchAll(db) + /// ``` static var databaseTableName: String { get } - /// The default request selection. + /// The columns selected by the record. /// - /// Unless said otherwise, requests select all columns: + /// For example: /// - /// // SELECT * FROM player - /// try Player.fetchAll(db) + /// ```swift + /// struct Player: TableRecord { + /// static let databaseSelection = [AllColumns()] + /// } /// - /// You can provide a custom implementation and provide an explicit list - /// of columns: + /// struct PartialPlayer: TableRecord { + /// static let databaseTableName = "player" + /// static let databaseSelection = [Column("id"), Column("name")] + /// } /// - /// struct RestrictedPlayer : TableRecord { - /// static var databaseTableName = "player" - /// static var databaseSelection = [Column("id"), Column("name")] - /// } + /// // SELECT * FROM player + /// try Player.fetchAll(db) /// - /// // SELECT id, name FROM player - /// try RestrictedPlayer.fetchAll(db) - /// - /// You can also add extra columns such as the `rowid` column: - /// - /// struct ExtendedPlayer : TableRecord { - /// static var databaseTableName = "player" - /// static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] - /// } - /// - /// // SELECT *, rowid FROM player - /// try ExtendedPlayer.fetchAll(db) + /// // SELECT id, name FROM player + /// try PartialPlayer.fetchAll(db) + /// ``` static var databaseSelection: [any SQLSelectable] { get } } @@ -58,7 +152,7 @@ extension TableRecord { /// - PostalAddress -> "postalAddress" /// - HTTPRequest -> "httpRequest" /// - TOEFL -> "toefl" - internal static var defaultDatabaseTableName: String { + static var defaultDatabaseTableName: String { if let cached = defaultDatabaseTableNameCache.object(forKey: "\(Self.self)" as NSString) { return cached as String } @@ -79,18 +173,19 @@ extension TableRecord { return tableName } - /// The default name of the database table used to build requests. + /// The default name of the database table is derived from the name of + /// the type. /// - /// - Player -> "player" - /// - Place -> "place" - /// - PostalAddress -> "postalAddress" - /// - HTTPRequest -> "httpRequest" - /// - TOEFL -> "toefl" + /// - `Player` -> "player" + /// - `Place` -> "place" + /// - `PostalAddress` -> "postalAddress" + /// - `HTTPRequest` -> "httpRequest" + /// - `TOEFL` -> "toefl" public static var databaseTableName: String { defaultDatabaseTableName } - /// Default value: `[AllColumns()]`. + /// The default selection is all columns: `[AllColumns()]`. public static var databaseSelection: [any SQLSelectable] { [AllColumns()] } @@ -100,7 +195,18 @@ extension TableRecord { // MARK: - Counting All - /// The number of records. + /// Returns the number of records in the database table. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// try dbQueue.read { db in + /// // SELECT COUNT(*) FROM player + /// let count = try Player.fetchCount(db) + /// } + /// ``` /// /// - parameter db: A database connection. public static func fetchCount(_ db: Database) throws -> Int { @@ -116,20 +222,25 @@ extension TableRecord { /// /// For example: /// - /// struct Player: TableRecord { - /// static let databaseTableName = "player" + /// ```swift + /// struct Player: TableRecord { } + /// + /// struct PartialPlayer: TableRecord { + /// static let databaseTableName = "player" + /// static let databaseSelection = [Column("id"), Column("name")] + /// } + /// + /// try dbQueue.write { db in + /// try db.create(table: "player") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("name", .text) + /// t.column("score", .integer) /// } /// - /// try dbQueue.write { db in - /// try db.create(table: "player") { t in - /// t.autoIncrementedPrimaryKey("id") - /// t.column("name", .text) - /// t.column("score", .integer) - /// } - /// - /// // 3 - /// try Player.numberOfSelectedColumns(db) - /// } + /// try Player.numberOfSelectedColumns(db) // 3 + /// try PartialPlayer.numberOfSelectedColumns(db) // 2 + /// } + /// ``` public static func numberOfSelectedColumns(_ db: Database) throws -> Int { // The alias makes it possible to count the columns in `SELECT *`: let alias = TableAlias(tableName: databaseTableName) @@ -146,9 +257,20 @@ extension TableRecord { /// Deletes all records, and returns the number of deleted records. /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// try dbQueue.write { db in + /// // DELETE FROM player + /// let count = try Player.deleteAll(db) + /// } + /// ``` + /// /// - parameter db: A database connection. - /// - returns: The number of deleted records - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - returns: The number of deleted records. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult public static func deleteAll(_ db: Database) throws -> Int { try all().deleteAll(db) @@ -160,13 +282,17 @@ extension TableRecord { extension TableRecord { /// Returns whether a record exists for this primary key. /// - /// try Player.exists(db, key: 123) - /// try Country.exists(db, key: "FR") + /// All single-column primary keys are supported: /// - /// When the table has no explicit primary key, GRDB uses the hidden - /// "rowid" column: + /// ```swift + /// struct Player: TableRecord { } + /// struct Country: TableRecord { } /// - /// try Document.exists(db, key: 1) + /// try dbQueue.read { db in + /// let playerExists = try Player.exists(db, key: 1) + /// let countryExists = try Country.exists(db, key: "FR") + /// } + /// ``` /// /// - parameters: /// - db: A database connection. @@ -181,13 +307,21 @@ extension TableRecord { extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { /// Returns whether a record exists for this primary key. /// - /// try Player.deleteOne(db, id: 123) - /// try Country.deleteOne(db, id: "FR") + /// All single-column primary keys are supported: /// - /// When the table has no explicit primary key, GRDB uses the hidden - /// "rowid" column: + /// ```swift + /// struct Player: TableRecord, Identifiable { + /// var id: Int64 + /// } + /// struct Country: TableRecord, Identifiable { + /// var id: String + /// } /// - /// try Document.deleteOne(db, id: 1) + /// try dbQueue.read { db in + /// let playerExists = try Player.exists(db, id: 1) + /// let countryExists = try Country.exists(db, id: "FR") + /// } + /// ``` /// /// - parameters: /// - db: A database connection. @@ -205,14 +339,30 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { // MARK: - Check Existence by Key extension TableRecord { - /// Returns whether a record exists for this unique key (primary key or any - /// key with a unique index on it). + /// Returns whether a record exists for this primary or unique key. /// - /// try Player.exists(db, key: ["name": Arthur"]) + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// struct Citizenship: TableRecord { } + /// + /// try dbQueue.read { db in + /// let playerExists = Player.exists(db, key: ["id": 1]) + /// let playerExists = Player.exists(db, key: ["email": "arthur@example.com"]) + /// let citizenshipExists = Citizenship.exists(db, key: [ + /// "citizenId": 1, + /// "countryCode": "FR", + /// ]) + /// } + /// ``` + /// + /// A fatal error is raised if no unique index exists on a subset of the + /// key columns. /// /// - parameters: /// - db: A database connection. - /// - key: A dictionary of values. + /// - key: A unique key. /// - returns: Whether a record exists for this key. public static func exists(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool { try !filter(key: key).isEmpty(db) @@ -222,26 +372,28 @@ extension TableRecord { // MARK: - Deleting by Single-Column Primary Key extension TableRecord { - - /// Delete records identified by their primary keys, and returns the number + /// Deletes records identified by their primary keys, and returns the number /// of deleted records. /// + /// All single-column primary keys are supported: + /// + /// ```swift + /// struct Player: TableRecord { } + /// struct Country: TableRecord { } + /// + /// try dbQueue.write { db in /// // DELETE FROM player WHERE id IN (1, 2, 3) /// try Player.deleteAll(db, keys: [1, 2, 3]) /// - /// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE') - /// try Country.deleteAll(db, keys: ["FR", "US", "DE"]) - /// - /// When the table has no explicit primary key, GRDB uses the hidden - /// "rowid" column: - /// - /// // DELETE FROM document WHERE rowid IN (1, 2, 3) - /// try Document.deleteAll(db, keys: [1, 2, 3]) + /// // DELETE FROM country WHERE code IN ('FR', 'US') + /// try Country.deleteAll(db, keys: ["FR", "US"]) + /// } + /// ``` /// /// - parameters: /// - db: A database connection. /// - keys: A sequence of primary keys. - /// - returns: The number of deleted records + /// - returns: The number of deleted records. @discardableResult public static func deleteAll(_ db: Database, keys: Keys) throws -> Int @@ -255,20 +407,23 @@ extension TableRecord { return try filter(keys: keys).deleteAll(db) } - /// Delete a record, identified by its primary key, and returns whether a + /// Deletes the record identified by its primary key, and returns whether a /// record was deleted. /// - /// // DELETE FROM player WHERE id = 123 - /// try Player.deleteOne(db, key: 123) + /// All single-column primary keys are supported: + /// + /// ```swift + /// struct Player: TableRecord { } + /// struct Country: TableRecord { } + /// + /// try dbQueue.write { db in + /// // DELETE FROM player WHERE id = 1 + /// try Player.deleteOne(db, key: 1) /// /// // DELETE FROM country WHERE code = 'FR' /// try Country.deleteOne(db, key: "FR") - /// - /// When the table has no explicit primary key, GRDB uses the hidden - /// "rowid" column: - /// - /// // DELETE FROM document WHERE rowid = 1 - /// try Document.deleteOne(db, key: 1) + /// } + /// ``` /// /// - parameters: /// - db: A database connection. @@ -286,25 +441,32 @@ extension TableRecord { @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { - /// Delete records identified by their primary keys, and returns the number + /// Deletes records identified by their primary keys, and returns the number /// of deleted records. /// + /// All single-column primary keys are supported: + /// + /// ```swift + /// struct Player: TableRecord, Identifiable { + /// var id: Int64 + /// } + /// struct Country: TableRecord, Identifiable { + /// var id: String + /// } + /// + /// try dbQueue.write { db in /// // DELETE FROM player WHERE id IN (1, 2, 3) /// try Player.deleteAll(db, ids: [1, 2, 3]) /// - /// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE') - /// try Country.deleteAll(db, ids: ["FR", "US", "DE"]) - /// - /// When the table has no explicit primary key, GRDB uses the hidden - /// "rowid" column: - /// - /// // DELETE FROM document WHERE rowid IN (1, 2, 3) - /// try Document.deleteAll(db, ids: [1, 2, 3]) + /// // DELETE FROM country WHERE code IN ('FR', 'US') + /// try Country.deleteAll(db, ids: ["FR", "US"]) + /// } + /// ``` /// /// - parameters: /// - db: A database connection. /// - ids: A collection of primary keys. - /// - returns: The number of deleted records + /// - returns: The number of deleted records. @discardableResult public static func deleteAll(_ db: Database, ids: IDS) throws -> Int where IDS: Collection, IDS.Element == ID @@ -316,20 +478,27 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { return try filter(ids: ids).deleteAll(db) } - /// Delete a record, identified by its primary key, and returns whether a + /// Deletes the record identified by its primary key, and returns whether a /// record was deleted. /// - /// // DELETE FROM player WHERE id = 123 - /// try Player.deleteOne(db, id: 123) + /// All single-column primary keys are supported: + /// + /// ```swift + /// struct Player: TableRecord, Identifiable { + /// var id: Int64 + /// } + /// struct Country: TableRecord, Identifiable { + /// var id: String + /// } + /// + /// try dbQueue.write { db in + /// // DELETE FROM player WHERE id = 1 + /// try Player.deleteOne(db, id: 1) /// /// // DELETE FROM country WHERE code = 'FR' /// try Country.deleteOne(db, id: "FR") - /// - /// When the table has no explicit primary key, GRDB uses the hidden - /// "rowid" column: - /// - /// // DELETE FROM document WHERE rowid = 1 - /// try Document.deleteOne(db, id: 1) + /// } + /// ``` /// /// - parameters: /// - db: A database connection. @@ -344,16 +513,36 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { // MARK: - Deleting by Key extension TableRecord { - /// Delete records identified by the provided unique keys (primary key or - /// any key with a unique index on it), and returns the number of - /// deleted records. + /// Deletes records identified by their primary or unique keys, and returns + /// the number of deleted records. /// - /// try Player.deleteAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// struct Citizenship: TableRecord { } + /// + /// try dbQueue.write { db in + /// // DELETE FROM player WHERE id = 1 + /// try Player.deleteAll(db, keys: [["id": 1]]) + /// + /// // DELETE FROM player WHERE email = 'arthur@example.com' + /// try Player.deleteAll(db, keys: [["email": "arthur@example.com"]]) + /// + /// // DELETE FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR' + /// try Citizenship.deleteAll(db, keys: [ + /// ["citizenId": 1, "countryCode": "FR"], + /// ]) + /// } + /// ``` + /// + /// A fatal error is raised if no unique index exists on a subset of the + /// key columns. /// /// - parameters: /// - db: A database connection. /// - keys: An array of key dictionaries. - /// - returns: The number of deleted records + /// - returns: The number of deleted records. @discardableResult public static func deleteAll(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> Int { if keys.isEmpty { @@ -363,12 +552,32 @@ extension TableRecord { return try filter(keys: keys).deleteAll(db) } - /// Delete a record, identified by a unique key (the primary key or any key - /// with a unique index on it), and returns whether a database record - /// was deleted. + /// Deletes the record identified by its primary or unique keys, and returns + /// whether a record was deleted. /// - /// Player.deleteOne(db, key: ["name": Arthur"]) + /// For example: /// + /// ```swift + /// struct Player: TableRecord { } + /// struct Citizenship: TableRecord { } + /// + /// try dbQueue.write { db in + /// // DELETE FROM player WHERE id = 1 + /// try Player.deleteOne(db, key: ["id": 1]) + /// + /// // DELETE FROM player WHERE email = 'arthur@example.com' + /// try Player.deleteOne(db, key: ["email": "arthur@example.com"]) + /// + /// // DELETE FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR' + /// try Citizenship.deleteOne(db, key: [ + /// "citizenId": 1, + /// "countryCode": "FR", + /// ]) + /// } + /// ``` + /// + /// A fatal error is raised if no unique index exists on a subset of the + /// key columns. /// - parameters: /// - db: A database connection. /// - key: A dictionary of values. @@ -387,17 +596,21 @@ extension TableRecord { /// /// For example: /// - /// try dbQueue.write { db in - /// // UPDATE player SET score = 0 - /// try Player.updateAll(db, [Column("score").set(to: 0)]) - /// } + /// ```swift + /// struct Player: TableRecord { } + /// + /// try dbQueue.write { db in + /// // UPDATE player SET score = 0 + /// try Player.updateAll(db, [Column("score").set(to: 0)]) + /// } + /// ``` /// /// - parameter db: A database connection. /// - parameter conflictResolution: A policy for conflict resolution, /// defaulting to the record's persistenceConflictPolicy. /// - parameter assignments: An array of column assignments. /// - returns: The number of updated records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult public static func updateAll( _ db: Database, @@ -412,17 +625,21 @@ extension TableRecord { /// /// For example: /// - /// try dbQueue.write { db in - /// // UPDATE player SET score = 0 - /// try Player.updateAll(db, Column("score").set(to: 0)) - /// } + /// ```swift + /// struct Player: TableRecord { } + /// + /// try dbQueue.write { db in + /// // UPDATE player SET score = 0 + /// try Player.updateAll(db, Column("score").set(to: 0)) + /// } + /// ``` /// /// - parameter db: A database connection. /// - parameter conflictResolution: A policy for conflict resolution, /// defaulting to the record's persistenceConflictPolicy. /// - parameter assignments: Column assignments. /// - returns: The number of updated records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult public static func updateAll( _ db: Database, diff --git a/GRDB/Utils/Inflections.swift b/GRDB/Utils/Inflections.swift index 5302926c2..860b4d0ba 100644 --- a/GRDB/Utils/Inflections.swift +++ b/GRDB/Utils/Inflections.swift @@ -28,9 +28,9 @@ extension String { } } -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// /// 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 { private var pluralizeRules: [(NSRegularExpression, String)] = [] private var singularizeRules: [(NSRegularExpression, String)] = [] diff --git a/GRDB/Utils/OnDemandFuture.swift b/GRDB/Utils/OnDemandFuture.swift index a43985051..6a5e71d3f 100644 --- a/GRDB/Utils/OnDemandFuture.swift +++ b/GRDB/Utils/OnDemandFuture.swift @@ -25,7 +25,6 @@ struct OnDemandFuture: Publisher { self.attemptToFulfill = attemptToFulfill } - /// :nodoc: func receive(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input { let subscription = OnDemandFutureSubscription( attemptToFulfill: attemptToFulfill, diff --git a/GRDB/ValueObservation/DatabaseCancellable.swift b/GRDB/ValueObservation/DatabaseCancellable.swift index 079b08e9f..de6298791 100644 --- a/GRDB/ValueObservation/DatabaseCancellable.swift +++ b/GRDB/ValueObservation/DatabaseCancellable.swift @@ -1,4 +1,10 @@ /// A protocol indicating that an activity or action supports cancellation. +/// +/// ## Topics +/// +/// ### Supporting Types +/// +/// - ``AnyDatabaseCancellable`` public protocol DatabaseCancellable { /// Cancel the activity. func cancel() @@ -7,7 +13,7 @@ public protocol DatabaseCancellable { /// A type-erasing cancellable object that executes a provided closure /// when canceled. /// -/// An AnyDatabaseCancellable instance automatically calls cancel() +/// An `AnyDatabaseCancellable` instance automatically calls ``cancel()`` /// when deinitialized. public class AnyDatabaseCancellable: DatabaseCancellable { private var _cancel: (() -> Void)? @@ -17,10 +23,9 @@ public class AnyDatabaseCancellable: DatabaseCancellable { _cancel = cancel } - /// Creates a cancellable object that forwards cancellation to the - /// provided cancellable. - public convenience init(_ cancellable: some DatabaseCancellable) { - var cancellable = Optional.some(cancellable) + /// Creates a cancellable object that forwards cancellation to `base`. + public convenience init(_ base: some DatabaseCancellable) { + var cancellable = Optional.some(base) self.init { cancellable?.cancel() cancellable = nil // Release memory diff --git a/GRDB/ValueObservation/SharedValueObservation.swift b/GRDB/ValueObservation/SharedValueObservation.swift index 89752f825..2732c077b 100644 --- a/GRDB/ValueObservation/SharedValueObservation.swift +++ b/GRDB/ValueObservation/SharedValueObservation.swift @@ -1,20 +1,19 @@ import Foundation -/// Controls the extent of the shared database observation -/// of `SharedValueObservation`. +/// The extent of the shared subscription to a ``SharedValueObservation``. public enum SharedValueObservationExtent { - /// The `SharedValueObservation` starts a single database observation, which - /// ends when the `SharedValueObservation` is deallocated and all + /// The ``SharedValueObservation`` starts a single database observation, + /// which stops when the `SharedValueObservation` is deallocated and all /// subscriptions terminated. /// /// This extent prevents the shared observation from recovering from - /// database errors. To recover from database errors, create a new shared - /// `SharedValueObservation` instance. + /// database errors. To recover from database errors, you must create a new + /// shared `SharedValueObservation` instance. case observationLifetime - /// The `SharedValueObservation` ends database observation when the number - /// of subscriptions drops down to zero. The database observation restarts - /// on the next subscription. + /// The ``SharedValueObservation`` stops database observation when the + /// number of subscriptions drops down to zero. Database observation + /// restarts on the next subscription. /// /// Database errors can be recovered by resubscribing to the /// shared observation. @@ -22,56 +21,74 @@ public enum SharedValueObservationExtent { } extension ValueObservation { - /// Returns a shared value observation that shares a single underlying - /// database observation for all subscriptions, and thus spares - /// database resources. + /// Returns a shared value observation that spares database resources by + /// sharing a single underlying ``ValueObservation`` subscription. + /// + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) /// - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// For example: /// - /// let sharedObservation = ValueObservation - /// .tracking { db in try Player.fetchAll(db) } - /// .shared(in: dbQueue) + /// ```swift + /// let observation = ValueObservation.tracking { db in + /// try Player.fetchAll(db) + /// } /// - /// The sharing only applies if you start observing the database from the - /// same `SharedValueObservation` instance: + /// let sharedObservation = observation.shared(in: dbQueue) /// - /// // NOT shared - /// let cancellable1 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...) - /// let cancellable2 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...) + /// let cancellable = try sharedObservation.start { error in + /// // handle error + /// } onChange: { (players: [Player]) in + /// print("Fresh players: \(players)") + /// } + /// ``` /// - /// // Shared - /// let sharedObservation = ValueObservation.tracking { db in ... }.shared(in: dbQueue) - /// let cancellable1 = sharedObservation.start(...) - /// let cancellable2 = sharedObservation.start(...) + /// The underlying subscription is shared if and only if you start observing + /// the database from the same `SharedValueObservation` instance: /// - /// By default, fresh values are dispatched asynchronously on the - /// main queue. You can change this behavior by providing a scheduler. - /// For example, `.immediate` notifies all values on the main queue as well, - /// and the first one is immediately notified when the start() method - /// is called: + /// ```swift + /// // Shared + /// let sharedObservation = ValueObservation.tracking { db in ... }.shared(in: dbQueue) + /// let cancellable1 = sharedObservation.start(...) + /// let cancellable2 = sharedObservation.start(...) /// - /// let sharedObservation = ValueObservation - /// .tracking { db in try Player.fetchAll(db) } - /// .shared( - /// in: dbQueue, - /// scheduling: .immediate) // <- - /// - /// let cancellable = try sharedObservation.start( - /// onError: { error in ... }, - /// onChange: { (players: [Player]) in - /// print("fresh players: \(players)") - /// }) - /// // <- here "fresh players" is already printed. - /// - /// Note that the `.immediate` scheduler requires that the observation is - /// subscribed from the main thread. It raises a fatal error otherwise. + /// // NOT shared + /// let cancellable1 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...) + /// let cancellable2 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...) + /// ``` /// /// A shared observation starts observing the database as soon as it is /// subscribed. You can choose if database observation should stop, or not, /// when its number of subscriptions drops down to zero, with the `extent` - /// parameter. See `SharedValueObservationExtent` for available options. + /// parameter. + /// + /// By default, fresh values are dispatched asynchronously on the + /// main dispatch queue. You can change this behavior by providing a + /// scheduler. + /// + /// For example, the ``ValueObservationScheduler/immediate`` scheduler + /// notifies all values on the main dispatch queue, and notifies the first + /// one immediately when the + /// ``SharedValueObservation/start(onError:onChange:)`` method is called: + /// + /// ```swift + /// let observation = ValueObservation.tracking { db in + /// try Player.fetchAll(db) + /// } + /// + /// let sharedObservation = observation.shared( + /// in: dbQueue, + /// scheduling: .immediate) + /// + /// let cancellable = try sharedObservation.start { error in + /// // handle error + /// } onChange: { (players: [Player]) in + /// print("fresh players: \(players)") + /// } + /// // <- here "fresh players" is already printed. + /// ``` + /// + /// Note that the `.immediate` scheduler requires that the observation is + /// subscribed from the main thread. It raises a fatal error otherwise. /// /// - parameter reader: A DatabaseReader. /// - parameter scheduler: A Scheduler. By default, fresh values are @@ -91,34 +108,41 @@ extension ValueObservation { } } -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// A shared value observation spares database resources by sharing a single +/// underlying ``ValueObservation`` subscription. /// -/// A shared value observation that shares a single underlying database -/// observation for all subscriptions, and thus spares database resources. +/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) /// -/// For example: +/// You build a `SharedValueObservation` with the ``ValueObservation`` method +/// ``ValueObservation/shared(in:scheduling:extent:)``. For example: /// -/// let sharedObservation = ValueObservation -/// .tracking { db in try Player.fetchAll(db) } -/// .shared(in: dbQueue) +/// ```swift +/// let observation = ValueObservation.tracking { db in +/// try Player.fetchAll(db) +/// } /// -/// let cancellable = try sharedObservation.start( -/// onError: { error in ... }, -/// onChange: { (players: [Player]) in -/// print("Players have changed.") -/// }) +/// let sharedObservation = observation.shared(in: dbQueue) /// -/// The sharing only applies if you start observing the database from the -/// same `SharedValueObservation` instance: +/// let cancellable = try sharedObservation.start { error in +/// // handle error +/// } onChange: { (players: [Player]) in +/// print("Fresh players: \(players)") +/// } +/// ``` /// -/// // NOT shared -/// let cancellable1 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...) -/// let cancellable2 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...) +/// The underlying subscription is shared if and only if you start observing +/// the database from the same `SharedValueObservation` instance: /// -/// // Shared -/// let sharedObservation = ValueObservation.tracking { db in ... }.shared(in: dbQueue) -/// let cancellable1 = sharedObservation.start(...) -/// let cancellable2 = sharedObservation.start(...) +/// ```swift +/// // Shared +/// let sharedObservation = ValueObservation.tracking { db in ... }.shared(in: dbQueue) +/// let cancellable1 = sharedObservation.start(...) +/// let cancellable2 = sharedObservation.start(...) +/// +/// // NOT shared +/// let cancellable1 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...) +/// let cancellable2 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...) +/// ``` public final class SharedValueObservation { private let scheduler: ValueObservationScheduler private let extent: SharedValueObservationExtent @@ -159,20 +183,22 @@ public final class SharedValueObservation { /// /// For example: /// - /// let sharedObservation = ValueObservation - /// .tracking { db in try Player.fetchAll(db) } - /// .shared(in: dbQueue) + /// ```swift + /// let sharedObservation = ValueObservation + /// .tracking { db in try Player.fetchAll(db) } + /// .shared(in: dbQueue) /// - /// let cancellable = try sharedObservation.start( - /// onError: { error in ... }, - /// onChange: { (players: [Player]) in - /// print("fresh players: \(players)") - /// }) + /// let cancellable = try sharedObservation.start { error in + /// // handle error + /// } onChange: { (players: [Player]) in + /// print("fresh players: \(players)") + /// } + /// ``` /// - /// - parameter onError: A closure that is provided eventual errors that - /// happen during observation - /// - parameter onChange: A closure that is provided fresh values - /// - returns: a DatabaseCancellable + /// - parameter onError: The closure to execute when the observation fails. + /// - parameter onChange: The closure to execute on receipt of a + /// fresh value. + /// - returns: A DatabaseCancellable that can stop the observation. public func start( onError: @escaping (Error) -> Void, onChange: @escaping (Element) -> Void) @@ -224,22 +250,23 @@ public final class SharedValueObservation { } #if canImport(Combine) - /// Creates a publisher which tracks changes in database values. + /// Returns a publisher of observed values. /// /// For example: /// - /// let publisher = ValueObservation - /// .tracking { db in try Player.fetchAll(db) } - /// .shared(in: dbQueue) - /// .publisher() + /// ```swift + /// let observation = ValueObservation + /// .tracking { db in try Player.fetchAll(db) } + /// .shared(in: dbQueue) /// - /// let cancellable = publisher.sink( - /// receiveCompletion: { completion in ... }, - /// receiveValue: { (players: [Player]) in - /// print("fresh players: \(players)") - /// }) + /// let publisher = observation.publisher() /// - /// - returns: A Combine publisher + /// let cancellable = publisher.sink { completion in + /// // handle completion + /// } receiveValue: { (players: [Player]) in + /// print("fresh players: \(players)") + /// } + /// ``` @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) public func publisher() -> DatabasePublishers.Value { DatabasePublishers.Value { onError, onChange in @@ -302,10 +329,21 @@ public final class SharedValueObservation { extension SharedValueObservation { // MARK: - Asynchronous Observation - /// The database observation, as an asynchronous sequence of - /// database changes. + /// Returns an asynchronous sequence of observed values. /// - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// For example: + /// + /// ```swift + /// let sharedObservation = ValueObservation + /// .tracking { db in try Player.fetchAll(db) } + /// .shared(in: dbQueue) + /// + /// for try await players in sharedObservation.values() { + /// print("Fresh players: \(players)") + /// } + /// ``` @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public func values(bufferingPolicy: AsyncValueObservation.BufferingPolicy = .unbounded) -> AsyncValueObservation diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 549d7024e..13dac99cc 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -4,30 +4,76 @@ import Combine import Dispatch import Foundation -/// ValueObservation tracks changes in the results of database requests, and +/// `ValueObservation` tracks changes in the results of database requests, and /// notifies fresh values whenever the database changes. /// /// For example: /// -/// let observation = ValueObservation.tracking { db in -/// try Player.fetchAll(db) -/// } +/// ```swift +/// // Track all players +/// let observation = ValueObservation.tracking { db in +/// try Player.fetchAll(db) +/// } /// -/// let cancellable = try observation.start( -/// in: dbQueue, -/// onError: { error in ... }, -/// onChange: { (players: [Player]) in -/// print("Players have changed.") -/// }) +/// let cancellable = try observation.start(in: dbQueue) { error in +/// // handle error +/// } onChange: { (players: [Player]) in +/// print("Fresh players: \(players)") +/// } +/// ``` +/// +/// ## Topics +/// +/// ### Creating a ValueObservation +/// +/// - ``tracking(_:)`` +/// - ``trackingConstantRegion(_:)`` +/// - ``tracking(region:fetch:)`` +/// - ``tracking(regions:fetch:)`` +/// +/// ### Creating A Shared Observation +/// +/// - ``shared(in:scheduling:extent:)`` +/// - ``SharedValueObservationExtent`` +/// +/// ### Accessing Observed Values +/// +/// - ``publisher(in:scheduling:)`` +/// - ``start(in:scheduling:onError:onChange:)`` +/// - ``values(in:scheduling:bufferingPolicy:)`` +/// - ``DatabaseCancellable`` +/// - ``ValueObservationScheduler`` +/// +/// ### Mapping Values +/// +/// - ``map(_:)`` +/// +/// ### Filtering Values +/// +/// - ``removeDuplicates()`` +/// - ``removeDuplicates(by:)`` +/// +/// ### Requiring Write Access +/// +/// - ``requiresWriteAccess`` +/// +/// ### Debugging +/// +/// - ``handleEvents(willStart:willFetch:willTrackRegion:databaseDidChange:didReceiveValue:didFail:didCancel:)`` +/// - ``print(_:to:)`` +/// +/// ### Support +/// +/// - ``ValueReducer`` public struct ValueObservation { var events = ValueObservationEvents() - /// Default is false. Set this property to true when the observation - /// requires write access in order to fetch fresh values. Fetches are then - /// wrapped inside a savepoint. + /// A boolean value indicating whether the observation requires write access + /// when it fetch fresh values. /// - /// Don't set this flag to true unless you really need it. A read/write - /// observation is less efficient than a read-only observation. + /// The default is false. Setting it to true can disable scheduling + /// optimizations when the observation is started in + /// a ``DatabasePool``. public var requiresWriteAccess = false var trackingMode: ValueObservationTrackingMode @@ -94,50 +140,53 @@ extension ValueObservation: Refinable { // MARK: - Starting Observation - /// Starts the value observation in the provided database reader (such as - /// a database queue or database pool). + /// Starts observing the database. /// /// The observation lasts until the returned cancellable is cancelled /// or deallocated. /// /// For example: /// - /// let observation = ValueObservation.tracking { db in - /// try Player.fetchAll(db) - /// } + /// ```swift + /// let observation = ValueObservation.tracking { db in + /// try Player.fetchAll(db) + /// } /// - /// let cancellable = try observation.start( - /// in: dbQueue, - /// onError: { error in ... }, - /// onChange: { (players: [Player]) in - /// print("fresh players: \(players)") - /// }) + /// let cancellable = try observation.start(in: dbQueue) { error in + /// // handle error + /// } onChange: { (players: [Player]) in + /// print("fresh players: \(players)") + /// } + /// ``` /// /// By default, fresh values are dispatched asynchronously on the - /// main queue. You can change this behavior by providing a scheduler. - /// For example, `.immediate` notifies all values on the main queue as well, - /// and the first one is immediately notified when the start() method - /// is called: + /// main dispatch queue. You can change this behavior by providing a + /// scheduler. /// - /// let cancellable = try observation.start( - /// in: dbQueue, - /// scheduling: .immediate, // <- - /// onError: { error in ... }, - /// onChange: { (players: [Player]) in - /// print("fresh players: \(players)") - /// }) - /// // <- here "fresh players" is already printed. + /// For example, the ``ValueObservationScheduler/immediate`` scheduler + /// notifies all values on the main dispatch queue, and notifies the first + /// one immediately when the ``start(in:scheduling:onError:onChange:)`` + /// method is called: + /// + /// ```swift + /// let cancellable = try observation.start(in: dbQueue, scheduling: .immediate) { error in + /// // handle error + /// } onChange: { (players: [Player]) in + /// print("fresh players: \(players)") + /// } + /// // <- here "fresh players" is already printed. + /// ``` /// /// Note that the `.immediate` scheduler requires that the observation is /// subscribed from the main thread. It raises a fatal error otherwise. /// /// - parameter reader: A DatabaseReader. - /// - parameter scheduler: A Scheduler. By default, fresh values are - /// dispatched asynchronously on the main queue. - /// - parameter onError: A closure that is provided eventual errors that - /// happen during observation - /// - parameter onChange: A closure that is provided fresh values - /// - returns: a cancellable. + /// - parameter scheduler: A ValueObservationScheduler. By default, fresh + /// values are dispatched asynchronously on the main queue. + /// - parameter onError: The closure to execute when the observation fails. + /// - parameter onChange: The closure to execute on receipt of a + /// fresh value. + /// - returns: A DatabaseCancellable that can stop the observation. public func start( in reader: some DatabaseReader, scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main), @@ -158,25 +207,23 @@ extension ValueObservation: Refinable { // MARK: - Debugging - /// Performs the specified closures when ValueObservation events occur. + /// Performs the specified closures when observation events occur. + /// + /// All closures run on unspecified dispatch queues - don't make + /// any assumption. /// /// - parameters: - /// - willStart: A closure that executes when the observation starts. - /// Defaults to `nil`. - /// - willFetch: A closure that executes when the observed value is - /// about to be fetched. Defaults to `nil`. - /// - willTrackRegion: A closure that executes when the observation - /// starts tracking a database region. Defaults to `nil`. - /// - databaseDidChange: A closure that executes after the observation - /// was impacted by a database change. Defaults to `nil`. - /// - didReceiveValue: A closure that executes on fresh values. Defaults - /// to `nil`. - /// - /// NOTE: This closure runs on an unspecified DispatchQueue. - /// - didFail: A closure that executes when the observation fails. - /// Defaults to `nil`. - /// - didCancel: A closure that executes when the observation is - /// cancelled. Defaults to `nil`. + /// - willStart: The closure to execute when the observation starts. + /// - willFetch: The closure to execute when the observed value is + /// about to be fetched. + /// - willTrackRegion: The closure to execute when the observation + /// starts tracking a database region. + /// - databaseDidChange: The closure to execute after the observation + /// was impacted by a database change. + /// - didReceiveValue: The closure to execute on fresh values. + /// - didFail: The closure to execute when the observation fails. + /// - didCancel: The closure to execute when the observation is + /// cancelled. /// - returns: A `ValueObservation` that performs the specified closures /// when ValueObservation events occur. public func handleEvents( @@ -209,7 +256,7 @@ extension ValueObservation: Refinable { } } - /// Prints log messages for all ValueObservation events. + /// Prints log messages for all observation events. public func print( _ prefix: String = "", to stream: TextOutputStream? = nil) @@ -258,14 +305,25 @@ extension ValueObservation: Refinable { extension ValueObservation { // MARK: - Asynchronous Observation - /// The database observation, as an asynchronous sequence of - /// database changes. + /// Returns an asynchronous sequence of observed values. /// - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// For example: + /// + /// ```swift + /// let observation = ValueObservation.tracking { db in + /// try Player.fetchAll(db) + /// } + /// + /// for try await players in observation.values(in: dbQueue) { + /// print("Fresh players: \(players)") + /// } + /// ``` /// /// - parameter reader: A DatabaseReader. - /// - parameter scheduler: A Scheduler. By default, fresh values are - /// dispatched asynchronously on the main queue. + /// - parameter scheduler: A ValueObservationScheduler. By default, fresh + /// values are dispatched asynchronously on the main dispatch queue. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public func values( in reader: some DatabaseReader, @@ -280,23 +338,27 @@ extension ValueObservation { } } -/// An asynchronous sequence of database changes. +/// An asynchronous sequence of values observed by a ``ValueObservation``. /// -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) /// -/// Usage: +/// An `AsyncValueObservation` sequence produces a fresh value whenever the +/// results of database requests change. /// -/// let observation = ValueObservation.tracking(Player.fetchAll) -/// let dbQueue: DatabaseQueue: ... +/// For example: /// -/// // Each database change in the player prints "Fresh players: ..." -/// for try await players in observation.values(in: dbQueue) { -/// print("Fresh players: \(players)") -/// } +/// ```swift +/// let observation = ValueObservation.tracking { db in +/// try Player.fetchAll(db) +/// } /// -/// See `ValueObservation` for more information. +/// for try await players in observation.values(in: dbQueue) { +/// print("Fresh players: \(players)") +/// } +/// ``` /// -/// - note: This async sequence never ends. +/// You build an `AsyncValueObservation` from ``ValueObservation`` or +/// ``SharedValueObservation``. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public struct AsyncValueObservation: AsyncSequence { public typealias BufferingPolicy = AsyncThrowingStream.Continuation.BufferingPolicy @@ -342,9 +404,6 @@ public struct AsyncValueObservation: AsyncSequence { } } - /// An asynchronous iterator that supplies database changes one at a time. - /// - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) public struct Iterator: AsyncIteratorProtocol { var iterator: AsyncThrowingStream.AsyncIterator let cancellable: AnyDatabaseCancellable @@ -359,45 +418,49 @@ public struct AsyncValueObservation: AsyncSequence { extension ValueObservation { // MARK: - Publishing Observed Values - /// Creates a publisher which tracks changes in database values. + /// Returns a publisher of observed values. /// /// For example: /// - /// let observation = ValueObservation.tracking { db in - /// try Player.fetchAll(db) - /// } - /// let cancellable = observation - /// .publisher(in: dbQueue) - /// .sink( - /// receiveCompletion: { completion in ... }, - /// receiveValue: { (players: [Player]) in - /// print("fresh players: \(players)") - /// }) + /// ```swift + /// let observation = ValueObservation.tracking { db in + /// try Player.fetchAll(db) + /// } + /// + /// let publisher = observation.publisher(in: dbQueue) + /// + /// let cancellable = publisher.sink { completion in + /// // handle completion + /// } receiveValue: { (players: [Player]) in + /// print("fresh players: \(players)") + /// } + /// ``` /// /// By default, fresh values are dispatched asynchronously on the - /// main queue. You can change this behavior by by providing a scheduler. + /// main dispatch queue. You can change this behavior by providing a + /// scheduler. /// - /// For example, `.immediate` notifies all values on the main queue as well, - /// and the first one is immediately notified when the publisher - /// is subscribed: + /// For example, the ``ValueObservationScheduler/immediate`` scheduler + /// notifies all values on the main dispatch queue, and notifies the first + /// one immediately when the publisher is subscribed: /// - /// let cancellable = observation - /// .publisher( - /// in: dbQueue, - /// scheduling: .immediate) // <- - /// .sink( - /// receiveCompletion: { completion in ... }, - /// receiveValue: { (players: [Player]) in - /// print("fresh players: \(players)") - /// }) - /// // <- here "fresh players" is already printed. + /// ```swift + /// let publisher = observation.publisher(in: dbQueue, scheduling: .immediate) + /// + /// let cancellable = publisher.sink { completion in + /// // handle completion + /// } receiveValue: { (players: [Player]) in + /// print("fresh players: \(players)") + /// } + /// // <- here "fresh players" is already printed. + /// ``` /// /// Note that the `.immediate` scheduler requires that the publisher is /// subscribed from the main thread. It raises a fatal error otherwise. /// /// - parameter reader: A DatabaseReader. - /// - parameter scheduler: A Scheduler. By default, fresh values are - /// dispatched asynchronously on the main queue. + /// - parameter scheduler: A ValueObservationScheduler. By default, fresh + /// values are dispatched asynchronously on the main dispatch queue. /// - returns: A Combine publisher @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) public func publisher( @@ -418,9 +481,10 @@ extension ValueObservation { @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) extension DatabasePublishers { - /// A publisher that tracks changes in the database. + /// A publisher that publishes the values of a ``ValueObservation``. /// - /// See `ValueObservation.publisher(in:scheduling:)`. + /// You build such a publisher from ``ValueObservation`` + /// or ``SharedValueObservation``. public struct Value: Publisher { public typealias Failure = Error private let start: ValueObservationStart @@ -556,76 +620,80 @@ extension ValueObservation where Reducer == ValueReducers.Auto { // MARK: - Creating ValueObservation - /// Creates an optimized `ValueObservation` that notifies the values - /// returned by the `fetch` function whenever a database transaction - /// changes them. + /// Creates an optimized `ValueObservation` that notifies the fetched value + /// whenever it changes. /// - /// The optimization only kicks in when the observation is started from a - /// `DatabasePool`: fresh values are fetched concurrently, and do not block - /// database writes. + /// The optimization reduces database contention by not blocking database + /// writes when the fresh value is fetched. /// - /// - precondition: The *fetch* function must perform requests that fetch - /// from a single and constant database region. The tracked region is made - /// of tables, columns, and, when possible, rowids of individual rows. All - /// changes that happen outside of this region do not impact - /// the observation. + /// The optimization is only applied when the observation is started from a + /// ``DatabasePool``. You can start such an observation from a + /// ``DatabaseQueue``, but the optimization will not be applied. /// - /// For example: + /// **Precondition**: The `fetch` function must perform requests that fetch + /// from a single and constant database region. This region is made of + /// tables, columns, and rowids of individual rows. All changes that happen + /// outside of this region are not notified. /// - /// // Tracks the full 'player' table - /// let observation = ValueObservation.trackingConstantRegion { db -> [Player] in - /// try Player.fetchAll(db) + /// For example, the observations below track a constant region and can + /// be optimized: + /// + /// ```swift + /// // Tracks the full 'player' table + /// let observation = ValueObservation.trackingConstantRegion { db -> [Player] in + /// try Player.fetchAll(db) + /// } + /// + /// // Tracks the row with id 42 in the 'player' table + /// let observation = ValueObservation.trackingConstantRegion { db -> Player? in + /// try Player.fetchOne(db, key: 42) + /// } + /// + /// // Tracks the 'score' column in the 'player' table + /// let observation = ValueObservation.trackingConstantRegion { db -> Int? in + /// try Player.select(max(Column("score"))).fetchOne(db) + /// } + /// + /// // Tracks both the 'player' and 'team' tables + /// let observation = ValueObservation.trackingConstantRegion { db -> ([Team], [Player]) in + /// let teams = try Team.fetchAll(db) + /// let players = try Player.fetchAll(db) + /// return (teams, players) + /// } + /// ``` + /// + /// Observations that do not track a constant region must not use this + /// method. Use ``tracking(_:)`` instead, or else some changes will not + /// be notified. + /// + /// For example, the observations below do not track a constant region, and + /// must not be optimized: + /// + /// ```swift + /// // Does not always track the same row in the player table. + /// let observation = ValueObservation.tracking { db -> Player? in + /// let pref = try Preference.fetchOne(db) ?? .default + /// return try Player.fetchOne(db, id: pref.favoritePlayerId) + /// } + /// + /// // Does not always track the 'user' table. + /// let observation = ValueObservation.tracking { db -> [User] in + /// let pref = try Preference.fetchOne(db) ?? .default + /// let playerIds: [Int64] = pref.favoritePlayerIds // may be empty + /// return try Player.fetchAll(db, ids: playerIds) + /// } + /// + /// // Sometimes tracks the 'food' table, and sometimes the 'beverage' table. + /// let observation = ValueObservation.tracking { db -> Int in + /// let pref = try Preference.fetchOne(db) ?? .default + /// switch pref.selection { + /// case .food: return try Food.fetchCount(db) + /// case .beverage: return try Beverage.fetchCount(db) /// } + /// } + /// ``` /// - /// // Tracks the row with id 42 in the 'player' table - /// let observation = ValueObservation.trackingConstantRegion { db -> Player? in - /// try Player.fetchOne(db, key: 42) - /// } - /// - /// // Tracks the 'score' column in the 'player' table - /// let observation = ValueObservation.trackingConstantRegion { db -> Int? in - /// try Player.select(max(Column("score"))).fetchOne(db) - /// } - /// - /// // Tracks both the 'player' and 'team' tables - /// let observation = ValueObservation.trackingConstantRegion { db -> ([Team], [Player]) in - /// let teams = try Team.fetchAll(db) - /// let players = try Player.fetchAll(db) - /// return (teams, players) - /// } - /// - /// When you want to observe a varying database region, make sure you use - /// the `ValueObservation.tracking(_:)` method instead, or else some changes - /// will not be notified. - /// - /// For example, consider those three observations below that depend on some - /// user preference. They all track a varying region, and must - /// use `ValueObservation.tracking(_:)`: - /// - /// // Does not always track the same row in the player table. - /// let observation = ValueObservation.tracking { db -> Player? in - /// let pref = try Preference.fetchOne(db) ?? .default - /// return try Player.fetchOne(db, key: pref.favoritePlayerId) - /// } - /// - /// // Only tracks the 'user' table if there are some blocked emails. - /// let observation = ValueObservation.tracking { db -> [User] in - /// let pref = try Preference.fetchOne(db) ?? .default - /// let blockedEmails = pref.blockedEmails - /// return try User.filter(blockedEmails.contains(Column("email"))).fetchAll(db) - /// } - /// - /// // Sometimes tracks the 'food' table, and sometimes the 'beverage' table. - /// let observation = ValueObservation.tracking { db -> Int in - /// let pref = try Preference.fetchOne(db) ?? .default - /// switch pref.selection { - /// case .food: return try Food.fetchCount(db) - /// case .beverage: return try Beverage.fetchCount(db) - /// } - /// } - /// - /// - parameter fetch: A function that fetches the observed value from - /// the database. + /// - parameter fetch: The closure that fetches the observed value. public static func trackingConstantRegion( _ fetch: @escaping (Database) throws -> Value) -> ValueObservation> @@ -635,43 +703,53 @@ extension ValueObservation where Reducer == ValueReducers.Auto { makeReducer: { ValueReducers.Fetch(fetch: fetch) }) } - /// Creates a `ValueObservation` that notifies the values returned by the - /// `fetch` function whenever a database transaction has an impact on the - /// given regions. + /// Creates a `ValueObservation` that notifies the fetched value whenever + /// the provided regions are modified. /// - /// The tracked region *is not* automatically inferred from the requests - /// performed in the `fetch` function. + /// Only database transactions that impact the provided regions trigger the + /// notification of fresh values. /// /// For example: /// - /// // Tracks the full database - /// let observation = ValueObservation.tracking - /// region: .fullDatabase, - /// fetch: { db in ... }) + /// ```swift + /// // Tracks the full database + /// let observation = ValueObservation.tracking + /// region: .fullDatabase, + /// fetch: { db in ... }) /// - /// // Tracks the full 'player' table - /// let observation = ValueObservation.tracking - /// region: Player.all(), - /// fetch: { db in ... }) + /// // Tracks the full 'player' table + /// let observation = ValueObservation.tracking + /// region: Player.all(), + /// fetch: { db in ... }) /// - /// // Tracks the row with id 42 in the 'player' table - /// let observation = ValueObservation.tracking - /// region: Player.filter(id: 42), - /// fetch: { db in ... }) + /// // Tracks the full 'player' table + /// let observation = ValueObservation.tracking + /// region: Table("player"), + /// fetch: { db in ... }) /// - /// // Tracks the 'score' column in the 'player' table - /// let observation = ValueObservation.tracking - /// region: Player.select(max(Column("score")), - /// fetch: { db in ... }) + /// // Tracks the row with id 42 in the 'player' table + /// let observation = ValueObservation.tracking + /// region: Player.filter(id: 42), + /// fetch: { db in ... }) /// - /// // Tracks both the 'player' and 'team' tables - /// let observation = ValueObservation.tracking - /// region: Player.all(), Team.all(), - /// fetch: { db in ... }) + /// // Tracks the 'score' column in the 'player' table + /// let observation = ValueObservation.tracking + /// region: Player.select(Column("score"), + /// fetch: { db in ... }) + /// + /// // Tracks the 'score' column in the 'player' table + /// let observation = ValueObservation.tracking + /// region: SQLRequest("SELECT score FROM player"), + /// fetch: { db in ... }) + /// + /// // Tracks both the 'player' and 'team' tables + /// let observation = ValueObservation.tracking + /// region: Player.all(), Team.all(), + /// fetch: { db in ... }) + /// ``` /// /// - parameter region: A list of observed regions. - /// - parameter fetch: A function that fetches the observed value from - /// the database. + /// - parameter fetch: The closure that fetches the observed value. public static func tracking( region: any DatabaseRegionConvertible..., fetch: @escaping (Database) throws -> Value) @@ -680,43 +758,53 @@ extension ValueObservation where Reducer == ValueReducers.Auto { tracking(regions: region, fetch: fetch) } - /// Creates a `ValueObservation` that notifies the values returned by the - /// `fetch` function whenever a database transaction has an impact on the - /// given regions. + /// Creates a `ValueObservation` that notifies the fetched value whenever + /// the provided regions are modified. /// - /// The tracked region *is not* automatically inferred from the requests - /// performed in the `fetch` function. + /// Only database transactions that impact the provided regions trigger the + /// notification of fresh values. /// /// For example: /// - /// // Tracks the full database - /// let observation = ValueObservation.tracking - /// regions: [.fullDatabase], - /// fetch: { db in ... }) + /// ```swift + /// // Tracks the full database + /// let observation = ValueObservation.tracking + /// regions: [.fullDatabase], + /// fetch: { db in ... }) /// - /// // Tracks the full 'player' table - /// let observation = ValueObservation.tracking - /// regions: [Player.all()], - /// fetch: { db in ... }) + /// // Tracks the full 'player' table + /// let observation = ValueObservation.tracking + /// regions: [Player.all()], + /// fetch: { db in ... }) /// - /// // Tracks the row with id 42 in the 'player' table - /// let observation = ValueObservation.tracking - /// regions: [Player.filter(id: 42)], - /// fetch: { db in ... }) + /// // Tracks the full 'player' table + /// let observation = ValueObservation.tracking + /// regions: [Table("player")], + /// fetch: { db in ... }) /// - /// // Tracks the 'score' column in the 'player' table - /// let observation = ValueObservation.tracking - /// regions: [Player.select(max(Column("score"))], - /// fetch: { db in ... }) + /// // Tracks the row with id 42 in the 'player' table + /// let observation = ValueObservation.tracking + /// regions: [Player.filter(id: 42)], + /// fetch: { db in ... }) /// - /// // Tracks both the 'player' and 'team' tables - /// let observation = ValueObservation.tracking - /// regions: [Player.all(), Team.all()], - /// fetch: { db in ... }) + /// // Tracks the 'score' column in the 'player' table + /// let observation = ValueObservation.tracking + /// regions: [Player.select(Column("score")], + /// fetch: { db in ... }) /// - /// - parameter regions: A list of observed regions. - /// - parameter fetch: A function that fetches the observed value from - /// the database. + /// // Tracks the 'score' column in the 'player' table + /// let observation = ValueObservation.tracking + /// regions: [SQLRequest("SELECT score FROM player")], + /// fetch: { db in ... }) + /// + /// // Tracks both the 'player' and 'team' tables + /// let observation = ValueObservation.tracking + /// regions: [Player.all(), Team.all()], + /// fetch: { db in ... }) + /// ``` + /// + /// - parameter regions: An array of observed regions. + /// - parameter fetch: The closure that fetches the observed value. public static func tracking( regions: [any DatabaseRegionConvertible], fetch: @escaping (Database) throws -> Value) @@ -727,24 +815,24 @@ extension ValueObservation where Reducer == ValueReducers.Auto { makeReducer: { ValueReducers.Fetch(fetch: fetch) }) } - /// Creates a `ValueObservation` that notifies the values returned by the - /// `fetch` function whenever a database transaction changes them. + /// Creates a `ValueObservation` that notifies the fetched values whenever + /// it changes. /// /// For example: /// - /// let observation = ValueObservation.tracking { db in - /// try Player.fetchAll(db) - /// } + /// ```swift + /// let observation = ValueObservation.tracking { db in + /// try Player.fetchAll(db) + /// } /// - /// let cancellable = try observation.start( - /// in: dbQueue, - /// onError: { error in ... }, - /// onChange: { (players: [Player]) in - /// print("Players have changed") - /// }) + /// let cancellable = try observation.start(in: dbQueue) { error in + /// // handle error + /// } onChange: { (players: [Player]) in + /// print("Players have changed") + /// } + /// ``` /// - /// - parameter fetch: A function that fetches the observed value from - /// the database. + /// - parameter fetch: The closure that fetches the observed value. public static func tracking( _ fetch: @escaping (Database) throws -> Value) -> ValueObservation> diff --git a/GRDB/ValueObservation/ValueReducer/Fetch.swift b/GRDB/ValueObservation/ValueReducer/Fetch.swift index 28e5bc6fc..4f9b16c88 100644 --- a/GRDB/ValueObservation/ValueReducer/Fetch.swift +++ b/GRDB/ValueObservation/ValueReducer/Fetch.swift @@ -1,5 +1,5 @@ extension ValueReducers { - /// A reducer which passes raw fetched values through. + /// A `ValueReducer` that perform database fetches. public struct Fetch: ValueReducer { private let __fetch: (Database) throws -> Value @@ -8,13 +8,11 @@ extension ValueReducers { self.__fetch = fetch } - /// :nodoc: public func _fetch(_ db: Database) throws -> Value { assert(db.isInsideTransaction, "Fetching in a non-isolated way is illegal") return try __fetch(db) } - /// :nodoc: public func _value(_ fetched: Value) -> Value? { fetched } diff --git a/GRDB/ValueObservation/ValueReducer/Map.swift b/GRDB/ValueObservation/ValueReducer/Map.swift index e39ec8fe3..453f84db0 100644 --- a/GRDB/ValueObservation/ValueReducer/Map.swift +++ b/GRDB/ValueObservation/ValueReducer/Map.swift @@ -1,7 +1,9 @@ extension ValueObservation { - /// Returns a ValueObservation which notifies the results of calling the - /// given transformation which each element notified by this - /// value observation. + /// Transforms all values from the upstream observation with a + /// provided closure. + /// + /// - parameter transform: A closure that takes one value as its parameter + /// and returns a new value. public func map(_ transform: @escaping (Reducer.Value) throws -> T) -> ValueObservation> { @@ -10,10 +12,10 @@ extension ValueObservation { } extension ValueReducers { - /// A reducer whose values consist of those in a `Base` reducer + /// A `ValueReducer` whose values consist of those in a `Base` reduced /// passed through a transform function. /// - /// See `ValueObservation.map(_:)` + /// See ``ValueObservation/map(_:)``. public struct Map: _ValueReducer { private var base: Base private let transform: (Base.Value) throws -> Value @@ -23,7 +25,6 @@ extension ValueReducers { self.transform = transform } - /// :nodoc: public mutating func _value(_ fetched: Base.Fetched) throws -> Value? { guard let value = try base._value(fetched) else { return nil } return try transform(value) @@ -32,7 +33,6 @@ extension ValueReducers { } extension ValueReducers.Map: _DatabaseValueReducer where Base: _DatabaseValueReducer { - /// :nodoc: public func _fetch(_ db: Database) throws -> Base.Fetched { try base._fetch(db) } diff --git a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift b/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift index 7233dce79..31ac711f9 100644 --- a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift +++ b/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift @@ -1,6 +1,10 @@ extension ValueObservation { - /// Returns a ValueObservation which only publishes elements that don’t - /// match the previous element, as evaluated by a provided closure. + /// Notifies only values that don’t match the previously observed value, as + /// evaluated by a provided closure. + /// + /// - parameter predicate: A closure to evaluate whether two values are + /// equivalent, for purposes of filtering. Return true from this closure + /// to indicate that the second element is a duplicate of the first. public func removeDuplicates(by predicate: @escaping (Reducer.Value, Reducer.Value) -> Bool) -> ValueObservation> { @@ -9,7 +13,7 @@ extension ValueObservation { } extension ValueObservation where Reducer.Value: Equatable { - /// Returns a ValueObservation which filters out consecutive equal values. + /// Notifies only values that don’t match the previously observed value. public func removeDuplicates() -> ValueObservation> { @@ -18,7 +22,10 @@ extension ValueObservation where Reducer.Value: Equatable { } extension ValueReducers { - /// See `ValueObservation.removeDuplicates()` + /// A `ValueReducer` that notifies only values that don’t match the + /// previously observed value. + /// + /// See ``ValueObservation/removeDuplicates()``. public struct RemoveDuplicates: _ValueReducer { private var base: Base private var previousValue: Base.Value? @@ -29,7 +36,6 @@ extension ValueReducers { self.predicate = predicate } - /// :nodoc: public mutating func _value(_ fetched: Base.Fetched) throws -> Base.Value? { guard let value = try base._value(fetched) else { return nil @@ -45,7 +51,6 @@ extension ValueReducers { } extension ValueReducers.RemoveDuplicates: _DatabaseValueReducer where Base: _DatabaseValueReducer { - /// :nodoc: public func _fetch(_ db: Database) throws -> Base.Fetched { try base._fetch(db) } diff --git a/GRDB/ValueObservation/ValueReducer/Trace.swift b/GRDB/ValueObservation/ValueReducer/Trace.swift index f375da797..da41cfd73 100644 --- a/GRDB/ValueObservation/ValueReducer/Trace.swift +++ b/GRDB/ValueObservation/ValueReducer/Trace.swift @@ -1,11 +1,14 @@ extension ValueReducers { - /// See `ValueObservation.handleEvents()` + // swiftlint:disable line_length + /// A `ValueReducer` that handles ``ValueObservation`` events. + /// + /// See ``ValueObservation/handleEvents(willStart:willFetch:willTrackRegion:databaseDidChange:didReceiveValue:didFail:didCancel:)`` + /// and ``ValueObservation/print(_:to:)``. public struct Trace: _ValueReducer { var base: Base let willFetch: () -> Void let didReceiveValue: (Base.Value) -> Void - /// :nodoc: public mutating func _value(_ fetched: Base.Fetched) throws -> Base.Value? { guard let value = try base._value(fetched) else { return nil @@ -14,10 +17,10 @@ extension ValueReducers { return value } } + // swiftlint:enable line_length } extension ValueReducers.Trace: _DatabaseValueReducer where Base: _DatabaseValueReducer { - /// :nodoc: public func _fetch(_ db: Database) throws -> Base.Fetched { willFetch() return try base._fetch(db) diff --git a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift index 7e536b735..d26f544c7 100644 --- a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift +++ b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift @@ -1,6 +1,4 @@ /// Implementation details of `ValueReducer`. -/// -/// :nodoc: public protocol _ValueReducer { /// The type of fetched database values associatedtype Fetched @@ -25,8 +23,6 @@ public protocol _ValueReducer { /// Implementation details of `ValueReducer`, able to observe from any database /// reader (``DatabaseQueue``, ``DatabasePool``). -/// -/// :nodoc: public protocol _DatabaseValueReducer: _ValueReducer { /// Fetches database values upon changes in an observed database region. /// @@ -34,17 +30,27 @@ public protocol _DatabaseValueReducer: _ValueReducer { func _fetch(_ db: Database) throws -> Fetched } -/// `ValueReducer` supports ``ValueObservation`` that can observe from any -/// database reader (``DatabaseQueue``, ``DatabasePool``). +/// `ValueReducer` supports ``ValueObservation``. +/// +/// A `ValueReducer` fetches and transforms the database values +/// observed by a ``ValueObservation``. +/// +/// ## Topics +/// +/// ### Support +/// +/// - ``ValueReducers`` public typealias ValueReducer = _ValueReducer & _DatabaseValueReducer -/// A namespace for types related to the `ValueReducer` protocol. +/// A namespace for concrete types that adopt the ``ValueReducer`` protocol. public enum ValueReducers { // ValueReducers.Auto allows us to define ValueObservation factory methods. // // For example, ValueObservation.tracking(_:) is, practically, // ValueObservation.tracking(_:). - /// :nodoc: + /// `Auto` supports ``ValueObservation`` factory methods. + /// + /// Do not use this type. public enum Auto: _ValueReducer { public mutating func _value(_ fetched: Never) -> Never? { } } diff --git a/Makefile b/Makefile index 38bfff2bb..1e4b7ffdd 100644 --- a/Makefile +++ b/Makefile @@ -50,7 +50,16 @@ TEST_ACTIONS = clean build build-for-testing test-without-building # When adding support for an Xcode version, look for available devices with # `xcrun xctrace list devices` (or the deprecated `instruments -s devices`). -ifeq ($(XCODEVERSION),14.0) +ifeq ($(XCODEVERSION),14.1) + MAX_SWIFT_VERSION = 5.7 + MIN_SWIFT_VERSION = # MAX_SWIFT_VERSION is the minimum supported Swift version + MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 14,OS=16.1" + #MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=12.4" TODO: restore + MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=16.1" + #MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" TODO: restore + OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' # -Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks' + GCC_PREPROCESSOR_DEFINITIONS = '$$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' +else ifeq ($(XCODEVERSION),14.0) MAX_SWIFT_VERSION = 5.7 MIN_SWIFT_VERSION = # MAX_SWIFT_VERSION is the minimum supported Swift version MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 13,OS=16.0" @@ -162,12 +171,14 @@ ifdef MIN_SWIFT_VERSION endif test_framework_GRDBiOS_minTarget: +ifdef MIN_IOS_DESTINATION $(XCODEBUILD) \ -project GRDB.xcodeproj \ -scheme GRDB \ -destination $(MIN_IOS_DESTINATION) \ SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ $(TEST_ACTIONS) +endif test_framework_GRDBtvOS: test_framework_GRDBtvOS_maxTarget test_framework_GRDBtvOS_minTarget test_framework_GRDBtvOS_maxTarget: test_framework_GRDBtvOS_maxTarget_maxSwift test_framework_GRDBtvOS_maxTarget_minSwift @@ -233,12 +244,14 @@ ifdef MIN_SWIFT_VERSION endif test_framework_GRDBCustomSQLiteiOS_minTarget: SQLiteCustom +ifdef MIN_IOS_DESTINATION $(XCODEBUILD) \ -project GRDBCustom.xcodeproj \ -scheme GRDBCustom \ -destination $(MIN_IOS_DESTINATION) \ SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ $(TEST_ACTIONS) +endif test_framework_SQLCipher3: ifdef POD @@ -470,6 +483,20 @@ SQLiteCustom/src/sqlite3.h: # Documentation # ============= +docs-localhost: + # Generates documentation in ~/Sites/GRDB + # See https://discussions.apple.com/docs/DOC-3083 for Apache setup on the mac + mkdir -p ~/Sites/GRDB + GRDB_DOCC_PLUGIN=1 swift package \ + --allow-writing-to-directory ~/Sites/GRDB \ + generate-documentation \ + --output-path ~/Sites/GRDB \ + --target GRDB \ + --disable-indexing \ + --transform-for-static-hosting \ + --hosting-base-path "~$(USER)/GRDB" + open "http://localhost/~$(USER)/GRDB/documentation/grdb/" + doc: ifdef JAZZY $(JAZZY) \ diff --git a/Package.swift b/Package.swift index 8d5340107..c4b3b0b4a 100644 --- a/Package.swift +++ b/Package.swift @@ -16,6 +16,13 @@ if ProcessInfo.processInfo.environment["SQLITE_ENABLE_PREUPDATE_HOOK"] == "1" { cSettings.append(.define("GRDB_SQLITE_ENABLE_PREUPDATE_HOOK")) } +// Don't rely on this environment variable. It is only a convenience: +// $ make docs-localhost +var dependencies: [PackageDescription.Package.Dependency] = [] +if ProcessInfo.processInfo.environment["GRDB_DOCC_PLUGIN"] == "1" { + dependencies.append(.package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0")) +} + let package = Package( name: "GRDB", defaultLocalization: "en", // for tests @@ -29,8 +36,7 @@ let package = Package( .library(name: "GRDB", targets: ["GRDB"]), .library(name: "GRDB-dynamic", type: .dynamic, targets: ["GRDB"]), ], - dependencies: [ - ], + dependencies: dependencies, targets: [ .systemLibrary( name: "CSQLite", diff --git a/README.md b/README.md index f83b1f302..86316301e 100644 --- a/README.md +++ b/README.md @@ -11,13 +11,13 @@ --- -**Latest release**: October 29, 2022 • [version 6.2.0](https://github.com/groue/GRDB.swift/tree/v6.2.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) +**Latest release**: November 6, 2022 • [version 6.3.0](https://github.com/groue/GRDB.swift/tree/v6.3.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+ | Swift version | GRDB version | | -------------- | ----------------------------------------------------------- | -| **Swift 5.7+** | **v6.2.0** | +| **Swift 5.7+** | **v6.3.0** | | Swift 5.3 | [v5.26.1](https://github.com/groue/GRDB.swift/tree/v5.26.1) | | Swift 5.2 | [v5.12.0](https://github.com/groue/GRDB.swift/tree/v5.12.0) | | Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | @@ -322,7 +322,7 @@ Documentation #### Reference -- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/6.2/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) +- [GRDB Reference](https://swiftpackageindex.com/groue/grdb/documentation/grdb/) #### Getting Started @@ -616,7 +616,7 @@ do { > **Warning**: It is your responsibility to prevent sensitive information from leaking in unexpected locations, so you should not set the `publicStatementArguments` flag in release builds (think about GDPR and other privacy-related rules). -See [Configuration](http://groue.github.io/GRDB.swift/docs/6.2/Structs/Configuration.html) for more details and configuration options. +See [Configuration](https://swiftpackageindex.com/groue/grdb/documentation/grdb/configuration) for more details and configuration options. SQLite API @@ -673,7 +673,7 @@ try dbQueue.write { db in } ``` -The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/6.2/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. +The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](https://swiftpackageindex.com/groue/grdb/documentation/grdb/statementarguments) for a detailed documentation of SQLite arguments. You can also embed query arguments right into your SQL queries, with the `literal` argument label, as in the example below. See [SQL Interpolation] for more details. @@ -931,7 +931,7 @@ try dbQueue.read { db in let dictionary = try Dictionary(uniqueKeysWithValues: cursor) ``` -- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/6.2/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: +- **Cursors adopt the [Cursor](https://swiftpackageindex.com/groue/grdb/documentation/grdb/cursor) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: ```swift // Prints all Github links @@ -1010,7 +1010,7 @@ let rows = try Row.fetchAll(db, arguments: ["name": "Arthur"]) ``` -See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/6.2/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. +See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](https://swiftpackageindex.com/groue/grdb/documentation/grdb/statementarguments) for a detailed documentation of SQLite arguments. Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care: @@ -1318,7 +1318,7 @@ GRDB ships with built-in support for the following value types: - Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol. -Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/6.2/Structs/StatementArguments.html): +Values can be used as [statement arguments](https://swiftpackageindex.com/groue/grdb/documentation/grdb/statementarguments): ```swift let url: URL = ... @@ -1383,7 +1383,9 @@ At each step of the request iteration, the `row[]` subscript creates *two copies ```swift while let row = try rows.next() { - let data = row.dataNoCopy(named: "data") // Data? + try row.withUnsafeData(name: "data") { (data: Data?) in + ... + } } ``` @@ -1789,7 +1791,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction } ``` -Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/6.2/Structs/Configuration.html) configuration flag: +Transactions can't be left opened unless you set the [allowsUnsafeTransactions](https://swiftpackageindex.com/groue/grdb/documentation/grdb/configuration/allowsunsafetransactions) configuration flag: ```swift // fatal error: A transaction has been left opened at the end of a database access @@ -1901,7 +1903,7 @@ try dbQueue.write { db in } ``` -The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/6.2/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). +The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](https://swiftpackageindex.com/groue/grdb/documentation/grdb/statementarguments), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). ```swift insertStatement.arguments = ["name": "Arthur", "score": 1000] @@ -1984,7 +1986,7 @@ See also `Database.execute(sql:)` in the [Executing Updates](#executing-updates) > **Note**: it is a programmer error to reuse a prepared statement that has failed: GRDB may crash if you do so. -For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/6.2/Classes/Statement.html). +For more information about prepared statements, see the [Statement reference](https://swiftpackageindex.com/groue/grdb/documentation/grdb/statement). ### Prepared Statements Cache @@ -2728,7 +2730,7 @@ try Place.fetchSet(db, sql: "SELECT ...", arguments:...) // Set try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place? ``` -See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/6.2/Structs/StatementArguments.html) for more information about the query arguments. +See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](https://swiftpackageindex.com/groue/grdb/documentation/grdb/statementarguments) for more information about the query arguments. > **Note**: for performance reasons, the same row argument to `init(row:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`. @@ -3238,7 +3240,7 @@ Here is a list with all the available [persistence callbacks], listed in the sam - `aroundDelete` - `didDelete` -For detailed information about each callback, check the [reference](http://groue.github.io/GRDB.swift/docs/6.2/Protocols/MutablePersistableRecord.html). +For detailed information about each callback, check the [reference](https://swiftpackageindex.com/groue/grdb/documentation/grdb/mutablepersistablerecord/). In the `MutablePersistableRecord` protocol, `willInsert` and `didInsert` are mutating methods. In `PersistableRecord`, they are not mutating. @@ -3431,7 +3433,7 @@ protocol EncodableRecord { } ``` -See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/6.2/Enums/DatabaseColumnDecodingStrategy.html) and [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/6.2/Enums/DatabaseColumnEncodingStrategy.html) to learn about all available strategies. +See [DatabaseColumnDecodingStrategy](https://swiftpackageindex.com/groue/grdb/documentation/grdb/databasecolumndecodingstrategy) and [DatabaseColumnEncodingStrategy](https://swiftpackageindex.com/groue/grdb/documentation/grdb/databasecolumnencodingstrategy/) to learn about all available strategies. ### Date and UUID Coding Strategies @@ -3453,7 +3455,7 @@ protocol EncodableRecord { } ``` -See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/6.2/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/6.2/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/6.2/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. +See [DatabaseDateDecodingStrategy](https://swiftpackageindex.com/groue/grdb/documentation/grdb/databasedatedecodingstrategy/), [DatabaseDateEncodingStrategy](https://swiftpackageindex.com/groue/grdb/documentation/grdb/databasedateencodingstrategy/), and [DatabaseUUIDEncodingStrategy](https://swiftpackageindex.com/groue/grdb/documentation/grdb/databaseuuidencodingstrategy/) to learn about all available strategies. There is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs and uuid strings, both uppercase and lowercase). @@ -5013,7 +5015,7 @@ Player // SELECT * FROM player ``` -Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/6.2/Structs/StatementArguments.html): +Raw SQL snippets are also accepted, with eventual [arguments](https://swiftpackageindex.com/groue/grdb/documentation/grdb/statementarguments): ```swift // SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate) @@ -5919,8 +5921,6 @@ try Player.customRequest().fetchAll(db) // [Player] - The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method. -- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/6.2/Structs/AnyFetchRequest.html): a type-erased request. - ## Joined Queries Support @@ -7252,7 +7252,7 @@ DatabaseRegion helps [ValueObservation] and [DatabaseRegionObservation] track ch For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table. -For more details, see the [reference](https://groue.github.io/GRDB.swift/docs/6.2/Structs/DatabaseRegion.html). +For more details, see the [reference](https://swiftpackageindex.com/groue/grdb/documentation/grdb/databaseregion/). #### The DatabaseRegionConvertible Protocol @@ -8616,7 +8616,7 @@ When this is the case, there are two possible explanations: try db.execute(sql: "UPDATE player SET name = ?", arguments: [name]) ``` -For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/6.2/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp). +For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](https://swiftpackageindex.com/groue/grdb/documentation/grdb/configuration/acceptsdoublequotedstringliterals). @@ -8765,7 +8765,7 @@ This chapter has [moved](Documentation/Concurrency.md#database-snapshots). #### DatabaseWriter and DatabaseReader Protocols -This chapter was removed. See the references of [DatabaseReader](http://groue.github.io/GRDB.swift/docs/6.2/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/6.2/Protocols/DatabaseWriter.html). +This chapter was removed. See the references of [DatabaseReader](https://swiftpackageindex.com/groue/grdb/documentation/grdb/databasereader) and [DatabaseWriter](https://swiftpackageindex.com/groue/grdb/documentation/grdb/databasewriter). #### Asynchronous APIs @@ -8819,7 +8819,7 @@ This chapter was renamed to [Embedding SQL in Query Interface Requests]. [Sharing a Database]: Documentation/SharingADatabase.md [FAQ]: #faq [Database Observation]: #database-changes-observation -[SQLRequest]: http://groue.github.io/GRDB.swift/docs/6.2/Structs/SQLRequest.html +[SQLRequest]: https://swiftpackageindex.com/groue/grdb/documentation/grdb/sqlrequest [SQL literal]: Documentation/SQLInterpolation.md#sql-literal [Identifiable]: https://developer.apple.com/documentation/swift/identifiable [Query Interface Organization]: Documentation/QueryInterfaceOrganization.md diff --git a/SQLiteCustom/grdb_config.h b/SQLiteCustom/grdb_config.h index 3e53403fe..b0bb605ef 100644 --- a/SQLiteCustom/grdb_config.h +++ b/SQLiteCustom/grdb_config.h @@ -1,30 +1,30 @@ #ifndef grdb_config_h #define grdb_config_h -typedef void(*errorLogCallback)(void *pArg, int iErrCode, const char *zMsg); +typedef void(*_errorLogCallback)(void *pArg, int iErrCode, const char *zMsg); /// Wrapper around sqlite3_config(SQLITE_CONFIG_LOG, ...) which is a variadic /// function that can't be used from Swift. -static inline void registerErrorLogCallback(errorLogCallback callback) { +static inline void _registerErrorLogCallback(_errorLogCallback callback) { sqlite3_config(SQLITE_CONFIG_LOG, callback, 0); } #if SQLITE_VERSION_NUMBER >= 3029000 /// Wrapper around sqlite3_db_config() which is a variadic function that can't /// be used from Swift. -static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) { +static inline void _disableDoubleQuotedStringLiterals(sqlite3 *db) { sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 0, (void *)0); sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 0, (void *)0); } /// Wrapper around sqlite3_db_config() which is a variadic function that can't /// be used from Swift. -static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) { +static inline void _enableDoubleQuotedStringLiterals(sqlite3 *db) { sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 1, (void *)0); sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 1, (void *)0); } #else -static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) { } -static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) { } +static inline void _disableDoubleQuotedStringLiterals(sqlite3 *db) { } +static inline void _enableDoubleQuotedStringLiterals(sqlite3 *db) { } #endif #endif /* grdb_config_h */ diff --git a/Sources/CSQLite/shim.h b/Sources/CSQLite/shim.h index 471b5432c..8a10c34cd 100644 --- a/Sources/CSQLite/shim.h +++ b/Sources/CSQLite/shim.h @@ -1,30 +1,30 @@ #include -typedef void(*errorLogCallback)(void *pArg, int iErrCode, const char *zMsg); +typedef void(*_errorLogCallback)(void *pArg, int iErrCode, const char *zMsg); /// Wrapper around sqlite3_config(SQLITE_CONFIG_LOG, ...) which is a variadic /// function that can't be used from Swift. -static inline void registerErrorLogCallback(errorLogCallback callback) { +static inline void _registerErrorLogCallback(_errorLogCallback callback) { sqlite3_config(SQLITE_CONFIG_LOG, callback, 0); } #if SQLITE_VERSION_NUMBER >= 3029000 /// Wrapper around sqlite3_db_config() which is a variadic function that can't /// be used from Swift. -static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) { +static inline void _disableDoubleQuotedStringLiterals(sqlite3 *db) { sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 0, (void *)0); sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 0, (void *)0); } /// Wrapper around sqlite3_db_config() which is a variadic function that can't /// be used from Swift. -static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) { +static inline void _enableDoubleQuotedStringLiterals(sqlite3 *db) { sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 1, (void *)0); sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 1, (void *)0); } #else -static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) { } -static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) { } +static inline void _disableDoubleQuotedStringLiterals(sqlite3 *db) { } +static inline void _enableDoubleQuotedStringLiterals(sqlite3 *db) { } #endif // Expose APIs that are missing from system diff --git a/Support/Info.plist b/Support/Info.plist index 6e9c6cfd5..c93142d06 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 6.2.0 + 6.3.0 CFBundleSignature ???? CFBundleVersion diff --git a/Support/SQLCipher_config.h b/Support/SQLCipher_config.h index 2a59df68c..a405306f6 100644 --- a/Support/SQLCipher_config.h +++ b/Support/SQLCipher_config.h @@ -3,30 +3,30 @@ #include -typedef void(*errorLogCallback)(void *pArg, int iErrCode, const char *zMsg); +typedef void(*_errorLogCallback)(void *pArg, int iErrCode, const char *zMsg); /// Wrapper around sqlite3_config(SQLITE_CONFIG_LOG, ...) which is a variadic /// function that can't be used from Swift. -static inline void registerErrorLogCallback(errorLogCallback callback) { +static inline void _registerErrorLogCallback(_errorLogCallback callback) { sqlite3_config(SQLITE_CONFIG_LOG, callback, 0); } #if SQLITE_VERSION_NUMBER >= 3029000 /// Wrapper around sqlite3_db_config() which is a variadic function that can't /// be used from Swift. -static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) { +static inline void _disableDoubleQuotedStringLiterals(sqlite3 *db) { sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 0, (void *)0); sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 0, (void *)0); } /// Wrapper around sqlite3_db_config() which is a variadic function that can't /// be used from Swift. -static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) { +static inline void _enableDoubleQuotedStringLiterals(sqlite3 *db) { sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 1, (void *)0); sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 1, (void *)0); } #else -static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) { } -static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) { } +static inline void _disableDoubleQuotedStringLiterals(sqlite3 *db) { } +static inline void _enableDoubleQuotedStringLiterals(sqlite3 *db) { } #endif #endif /* grdb_config_h */ diff --git a/Support/grdb_config.h b/Support/grdb_config.h index 0987e0eeb..5cdaf6e05 100644 --- a/Support/grdb_config.h +++ b/Support/grdb_config.h @@ -3,31 +3,31 @@ #include -typedef void(*errorLogCallback)(void *pArg, int iErrCode, const char *zMsg); +typedef void(*_errorLogCallback)(void *pArg, int iErrCode, const char *zMsg); /// Wrapper around sqlite3_config(SQLITE_CONFIG_LOG, ...) which is a variadic /// function that can't be used from Swift. -static inline void registerErrorLogCallback(errorLogCallback callback) { +static inline void _registerErrorLogCallback(_errorLogCallback callback) { sqlite3_config(SQLITE_CONFIG_LOG, callback, 0); } #if SQLITE_VERSION_NUMBER >= 3029000 /// Wrapper around sqlite3_db_config() which is a variadic function that can't /// be used from Swift. -static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) { +static inline void _disableDoubleQuotedStringLiterals(sqlite3 *db) { sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 0, (void *)0); sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 0, (void *)0); } /// Wrapper around sqlite3_db_config() which is a variadic function that can't /// be used from Swift. -static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) { +static inline void _enableDoubleQuotedStringLiterals(sqlite3 *db) { sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 1, (void *)0); sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 1, (void *)0); } #else -static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) { } -static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) { } +static inline void _disableDoubleQuotedStringLiterals(sqlite3 *db) { } +static inline void _enableDoubleQuotedStringLiterals(sqlite3 *db) { } #endif // Expose APIs that are missing from system diff --git a/Tests/CombineExpectations/PublisherExpectation.swift b/Tests/CombineExpectations/PublisherExpectation.swift index b8fca0b5a..c9c570f11 100644 --- a/Tests/CombineExpectations/PublisherExpectation.swift +++ b/Tests/CombineExpectations/PublisherExpectation.swift @@ -6,8 +6,6 @@ public enum PublisherExpectations { } /// The base protocol for PublisherExpectation. It is an implementation detail /// that you are not supposed to use, as shown by the underscore prefix. -/// -/// :nodoc: public protocol _PublisherExpectationBase { /// Sets up an XCTestExpectation. This method is an implementation detail /// that you are not supposed to use, as shown by the underscore prefix. @@ -19,7 +17,6 @@ public protocol _PublisherExpectationBase { } extension _PublisherExpectationBase { - /// :nodoc: public func _makeWaiter() -> XCTWaiter? { nil } } diff --git a/Tests/GRDBTests/DataMemoryTests.swift b/Tests/GRDBTests/DataMemoryTests.swift index 159a48a36..83c265e8f 100644 --- a/Tests/GRDBTests/DataMemoryTests.swift +++ b/Tests/GRDBTests/DataMemoryTests.swift @@ -25,6 +25,16 @@ class DataMemoryTests: GRDBTestCase { } } + do { + // This data should not be copied + try row.withUnsafeData(atIndex: 0) { nonCopiedData in + XCTAssertEqual(nonCopiedData, data) + nonCopiedData!.withUnsafeBytes { + XCTAssertEqual($0.baseAddress, blobPointer) + } + } + } + do { // This data should not be copied let nonCopiedData = row.dataNoCopy(atIndex: 0)! @@ -52,6 +62,16 @@ class DataMemoryTests: GRDBTestCase { } } + do { + // This data should not be copied + try nestedRow.withUnsafeData(atIndex: 0) { nonCopiedData in + XCTAssertEqual(nonCopiedData, data) + nonCopiedData!.withUnsafeBytes { + XCTAssertEqual($0.baseAddress, blobPointer) + } + } + } + do { // This data should not be copied let nonCopiedData = nestedRow.dataNoCopy(atIndex: 0)! @@ -68,7 +88,7 @@ class DataMemoryTests: GRDBTestCase { let dbValue = row.first!.1 // TODO: think about exposing a (column:,databaseValue:) tuple switch dbValue.storage { case .blob(let data): - data.withUnsafeBytes { buffer in + try data.withUnsafeBytes { buffer in do { // This data should not be copied: let nonCopiedData: Data = row[0] @@ -78,6 +98,15 @@ class DataMemoryTests: GRDBTestCase { } } + do { + // This data should not be copied: + try row.withUnsafeData(atIndex: 0) { nonCopiedData in + XCTAssertEqual(nonCopiedData, data) + nonCopiedData!.withUnsafeBytes { nonCopiedBuffer in + XCTAssertEqual(nonCopiedBuffer.baseAddress, buffer.baseAddress) + } + } + } do { // This data should not be copied: let nonCopiedData = row.dataNoCopy(atIndex: 0)! diff --git a/Tests/GRDBTests/FetchableRecordDecodableTests.swift b/Tests/GRDBTests/FetchableRecordDecodableTests.swift index 6c8113a33..5d336fdac 100644 --- a/Tests/GRDBTests/FetchableRecordDecodableTests.swift +++ b/Tests/GRDBTests/FetchableRecordDecodableTests.swift @@ -616,8 +616,9 @@ extension FetchableRecordDecodableTests { for row in array { let data1: Data? = row["name"] XCTAssertEqual(jsonAsData, data1) - let data = row.dataNoCopy(named: "name") - XCTAssertEqual(jsonAsData, data) + try row.withUnsafeData(named: "name") { data in + XCTAssertEqual(jsonAsData, data) + } } } } @@ -676,8 +677,9 @@ extension FetchableRecordDecodableTests { while let row = try cursor.next() { let data1: Data? = row["name"] XCTAssertEqual(jsonAsData, data1) - let data = row.dataNoCopy(named: "name") - XCTAssertEqual(jsonAsData, data) + try row.withUnsafeData(named: "name") { data in + XCTAssertEqual(jsonAsData, data) + } } } } diff --git a/Tests/GRDBTests/MutablePersistableRecordTests.swift b/Tests/GRDBTests/MutablePersistableRecordTests.swift index d9a62ef17..13bd726e6 100644 --- a/Tests/GRDBTests/MutablePersistableRecordTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordTests.swift @@ -1280,6 +1280,43 @@ extension MutablePersistableRecordTests { XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0) XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0) } + + do { + // Test onConflict: .ignore + sqlQueries.removeAll() + var player = FullPlayer(id: 1, name: "Barbara", score: 100) + try XCTAssertTrue(player.exists(db)) + let score = try player.insertAndFetch(db, onConflict: .ignore, selection: [Column("score")]) { (statement: Statement) in + try Int.fetchOne(statement) + } + + XCTAssert(sqlQueries.contains(""" + INSERT OR IGNORE INTO "player" ("id", "name", "score") VALUES (1,'Barbara',100) RETURNING "score" + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(player.id, 1) + XCTAssertNil(score) + + XCTAssertEqual(player.callbacks.willInsertCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(player.callbacks.didInsertCount, 1) + + XCTAssertEqual(player.callbacks.willUpdateCount, 0) + XCTAssertEqual(player.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(player.callbacks.didUpdateCount, 0) + + XCTAssertEqual(player.callbacks.willSaveCount, 1) + XCTAssertEqual(player.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(player.callbacks.didSaveCount, 1) + + XCTAssertEqual(player.callbacks.willDeleteCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(player.callbacks.didDeleteCount, 0) + } } } } diff --git a/Tests/GRDBTests/RowAdapterTests.swift b/Tests/GRDBTests/RowAdapterTests.swift index 24560203f..bcf7a3f68 100644 --- a/Tests/GRDBTests/RowAdapterTests.swift +++ b/Tests/GRDBTests/RowAdapterTests.swift @@ -104,7 +104,7 @@ class AdapterRowTests : RowTestCase { } } - func testDataNoCopy() throws { + func testWithUnsafeData() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let data = "foo".data(using: .utf8)! @@ -112,17 +112,20 @@ class AdapterRowTests : RowTestCase { let adapter = ColumnMapping(["a": "basea", "b": "baseb", "c": "basec"]) let row = try Row.fetchOne(db, sql: "SELECT ? AS basea, ? AS baseb, ? AS basec", arguments: [data, emptyData, nil], adapter: adapter)! - XCTAssertEqual(row.dataNoCopy(atIndex: 0), data) - XCTAssertEqual(row.dataNoCopy(named: "a"), data) - XCTAssertEqual(row.dataNoCopy(Column("a")), data) + try row.withUnsafeData(atIndex: 0) { XCTAssertEqual($0, data) } + try row.withUnsafeData(named: "a") { XCTAssertEqual($0, data) } + try row.withUnsafeData(at: Column("a")) { XCTAssertEqual($0, data) } - XCTAssertEqual(row.dataNoCopy(atIndex: 1), emptyData) - XCTAssertEqual(row.dataNoCopy(named: "b"), emptyData) - XCTAssertEqual(row.dataNoCopy(Column("b")), emptyData) + try row.withUnsafeData(atIndex: 1) { XCTAssertEqual($0, emptyData) } + try row.withUnsafeData(named: "b") { XCTAssertEqual($0, emptyData) } + try row.withUnsafeData(at: Column("b")) { XCTAssertEqual($0, emptyData) } - XCTAssertNil(row.dataNoCopy(atIndex: 2)) - XCTAssertNil(row.dataNoCopy(named: "c")) - XCTAssertNil(row.dataNoCopy(Column("c"))) + try row.withUnsafeData(atIndex: 2) { XCTAssertNil($0) } + try row.withUnsafeData(named: "c") { XCTAssertNil($0) } + try row.withUnsafeData(at: Column("c")) { XCTAssertNil($0) } + + try row.withUnsafeData(named: "missing") { XCTAssertNil($0) } + try row.withUnsafeData(at: Column("missing")) { XCTAssertNil($0) } } } diff --git a/Tests/GRDBTests/RowCopiedFromStatementTests.swift b/Tests/GRDBTests/RowCopiedFromStatementTests.swift index 03f0ecedf..8bc077c5b 100644 --- a/Tests/GRDBTests/RowCopiedFromStatementTests.swift +++ b/Tests/GRDBTests/RowCopiedFromStatementTests.swift @@ -108,24 +108,27 @@ class RowCopiedFromStatementTests: RowTestCase { } } - func testDataNoCopy() throws { + func testWithUnsafeData() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let data = "foo".data(using: .utf8)! let emptyData = Data() let row = try Row.fetchOne(db, sql: "SELECT ? AS a, ? AS b, ? AS c", arguments: [data, emptyData, nil])! - XCTAssertEqual(row.dataNoCopy(atIndex: 0), data) - XCTAssertEqual(row.dataNoCopy(named: "a"), data) - XCTAssertEqual(row.dataNoCopy(Column("a")), data) + try row.withUnsafeData(atIndex: 0) { XCTAssertEqual($0, data) } + try row.withUnsafeData(named: "a") { XCTAssertEqual($0, data) } + try row.withUnsafeData(at: Column("a")) { XCTAssertEqual($0, data) } - XCTAssertEqual(row.dataNoCopy(atIndex: 1), emptyData) - XCTAssertEqual(row.dataNoCopy(named: "b"), emptyData) - XCTAssertEqual(row.dataNoCopy(Column("b")), emptyData) + try row.withUnsafeData(atIndex: 1) { XCTAssertEqual($0, emptyData) } + try row.withUnsafeData(named: "b") { XCTAssertEqual($0, emptyData) } + try row.withUnsafeData(at: Column("b")) { XCTAssertEqual($0, emptyData) } - XCTAssertNil(row.dataNoCopy(atIndex: 2)) - XCTAssertNil(row.dataNoCopy(named: "c")) - XCTAssertNil(row.dataNoCopy(Column("c"))) + try row.withUnsafeData(atIndex: 2) { XCTAssertNil($0) } + try row.withUnsafeData(named: "c") { XCTAssertNil($0) } + try row.withUnsafeData(at: Column("c")) { XCTAssertNil($0) } + + try row.withUnsafeData(named: "missing") { XCTAssertNil($0) } + try row.withUnsafeData(at: Column("missing")) { XCTAssertNil($0) } } } diff --git a/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift b/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift index bfb7e4b3d..f840c437a 100644 --- a/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift +++ b/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift @@ -105,29 +105,32 @@ class RowFromDictionaryLiteralTests : RowTestCase { assertRowConvertedValueEqual(row, column: Column("c"), value: CustomValue.c) } - func testDataNoCopy() { + func testWithUnsafeData() throws { do { let data = "foo".data(using: .utf8)! let row: Row = ["a": data] - XCTAssertEqual(row.dataNoCopy(atIndex: 0), data) - XCTAssertEqual(row.dataNoCopy(named: "a"), data) - XCTAssertEqual(row.dataNoCopy(Column("a")), data) + try row.withUnsafeData(atIndex: 0) { XCTAssertEqual($0, data) } + try row.withUnsafeData(named: "a") { XCTAssertEqual($0, data) } + try row.withUnsafeData(at: Column("a")) { XCTAssertEqual($0, data) } + + try row.withUnsafeData(named: "missing") { XCTAssertNil($0) } + try row.withUnsafeData(at: Column("missing")) { XCTAssertNil($0) } } do { let emptyData = Data() let row: Row = ["a": emptyData] - XCTAssertEqual(row.dataNoCopy(atIndex: 0), emptyData) - XCTAssertEqual(row.dataNoCopy(named: "a"), emptyData) - XCTAssertEqual(row.dataNoCopy(Column("a")), emptyData) + try row.withUnsafeData(atIndex: 0) { XCTAssertEqual($0, emptyData) } + try row.withUnsafeData(named: "a") { XCTAssertEqual($0, emptyData) } + try row.withUnsafeData(at: Column("a")) { XCTAssertEqual($0, emptyData) } } do { let row: Row = ["a": nil] - XCTAssertNil(row.dataNoCopy(atIndex: 0)) - XCTAssertNil(row.dataNoCopy(named: "a")) - XCTAssertNil(row.dataNoCopy(Column("a"))) + try row.withUnsafeData(atIndex: 0) { XCTAssertNil($0) } + try row.withUnsafeData(named: "a") { XCTAssertNil($0) } + try row.withUnsafeData(at: Column("a")) { XCTAssertNil($0) } } } diff --git a/Tests/GRDBTests/RowFromDictionaryTests.swift b/Tests/GRDBTests/RowFromDictionaryTests.swift index 994f0bba8..c4a8362c6 100644 --- a/Tests/GRDBTests/RowFromDictionaryTests.swift +++ b/Tests/GRDBTests/RowFromDictionaryTests.swift @@ -93,29 +93,32 @@ class RowFromDictionaryTests : RowTestCase { assertRowConvertedValueEqual(row, column: Column("c"), value: CustomValue.c) } - func testDataNoCopy() { + func testWithUnsafeData() throws { do { let data = "foo".data(using: .utf8)! - let row = Row(["a": data]) + let row: Row = ["a": data] - XCTAssertEqual(row.dataNoCopy(atIndex: 0), data) - XCTAssertEqual(row.dataNoCopy(named: "a"), data) - XCTAssertEqual(row.dataNoCopy(Column("a")), data) + try row.withUnsafeData(atIndex: 0) { XCTAssertEqual($0, data) } + try row.withUnsafeData(named: "a") { XCTAssertEqual($0, data) } + try row.withUnsafeData(at: Column("a")) { XCTAssertEqual($0, data) } + + try row.withUnsafeData(named: "missing") { XCTAssertNil($0) } + try row.withUnsafeData(at: Column("missing")) { XCTAssertNil($0) } } do { let emptyData = Data() - let row = Row(["a": emptyData]) + let row: Row = ["a": emptyData] - XCTAssertEqual(row.dataNoCopy(atIndex: 0), emptyData) - XCTAssertEqual(row.dataNoCopy(named: "a"), emptyData) - XCTAssertEqual(row.dataNoCopy(Column("a")), emptyData) + try row.withUnsafeData(atIndex: 0) { XCTAssertEqual($0, emptyData) } + try row.withUnsafeData(named: "a") { XCTAssertEqual($0, emptyData) } + try row.withUnsafeData(at: Column("a")) { XCTAssertEqual($0, emptyData) } } do { - let row = Row(["a": nil]) + let row: Row = ["a": nil] - XCTAssertNil(row.dataNoCopy(atIndex: 0)) - XCTAssertNil(row.dataNoCopy(named: "a")) - XCTAssertNil(row.dataNoCopy(Column("a"))) + try row.withUnsafeData(atIndex: 0) { XCTAssertNil($0) } + try row.withUnsafeData(named: "a") { XCTAssertNil($0) } + try row.withUnsafeData(at: Column("a")) { XCTAssertNil($0) } } } diff --git a/Tests/GRDBTests/RowFromStatementTests.swift b/Tests/GRDBTests/RowFromStatementTests.swift index 38fd82b81..c42624a2b 100644 --- a/Tests/GRDBTests/RowFromStatementTests.swift +++ b/Tests/GRDBTests/RowFromStatementTests.swift @@ -127,7 +127,7 @@ class RowFromStatementTests : RowTestCase { } } - func testDataNoCopy() throws { + func testWithUnsafeData() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let data = "foo".data(using: .utf8)! @@ -137,17 +137,20 @@ class RowFromStatementTests : RowTestCase { while let row = try rows.next() { rowFetched = true - XCTAssertEqual(row.dataNoCopy(atIndex: 0), data) - XCTAssertEqual(row.dataNoCopy(named: "a"), data) - XCTAssertEqual(row.dataNoCopy(Column("a")), data) + try row.withUnsafeData(atIndex: 0) { XCTAssertEqual($0, data) } + try row.withUnsafeData(named: "a") { XCTAssertEqual($0, data) } + try row.withUnsafeData(at: Column("a")) { XCTAssertEqual($0, data) } - XCTAssertEqual(row.dataNoCopy(atIndex: 1), emptyData) - XCTAssertEqual(row.dataNoCopy(named: "b"), emptyData) - XCTAssertEqual(row.dataNoCopy(Column("b")), emptyData) + try row.withUnsafeData(atIndex: 1) { XCTAssertEqual($0, emptyData) } + try row.withUnsafeData(named: "b") { XCTAssertEqual($0, emptyData) } + try row.withUnsafeData(at: Column("b")) { XCTAssertEqual($0, emptyData) } + + try row.withUnsafeData(atIndex: 2) { XCTAssertNil($0) } + try row.withUnsafeData(named: "c") { XCTAssertNil($0) } + try row.withUnsafeData(at: Column("c")) { XCTAssertNil($0) } - XCTAssertNil(row.dataNoCopy(atIndex: 2)) - XCTAssertNil(row.dataNoCopy(named: "c")) - XCTAssertNil(row.dataNoCopy(Column("c"))) + try row.withUnsafeData(named: "missing") { XCTAssertNil($0) } + try row.withUnsafeData(at: Column("missing")) { XCTAssertNil($0) } } XCTAssertTrue(rowFetched) }