diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index 01b6d86ac..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,6 +237,20 @@ 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 diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 70c96c5a6..89ef2c4c8 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -50,9 +50,6 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_ /// - ``execute(sql:arguments:)`` /// - ``makeStatement(literal:)`` /// - ``makeStatement(sql:)`` -/// - ``DatabaseCursor`` -/// - ``Statement`` -/// - ``StatementArguments`` /// - ``SQLStatementCursor`` /// /// ### Database Transactions @@ -178,14 +175,14 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib 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) } } } @@ -417,9 +414,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib private func setupDoubleQuotedStringLiterals() { if configuration.acceptsDoubleQuotedStringLiterals { - enableDoubleQuotedStringLiterals(sqliteConnection) + _enableDoubleQuotedStringLiterals(sqliteConnection) } else { - disableDoubleQuotedStringLiterals(sqliteConnection) + _disableDoubleQuotedStringLiterals(sqliteConnection) } } diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index b6e72abcc..7fdc9d1ab 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -215,10 +215,15 @@ extension ResultCode: Sendable { } /// ```swift /// do { /// try player.insert(db) -/// } catch let error as DatabaseError -/// where error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY -/// { -/// // A foreign key constraint error occurred. +/// } 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 +/// } /// } /// ``` /// @@ -228,7 +233,11 @@ extension ResultCode: Sendable { } /// do { /// try player.insert(db) /// } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { -/// // A foreign key constraint error occurred. +/// // foreign key constraint error +/// } catch DatabaseError.SQLITE_CONSTRAINT { +/// // any other constraint error +/// } catch { +/// // any other database error /// } /// ``` /// diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index cec7abf0d..89a119452 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -260,9 +260,6 @@ extension DatabaseQueue: DatabaseReader { }) } - /// 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 @@ -287,7 +284,6 @@ extension DatabaseQueue: DatabaseReader { // MARK: - Database Observation - /// :nodoc: public func _add( observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, @@ -365,15 +361,39 @@ extension DatabaseQueue: DatabaseWriter { writer.async { updates(.success($0)) } } - /// Executes database operations outside of any transaction. - /// - /// The `updates` function runs in the writer dispatch queue, serialized - /// with all database updates. + /// Executes database operations, and returns their result after they have + /// finished executing. /// /// This method is identical to /// ``DatabaseWriter/writeWithoutTransaction(_:)-4qh1w`` /// - /// - parameter updates: A function that accesses the database. + /// For example: + /// + /// ```swift + /// let newPlayerCount = try dbQueue.inDatabase { 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`. public func inDatabase(_ updates: (Database) throws -> T) rethrows -> T { try writer.sync(updates) diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index a851de217..e1a555f1d 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -3,7 +3,7 @@ import Combine #endif import Dispatch -/// The protocol for types that can read from an SQLite database. +/// The protocol for types that read from an SQLite database. /// /// Do not declare new conformances to `DatabaseReader`. Only the /// ``DatabaseQueue``, ``DatabasePool``, and ``DatabaseSnapshot`` types are @@ -157,8 +157,8 @@ public protocol DatabaseReader: AnyObject, Sendable { /// 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 + /// 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 @@ -215,8 +215,8 @@ public protocol DatabaseReader: AnyObject, Sendable { /// } /// ``` /// - /// The `Database` argument to `value` is valid only during the execution of - /// the closure. Do not store or return the database connection for + /// 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 @@ -286,8 +286,8 @@ public protocol DatabaseReader: AnyObject, Sendable { /// } /// ``` /// - /// The `Database` argument to `value` is valid only during the execution of - /// the closure. Do not store or return the database connection for + /// 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. /// /// - warning: Database operations are not wrapped in a transaction. They @@ -310,7 +310,7 @@ public protocol DatabaseReader: AnyObject, Sendable { /// method instead. /// /// - parameter observation: a ValueObservation. - /// - returns: a cancellable. + /// - returns: A DatabaseCancellable that can stop the observation. func _add( observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, @@ -422,8 +422,8 @@ extension DatabaseReader { /// 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 + /// 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 closure which accesses the database. @@ -460,8 +460,8 @@ extension DatabaseReader { /// } /// ``` /// - /// The `Database` argument to `value` is valid only during the execution of - /// the closure. Do not store or return the database connection for + /// 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. /// /// - warning: Database operations are not wrapped in a transaction. They @@ -512,8 +512,8 @@ extension DatabaseReader { /// 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 + /// 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. @@ -538,11 +538,11 @@ extension DatabaseReader { @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) extension DatabasePublishers { - /// A Combine publisher that reads a value from the database. + /// A publisher that reads from the database. /// /// `Read` publishes exactly one element, or an error. /// - /// See ``DatabaseReader/readPublisher(receiveOn:value:)`` + /// You build such a publisher from ``DatabaseReader``. public struct Read: Publisher { public typealias Output = Output public typealias Failure = Error 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 3b88cef8e..01e5986a0 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -89,7 +89,6 @@ extension DatabaseSnapshot: DatabaseReader { // 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 51f77cca7..2ab122672 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -4,19 +4,24 @@ import Foundation /// /// To get `DatabaseValue` instances, you can: /// -/// - Fetch `DatabaseValue` from the database: +/// - Fetch `DatabaseValue` from a ``Database`` instace: /// /// ```swift /// try dbQueue.read { db in -/// let dbValue = try DatabaseValue.fetchOne(db, sql: "SELECT name FROM player") +/// let dbValue = try DatabaseValue.fetchOne(db, sql: """ +/// SELECT name FROM player +/// """) /// } /// ``` /// -/// - Extract `DatabaseValue` from a database row: +/// - Extract `DatabaseValue` from a database ``Row``: /// /// ```swift /// try dbQueue.read { db in -/// if let row = try Row.fetchOne(db, sql: "SELECT name FROM player") { +/// if let row = try Row.fetchOne(db, sql: """ +/// SELECT name FROM player +/// """) +/// { /// let dbValue = row[0] as DatabaseValue /// } /// } @@ -26,12 +31,26 @@ import Foundation /// ``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 @@ -44,7 +63,7 @@ public struct DatabaseValue: Hashable { /// /// Related SQLite documentation: @frozen - public enum Storage: Equatable { + public enum Storage { /// The NULL storage class. case null @@ -75,22 +94,6 @@ public struct DatabaseValue: Hashable { return data } } - - /// 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: 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 value. @@ -194,6 +197,24 @@ extension DatabaseValue.Storage: @unchecked Sendable { } // MARK: - Hashable & Equatable +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 + } + } +} + extension DatabaseValue: Equatable { /// Returns whether two ``DatabaseValue`` are equal. /// diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 515fed9e3..44afac439 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -1,4 +1,4 @@ -/// A type that can be converted to and from a ``DatabaseValue``. +/// A type that can convert itself into and out of a database value. /// /// `DatabaseValueConvertible` is adopted by `Bool`, `Int`, `String`, /// `Date`, etc. @@ -217,6 +217,9 @@ extension DatabaseValueConvertible { /// } /// ``` /// + /// 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. /// @@ -251,6 +254,9 @@ extension DatabaseValueConvertible { /// } /// ``` /// + /// Values are decoded from the leftmost column if the `adapter` argument + /// is nil. + /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. @@ -268,6 +274,9 @@ extension DatabaseValueConvertible { /// Returns a single value fetched from a prepared statement. /// + /// 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. /// @@ -314,6 +323,9 @@ extension DatabaseValueConvertible where Self: Hashable { /// } /// ``` /// + /// Values are decoded from the leftmost column if the `adapter` argument + /// is nil. + /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. @@ -349,6 +361,9 @@ extension DatabaseValueConvertible { /// } /// ``` /// + /// 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. /// @@ -384,6 +399,9 @@ extension DatabaseValueConvertible { /// } /// ``` /// + /// Values are decoded from the leftmost column if the `adapter` argument + /// is nil. + /// /// - parameters: /// - db: A database connection. /// - sql: An SQL string. @@ -403,6 +421,9 @@ extension DatabaseValueConvertible { /// Returns a single value fetched from an SQL query. /// + /// 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. /// @@ -447,6 +468,9 @@ extension DatabaseValueConvertible where Self: Hashable { /// } /// ``` /// + /// Values are decoded from the leftmost column if the `adapter` argument + /// is nil. + /// /// - parameters: /// - db: A database connection. /// - sql: An SQL string. @@ -494,6 +518,8 @@ extension DatabaseValueConvertible { /// } /// ``` /// + /// 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. /// @@ -532,6 +558,8 @@ extension DatabaseValueConvertible { /// } /// ``` /// + /// Values are decoded from the leftmost column. + /// /// - parameters: /// - db: A database connection. /// - request: A FetchRequest. @@ -544,6 +572,8 @@ extension DatabaseValueConvertible { /// Returns a single value fetched from a fetch request. /// + /// 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. /// @@ -601,6 +631,8 @@ extension DatabaseValueConvertible where Self: Hashable { /// } /// ``` /// + /// Values are decoded from the leftmost column. + /// /// - parameters: /// - db: A database connection. /// - request: A FetchRequest. @@ -641,6 +673,8 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { /// } /// ``` /// + /// 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. /// @@ -676,6 +710,8 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { /// } /// ``` /// + /// Values are decoded from the leftmost column. + /// /// - parameter db: A database connection. /// - returns: An array of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @@ -685,6 +721,8 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { /// Returns a single fetched value. /// + /// 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. /// @@ -739,6 +777,8 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable { /// } /// ``` /// + /// Values are decoded from the leftmost column. + /// /// - parameter db: A database connection. /// - returns: A set of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 7e04568e9..c4f0c5743 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -3,7 +3,7 @@ import Combine #endif import Dispatch -/// The protocol for types that can write into an SQLite database. +/// The protocol for types that write into an SQLite database. /// /// Do not declare new conformances to `DatabaseWriter`. Only the /// ``DatabaseQueue`` and ``DatabasePool`` types are valid conforming types. @@ -31,6 +31,7 @@ import Dispatch /// /// - ``concurrentRead(_:)`` /// - ``spawnConcurrentRead(_:)`` +/// - ``DatabaseFuture`` /// /// ### Exclusive Access to the Database /// @@ -78,9 +79,9 @@ public protocol DatabaseWriter: DatabaseReader { /// 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. + /// 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" @@ -117,9 +118,9 @@ public protocol DatabaseWriter: DatabaseReader { /// 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. + /// 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" @@ -161,9 +162,9 @@ public protocol DatabaseWriter: DatabaseReader { /// 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. + /// 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 @@ -194,9 +195,9 @@ public protocol DatabaseWriter: DatabaseReader { /// 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. + /// 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 @@ -226,9 +227,9 @@ public protocol DatabaseWriter: DatabaseReader { /// 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. + /// 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 @@ -353,9 +354,9 @@ extension DatabaseWriter { /// 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. + /// 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" @@ -407,7 +408,7 @@ extension DatabaseWriter { /// 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 + /// 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. /// @@ -563,9 +564,9 @@ extension DatabaseWriter { /// 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. + /// 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" @@ -599,9 +600,9 @@ extension DatabaseWriter { /// 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. + /// 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" @@ -649,9 +650,9 @@ extension DatabaseWriter { /// 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. + /// 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" @@ -762,9 +763,9 @@ extension DatabaseWriter { /// 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. + /// 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 accesses the database. @@ -826,7 +827,7 @@ extension DatabaseWriter { /// 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 ``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. /// @@ -867,15 +868,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 diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index a6b2c4b18..8c7d24711 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -38,13 +38,14 @@ /// - ``makePreparedRequest(_:forSingleResult:)`` /// - ``PreparedRequest`` /// -/// ### Support for Database Observation +/// ### Database Observation Support /// /// - ``databaseRegion(_:)`` /// /// ### Adapting the Fetched Rows /// /// - ``adapted(_:)`` +/// - ``AdaptedFetchRequest`` /// /// ### Supporting Types /// diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index cbd052911..b37822c02 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -2,6 +2,21 @@ import Foundation /// A database row. /// +/// 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 @@ -28,24 +43,24 @@ import Foundation /// - ``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`` -/// -/// ### Accessing Data Values -/// +/// - ``withUnsafeData(at:_:)`` /// - ``dataNoCopy(_:)`` -/// - ``dataNoCopy(atIndex:)`` -/// - ``dataNoCopy(named:)`` /// /// ### Row Scopes & Associated Rows /// @@ -55,22 +70,39 @@ import Foundation /// - ``unadapted`` /// - ``unscoped`` /// - ``subscript(_:)-4dx01`` -/// - ``subscript(_:)-6ge6t`` /// - ``subscript(_:)-8god3`` /// - ``subscript(_:)-jwnx`` +/// - ``subscript(_:)-6ge6t`` /// - ``PrefetchedRowsView`` /// - ``ScopesTreeView`` /// - ``ScopesView`` /// -/// ### Fetching Rows +/// ### 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 /// -/// - ``columnNames`` /// - ``count-5flaw`` -/// - ``databaseValues`` -/// - ``subscript(_:)-11eb`` -/// - ``RowIndex`` +/// - ``subscript(_:)-68yae`` +/// - ``Index`` /// /// ### Adapting Rows /// @@ -98,17 +130,30 @@ public final class Row { /// 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 @@ -630,99 +675,119 @@ 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: /// /// ```swift - /// let request = Book.including(required: Book.author) - /// let row = try Row.fetchOne(db, request)! + /// 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 { } + /// + /// // 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 book = try Book(row: bookRow) + /// let author: Author = bookRow["author"] + /// let country: Country = bookRow["country"] /// ``` /// - /// Associated records stored in nested associations are available, too: + /// See also: ``scopesTree`` /// - /// ```swift - /// let request = Book.including(required: Book.author.including(required: Author.country)) - /// let row = try Row.fetchOne(db, request)! - /// - /// try print(Book(row: row).title) - /// // Prints "Moby-Dick" - /// - /// 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: /// /// ```swift - /// let request = Book.including(optional: Book.author) - /// let row = try Row.fetchOne(db, request)! + /// 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 { } + /// + /// // 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 book = try Book(row: bookRow) + /// let author: Author? = bookRow["author"] + /// let country: Country? = bookRow["country"] /// ``` /// - /// Associated records stored in nested associations are available, too: + /// See also: ``scopesTree`` /// - /// ```swift - /// let request = Book.including(optional: Book.author.including(optional: Author.country)) - /// let row = try Row.fetchOne(db, request)! - /// - /// try print(Book(row: row).title) - /// // Prints "Moby-Dick" - /// - /// 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: /// /// ```swift + /// struct Author: TableRecord, FetchableRecord { + /// static let books = hasMany(Book.self) + /// } + /// + /// struct Book: TableRecord, FetchableRecord { } + /// /// let request = Author.including(all: Author.books) - /// let row = try Row.fetchOne(db, request)! + /// let authorRow = try Row.fetchOne(db, request)! /// - /// try print(Author(row: row).name) - /// // Prints "Herman Melville" - /// - /// let books: [Book] = row["books"] - /// print(books[0].title) - /// // Prints "Moby-Dick" + /// 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 @@ -732,21 +797,30 @@ extension Row { 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: /// /// ```swift + /// struct Author: TableRecord, FetchableRecord { + /// static let books = hasMany(Book.self) + /// } + /// + /// struct Book: TableRecord, FetchableRecord, Hashable { } + /// /// let request = Author.including(all: Author.books) - /// let row = try Row.fetchOne(db, request)! + /// let authorRow = try Row.fetchOne(db, request)! /// - /// try print(Author(row: row).name) - /// // Prints "Herman Melville" - /// - /// let books: Set = row["books"] - /// print(books.first!.title) - /// // Prints "Moby-Dick" + /// 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) } @@ -756,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) @@ -826,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) } @@ -1192,8 +1350,8 @@ extension Row { /// SELECT * FROM player /// """) /// while let row = try rows.next() { -/// let id: Int64 = row[0] -/// let name: String = row[1] +/// let id: Int64 = row["id"] +/// let name: String = row["name"] /// } /// } /// ``` @@ -1227,17 +1385,25 @@ 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 + /// 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[0] - /// let name: String = row[1] + /// 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()`. @@ -1266,8 +1432,16 @@ 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. @@ -1287,8 +1461,16 @@ 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. @@ -1308,8 +1490,16 @@ 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. @@ -1337,16 +1527,24 @@ 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 + /// 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[0] - /// let name: String = row[1] + /// 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()`. @@ -1376,11 +1574,15 @@ 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. @@ -1401,11 +1603,15 @@ 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. @@ -1426,11 +1632,15 @@ 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. @@ -1456,17 +1666,32 @@ extension Row { /// Returns a cursor over rows fetched from a fetch request. /// - /// let request = Player.all() - /// let rows = try Row.fetchCursor(db, request) // RowCursor + /// 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()`. @@ -1490,8 +1715,23 @@ 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. @@ -1507,8 +1747,23 @@ 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. @@ -1528,8 +1783,23 @@ 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. @@ -1562,8 +1832,8 @@ extension FetchRequest { /// """ /// let rows = try request.fetchCursor(db) /// while let row = try rows.next() { - /// let id: Int64 = row[0] - /// let name: String = row[1] + /// let id: Int64 = row["id"] + /// let name: String = row["name"] /// } /// } /// ``` @@ -1654,16 +1924,12 @@ extension FetchRequest { } extension Row: RandomAccessCollection { + public var startIndex: Index { Index(0) } - /// The index of the first (ColumnName, DatabaseValue) pair. - public var startIndex: RowIndex { RowIndex(0) } + public var endIndex: Index { Index(count) } - /// The "past-the-end" index, successor of the index of the last - /// (ColumnName, DatabaseValue) pair. - 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 ( @@ -1788,68 +2054,55 @@ extension Row: ExpressibleByDictionaryLiteral { } } -// MARK: - RowIndex +// MARK: - Index -/// Indexes to (ColumnName, DatabaseValue) pairs in a database row. -public struct RowIndex { - let index: Int - init(_ index: Int) { self.index = 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 RowIndex: Equatable { - public static func == (lhs: RowIndex, rhs: RowIndex) -> Bool { +extension Row.Index: Equatable { + public static func == (lhs: Self, rhs: Self) -> Bool { lhs.index == rhs.index } } -extension RowIndex: Comparable { - public static func < (lhs: RowIndex, rhs: RowIndex) -> Bool { +extension Row.Index: Comparable { + public static func < (lhs: Self, rhs: Self) -> Bool { lhs.index < rhs.index } } -extension RowIndex: Strideable { - public func distance(to other: RowIndex) -> Int { +extension Row.Index: Strideable { + public func distance(to other: Self) -> Int { other.index - index } - 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 } @@ -1864,69 +2117,57 @@ extension Row { self.prefetchedRows = prefetchedRows } - 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) - } - - /// 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 { @@ -1936,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 { @@ -1990,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) @@ -2033,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 { diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index f26219254..77754ed64 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -41,8 +41,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 +91,6 @@ public struct _LayoutedColumnMapping { } } -/// :nodoc: extension _LayoutedColumnMapping: _LayoutedRowAdapter { /// Returns self. public var _mapping: _LayoutedColumnMapping { self } @@ -102,7 +99,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 +114,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 +125,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 +136,41 @@ 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`. +/// `RowAdapter` is a protocol that helps two incompatible row interfaces +/// working together. /// -/// :nodoc: -public protocol _RowAdapter { +/// 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) +/// +/// ## 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,29 +193,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. -/// -/// 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) -/// -/// ## Topics -/// -/// ### Built-in Adapters -/// -/// - ``ColumnMapping`` -/// - ``EmptyRowAdapter`` -/// - ``RangeRowAdapter`` -/// - ``RenameColumnAdapter`` -/// - ``ScopeAdapter`` -/// - ``SuffixRowAdapter`` -public protocol RowAdapter: _RowAdapter { } - extension RowAdapter { /// Returns an adapter based on self, with added scopes. /// @@ -232,7 +221,6 @@ public struct EmptyRowAdapter: RowAdapter { /// Creates an EmptyRowAdapter public init() { } - /// :nodoc: public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter { _LayoutedColumnMapping(layoutColumns: []) } @@ -255,7 +243,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 @@ -296,7 +283,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)) } @@ -325,7 +311,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]) } @@ -401,7 +386,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 @@ -447,7 +431,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) diff --git a/GRDB/Core/SQL.swift b/GRDB/Core/SQL.swift index b656cb16c..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,26 +260,30 @@ 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) } @@ -267,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)) @@ -291,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)) @@ -312,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 9183ba3d6..a9e6304e4 100644 --- a/GRDB/Core/SQLRequest.swift +++ b/GRDB/Core/SQLRequest.swift @@ -20,14 +20,24 @@ /// /// ## Topics /// -/// ### Initializers +/// ### 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(sql:arguments:adapter:cached:)-3qq8t`` -/// -/// ### Convenience Initializers of `SQLRequest` -/// /// - ``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 @@ -210,6 +220,7 @@ extension SQLRequest: ExpressibleByStringInterpolation { self.init(sql: extendedGraphemeClusterLiteral) } + /// Creates an `SQLRequest` from the given literal SQL string. public init(stringLiteral: String) { self.init(sql: stringLiteral) } diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 480b2fe86..7567b128b 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -27,6 +27,33 @@ extension String { /// 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 @@ -39,6 +66,7 @@ extension String { /// - ``setArguments(_:)`` /// - ``setUncheckedArguments(_:)`` /// - ``validateArguments(_:)`` +/// - ``StatementArguments`` /// /// ### Statement Informations /// @@ -477,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 } @@ -493,10 +518,6 @@ public protocol _DatabaseCursor: Cursor { func _element(sqliteStatement: SQLiteStatement) throws -> Element } -/// A `DatabaseCursor` is as ``Cursor`` that iterates the result of a -/// prepared ``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 { diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 501ebdf7d..27995317e 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -1,4 +1,4 @@ -/// A type that can be extracted from the low-level C interface to +/// A type that can decode itself from the low-level C interface to /// SQLite results. /// /// `StatementColumnConvertible` is adopted by `Bool`, `Int`, `String`, @@ -266,6 +266,9 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// } /// ``` /// + /// 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. /// @@ -300,6 +303,9 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// } /// ``` /// + /// Values are decoded from the leftmost column if the `adapter` argument + /// is nil. + /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. @@ -317,6 +323,9 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// Returns a single value fetched from a prepared statement. /// + /// 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. /// @@ -366,6 +375,9 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash /// } /// ``` /// + /// Values are decoded from the leftmost column if the `adapter` argument + /// is nil. + /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. @@ -401,6 +413,9 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// } /// ``` /// + /// 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. /// @@ -436,6 +451,9 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// } /// ``` /// + /// Values are decoded from the leftmost column if the `adapter` argument + /// is nil. + /// /// - parameters: /// - db: A database connection. /// - sql: An SQL string. @@ -455,6 +473,9 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// Returns a single value fetched from an SQL query. /// + /// 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. /// @@ -499,6 +520,9 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash /// } /// ``` /// + /// Values are decoded from the leftmost column if the `adapter` argument + /// is nil. + /// /// - parameters: /// - db: A database connection. /// - sql: An SQL string. @@ -546,6 +570,8 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// } /// ``` /// + /// 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. /// @@ -586,6 +612,8 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// } /// ``` /// + /// Values are decoded from the leftmost column. + /// /// - parameters: /// - db: A database connection. /// - request: A FetchRequest. @@ -598,6 +626,8 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// Returns a single value fetched from a fetch request. /// + /// 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. /// @@ -655,6 +685,8 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash /// } /// ``` /// + /// Values are decoded from the leftmost column. + /// /// - parameters: /// - db: A database connection. /// - request: A FetchRequest. @@ -695,6 +727,8 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// } /// ``` /// + /// 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. /// @@ -730,6 +764,8 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// } /// ``` /// + /// Values are decoded from the leftmost column. + /// /// - parameter db: A database connection. /// - returns: An array of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @@ -739,6 +775,8 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// Returns a single fetched value. /// + /// 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. /// @@ -793,6 +831,8 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// } /// ``` /// + /// Values are decoded from the leftmost column. + /// /// - parameter db: A database connection. /// - returns: A set of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. diff --git a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift index 63cc69c0c..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,9 +84,9 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC } self.init(components.dateComponents, format: components.format) } - - // MARK: - DatabaseValueConvertible adoption - +} + +extension DatabaseDateComponents: DatabaseValueConvertible { /// Returns a TEXT database value. public var databaseValue: DatabaseValue { let dateString: String? @@ -151,14 +149,9 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC 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) @@ -168,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/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 5d2b2d3d6..531b8ce42 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -718,18 +718,19 @@ class DatabaseObservationBroker { // MARK: - TransactionObserver -/// A `TransactionObserver` is notified of all database changes and transactions -/// performed in a database. +/// A type that tracks all database changes and transactions performed in +/// a database. /// -/// An observer starts receiving notifications after it has been added to a -/// database connection with the +/// 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 protected dispatch queue, serialized -/// with all database updates. +/// 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`). 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 index 21a74c5b4..5a7b503aa 100644 --- a/GRDB/Documentation.docc/Documentation.md +++ b/GRDB/Documentation.docc/Documentation.md @@ -9,81 +9,29 @@ GRDB provides raw access to SQL and advanced SQLite features, because one someti ## Topics -### Database Connections +### Fundamentals -- ``Configuration`` -- ``DatabasePool`` -- ``DatabaseQueue`` -- ``DatabaseSnapshot`` -- ``Database`` -- ``DatabaseReader`` -- ``DatabaseWriter`` - -### Errors - -- ``DatabaseError`` -- ``PersistenceError`` +- +- +- ### Migrations - ``DatabaseMigrator`` -### Database Rows & Values +### Record Types and the Query Interface -- ``DatabaseValue`` -- ``Row`` -- ``DatabaseValueConvertible`` -- ``StatementColumnConvertible`` - -### Records - -- ``Record`` -- ``EncodableRecord`` -- ``FetchableRecord`` -- ``MutablePersistableRecord`` -- ``PersistableRecord`` -- ``TableRecord`` - -### Requests - -- ``AdaptedFetchRequest`` -- ``QueryInterfaceRequest`` -- ``SQLRequest`` -- ``FetchRequest`` - -### The Query Interface - -- ``AllColumns`` -- ``Column`` -- ``CommonTableExpression`` -- ``ForeignKey`` -- ``QueryInterfaceRequest`` -- ``SQLExpression`` -- ``SQLOrdering`` -- ``SQLSelection`` -- ``SQLSubquery`` -- ``Table`` -- ``Association`` -- ``ColumnExpression`` -- ``DerivableRequest`` -- ``SQLExpressible`` -- ``SQLOrderingTerm`` -- ``SQLSelectable`` -- ``SQLSpecificExpressible`` -- ``SQLSubqueryable`` +- ### Database Observation -- ``AsyncValueObservation`` -- ``DatabaseRegion`` -- ``DatabaseRegionConvertible`` -- ``DatabaseRegionObservation`` -- ``SharedValueObservation`` -- ``ValueObservation`` -- ``ValueObservationScheduler`` -- ``TransactionObserver`` +- ### 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/SQLLanguage.md b/GRDB/Documentation.docc/SQLLanguage.md new file mode 100644 index 000000000..cdae48a7f --- /dev/null +++ b/GRDB/Documentation.docc/SQLLanguage.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 916fc7ad0..d93549816 100644 --- a/GRDB/FTS/FTS3.swift +++ b/GRDB/FTS/FTS3.swift @@ -1,13 +1,15 @@ /// The virtual table module for the FTS3 full-text engine. /// +/// To create FTS3 tables, use the ``Database`` method +/// ``Database/create(virtualTable:ifNotExists:using:_:)``. +/// /// Related SQLite documentation: /// /// ## Topics /// -/// ### Creating Full-Text Virtual Tables +/// ### The FTS3 Module /// /// - ``init()`` -/// - ``Database/create(virtualTable:ifNotExists:using:_:)`` /// - ``FTS3TableDefinition`` /// - ``FTS3TokenizerDescriptor`` /// diff --git a/GRDB/FTS/FTS3Pattern.swift b/GRDB/FTS/FTS3Pattern.swift index c6b1656d3..9862566f2 100644 --- a/GRDB/FTS/FTS3Pattern.swift +++ b/GRDB/FTS/FTS3Pattern.swift @@ -1,4 +1,4 @@ -/// An ``FTS3`` search pattern. +/// A full text pattern for querying FTS3 virtual tables. /// /// `FTS3Pattern` can be used with both ``FTS3`` and ``FTS4`` tables. /// diff --git a/GRDB/FTS/FTS4.swift b/GRDB/FTS/FTS4.swift index bb1de5fd1..ab5cbefef 100644 --- a/GRDB/FTS/FTS4.swift +++ b/GRDB/FTS/FTS4.swift @@ -1,13 +1,15 @@ /// The virtual table module for the FTS4 full-text engine. /// +/// To create FTS4 tables, use the ``Database`` method +/// ``Database/create(virtualTable:ifNotExists:using:_:)``. +/// /// Related SQLite documentation: /// /// ## Topics /// -/// ### Creating Full-Text Virtual Tables +/// ### The FTS4 Module /// /// - ``init()`` -/// - ``Database/create(virtualTable:ifNotExists:using:_:)`` /// - ``FTS4TableDefinition`` /// - ``FTS4ColumnDefinition`` public struct FTS4 { diff --git a/GRDB/FTS/FTS5Pattern.swift b/GRDB/FTS/FTS5Pattern.swift index df265c35f..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. diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 0d7cf9956..d997af7c4 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -537,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 95d61e469..49fbc559c 100644 --- a/GRDB/QueryInterface/FTS3+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS3+QueryInterface.swift @@ -29,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 62f41b4ce..b49f10514 100644 --- a/GRDB/QueryInterface/FTS5+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS5+QueryInterface.swift @@ -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 a14c89643..222ac6dcb 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -1,25 +1,25 @@ 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 associations that define a connection between two -/// record types. +/// ``Association`` feeds methods of the ``JoinableRequest`` protocol. They are +/// built from a ``TableRecord`` type, or a ``Table`` instance. /// /// ## Topics /// -/// ### Association To One +/// ### Instance Methods +/// +/// - ``forKey(_:)-247af`` +/// - ``forKey(_:)-54yh6`` +/// +/// ### Associations To One /// /// - ``BelongsToAssociation`` /// - ``HasOneAssociation`` /// - ``HasOneThroughAssociation`` /// - ``AssociationToOne`` /// -/// ### Association To Many +/// ### Associations To Many /// /// - ``HasManyAssociation`` /// - ``HasManyThroughAssociation`` @@ -27,13 +27,13 @@ public protocol _Association { /// /// ### Associations to Common Table Expressions /// -/// - ``CommonTableExpression`` /// - ``JoinAssociation`` /// -/// ### Association Aggregates +/// ### Supporting Types /// -/// - ``AssociationAggregate`` -public protocol Association: _Association, DerivableRequest { +/// - ``ForeignKey`` +/// - ``Inflections`` +public protocol Association: DerivableRequest { // OriginRowDecoder and RowDecoder inherited from DerivableRequest provide // type safety: // @@ -42,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 } @@ -84,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) @@ -147,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) @@ -210,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 discarded: - /// - /// // 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 @@ -240,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 @@ -264,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 @@ -287,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 @@ -319,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() @@ -372,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 @@ -381,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 @@ -409,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 { @@ -423,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..432a82d40 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,614 +558,448 @@ 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 { + /// Returns a logically negated aggregate. + /// + /// For example: + /// + /// Author.having(!Author.books.isEmpty) + public static prefix func ! (aggregate: Self) -> Self { + aggregate.map { !$0 } + } + + /// Groups two aggregates with the `AND` SQL operator. + /// + /// For example: + /// + /// Author.having(Author.books.isEmpty && Author.paintings.isEmpty) + public static func && (lhs: Self, rhs: Self) -> Self { + combine(lhs, rhs, with: &&) + } + + // TODO: test + public static func && (lhs: Self, rhs: some SQLExpressible) -> Self { + lhs.map { $0 && rhs } + } + + // TODO: test + public static func && (lhs: some SQLExpressible, rhs: Self) -> Self { + rhs.map { lhs && $0 } + } + + + /// Groups two aggregates with the `OR` SQL operator. + /// + /// For example: + /// + /// Author.having(!Author.books.isEmpty || !Author.paintings.isEmpty) + public static func || (lhs: Self, rhs: Self) -> Self { + combine(lhs, rhs, with: ||) + } + + // TODO: test + public static func || (lhs: Self, rhs: some SQLExpressible) -> Self { + lhs.map { $0 || rhs } + } + + // TODO: test + 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 { + /// Returns an aggregate that compares two aggregates with the `=` SQL operator. + /// + /// For example: + /// + /// Author.having(Author.books.count == Author.paintings.count) + public static func == (lhs: Self, rhs: Self) -> Self { + combine(lhs, rhs, with: ==) + } + + /// Returns an aggregate that compares an aggregate with the `=` SQL operator. + /// + /// For example: + /// + /// Author.having(Author.books.count == 3) + public static func == (lhs: Self, rhs: some SQLExpressible) -> Self { + lhs.map { $0 == rhs } + } + + /// Returns an aggregate that compares an aggregate with the `=` SQL operator. + /// + /// For example: + /// + /// Author.having(3 == Author.books.count) + public static func == (lhs: some SQLExpressible, rhs: Self) -> Self { + rhs.map { lhs == $0 } + } + + /// Returns an aggregate that checks the boolean value of an aggregate. + /// + /// For example: + /// + /// Author.having(Author.books.isEmpty == false) + public static func == (lhs: Self, rhs: Bool) -> Self { + lhs.map { $0 == rhs } + } + + /// Returns an aggregate that checks the boolean value of an aggregate. + /// + /// For example: + /// + /// Author.having(false == Author.books.isEmpty) + public static func == (lhs: Bool, rhs: Self) -> Self { + 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 static func != (lhs: Self, rhs: Self) -> Self { + combine(lhs, rhs, with: !=) + } + + /// Returns an aggregate that compares an aggregate with the `<>` SQL operator. + /// + /// For example: + /// + /// Author.having(Author.books.count != 3) + public static func != (lhs: Self, rhs: some SQLExpressible) -> Self { + lhs.map { $0 != rhs } + } + + /// Returns an aggregate that compares an aggregate with the `<>` SQL operator. + /// + /// For example: + /// + /// Author.having(3 != Author.books.count) + public static func != (lhs: some SQLExpressible, rhs: Self) -> Self { + rhs.map { lhs != $0 } + } + + /// Returns an aggregate that checks the boolean value of an aggregate. + /// + /// For example: + /// + /// Author.having(Author.books.isEmpty != true) + public static func != (lhs: Self, rhs: Bool) -> Self { + lhs.map { $0 != rhs } + } + + /// Returns an aggregate that checks the boolean value of an aggregate. + /// + /// For example: + /// + /// Author.having(true != Author.books.isEmpty) + public static func != (lhs: Bool, rhs: Self) -> Self { + 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 static func === (lhs: Self, rhs: Self) -> Self { + 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 static func === (lhs: Self, rhs: some SQLExpressible) -> Self { + 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 static func === (lhs: some SQLExpressible, rhs: Self) -> Self { + 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 static func !== (lhs: Self, rhs: Self) -> Self { + 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 static func !== (lhs: Self, rhs: some SQLExpressible) -> Self { + 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 static func !== (lhs: some 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 { + /// Returns an aggregate that compares two aggregates with the `<=` SQL operator. + /// + /// For example: + /// + /// Author.having(Author.books.count <= Author.paintings.count) + public static func <= (lhs: Self, rhs: Self) -> Self { + combine(lhs, rhs, with: <=) + } + + /// Returns an aggregate that compares an aggregate with the `<=` SQL operator. + /// + /// For example: + /// + /// Author.having(Author.books.count <= 3) + public static func <= (lhs: Self, rhs: some SQLExpressible) -> Self { + lhs.map { $0 <= rhs } + } + + /// Returns an aggregate that compares an aggregate with the `<=` SQL operator. + /// + /// For example: + /// + /// Author.having(3 <= Author.books.count) + public static func <= (lhs: some SQLExpressible, rhs: Self) -> Self { + 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 static func < (lhs: Self, rhs: Self) -> Self { + combine(lhs, rhs, with: <) + } + + /// Returns an aggregate that compares an aggregate with the `<` SQL operator. + /// + /// For example: + /// + /// Author.having(Author.books.count < 3) + public static func < (lhs: Self, rhs: some SQLExpressible) -> Self { + lhs.map { $0 < rhs } + } + + /// Returns an aggregate that compares an aggregate with the `<` SQL operator. + /// + /// For example: + /// + /// Author.having(3 < Author.books.count) + public static func < (lhs: some SQLExpressible, rhs: Self) -> Self { + 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 static func > (lhs: Self, rhs: Self) -> Self { + combine(lhs, rhs, with: >) + } + + /// Returns an aggregate that compares an aggregate with the `>` SQL operator. + /// + /// For example: + /// + /// Author.having(Author.books.count > 3) + public static func > (lhs: Self, rhs: some SQLExpressible) -> Self { + lhs.map { $0 > rhs } + } + + /// Returns an aggregate that compares an aggregate with the `>` SQL operator. + /// + /// For example: + /// + /// Author.having(3 > Author.books.count) + public static func > (lhs: some SQLExpressible, rhs: Self) -> Self { + 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 static func >= (lhs: Self, rhs: Self) -> Self { + combine(lhs, rhs, with: >=) + } + + /// Returns an aggregate that compares an aggregate with the `>=` SQL operator. + /// + /// For example: + /// + /// Author.having(Author.books.count >= 3) + public static func >= (lhs: Self, rhs: some SQLExpressible) -> Self { + lhs.map { $0 >= rhs } + } + + /// Returns an aggregate that compares an aggregate with the `>=` SQL operator. + /// + /// For example: + /// + /// Author.having(3 >= Author.books.count) + 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 { + /// Returns an arithmetically negated aggregate. + /// + /// For example: + /// + /// Author.annotated(with: -Author.books.count) + public static prefix func - (aggregate: Self) -> Self { + 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 static func + (lhs: Self, rhs: Self) -> Self { + 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 static func + (lhs: Self, rhs: some SQLExpressible) -> Self { + 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 static func + (lhs: some SQLExpressible, rhs: Self) -> Self { + 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 static func - (lhs: Self, rhs: Self) -> Self { + 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 static func - (lhs: Self, rhs: some SQLExpressible) -> Self { + 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 static func - (lhs: some SQLExpressible, rhs: Self) -> Self { + 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 static func * (lhs: Self, rhs: Self) -> Self { + 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 static func * (lhs: Self, rhs: some SQLExpressible) -> Self { + 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 static func * (lhs: some SQLExpressible, rhs: Self) -> Self { + 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 static func / (lhs: Self, rhs: Self) -> Self { + 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 static func / (lhs: Self, rhs: some SQLExpressible) -> Self { + 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 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 { + /// Returns an aggregate that evaluates the `IFNULL` SQL function. + /// + /// Team.annotated(with: Team.players.min(Column("score")) ?? 0) + public static func ?? (lhs: Self, rhs: some SQLExpressible) -> Self { + lhs + .map { $0 ?? rhs } + .with { $0.key = lhs.key } // Preserve key + } } // MARK: - ABS(...) 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/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index a3695fca8..e3415ff5a 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -17,19 +17,22 @@ // playerRequest.including(required: Player.team) // OK // fruitRequest.including(required: Player.team) // Does not compile -/// A request that builds SQL query with Swift. +/// A request that builds SQL queries with Swift. /// -/// For example: +/// You build a `QueryInterfaceRequest` from a ``TableRecord`` type, or a +/// ``Table`` instance. For example: /// /// ```swift +/// struct Player: TableRecord, FetchableRecord, DecodableRecord { } +/// /// try dbQueue.read { db in /// // SELECT * FROM player -/// // WHERE score > 1000 -/// // ORDER BY name +/// // WHERE name = 'O''Reilly' +/// // ORDER BY score DESC /// let request = Player -/// .filter(Column("score") > 1000) -/// .order(Column("name")) -/// let players = try request.fetchAll(db) // [Player] +/// .filter(Column("name") == "O'Reilly") +/// .order(Column("score").desc) +/// let players: [Player] = try request.fetchAll(db) /// } /// ``` /// @@ -362,7 +365,7 @@ extension QueryInterfaceRequest: AggregatingRequest { } } -extension QueryInterfaceRequest: _JoinableRequest { +extension QueryInterfaceRequest: JoinableRequest { public func _including(all association: _SQLAssociation) -> Self { with { $0.relation = $0.relation._including(all: association) @@ -394,8 +397,6 @@ extension QueryInterfaceRequest: _JoinableRequest { } } -extension QueryInterfaceRequest: JoinableRequest { } - extension QueryInterfaceRequest: TableRequest { public var databaseTableName: String { relation.source.tableName diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 65ad94591..2ee094189 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -347,9 +347,10 @@ public protocol TableRequest { /// // JOIN author ON author.id = book.authorId /// // WHERE book.publishDate >= author.deathDate /// let authorAlias = TableAlias() - /// let request = Book + /// 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: @@ -360,9 +361,10 @@ public protocol TableRequest { /// // JOIN author ON author.id = book.authorId /// // ORDER BY author.name, book.title /// let authorAlias = TableAlias() - /// let request = Book + /// 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 @@ -376,10 +378,11 @@ public protocol TableRequest { /// // WHERE b.publishDate >= a.deathDate /// let bookAlias = TableAlias(name: "b") /// let authorAlias = TableAlias(name: "a") - /// let request = Book.aliased(bookAlias) + /// 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 } @@ -480,7 +483,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { /// /// ```swift /// // SELECT * FROM player WHERE id = 1 - /// let request = Player.all().filter(keys: ["id": 1]) + /// let request = Player.all().filter(key: ["id": 1]) /// /// // SELECT * FROM player WHERE email = 'arthur@example.com' /// let request = Player.all().filter(key: ["email": "arthur@example.com"]) @@ -495,7 +498,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { /// 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 + /// - parameter key: A unique key. public func filter(key: [String: (any DatabaseValueConvertible)?]?) -> Self { guard let key else { return none() @@ -614,6 +617,19 @@ where Self: FilteredRequest, extension TableRequest where Self: OrderedRequest { /// 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 @@ -1017,8 +1033,32 @@ extension OrderedRequest { // MARK: - JoinableRequest -/// Implementation details of `JoinableRequest`. -public protocol _JoinableRequest { +/// A request that can join and prefetch associations. +/// +/// `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 @@ -1043,21 +1083,6 @@ public protocol _JoinableRequest { func _joining(required association: _SQLAssociation) -> Self } -/// A request that can join and prefetch associations. -/// -/// ## Topics -/// -/// ### Associations -/// -/// - ``annotated(withOptional:)`` -/// - ``annotated(withRequired:)`` -/// - ``including(all:)`` -/// - ``including(optional:)`` -/// - ``including(required:)`` -/// - ``joining(optional:)`` -/// - ``joining(required:)`` -public protocol JoinableRequest: TypedRequest, _JoinableRequest { } - extension JoinableRequest { /// Returns a request that fetches all records associated with each record /// in this request. @@ -1271,7 +1296,8 @@ extension JoinableRequest where Self: SelectionRequest { // MARK: - DerivableRequest -/// The base protocol for ``QueryInterfaceRequest`` and ``Association``. +/// `DerivableRequest` is the base protocol for ``QueryInterfaceRequest`` +/// and ``Association``. /// /// Most features of `DerivableRequest` come from the protocols it /// inherits from. diff --git a/GRDB/QueryInterface/SQL/Column.swift b/GRDB/QueryInterface/SQL/Column.swift index a95c2f84c..331789d45 100644 --- a/GRDB/QueryInterface/SQL/Column.swift +++ b/GRDB/QueryInterface/SQL/Column.swift @@ -1,4 +1,4 @@ -/// A column in a database table. +/// A type that represents a column in a database table. /// /// ## Topics /// @@ -16,9 +16,12 @@ /// - ``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 } } 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 a0a2780e2..e9de5892d 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -1692,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 } @@ -1709,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 @@ -1761,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)) } @@ -1785,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)) } @@ -1807,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) @@ -1857,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) } @@ -1917,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) } @@ -1926,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 f981aa316..e7b18f974 100644 --- a/GRDB/QueryInterface/SQL/SQLOrdering.swift +++ b/GRDB/QueryInterface/SQL/SQLOrdering.swift @@ -129,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 f70f89a31..aec58de09 100644 --- a/GRDB/QueryInterface/SQL/SQLSelection.swift +++ b/GRDB/QueryInterface/SQL/SQLSelection.swift @@ -279,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 } diff --git a/GRDB/QueryInterface/SQL/SQLSubquery.swift b/GRDB/QueryInterface/SQL/SQLSubquery.swift index 5e1b1c51c..fb3d59584 100644 --- a/GRDB/QueryInterface/SQL/SQLSubquery.swift +++ b/GRDB/QueryInterface/SQL/SQLSubquery.swift @@ -87,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 6184a2361..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. /// /// ``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. /// /// ``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. /// /// ``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,14 +808,22 @@ 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) /// } + /// } + /// ``` /// /// The order in which the records are returned is undefined /// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)). @@ -455,17 +835,25 @@ extension Table where RowDecoder: FetchableRecord { /// elements are undefined. /// /// - parameter db: A database connection. - /// - returns: A cursor over fetched records. + /// - 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)). @@ -475,12 +863,20 @@ extension Table where RowDecoder: FetchableRecord { 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`` whenever an SQLite error occurs. @@ -490,11 +886,19 @@ extension Table where RowDecoder: FetchableRecord { } 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`` whenever an SQLite error occurs. @@ -506,14 +910,22 @@ 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"] /// } + /// } + /// ``` /// /// The order in which the rows are returned is undefined /// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)). @@ -525,17 +937,24 @@ extension Table where RowDecoder == Row { /// elements are undefined. /// /// - parameter db: A database connection. - /// - returns: A cursor over fetched records. + /// - 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)). @@ -545,24 +964,38 @@ extension Table where RowDecoder == Row { 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`` 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`` whenever an SQLite error occurs. @@ -574,18 +1007,13 @@ 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. - /// - /// // SELECT * FROM name - /// let table = Table("name") - /// let names = try table.fetchCursor(db) // Cursor of String - /// while let name = try names.next() { // String - /// ... - /// } + /// Returns a cursor over fetched values. /// /// The order in which the values are returned is undefined /// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)). /// + /// 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. /// @@ -593,34 +1021,32 @@ extension Table where RowDecoder: DatabaseValueConvertible { /// elements are undefined. /// /// - parameter db: A database connection. - /// - returns: A cursor over fetched records. + /// - 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] - /// - /// The order in which the values are returned is undefined - /// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)). + /// Values are decoded from the leftmost column. /// /// - parameter db: A database connection. + /// - 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. + /// - returns: An optional value. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchOne(_ db: Database) throws -> RowDecoder? { try all().fetchOne(db) @@ -628,13 +1054,12 @@ extension Table where RowDecoder: DatabaseValueConvertible { } 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. + /// - returns: A set of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchSet(_ db: Database) throws -> Set { try all().fetchSet(db) @@ -644,18 +1069,13 @@ 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. - /// - /// // SELECT * FROM name - /// let table = Table("name") - /// let names = try table.fetchCursor(db) // Cursor of String - /// while let name = try names.next() { // String - /// ... - /// } + /// Returns a cursor over fetched values. /// /// The order in which the values are returned is undefined /// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)). /// + /// 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. /// @@ -663,34 +1083,32 @@ extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConv /// elements are undefined. /// /// - parameter db: A database connection. - /// - returns: A cursor over fetched records. + /// - 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] - /// - /// The order in which the values are returned is undefined - /// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)). + /// Values are decoded from the leftmost column. /// /// - parameter db: A database connection. + /// - 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. + /// - returns: An optional value. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchOne(_ db: Database) throws -> RowDecoder? { try all().fetchOne(db) @@ -698,13 +1116,12 @@ extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConv } 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. + /// - returns: A set of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchSet(_ db: Database) throws -> Set { try all().fetchSet(db) @@ -714,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, @@ -740,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, @@ -767,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, @@ -799,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, @@ -824,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, @@ -850,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, @@ -881,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. @@ -900,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. @@ -920,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, @@ -944,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. @@ -976,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 { @@ -988,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 @@ -1122,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) } @@ -1178,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. @@ -1202,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. @@ -1226,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) @@ -1243,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 @@ -1274,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 { @@ -1309,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 @@ -1338,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 { @@ -1371,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 { @@ -1389,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 @@ -1409,14 +1853,18 @@ 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. @@ -1432,19 +1880,23 @@ 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`` whenever an SQLite error occurs. @discardableResult 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 4fa0d0103..219aad488 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -254,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. @@ -1607,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/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 e94b2f27b..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. /// /// ``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. /// /// ``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. /// /// ``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.swift b/GRDB/Record/EncodableRecord.swift index a91d530cc..336cae571 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -1,6 +1,14 @@ import Foundation // For JSONEncoder -/// A type that can be encoded in a database row. +/// 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 /// @@ -313,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] { diff --git a/GRDB/Record/FetchableRecord+TableRecord.swift b/GRDB/Record/FetchableRecord+TableRecord.swift index c90009d8e..ceb76c048 100644 --- a/GRDB/Record/FetchableRecord+TableRecord.swift +++ b/GRDB/Record/FetchableRecord+TableRecord.swift @@ -7,6 +7,8 @@ extension FetchableRecord where Self: TableRecord { /// For example: /// /// ```swift + /// struct Player: FetchableRecord, TableRecord { } + /// /// try dbQueue.read { db in /// // SELECT * FROM player /// let players = try Player.fetchCursor(db) @@ -37,6 +39,8 @@ extension FetchableRecord where Self: TableRecord { /// For example: /// /// ```swift + /// struct Player: FetchableRecord, TableRecord { } + /// /// try dbQueue.read { db in /// // SELECT * FROM player /// let players = try Player.fetchAll(db) @@ -57,6 +61,8 @@ extension FetchableRecord where Self: TableRecord { /// For example: /// /// ```swift + /// struct Player: FetchableRecord, TableRecord { } + /// /// try dbQueue.read { db in /// // SELECT * FROM player LIMIT 1 /// let player = try Player.fetchOne(db) @@ -76,6 +82,8 @@ extension FetchableRecord where Self: TableRecord & Hashable { /// For example: /// /// ```swift + /// struct Player: FetchableRecord, TableRecord, Hashable { } + /// /// try dbQueue.read { db in /// // SELECT * FROM player /// let players = try Player.fetchSet(db) diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index e339f4bf8..424664eeb 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -1,42 +1,35 @@ import Foundation -/// A type that can be decoded from a database row. +/// A type that can decode itself from a database row. +/// +/// To conform to `FetchableRecord`, provide an implementation for the +/// ``init(row:)-9w9yp`` initializer. This implementation is ready-made for +/// `Decodable` types. /// /// For example: /// /// ```swift +/// struct Player: FetchableRecord, Decodable { +/// var name: String +/// var score: Int +/// } +/// /// if let row = try Row.fetchOne(db, sql: "SELECT * FROM player") { /// let player = try Player(row: row) /// } /// ``` /// -/// The protocol comes with built-in methods that allow to fetch cursors, -/// arrays, sets, or single records: +/// If you add conformance to ``TableRecord``, the record type can generate +/// SQL queries for you: /// /// ```swift -/// let lastName = "O'Reilly" +/// struct Player: FetchableRecord, TableRecord, Decodable { +/// var name: String +/// var score: Int +/// } /// -/// // Raw SQL -/// let players = try Player.fetchAll(db, sql: """ -/// SELECT * FROM player WHERE lastName = ? -/// """, -/// arguments: [lastName]) -/// -/// // Prepared Statements -/// let statement = try db.makeStatement(sql: """ -/// SELECT * FROM player WHERE lastName = ? -/// """) -/// let players = try Player.fetchAll(statement, arguments: [lastName]) -/// -/// // SQL Requests -/// let request: SQLRequest = """ -/// SELECT * FROM player WHERE lastName = \(lastName) -/// """ -/// let players = try request.fetchAll(db) -/// -/// // Query Interface Requests -/// let request = Player.filter(Column("lastName") == lastName) -/// let players = try request.fetchAll(db) +/// let players = try Player.fetchAll(db) +/// let players = try Player.order(Column("score")).fetchAll(db) /// ``` /// /// ## Topics @@ -96,6 +89,8 @@ import Foundation /// - ``databaseDateDecodingStrategy-78y03`` /// - ``databaseDecodingUserInfo-77jim`` /// - ``databaseJSONDecoder(for:)-7lmxd`` +/// - ``DatabaseColumnDecodingStrategy`` +/// - ``DatabaseDateDecodingStrategy`` /// /// ### Supporting Types /// diff --git a/GRDB/Record/MutablePersistableRecord.swift b/GRDB/Record/MutablePersistableRecord.swift index 914082479..75a79741d 100644 --- a/GRDB/Record/MutablePersistableRecord.swift +++ b/GRDB/Record/MutablePersistableRecord.swift @@ -1,4 +1,48 @@ -/// A type that can be persisted in a database row. +/// 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 /// @@ -22,6 +66,8 @@ /// /// ### Updating a Record /// +/// See inherited ``TableRecord`` methods for batch updates. +/// /// - ``update(_:onConflict:)`` /// - ``update(_:onConflict:columns:)-4foo1`` /// - ``update(_:onConflict:columns:)-5hxyx`` @@ -50,16 +96,11 @@ /// - ``saveAndFetch(_:onConflict:as:)`` /// - ``saveAndFetch(_:onConflict:selection:fetch:)`` /// -/// ### Deleting Records +/// ### Deleting a Record +/// +/// See inherited ``TableRecord`` methods for batch deletes. /// /// - ``delete(_:)`` -/// - ``TableRecord/deleteAll(_:)`` -/// - ``TableRecord/deleteAll(_:ids:)`` -/// - ``TableRecord/deleteAll(_:keys:)-jbkm`` -/// - ``TableRecord/deleteAll(_:keys:)-5s1jg`` -/// - ``TableRecord/deleteOne(_:id:)`` -/// - ``TableRecord/deleteOne(_:key:)-413u8`` -/// - ``TableRecord/deleteOne(_:key:)-5pdh5`` /// /// ### Persistence Callbacks /// @@ -109,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 @@ -129,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) @@ -159,13 +204,14 @@ 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. @@ -198,13 +244,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 @@ -235,13 +283,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 @@ -307,7 +357,6 @@ public enum PersistenceError: Error { } extension PersistenceError: CustomStringConvertible { - /// :nodoc: public var description: String { switch self { case let .recordNotFound(databaseTableName: databaseTableName, key: key): @@ -340,35 +389,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 712984d95..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,18 @@ 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. If - /// nil, + /// nil, /// is used. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. @@ -51,47 +64,49 @@ extension PersistableRecord { /// /// 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 partial 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. If - /// nil, + /// 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, or any /// error thrown by the persistence callbacks defined by the record type. @@ -115,36 +130,38 @@ extension PersistableRecord { /// /// 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 partial 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. If - /// nil, + /// nil, /// is used. /// - parameter selection: The returned columns (must not be empty). /// - parameter fetch: A closure that executes its ``Statement`` argument. @@ -189,47 +206,49 @@ extension PersistableRecord { /// /// 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 partial 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. If - /// nil, + /// 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, or any /// error thrown by the persistence callbacks defined by the record type. @@ -254,36 +273,38 @@ extension PersistableRecord { /// /// 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 partial 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. If - /// nil, + /// nil, /// is used. /// - parameter selection: The returned columns (must not be empty). /// - parameter fetch: A closure that executes its ``Statement`` argument. diff --git a/GRDB/Record/PersistableRecord+Save.swift b/GRDB/Record/PersistableRecord+Save.swift index cd3482522..ea5b06796 100644 --- a/GRDB/Record/PersistableRecord+Save.swift +++ b/GRDB/Record/PersistableRecord+Save.swift @@ -10,7 +10,7 @@ extension PersistableRecord { /// /// - parameter db: A database connection. /// - parameter conflictResolution: A policy for conflict resolution. If - /// nil, + /// nil, /// is used. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. @@ -48,7 +48,7 @@ extension PersistableRecord { /// /// - parameter db: A database connection. /// - parameter conflictResolution: A policy for conflict resolution. If - /// nil, + /// nil, /// is used. /// - parameter returnedType: The type of the returned record. /// - returns: A record of type `returnedType`. The result can be nil when @@ -91,7 +91,7 @@ extension PersistableRecord { /// /// - parameter db: A database connection. /// - parameter conflictResolution: A policy for conflict resolution. If - /// nil, + /// nil, /// is used. /// - parameter selection: The returned columns (must not be empty). /// - parameter fetch: A function that executes it ``Statement`` argument. @@ -136,7 +136,7 @@ extension PersistableRecord { /// /// - parameter db: A database connection. /// - parameter conflictResolution: A policy for conflict resolution. If - /// nil, + /// nil, /// is used. /// - parameter returnedType: The type of the returned record. /// - returns: A record of type `returnedType`. The result can be nil when @@ -180,7 +180,7 @@ extension PersistableRecord { /// /// - parameter db: A database connection. /// - parameter conflictResolution: A policy for conflict resolution. If - /// nil, + /// nil, /// is used. /// - parameter selection: The returned columns (must not be empty). /// - parameter fetch: A function that executes it ``Statement`` argument. @@ -219,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 fb0a7260e..df5df0d3c 100644 --- a/GRDB/Record/PersistableRecord+Upsert.swift +++ b/GRDB/Record/PersistableRecord+Upsert.swift @@ -7,21 +7,25 @@ extension PersistableRecord { /// 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 @@ -51,20 +55,22 @@ extension PersistableRecord { /// (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 @@ -81,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. @@ -175,21 +183,25 @@ extension PersistableRecord { /// 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 @@ -220,20 +232,22 @@ extension PersistableRecord { /// (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 @@ -250,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. @@ -300,8 +316,8 @@ extension PersistableRecord { /// 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. 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 42a0dbcf6..c66d38812 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -1,6 +1,6 @@ // MARK: - Record -/// A base class for types that can decode database rows. +/// A base class for types that can be fetched and persisted in the database. /// /// ## Topics /// @@ -9,6 +9,10 @@ /// - ``init()`` /// - ``init(row:)`` /// +/// ### Encoding a Database Row +/// +/// - ``encode(to:)`` +/// /// ### Changes Tracking /// /// - ``databaseChanges`` @@ -50,7 +54,7 @@ open class Record { // MARK: - Core methods - /// The name of the database table used to build requests. + /// The name of the database table used to build SQL queries. /// /// Subclasses must override this method. For example: /// @@ -72,9 +76,9 @@ open class Record { 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: /// /// ```swift /// class Player: Record { } @@ -100,6 +104,33 @@ open class Record { [AllColumns()] } + /// Encodes the record into the provided persistence container. + /// + /// 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. + /// + /// For example: + /// + /// ```swift + /// class Player: Record { + /// var id: Int64? + /// var name: String? + /// + /// override 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" + /// 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 diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index 438046bb5..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,8 +257,19 @@ 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 + /// - returns: The number of deleted records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult public static func deleteAll(_ db: Database) throws -> Int { @@ -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,10 +596,14 @@ 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, @@ -412,10 +625,14 @@ 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, 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/SharedValueObservation.swift b/GRDB/ValueObservation/SharedValueObservation.swift index f30330d8d..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) /// /// 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 { } } -/// A shared value observation that shares a single underlying database -/// observation for all subscriptions, and thus spares database resources. +/// A shared value observation 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) /// -/// 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. /// /// - 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 15549b4a2..13dac99cc 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -10,17 +10,16 @@ import Foundation /// For example: /// /// ```swift +/// // Track all players /// let observation = ValueObservation.tracking { db in /// try Player.fetchAll(db) /// } /// -/// let cancellable = try observation.start( -/// in: dbQueue, -/// onError: { error in -/// print("An error occurred: \(error)") }, -/// 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)") +/// } /// ``` /// /// ## Topics @@ -32,13 +31,17 @@ import Foundation /// - ``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`` -/// - ``DatabasePublishers/Value`` /// - ``ValueObservationScheduler`` /// /// ### Mapping Values @@ -59,23 +62,18 @@ import Foundation /// - ``handleEvents(willStart:willFetch:willTrackRegion:databaseDidChange:didReceiveValue:didFail:didCancel:)`` /// - ``print(_:to:)`` /// -/// ### Creating A Shared Observation -/// -/// - ``shared(in:scheduling:extent:)`` -/// - ``SharedValueObservationExtent`` -/// /// ### 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 @@ -142,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), @@ -206,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( @@ -257,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) @@ -306,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. /// /// - 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, @@ -328,23 +338,27 @@ extension ValueObservation { } } -/// An asynchronous sequence of database changes. +/// An asynchronous sequence of values observed by a ``ValueObservation``. /// /// - 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 @@ -390,9 +404,6 @@ public struct AsyncValueObservation: AsyncSequence { } } - /// An asynchronous iterator that supplies database changes one at a time. - /// - /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) public struct Iterator: AsyncIteratorProtocol { var iterator: AsyncThrowingStream.AsyncIterator let cancellable: AnyDatabaseCancellable @@ -407,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( @@ -466,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 @@ -604,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> @@ -683,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) @@ -728,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) @@ -775,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/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/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 } }