mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-22 04:00:39 +00:00
DocC
This commit is contained in:
1 parent
811d287bd9
commit
13c804d1cc
76 files changed
+6222
-4527
No files matched your search
+20
-6
@@ -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<Element>: AnyObject {
|
||||
/// The type of element traversed by the cursor.
|
||||
associatedtype Element
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
|
||||
@@ -260,9 +260,6 @@ extension DatabaseQueue: DatabaseReader {
|
||||
})
|
||||
}
|
||||
|
||||
/// Performs the same job as asyncConcurrentRead.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> 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<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
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<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try writer.sync(updates)
|
||||
|
||||
@@ -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<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
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<Output>: Publisher {
|
||||
public typealias Output = Output
|
||||
public typealias Failure = Error
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
|
||||
let subscription = DatabaseRegionSubscription(
|
||||
writer: writer,
|
||||
|
||||
@@ -89,7 +89,6 @@ extension DatabaseSnapshot: DatabaseReader {
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// :nodoc:
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
|
||||
@@ -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: <https://www.sqlite.org/datatype3.html>
|
||||
///
|
||||
/// ## 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: <https://www.sqlite.org/datatype3.html#storage_classes_and_datatypes>
|
||||
@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.
|
||||
///
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<Output>: Publisher {
|
||||
public typealias Output = Output
|
||||
public typealias Failure = Error
|
||||
|
||||
@@ -38,13 +38,14 @@
|
||||
/// - ``makePreparedRequest(_:forSingleResult:)``
|
||||
/// - ``PreparedRequest``
|
||||
///
|
||||
/// ### Support for Database Observation
|
||||
/// ### Database Observation Support
|
||||
///
|
||||
/// - ``databaseRegion(_:)``
|
||||
///
|
||||
/// ### Adapting the Fetched Rows
|
||||
///
|
||||
/// - ``adapted(_:)``
|
||||
/// - ``AdaptedFetchRequest``
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
|
||||
+535
-319
File diff suppressed because it is too large.
Load diff
+25
-42
@@ -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)
|
||||
|
||||
+114
-61
@@ -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)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
/// :nodoc:
|
||||
public struct SQLInterpolation: StringInterpolationProtocol {
|
||||
var elements: [SQL.Element]
|
||||
|
||||
|
||||
@@ -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<Row>`
|
||||
///
|
||||
/// - ``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<RowDecoder> {
|
||||
/// 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)
|
||||
}
|
||||
|
||||
@@ -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: <https://www.sqlite.org/c3ref/stmt.html>
|
||||
///
|
||||
/// ## 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 {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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)!)
|
||||
|
||||
@@ -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`).
|
||||
|
||||
@@ -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``
|
||||
@@ -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``
|
||||
@@ -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``
|
||||
- <doc:DatabaseConnections>
|
||||
- <doc:SQLLanguage>
|
||||
- <doc:Errors>
|
||||
|
||||
### 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``
|
||||
- <doc:QueryInterface>
|
||||
|
||||
### Database Observation
|
||||
|
||||
- ``AsyncValueObservation``
|
||||
- ``DatabaseRegion``
|
||||
- ``DatabaseRegionConvertible``
|
||||
- ``DatabaseRegionObservation``
|
||||
- ``SharedValueObservation``
|
||||
- ``ValueObservation``
|
||||
- ``ValueObservationScheduler``
|
||||
- ``TransactionObserver``
|
||||
- <doc:DatabaseObservation>
|
||||
|
||||
### Full-Text Search
|
||||
|
||||
- ``FTS3``
|
||||
- ``FTS4``
|
||||
|
||||
### Combine Publishers
|
||||
|
||||
- ``DatabasePublishers``
|
||||
@@ -0,0 +1,13 @@
|
||||
# Database Errors
|
||||
|
||||
The errors thrown when accessing an SQLite database.
|
||||
|
||||
## Topics
|
||||
|
||||
### SQLite Errors
|
||||
|
||||
- ``DatabaseError``
|
||||
|
||||
### Record Errors
|
||||
|
||||
- ``PersistenceError``
|
||||
@@ -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``
|
||||
@@ -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``
|
||||
+4
-2
@@ -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: <https://www.sqlite.org/fts3.html>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating Full-Text Virtual Tables
|
||||
/// ### The FTS3 Module
|
||||
///
|
||||
/// - ``init()``
|
||||
/// - ``Database/create(virtualTable:ifNotExists:using:_:)``
|
||||
/// - ``FTS3TableDefinition``
|
||||
/// - ``FTS3TokenizerDescriptor``
|
||||
///
|
||||
|
||||
@@ -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.
|
||||
///
|
||||
|
||||
+4
-2
@@ -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: <https://www.sqlite.org/fts3.html>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating Full-Text Virtual Tables
|
||||
/// ### The FTS4 Module
|
||||
///
|
||||
/// - ``init()``
|
||||
/// - ``Database/create(virtualTable:ifNotExists:using:_:)``
|
||||
/// - ``FTS4TableDefinition``
|
||||
/// - ``FTS4ColumnDefinition``
|
||||
public struct FTS4 {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<Self> {
|
||||
all().matching(pattern)
|
||||
}
|
||||
|
||||
@@ -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<Self> {
|
||||
all().matching(pattern)
|
||||
}
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
@@ -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<Book, Author>
|
||||
/// static let author = belongsTo(Author.self)
|
||||
/// }
|
||||
/// ```swift
|
||||
/// struct Book: TableRecord {
|
||||
/// // BelongsToAssociation<Book, Author>
|
||||
/// 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<PlayerInfo> {
|
||||
/// 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 {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<Origin, Destination>: 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<Origin, Destination> {
|
||||
public var _sqlAssociation: _SQLAssociation
|
||||
|
||||
init(
|
||||
@@ -94,3 +90,8 @@ public struct BelongsToAssociation<Origin, Destination>: AssociationToOne {
|
||||
cardinality: .toOne)
|
||||
}
|
||||
}
|
||||
|
||||
extension BelongsToAssociation: AssociationToOne {
|
||||
public typealias OriginRowDecoder = Origin
|
||||
public typealias RowDecoder = Destination
|
||||
}
|
||||
@@ -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<Origin, Destination>: 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<Origin, Destination> {
|
||||
public var _sqlAssociation: _SQLAssociation
|
||||
|
||||
init(
|
||||
@@ -94,3 +90,8 @@ public struct HasManyAssociation<Origin, Destination>: AssociationToMany {
|
||||
cardinality: .toMany)
|
||||
}
|
||||
}
|
||||
|
||||
extension HasManyAssociation: AssociationToMany {
|
||||
public typealias OriginRowDecoder = Origin
|
||||
public typealias RowDecoder = Destination
|
||||
}
|
||||
@@ -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<Origin, Destination>: 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<Origin, Destination> {
|
||||
public var _sqlAssociation: _SQLAssociation
|
||||
|
||||
init<Pivot, Target>(
|
||||
@@ -63,3 +59,8 @@ public struct HasManyThroughAssociation<Origin, Destination>: AssociationToMany
|
||||
_sqlAssociation = target._sqlAssociation.through(pivot._sqlAssociation)
|
||||
}
|
||||
}
|
||||
|
||||
extension HasManyThroughAssociation: AssociationToMany {
|
||||
public typealias OriginRowDecoder = Origin
|
||||
public typealias RowDecoder = Destination
|
||||
}
|
||||
@@ -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 <https://sqlite.org/foreignkeys.html#fk_actions> 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<Origin, Destination>: 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<Origin, Destination> {
|
||||
public var _sqlAssociation: _SQLAssociation
|
||||
|
||||
init(
|
||||
@@ -96,3 +93,8 @@ public struct HasOneAssociation<Origin, Destination>: AssociationToOne {
|
||||
cardinality: .toOne)
|
||||
}
|
||||
}
|
||||
|
||||
extension HasOneAssociation: AssociationToOne {
|
||||
public typealias OriginRowDecoder = Origin
|
||||
public typealias RowDecoder = Destination
|
||||
}
|
||||
@@ -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<Origin, Destination>: 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<Origin, Destination> {
|
||||
public var _sqlAssociation: _SQLAssociation
|
||||
|
||||
init<Pivot, Target>(
|
||||
@@ -43,3 +40,8 @@ public struct HasOneThroughAssociation<Origin, Destination>: AssociationToOne {
|
||||
_sqlAssociation = target._sqlAssociation.through(pivot._sqlAssociation)
|
||||
}
|
||||
}
|
||||
|
||||
extension HasOneThroughAssociation: AssociationToOne {
|
||||
public typealias OriginRowDecoder = Origin
|
||||
public typealias RowDecoder = Destination
|
||||
}
|
||||
@@ -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<Origin, Destination>: AssociationToOne {
|
||||
/// :nodoc:
|
||||
public typealias OriginRowDecoder = Origin
|
||||
|
||||
/// :nodoc:
|
||||
public typealias RowDecoder = Destination
|
||||
|
||||
/// :nodoc:
|
||||
public struct JoinAssociation<Origin, Destination> {
|
||||
public var _sqlAssociation: _SQLAssociation
|
||||
|
||||
/// Creates a `JoinAssociation` whose key is the table name of the relation.
|
||||
@@ -22,3 +15,8 @@ public struct JoinAssociation<Origin, Destination>: AssociationToOne {
|
||||
cardinality: .toOne)
|
||||
}
|
||||
}
|
||||
|
||||
extension JoinAssociation: AssociationToOne {
|
||||
public typealias OriginRowDecoder = Origin
|
||||
public typealias RowDecoder = Destination
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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<RowDecoder>: 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<RowDecoder>: 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.
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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 <https://www.sqlite.org/syntax/expr.html>
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/#the-query-interface>
|
||||
/// ## 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 <https://github.com/groue/GRDB.swift/#the-query-interface>
|
||||
/// 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 <https://github.com/groue/GRDB.swift/#the-query-interface>
|
||||
/// 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 <https://github.com/groue/GRDB.swift/#the-query-interface>
|
||||
/// 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 <https://github.com/groue/GRDB.swift/#the-query-interface>
|
||||
/// 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 <https://github.com/groue/GRDB.swift/#the-query-interface>
|
||||
/// 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 <https://github.com/groue/GRDB.swift/#the-query-interface>
|
||||
/// 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))
|
||||
}
|
||||
|
||||
@@ -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 <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
|
||||
/// For example:
|
||||
///
|
||||
/// See also `total(_:)`.
|
||||
/// ```swift
|
||||
/// // SUM(amount)
|
||||
/// sum(Column("amount"))
|
||||
/// ```
|
||||
///
|
||||
/// // SUM(amount)
|
||||
/// sum(Column("amount"))
|
||||
/// See also ``total(_:)``.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
|
||||
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 <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
|
||||
/// For example:
|
||||
///
|
||||
/// See also `sum(_:)`.
|
||||
/// ```swift
|
||||
/// // TOTAL(amount)
|
||||
/// total(Column("amount"))
|
||||
/// ```
|
||||
///
|
||||
/// // TOTAL(amount)
|
||||
/// total(Column("amount"))
|
||||
/// See also ``sum(_:)``.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
|
||||
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 <https://www.sqlite.org/lang_datefunc.html>
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_datefunc.html>
|
||||
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 <https://www.sqlite.org/lang_datefunc.html>
|
||||
/// // JULIANDAY(date, '1 days')
|
||||
/// julianDay(Column("date"), .day(1))
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_datefunc.html>
|
||||
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 <https://www.sqlite.org/lang_datefunc.html>
|
||||
/// // DATETIME(date, '1 days')
|
||||
/// dateTime(Column("date"), .day(1))
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation:<https://www.sqlite.org/lang_datefunc.html>
|
||||
public func dateTime(_ value: some SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression {
|
||||
.function("DATETIME", [value.sqlExpression] + modifiers.map(\.sqlExpression))
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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 <https://www.sqlite.org/syntax/ordering-term.html>
|
||||
/// A type that can be used as an SQL ordering term.
|
||||
///
|
||||
/// Related SQLite documentation <https://www.sqlite.org/syntax/ordering-term.html>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Supporting Type
|
||||
///
|
||||
/// - ``SQLOrdering``
|
||||
public protocol SQLOrderingTerm {
|
||||
/// Returns an SQL ordering.
|
||||
var sqlOrdering: SQLOrdering { get }
|
||||
|
||||
@@ -279,8 +279,16 @@ enum SQLCount {
|
||||
|
||||
// MARK: - SQLSelectable
|
||||
|
||||
/// SQLSelectable is the protocol for types that can be selected, as
|
||||
/// described at <https://www.sqlite.org/syntax/result-column.html>
|
||||
/// A type that can be used as SQL result columns.
|
||||
///
|
||||
/// Related SQLite documentation <https://www.sqlite.org/syntax/result-column.html>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``AllColumns``
|
||||
/// - ``SQLSelection``
|
||||
public protocol SQLSelectable {
|
||||
/// Returns an SQL selection.
|
||||
var sqlSelection: SQLSelection { get }
|
||||
|
||||
@@ -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 <https://www.sqlite.org/syntax/select-stmt.html>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``SQLSubquery``
|
||||
public protocol SQLSubqueryable: SQLSpecificExpressible {
|
||||
var sqlSubquery: SQLSubquery { get }
|
||||
}
|
||||
|
||||
+1006
-554
File diff suppressed because it is too large.
Load diff
@@ -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<S>(_ expressible: S)
|
||||
where S: SQLExpressible, S: Sequence, S.Element: SQLExpressible
|
||||
{
|
||||
|
||||
@@ -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.
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<Self> {
|
||||
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<Self> {
|
||||
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<Self> {
|
||||
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<Self> {
|
||||
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<Self> {
|
||||
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<RowDecoder>(
|
||||
_ 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<RowDecoder>(
|
||||
_ 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<RowDecoder>(
|
||||
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<RowDecoder>(
|
||||
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<PrimaryKey>(as type: PrimaryKey.Type = PrimaryKey.self)
|
||||
-> QueryInterfaceRequest<PrimaryKey>
|
||||
{
|
||||
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<Self> {
|
||||
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<Self> {
|
||||
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<Self> {
|
||||
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<Self> {
|
||||
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: Keys)
|
||||
-> QueryInterfaceRequest<Self>
|
||||
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<Self> {
|
||||
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<Self> {
|
||||
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<Self> {
|
||||
// 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<Self> {
|
||||
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<Self> {
|
||||
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<Self> {
|
||||
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<Self> {
|
||||
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<Self> {
|
||||
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<Self> {
|
||||
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<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> QueryInterfaceRequest<Self> {
|
||||
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<Self> {
|
||||
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: IDS) -> QueryInterfaceRequest<Self>
|
||||
|
||||
@@ -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] {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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<Player> = """
|
||||
/// 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
|
||||
///
|
||||
|
||||
@@ -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<String>, update: () throws -> PersistenceSuccess) throws {
|
||||
/// print("Player will update")
|
||||
/// _ = try update()
|
||||
/// print("Player did update")
|
||||
/// }
|
||||
/// ```swift
|
||||
/// struct Player: MutablePersistableRecord {
|
||||
/// func aroundUpdate(_ db: Database, columns: Set<String>, 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 <https://www.sqlite.org/lang_createtable.html#rowids_and_the_integer_primary_key>.
|
||||
public var rowID: Int64
|
||||
|
||||
@@ -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, <doc:MutablePersistableRecord/persistenceConflictPolicy-1isyv>
|
||||
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
|
||||
/// 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, <doc:MutablePersistableRecord/persistenceConflictPolicy-1isyv>
|
||||
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
|
||||
/// 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, <doc:MutablePersistableRecord/persistenceConflictPolicy-1isyv>
|
||||
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
|
||||
/// 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, <doc:MutablePersistableRecord/persistenceConflictPolicy-1isyv>
|
||||
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
|
||||
/// 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, <doc:MutablePersistableRecord/persistenceConflictPolicy-1isyv>
|
||||
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
|
||||
/// is used.
|
||||
/// - parameter selection: The returned columns (must not be empty).
|
||||
/// - parameter fetch: A closure that executes its ``Statement`` argument.
|
||||
|
||||
@@ -10,7 +10,7 @@ extension PersistableRecord {
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution. If
|
||||
/// nil, <doc:MutablePersistableRecord/persistenceConflictPolicy-1isyv>
|
||||
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
|
||||
/// 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, <doc:MutablePersistableRecord/persistenceConflictPolicy-1isyv>
|
||||
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
|
||||
/// 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, <doc:MutablePersistableRecord/persistenceConflictPolicy-1isyv>
|
||||
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
|
||||
/// 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, <doc:MutablePersistableRecord/persistenceConflictPolicy-1isyv>
|
||||
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
|
||||
/// 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, <doc:MutablePersistableRecord/persistenceConflictPolicy-1isyv>
|
||||
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
|
||||
/// 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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
+343
-126
@@ -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<Keys>(_ 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<IDS>(_ 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,
|
||||
|
||||
@@ -25,7 +25,6 @@ struct OnDemandFuture<Output, Failure: Error>: Publisher {
|
||||
self.attemptToFulfill = attemptToFulfill
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
|
||||
let subscription = OnDemandFutureSubscription(
|
||||
attemptToFulfill: attemptToFulfill,
|
||||
|
||||
@@ -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<Element> {
|
||||
private let scheduler: ValueObservationScheduler
|
||||
private let extent: SharedValueObservationExtent
|
||||
@@ -159,20 +183,22 @@ public final class SharedValueObservation<Element> {
|
||||
///
|
||||
/// 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<Element> {
|
||||
}
|
||||
|
||||
#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<Element> {
|
||||
DatabasePublishers.Value { onError, onChange in
|
||||
@@ -302,10 +329,21 @@ public final class SharedValueObservation<Element> {
|
||||
|
||||
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<Element>.BufferingPolicy = .unbounded)
|
||||
-> AsyncValueObservation<Element>
|
||||
|
||||
@@ -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<Reducer: _ValueReducer> {
|
||||
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<Element>: AsyncSequence {
|
||||
public typealias BufferingPolicy = AsyncThrowingStream<Element, Error>.Continuation.BufferingPolicy
|
||||
@@ -390,9 +404,6 @@ public struct AsyncValueObservation<Element>: 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<Element, Error>.AsyncIterator
|
||||
let cancellable: AnyDatabaseCancellable
|
||||
@@ -407,45 +418,49 @@ public struct AsyncValueObservation<Element>: 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<Output>: Publisher {
|
||||
public typealias Failure = Error
|
||||
private let start: ValueObservationStart<Output>
|
||||
@@ -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<Value>(
|
||||
_ fetch: @escaping (Database) throws -> Value)
|
||||
-> ValueObservation<ValueReducers.Fetch<Value>>
|
||||
@@ -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<Value>(
|
||||
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<Value>(
|
||||
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<Value>(
|
||||
_ fetch: @escaping (Database) throws -> Value)
|
||||
-> ValueObservation<ValueReducers.Fetch<Value>>
|
||||
|
||||
@@ -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 */
|
||||
@@ -1,30 +1,30 @@
|
||||
#include <sqlite3.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
|
||||
|
||||
// Expose APIs that are missing from system <sqlite3.h>
|
||||
|
||||
@@ -3,30 +3,30 @@
|
||||
|
||||
#include <SQLCipher/sqlite3.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 */
|
||||
@@ -3,31 +3,31 @@
|
||||
|
||||
#include <sqlite3.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
|
||||
|
||||
// Expose APIs that are missing from system <sqlite3.h>
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user