mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-26 04:07:50 +00:00
Documentation
This commit is contained in:
1 parent
a8e266377c
commit
527aed0ea3
13 files changed
+311
-101
No files matched your search
+162
-31
@@ -1,5 +1,8 @@
|
||||
extension Array {
|
||||
/// TODO
|
||||
/// Creates an array containing the elements of a cursor.
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'bar'")
|
||||
/// let strings = try Array(cursor) // ["foo", "bar"]
|
||||
public init<C : Cursor>(_ cursor: C) throws where C.Element == Element {
|
||||
// TODO: cursors should have an underestimatedCount
|
||||
self.init()
|
||||
@@ -9,26 +12,70 @@ extension Array {
|
||||
}
|
||||
}
|
||||
|
||||
/// A type that supplies the values of a sequence one at a time.
|
||||
/// A type that supplies the values of some external resource, one at a time.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// The most common way to iterate over the elements of a cursor is to use a
|
||||
/// `while` loop:
|
||||
///
|
||||
/// let cursor = ...
|
||||
/// while let element = try cursor.next() {
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// ## Relationship with standard Sequence and IteratorProtocol
|
||||
///
|
||||
/// Cursors share traits with lazy sequences and iterators from the Swift
|
||||
/// standard library. Differences are:
|
||||
///
|
||||
/// - Cursor types are classes, and have a lifetime.
|
||||
/// - Cursor iteration may throw errors.
|
||||
/// - A cursor can not be repeated.
|
||||
///
|
||||
/// The protocol comes with default implementations for many operations similar
|
||||
/// to those defined by Swift's LazySequenceProtocol:
|
||||
///
|
||||
/// - `func contains(Self.Element)`
|
||||
/// - `func contains(where: (Self.Element) throws -> Bool)`
|
||||
/// - `func enumerated()`
|
||||
/// - `func filter((Self.Element) throws -> Bool)`
|
||||
/// - `func first(where: (Self.Element) throws -> Bool)`
|
||||
/// - `func flatMap<ElementOfResult>((Self.Element) throws -> ElementOfResult?)`
|
||||
/// - `func flatMap<SegmentOfResult>((Self.Element) throws -> SegmentOfResult)`
|
||||
/// - `func forEach((Self.Element) throws -> Void)`
|
||||
/// - `func joined()`
|
||||
/// - `func map<T>((Self.Element) throws -> T)`
|
||||
/// - `func reduce<Result>(Result, (Result, Self.Element) throws -> Result)`
|
||||
public protocol Cursor : class {
|
||||
// TODO: explain that Cursor is a class because it is designed to wrap an
|
||||
// external resource such as a SQLite statement.
|
||||
/// TODO
|
||||
/// The type of element traversed by the cursor.
|
||||
associatedtype Element
|
||||
|
||||
/// TODO
|
||||
/// Advances to the next element and returns it, or nil if no next element
|
||||
/// exists. Once nil has been returned, all subsequent calls return nil.
|
||||
func next() throws -> Element?
|
||||
}
|
||||
|
||||
/// TODO
|
||||
class AnyCursor<Element> : Cursor {
|
||||
/// TODO
|
||||
init<C : Cursor>(_ base: C) where C.Element == Element {
|
||||
/// A type-erased cursor of Element.
|
||||
///
|
||||
/// This cursor forwards its next() method to an arbitrary underlying cursor
|
||||
/// having the same Element type, hiding the specifics of the underlying
|
||||
/// cursor.
|
||||
public class AnyCursor<Element> : Cursor {
|
||||
/// Creates a cursor that wraps a base cursor but whose type depends only on
|
||||
/// the base cursor’s element type
|
||||
public init<C : Cursor>(_ base: C) where C.Element == Element {
|
||||
element = base.next
|
||||
}
|
||||
|
||||
/// TODO
|
||||
func next() throws -> Element? {
|
||||
/// Creates a cursor that wraps the given closure in its next() method
|
||||
public init(_ body: @escaping () throws -> Element?) {
|
||||
element = body
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
public func next() throws -> Element? {
|
||||
return try element()
|
||||
}
|
||||
|
||||
@@ -36,45 +83,86 @@ class AnyCursor<Element> : Cursor {
|
||||
}
|
||||
|
||||
extension Cursor {
|
||||
/// Returns a Boolean value indicating whether the cursor contains an
|
||||
/// element that satisfies the given predicate.
|
||||
///
|
||||
/// - parameter predicate: A closure that takes an element of the cursor as
|
||||
/// its argument and returns a Boolean value that indicates whether the
|
||||
/// passed element represents a match.
|
||||
/// - returns: true if the cursor contains an element that satisfies
|
||||
/// predicate; otherwise, false.
|
||||
public func contains(where predicate: (Element) throws -> Bool) throws -> Bool {
|
||||
while let element = try next() {
|
||||
if try predicate(element) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/// TODO
|
||||
/// Returns a cursor of pairs (n, x), where n represents a consecutive
|
||||
/// integer starting at zero, and x represents an element of the cursor.
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'bar'")
|
||||
/// let c = cursor.enumerated()
|
||||
/// while let (n, x) = c.next() {
|
||||
/// print("\(n): \(x)")
|
||||
/// }
|
||||
/// // Prints: "0: foo"
|
||||
/// // Prints: "1: bar"
|
||||
public func enumerated() -> EnumeratedCursor<Self> {
|
||||
return EnumeratedCursor(self)
|
||||
}
|
||||
|
||||
/// TODO
|
||||
/// Returns the elements of the cursor that satisfy the given predicate.
|
||||
public func filter(_ isIncluded: @escaping (Element) throws -> Bool) -> FilterCursor<Self> {
|
||||
return FilterCursor(self, isIncluded)
|
||||
}
|
||||
|
||||
/// TODO
|
||||
/// Returns the first element of the cursor that satisfies the given
|
||||
/// predicate or nil if no such element is found.
|
||||
public func first(where predicate: (Element) throws -> Bool) throws -> Element? {
|
||||
while let element = try next() {
|
||||
if try predicate(element) {
|
||||
return element
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Returns a cursor over the concatenated non-nil results of mapping
|
||||
/// transform over this cursor.
|
||||
public func flatMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult> {
|
||||
return map(transform).filter { $0 != nil }.map { $0! }
|
||||
}
|
||||
|
||||
/// TODO
|
||||
/// Returns a cursor over the concatenated results of mapping transform
|
||||
/// over self.
|
||||
public func flatMap<SegmentOfResult : Sequence>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, IteratorCursor<SegmentOfResult.Iterator>>> {
|
||||
return flatMap { try IteratorCursor(transform($0).makeIterator()) }
|
||||
}
|
||||
|
||||
/// TODO
|
||||
/// Returns a cursor over the concatenated results of mapping transform
|
||||
/// over self.
|
||||
public func flatMap<SegmentOfResult : Cursor>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, SegmentOfResult>> {
|
||||
return FlattenCursor(map(transform))
|
||||
return map(transform).joined()
|
||||
}
|
||||
|
||||
/// TODO
|
||||
/// Calls the given closure on each element in the cursor.
|
||||
public func forEach(_ body: (Element) throws -> Void) throws {
|
||||
while let element = try next() {
|
||||
try body(element)
|
||||
}
|
||||
}
|
||||
|
||||
/// TODO
|
||||
/// Returns a cursor over the results of the transform function applied to
|
||||
/// this cursor's elements.
|
||||
public func map<T>(_ transform: @escaping (Element) throws -> T) -> MapCursor<Self, T> {
|
||||
return MapCursor(self, transform)
|
||||
}
|
||||
|
||||
/// TODO
|
||||
/// Returns the result of calling the given combining closure with each
|
||||
/// element of this sequence and an accumulating value.
|
||||
public func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) throws -> Result {
|
||||
var result = initialResult
|
||||
while let element = try next() {
|
||||
@@ -84,14 +172,46 @@ extension Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
/// TODO
|
||||
extension Cursor where Element: Equatable {
|
||||
/// Returns a Boolean value indicating whether the cursor contains the
|
||||
/// given element.
|
||||
public func contains(_ element: Element) throws -> Bool {
|
||||
while let e = try next() {
|
||||
if e == element {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
extension Cursor where Element: Cursor {
|
||||
/// Returns the elements of this cursor of cursors, concatenated.
|
||||
public func joined() -> FlattenCursor<Self> {
|
||||
return FlattenCursor(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// An enumeration of the elements of a cursor.
|
||||
///
|
||||
/// To create an instance of `EnumeratedCursor`, call the `enumerated()` method
|
||||
/// on a cursor:
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'bar'")
|
||||
/// let c = cursor.enumerated()
|
||||
/// while let (n, x) = c.next() {
|
||||
/// print("\(n): \(x)")
|
||||
/// }
|
||||
/// // Prints: "0: foo"
|
||||
/// // Prints: "1: bar"
|
||||
public final class EnumeratedCursor<Base : Cursor> : Cursor {
|
||||
init(_ base: Base) {
|
||||
self.index = 0
|
||||
self.base = base
|
||||
}
|
||||
|
||||
/// TODO
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
public func next() throws -> (Int, Base.Element)? {
|
||||
guard let element = try base.next() else { return nil }
|
||||
defer { index += 1 }
|
||||
@@ -109,7 +229,8 @@ public final class FilterCursor<Base : Cursor> : Cursor {
|
||||
self.isIncluded = isIncluded
|
||||
}
|
||||
|
||||
/// TODO
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
public func next() throws -> Base.Element? {
|
||||
while let element = try base.next() {
|
||||
if try isIncluded(element) {
|
||||
@@ -123,13 +244,17 @@ public final class FilterCursor<Base : Cursor> : Cursor {
|
||||
private let isIncluded: (Base.Element) throws -> Bool
|
||||
}
|
||||
|
||||
/// TODO
|
||||
/// A cursor consisting of all the elements contained in each segment contained
|
||||
/// in some Base cursor.
|
||||
///
|
||||
/// See Cursor.joined(), Cursor.flatMap(_:), Sequence.flatMap(_:)
|
||||
public final class FlattenCursor<Base: Cursor> : Cursor where Base.Element: Cursor {
|
||||
init(_ base: Base) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
/// TODO
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
public func next() throws -> Base.Element.Element? {
|
||||
while true {
|
||||
if let element = try inner?.next() {
|
||||
@@ -146,14 +271,18 @@ public final class FlattenCursor<Base: Cursor> : Cursor where Base.Element: Curs
|
||||
private let base: Base
|
||||
}
|
||||
|
||||
/// TODO
|
||||
/// A Cursor whose elements consist of those in a Base Cursor passed through a
|
||||
/// transform function returning Element.
|
||||
///
|
||||
/// See Cursor.map(_:)
|
||||
public final class MapCursor<Base : Cursor, Element> : Cursor {
|
||||
init(_ base: Base, _ transform: @escaping (Base.Element) throws -> Element) {
|
||||
self.base = base
|
||||
self.transform = transform
|
||||
}
|
||||
|
||||
/// TODO
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
public func next() throws -> Element? {
|
||||
guard let element = try base.next() else { return nil }
|
||||
return try transform(element)
|
||||
@@ -163,14 +292,15 @@ public final class MapCursor<Base : Cursor, Element> : Cursor {
|
||||
private let transform: (Base.Element) throws -> Element
|
||||
}
|
||||
|
||||
/// TODO
|
||||
/// A Cursor whose elements are those of a sequence iterator.
|
||||
public final class IteratorCursor<Base : IteratorProtocol> : Cursor {
|
||||
// TODO: remove this type when `extension IteratorProtocol : Cursor { }` can be written
|
||||
init(_ base: Base) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
/// TODO
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
public func next() -> Base.Element? {
|
||||
return base.next()
|
||||
}
|
||||
@@ -180,7 +310,8 @@ public final class IteratorCursor<Base : IteratorProtocol> : Cursor {
|
||||
|
||||
extension Sequence {
|
||||
|
||||
/// TODO
|
||||
/// Returns a cursor over the concatenated results of mapping transform
|
||||
/// over self.
|
||||
public func flatMap<SegmentOfResult : Cursor>(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<IteratorCursor<Self.Iterator>, SegmentOfResult>> {
|
||||
return IteratorCursor(makeIterator()).flatMap(transform)
|
||||
}
|
||||
|
||||
@@ -89,7 +89,7 @@ extension DatabaseValueConvertible {
|
||||
/// try String.fetchOne(statement, arguments:...) // String
|
||||
///
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
public extension DatabaseValueConvertible {
|
||||
extension DatabaseValueConvertible {
|
||||
|
||||
|
||||
// MARK: Fetching From SelectStatement
|
||||
|
||||
@@ -47,7 +47,7 @@ public protocol StatementColumnConvertible {
|
||||
/// database values.
|
||||
///
|
||||
/// See DatabaseValueConvertible for more information.
|
||||
public extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
|
||||
// MARK: Fetching From SelectStatement
|
||||
|
||||
@@ -10,15 +10,15 @@
|
||||
///
|
||||
/// // ... then the RawRepresentable type can freely adopt DatabaseValueConvertible:
|
||||
/// extension Color : DatabaseValueConvertible { /* empty */ }
|
||||
public extension RawRepresentable where Self: DatabaseValueConvertible, Self.RawValue: DatabaseValueConvertible {
|
||||
extension RawRepresentable where Self: DatabaseValueConvertible, Self.RawValue: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
var databaseValue: DatabaseValue {
|
||||
public var databaseValue: DatabaseValue {
|
||||
return rawValue.databaseValue
|
||||
}
|
||||
|
||||
/// Returns a value initialized from *databaseValue*, if possible.
|
||||
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
return RawValue.fromDatabaseValue(databaseValue).flatMap { self.init(rawValue: $0) }
|
||||
}
|
||||
}
|
||||
+6
-3
@@ -222,7 +222,8 @@ public final class FTS4TableDefinition {
|
||||
/// }
|
||||
///
|
||||
/// - parameter name: the column name.
|
||||
@discardableResult public func column(_ name: String) -> FTS4ColumnDefinition {
|
||||
@discardableResult
|
||||
public func column(_ name: String) -> FTS4ColumnDefinition {
|
||||
let column = FTS4ColumnDefinition(name: name)
|
||||
columns.append(column)
|
||||
return column
|
||||
@@ -272,7 +273,8 @@ public final class FTS4ColumnDefinition {
|
||||
/// See https://www.sqlite.org/fts3.html#the_notindexed_option
|
||||
///
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult public func notIndexed() -> Self {
|
||||
@discardableResult
|
||||
public func notIndexed() -> Self {
|
||||
self.isIndexed = false
|
||||
return self
|
||||
}
|
||||
@@ -287,7 +289,8 @@ public final class FTS4ColumnDefinition {
|
||||
/// See https://www.sqlite.org/fts3.html#the_languageid_option
|
||||
///
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult public func asLanguageId() -> Self {
|
||||
@discardableResult
|
||||
public func asLanguageId() -> Self {
|
||||
self.isLanguageId = true
|
||||
return self
|
||||
}
|
||||
|
||||
+4
-2
@@ -253,7 +253,8 @@
|
||||
/// }
|
||||
///
|
||||
/// - parameter name: the column name.
|
||||
@discardableResult public func column(_ name: String) -> FTS5ColumnDefinition {
|
||||
@discardableResult
|
||||
public func column(_ name: String) -> FTS5ColumnDefinition {
|
||||
let column = FTS5ColumnDefinition(name: name)
|
||||
columns.append(column)
|
||||
return column
|
||||
@@ -301,7 +302,8 @@
|
||||
/// See https://www.sqlite.org/fts5.html#the_unindexed_column_option
|
||||
///
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult public func notIndexed() -> Self {
|
||||
@discardableResult
|
||||
public func notIndexed() -> Self {
|
||||
self.isIndexed = false
|
||||
return self
|
||||
}
|
||||
|
||||
@@ -304,7 +304,8 @@ extension QueryInterfaceRequest {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: The number of deleted rows
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
@discardableResult public func deleteAll(_ db: Database) throws -> Int {
|
||||
@discardableResult
|
||||
public func deleteAll(_ db: Database) throws -> Int {
|
||||
try query.makeDeleteStatement(db).execute()
|
||||
return db.changesCount
|
||||
}
|
||||
@@ -475,7 +476,8 @@ extension TableMapping {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: The number of deleted rows
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
@discardableResult public static func deleteAll(_ db: Database) throws -> Int {
|
||||
@discardableResult
|
||||
public static func deleteAll(_ db: Database) throws -> Int {
|
||||
return try all().deleteAll(db)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,7 +172,8 @@ public final class TableDefinition {
|
||||
/// - parameter type: the column type.
|
||||
/// - returns: An ColumnDefinition that allows you to refine the
|
||||
/// column definition.
|
||||
@discardableResult public func column(_ name: String, _ type: Database.ColumnType) -> ColumnDefinition {
|
||||
@discardableResult
|
||||
public func column(_ name: String, _ type: Database.ColumnType) -> ColumnDefinition {
|
||||
let column = ColumnDefinition(name: name, type: type)
|
||||
columns.append(column)
|
||||
return column
|
||||
@@ -395,7 +396,8 @@ public final class TableAlteration {
|
||||
/// - parameter type: the column type.
|
||||
/// - returns: An ColumnDefinition that allows you to refine the
|
||||
/// column definition.
|
||||
@discardableResult public func add(column name: String, _ type: Database.ColumnType) -> ColumnDefinition {
|
||||
@discardableResult
|
||||
public func add(column name: String, _ type: Database.ColumnType) -> ColumnDefinition {
|
||||
let column = ColumnDefinition(name: name, type: type)
|
||||
addedColumns.append(column)
|
||||
return column
|
||||
@@ -462,7 +464,8 @@ public final class ColumnDefinition {
|
||||
/// (see https://www.sqlite.org/lang_conflict.html).
|
||||
/// - autoincrement: If true, the primary key is autoincremented.
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult public func primaryKey(onConflict conflictResolution: Database.ConflictResolution? = nil, autoincrement: Bool = false) -> Self {
|
||||
@discardableResult
|
||||
public func primaryKey(onConflict conflictResolution: Database.ConflictResolution? = nil, autoincrement: Bool = false) -> Self {
|
||||
primaryKey = (conflictResolution: conflictResolution, autoincrement: autoincrement)
|
||||
return self
|
||||
}
|
||||
@@ -478,7 +481,8 @@ public final class ColumnDefinition {
|
||||
/// - parameter conflitResolution: An optional conflict resolution
|
||||
/// (see https://www.sqlite.org/lang_conflict.html).
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult public func notNull(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self {
|
||||
@discardableResult
|
||||
public func notNull(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self {
|
||||
notNullConflictResolution = conflictResolution ?? .abort
|
||||
return self
|
||||
}
|
||||
@@ -494,7 +498,8 @@ public final class ColumnDefinition {
|
||||
/// - parameter conflitResolution: An optional conflict resolution
|
||||
/// (see https://www.sqlite.org/lang_conflict.html).
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult public func unique(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self {
|
||||
@discardableResult
|
||||
public func unique(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self {
|
||||
uniqueConflictResolution = conflictResolution ?? .abort
|
||||
return self
|
||||
}
|
||||
@@ -510,7 +515,8 @@ public final class ColumnDefinition {
|
||||
/// - parameter condition: A closure whose argument is an Column that
|
||||
/// represents the defined column, and returns the expression to check.
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult public func check(_ condition: (Column) -> SQLExpressible) -> Self {
|
||||
@discardableResult
|
||||
public func check(_ condition: (Column) -> SQLExpressible) -> Self {
|
||||
checkConstraints.append(condition(Column(name)).sqlExpression)
|
||||
return self
|
||||
}
|
||||
@@ -525,7 +531,8 @@ public final class ColumnDefinition {
|
||||
///
|
||||
/// - parameter sql: An SQL snippet.
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult public func check(sql: String) -> Self {
|
||||
@discardableResult
|
||||
public func check(sql: String) -> Self {
|
||||
checkConstraints.append(SQLExpressionLiteral(sql))
|
||||
return self
|
||||
}
|
||||
@@ -540,7 +547,8 @@ public final class ColumnDefinition {
|
||||
///
|
||||
/// - parameter value: A DatabaseValueConvertible value.
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult public func defaults(to value: DatabaseValueConvertible) -> Self {
|
||||
@discardableResult
|
||||
public func defaults(to value: DatabaseValueConvertible) -> Self {
|
||||
defaultExpression = value.sqlExpression
|
||||
return self
|
||||
}
|
||||
@@ -555,7 +563,8 @@ public final class ColumnDefinition {
|
||||
///
|
||||
/// - parameter sql: An SQL snippet.
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult public func defaults(sql: String) -> Self {
|
||||
@discardableResult
|
||||
public func defaults(sql: String) -> Self {
|
||||
defaultExpression = SQLExpressionLiteral(sql)
|
||||
return self
|
||||
}
|
||||
@@ -570,7 +579,8 @@ public final class ColumnDefinition {
|
||||
///
|
||||
/// - parameter collation: An Database.CollationName.
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult public func collate(_ collation: Database.CollationName) -> Self {
|
||||
@discardableResult
|
||||
public func collate(_ collation: Database.CollationName) -> Self {
|
||||
collationName = collation.rawValue
|
||||
return self
|
||||
}
|
||||
@@ -585,7 +595,8 @@ public final class ColumnDefinition {
|
||||
///
|
||||
/// - parameter collation: A custom DatabaseCollation.
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult public func collate(_ collation: DatabaseCollation) -> Self {
|
||||
@discardableResult
|
||||
public func collate(_ collation: DatabaseCollation) -> Self {
|
||||
collationName = collation.name
|
||||
return self
|
||||
}
|
||||
@@ -607,7 +618,8 @@ public final class ColumnDefinition {
|
||||
/// - deferred: If true, defines a deferred foreign key constraint.
|
||||
/// See https://www.sqlite.org/foreignkeys.html#fk_deferred.
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult public func references(_ table: String, column: String? = nil, onDelete deleteAction: Database.ForeignKeyAction? = nil, onUpdate updateAction: Database.ForeignKeyAction? = nil, deferred: Bool = false) -> Self {
|
||||
@discardableResult
|
||||
public func references(_ table: String, column: String? = nil, onDelete deleteAction: Database.ForeignKeyAction? = nil, onUpdate updateAction: Database.ForeignKeyAction? = nil, deferred: Bool = false) -> Self {
|
||||
foreignKeyConstraints.append((table: table, column: column, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred))
|
||||
return self
|
||||
}
|
||||
|
||||
@@ -186,7 +186,8 @@ public protocol MutablePersistable : TableMapping {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: Whether a database row was deleted.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
@discardableResult func delete(_ db: Database) throws -> Bool
|
||||
@discardableResult
|
||||
func delete(_ db: Database) throws -> Bool
|
||||
|
||||
/// Returns true if and only if the primary key matches a row in
|
||||
/// the database.
|
||||
@@ -202,19 +203,19 @@ public protocol MutablePersistable : TableMapping {
|
||||
func exists(_ db: Database) throws -> Bool
|
||||
}
|
||||
|
||||
public extension MutablePersistable {
|
||||
extension MutablePersistable {
|
||||
/// Describes the conflict policy for insertions and updates.
|
||||
///
|
||||
/// The default value specifies ABORT policy for both insertions and
|
||||
/// updates, which has GRDB generate regular INSERT and UPDATE queries.
|
||||
static var persistenceConflictPolicy: PersistenceConflictPolicy {
|
||||
public static var persistenceConflictPolicy: PersistenceConflictPolicy {
|
||||
return PersistenceConflictPolicy(insert: .abort, update: .abort)
|
||||
}
|
||||
|
||||
/// Notifies the record that it was succesfully inserted.
|
||||
///
|
||||
/// The default implementation does nothing.
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
public mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
}
|
||||
|
||||
|
||||
@@ -223,7 +224,7 @@ public extension MutablePersistable {
|
||||
/// Executes an INSERT statement.
|
||||
///
|
||||
/// The default implementation for insert() invokes performInsert().
|
||||
mutating func insert(_ db: Database) throws {
|
||||
public mutating func insert(_ db: Database) throws {
|
||||
try performInsert(db)
|
||||
}
|
||||
|
||||
@@ -234,7 +235,7 @@ public extension MutablePersistable {
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// PersistenceError.recordNotFound is thrown if the primary key does not
|
||||
/// match any row in the database.
|
||||
func update(_ db: Database, columns: Set<String>) throws {
|
||||
public func update(_ db: Database, columns: Set<String>) throws {
|
||||
try performUpdate(db, columns: columns)
|
||||
}
|
||||
|
||||
@@ -245,7 +246,7 @@ public extension MutablePersistable {
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// PersistenceError.recordNotFound is thrown if the primary key does not
|
||||
/// match any row in the database.
|
||||
func update<Sequence: Swift.Sequence>(_ db: Database, columns: Sequence) throws where Sequence.Iterator.Element == Column {
|
||||
public func update<Sequence: Swift.Sequence>(_ db: Database, columns: Sequence) throws where Sequence.Iterator.Element == Column {
|
||||
try update(db, columns: Set(columns.map { $0.name }))
|
||||
}
|
||||
|
||||
@@ -256,7 +257,7 @@ public extension MutablePersistable {
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// PersistenceError.recordNotFound is thrown if the primary key does not
|
||||
/// match any row in the database.
|
||||
func update<Sequence: Swift.Sequence>(_ db: Database, columns: Sequence) throws where Sequence.Iterator.Element == String {
|
||||
public func update<Sequence: Swift.Sequence>(_ db: Database, columns: Sequence) throws where Sequence.Iterator.Element == String {
|
||||
try update(db, columns: Set(columns))
|
||||
}
|
||||
|
||||
@@ -266,7 +267,7 @@ public extension MutablePersistable {
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// PersistenceError.recordNotFound is thrown if the primary key does not
|
||||
/// match any row in the database.
|
||||
func update(_ db: Database) throws {
|
||||
public func update(_ db: Database) throws {
|
||||
let databaseTableName = type(of: self).databaseTableName
|
||||
let columns = try db.columns(in: databaseTableName)
|
||||
try update(db, columns: Set(columns.map { $0.name }))
|
||||
@@ -276,14 +277,15 @@ public extension MutablePersistable {
|
||||
/// the database.
|
||||
///
|
||||
/// The default implementation for save() invokes performSave().
|
||||
mutating func save(_ db: Database) throws {
|
||||
public mutating func save(_ db: Database) throws {
|
||||
try performSave(db)
|
||||
}
|
||||
|
||||
/// Executes a DELETE statement.
|
||||
///
|
||||
/// The default implementation for delete() invokes performDelete().
|
||||
@discardableResult func delete(_ db: Database) throws -> Bool {
|
||||
@discardableResult
|
||||
public func delete(_ db: Database) throws -> Bool {
|
||||
return try performDelete(db)
|
||||
}
|
||||
|
||||
@@ -291,7 +293,7 @@ public extension MutablePersistable {
|
||||
/// the database.
|
||||
///
|
||||
/// The default implementation for exists() invokes performExists().
|
||||
func exists(_ db: Database) throws -> Bool {
|
||||
public func exists(_ db: Database) throws -> Bool {
|
||||
return try performExists(db)
|
||||
}
|
||||
|
||||
@@ -320,7 +322,7 @@ public extension MutablePersistable {
|
||||
/// that adopt MutablePersistable can invoke performInsert() in their
|
||||
/// implementation of insert(). They should not provide their own
|
||||
/// implementation of performInsert().
|
||||
mutating func performInsert(_ db: Database) throws {
|
||||
public mutating func performInsert(_ db: Database) throws {
|
||||
let conflictResolutionForInsert = type(of: self).persistenceConflictPolicy.conflictResolutionForInsert
|
||||
let dao = try DAO(db, self)
|
||||
try dao.insertStatement(onConflict: conflictResolutionForInsert).execute()
|
||||
@@ -343,7 +345,7 @@ public extension MutablePersistable {
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// PersistenceError.recordNotFound is thrown if the primary key does not
|
||||
/// match any row in the database.
|
||||
func performUpdate(_ db: Database, columns: Set<String>) throws {
|
||||
public func performUpdate(_ db: Database, columns: Set<String>) throws {
|
||||
guard let statement = try DAO(db, self).updateStatement(columns: columns, onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) else {
|
||||
// Nil primary key
|
||||
throw PersistenceError.recordNotFound(self)
|
||||
@@ -363,7 +365,7 @@ public extension MutablePersistable {
|
||||
/// implementation of performSave().
|
||||
///
|
||||
/// This default implementation forwards the job to `update` or `insert`.
|
||||
mutating func performSave(_ db: Database) throws {
|
||||
public mutating func performSave(_ db: Database) throws {
|
||||
// Make sure we call self.insert and self.update so that classes
|
||||
// that override insert or save have opportunity to perform their
|
||||
// custom job.
|
||||
@@ -390,7 +392,7 @@ public extension MutablePersistable {
|
||||
/// that adopt MutablePersistable can invoke performDelete() in
|
||||
/// their implementation of delete(). They should not provide their own
|
||||
/// implementation of performDelete().
|
||||
func performDelete(_ db: Database) throws -> Bool {
|
||||
public func performDelete(_ db: Database) throws -> Bool {
|
||||
guard let statement = try DAO(db, self).deleteStatement() else {
|
||||
// Nil primary key
|
||||
return false
|
||||
@@ -406,7 +408,7 @@ public extension MutablePersistable {
|
||||
/// that adopt MutablePersistable can invoke performExists() in
|
||||
/// their implementation of exists(). They should not provide their own
|
||||
/// implementation of performExists().
|
||||
func performExists(_ db: Database) throws -> Bool {
|
||||
public func performExists(_ db: Database) throws -> Bool {
|
||||
guard let statement = try DAO(db, self).existsStatement() else {
|
||||
// Nil primary key
|
||||
return false
|
||||
@@ -494,12 +496,12 @@ public protocol Persistable : MutablePersistable {
|
||||
func save(_ db: Database) throws
|
||||
}
|
||||
|
||||
public extension Persistable {
|
||||
extension Persistable {
|
||||
|
||||
/// Notifies the record that it was succesfully inserted.
|
||||
///
|
||||
/// The default implementation does nothing.
|
||||
func didInsert(with rowID: Int64, for column: String?) {
|
||||
public func didInsert(with rowID: Int64, for column: String?) {
|
||||
}
|
||||
|
||||
// MARK: - Immutable CRUD
|
||||
@@ -507,7 +509,7 @@ public extension Persistable {
|
||||
/// Executes an INSERT statement.
|
||||
///
|
||||
/// The default implementation for insert() invokes performInsert().
|
||||
func insert(_ db: Database) throws {
|
||||
public func insert(_ db: Database) throws {
|
||||
try performInsert(db)
|
||||
}
|
||||
|
||||
@@ -515,7 +517,7 @@ public extension Persistable {
|
||||
/// the database.
|
||||
///
|
||||
/// The default implementation for save() invokes performSave().
|
||||
func save(_ db: Database) throws {
|
||||
public func save(_ db: Database) throws {
|
||||
try performSave(db)
|
||||
}
|
||||
|
||||
@@ -529,7 +531,7 @@ public extension Persistable {
|
||||
/// that adopt Persistable can invoke performInsert() in their
|
||||
/// implementation of insert(). They should not provide their own
|
||||
/// implementation of performInsert().
|
||||
func performInsert(_ db: Database) throws {
|
||||
public func performInsert(_ db: Database) throws {
|
||||
let conflictResolutionForInsert = type(of: self).persistenceConflictPolicy.conflictResolutionForInsert
|
||||
let dao = try DAO(db, self)
|
||||
try dao.insertStatement(onConflict: conflictResolutionForInsert).execute()
|
||||
@@ -548,7 +550,7 @@ public extension Persistable {
|
||||
/// implementation of performSave().
|
||||
///
|
||||
/// This default implementation forwards the job to `update` or `insert`.
|
||||
func performSave(_ db: Database) throws {
|
||||
public func performSave(_ db: Database) throws {
|
||||
// Make sure we call self.insert and self.update so that classes that
|
||||
// override insert or save have opportunity to perform their custom job.
|
||||
|
||||
|
||||
@@ -329,7 +329,8 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: Whether a database row was deleted.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
@discardableResult open func delete(_ db: Database) throws -> Bool {
|
||||
@discardableResult
|
||||
open func delete(_ db: Database) throws -> Bool {
|
||||
defer {
|
||||
// Future calls to update() will throw NotFound. Make the user
|
||||
// a favor and make sure this error is thrown even if she checks the
|
||||
|
||||
@@ -157,7 +157,8 @@ extension TableMapping {
|
||||
/// - db: A database connection.
|
||||
/// - keys: A sequence of primary keys.
|
||||
/// - returns: The number of deleted rows
|
||||
@discardableResult public static func deleteAll<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> Int where Sequence.Iterator.Element: DatabaseValueConvertible {
|
||||
@discardableResult
|
||||
public static func deleteAll<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> Int where Sequence.Iterator.Element: DatabaseValueConvertible {
|
||||
guard let statement = try makeDeleteByPrimaryKeyStatement(db, keys: keys) else {
|
||||
return 0
|
||||
}
|
||||
@@ -174,7 +175,8 @@ extension TableMapping {
|
||||
/// - db: A database connection.
|
||||
/// - key: A primary key value.
|
||||
/// - returns: Whether a database row was deleted.
|
||||
@discardableResult public static func deleteOne<PrimaryKeyType: DatabaseValueConvertible>(_ db: Database, key: PrimaryKeyType?) throws -> Bool {
|
||||
@discardableResult
|
||||
public static func deleteOne<PrimaryKeyType: DatabaseValueConvertible>(_ db: Database, key: PrimaryKeyType?) throws -> Bool {
|
||||
guard let key = key else {
|
||||
return false
|
||||
}
|
||||
@@ -335,7 +337,8 @@ extension TableMapping {
|
||||
/// - db: A database connection.
|
||||
/// - keys: An array of key dictionaries.
|
||||
/// - returns: The number of deleted rows
|
||||
@discardableResult public static func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int {
|
||||
@discardableResult
|
||||
public static func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int {
|
||||
guard let statement = try makeDeleteByKeyStatement(db, keys: keys) else {
|
||||
return 0
|
||||
}
|
||||
@@ -352,7 +355,8 @@ extension TableMapping {
|
||||
/// - db: A database connection.
|
||||
/// - key: A dictionary of values.
|
||||
/// - returns: Whether a database row was deleted.
|
||||
@discardableResult public static func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool {
|
||||
@discardableResult
|
||||
public static func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool {
|
||||
return try deleteAll(db, keys: [key]) > 0
|
||||
}
|
||||
|
||||
|
||||
@@ -541,7 +541,7 @@ while let url = try urls.next() {
|
||||
let wines = try Wine.fetchAll(db, "SELECT * FROM wines")
|
||||
```
|
||||
|
||||
- [Fetching Methods](#fetching-methods)
|
||||
- [Fetching Methods](#fetching-methods) and [Cursors](#cursors)
|
||||
- [Row Queries](#row-queries)
|
||||
- [Value Queries](#value-queries)
|
||||
- [Records](#records)
|
||||
@@ -557,7 +557,7 @@ try Type.fetchAll(...) // [Type]
|
||||
try Type.fetchOne(...) // Type?
|
||||
```
|
||||
|
||||
- `fetchCursor` returns a **cursor** that is memory efficient, but must be consumed in a protected dispatch queue.
|
||||
- `fetchCursor` returns a **cursor** over fetched values:
|
||||
|
||||
```swift
|
||||
let rows = try Row.fetchCursor(db, "SELECT ...") // DatabaseCursor<Row>
|
||||
@@ -566,18 +566,9 @@ try Type.fetchOne(...) // Type?
|
||||
}
|
||||
```
|
||||
|
||||
Don't modify the database during a cursor iteration:
|
||||
See [Cursors](#cursors) for more information.
|
||||
|
||||
```swift
|
||||
// Undefined behavior
|
||||
while let row = try rows.next() {
|
||||
try db.execute("DELETE FROM persons ...")
|
||||
}
|
||||
```
|
||||
|
||||
Cursors share some traits with Swift sequences and iterators, and implement methods like enumerated, filter, map, etc.
|
||||
|
||||
- `fetchAll` returns an **array** that can be consumed on any thread. It contains copies of database values, and can take a lot of memory:
|
||||
- `fetchAll` returns an **array**:
|
||||
|
||||
```swift
|
||||
let persons = try Person.fetchAll(db, "SELECT ...") // [Person]
|
||||
@@ -590,6 +581,73 @@ try Type.fetchOne(...) // Type?
|
||||
```
|
||||
|
||||
|
||||
#### Cursors
|
||||
|
||||
**Whenever you consume several rows from the database, you can fetch a Cursor, or an Array**.
|
||||
|
||||
Array contains copies of database values, can take a lot of memory, but may be consumed on any thread. Conversely, cursors iterate over database results in a lazy fashion, don't consume much memory, and are generally more efficient. But they must be consumed in a protected dispatch queue:
|
||||
|
||||
```swift
|
||||
let rows = try Row.fetchAll(db, "SELECT * FROM links") // [Row]
|
||||
let urls = try URL.fetchAll(db, "SELECT url FROM links") // [URL]
|
||||
let links = try Link.fetchAll(db, "SELECT * FROM links") // [Link]
|
||||
|
||||
let rows = try Row.fetchCursor(db, "SELECT * FROM links") // DatabaseCursor<Row>
|
||||
let urls = try URL.fetchCursor(db, "SELECT url FROM links") // DatabaseCursor<URL>
|
||||
let links = try Link.fetchCursor(db, "SELECT * FROM links") // DatabaseCursor<Link>
|
||||
```
|
||||
|
||||
|
||||
The most common way to iterate over the elements of a cursor is to use a `while` loop:
|
||||
|
||||
```swift
|
||||
let rows = try Row.fetchCursor(db, "SELECT * FROM links")
|
||||
while let row = try rows.next() {
|
||||
let url: URL = row.value(named: "url")
|
||||
print(url)
|
||||
}
|
||||
```
|
||||
|
||||
Don't modify the database during a cursor iteration:
|
||||
|
||||
```swift
|
||||
// Undefined behavior
|
||||
while let row = try rows.next() {
|
||||
try db.execute("DELETE FROM persons ...")
|
||||
}
|
||||
```
|
||||
|
||||
Cursors share traits with [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) and [iterators](https://developer.apple.com/reference/swift/iteratorprotocol) from the Swift standard library. Differences are:
|
||||
|
||||
- Cursor types are classes, and have a lifetime.
|
||||
- Cursors may throw errors.
|
||||
- Cursor can not be repeated.
|
||||
|
||||
The protocol comes with default implementations for many operations similar
|
||||
to those defined by lazy sequences:
|
||||
|
||||
```swift
|
||||
extension Cursor {
|
||||
func contains(Element)
|
||||
func contains(where: (Element) throws -> Bool)
|
||||
func enumerated()
|
||||
func filter((Element) throws -> Bool)
|
||||
func first(where: (Element) throws -> Bool)
|
||||
func flatMap<T>((Element) throws -> T?)
|
||||
func flatMap((Element) throws -> Sequence)
|
||||
func flatMap((Element) throws -> Cursor)
|
||||
func forEach((Element) throws -> Void)
|
||||
func joined()
|
||||
func map<T>((Element) throws -> T)
|
||||
func reduce(Result, (Result, Element) throws -> Result)
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
func flatMap((Iterator.Element) throws -> Cursor)
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Row Queries
|
||||
|
||||
- [Fetching Rows](#fetching-rows)
|
||||
|
||||
@@ -1,9 +1,4 @@
|
||||
- [ ] Think about supporting Cursor's underestimatedCount, which could speed up Array(cursor)
|
||||
- [ ] Cursor.first(where:)
|
||||
- [ ] Cursor.contains(where:)
|
||||
- [ ] Cursor.contains(_:)
|
||||
- [ ] Cursor.joined()
|
||||
- [ ] Cursor.joined(separator:)
|
||||
- [ ] FetchedRecordsController: handle fetch errors
|
||||
- [ ] Swift 3.0.2 (Xcode 8.2): "Type inference will properly unwrap optionals when used with generics and implicitly-unwrapped optionals." Maybe this fixes `row.value(named: "foo") as? Int`?
|
||||
- [ ] Refactor Database notion of transaction/savepoints into a single type. Support INSERT OR ROLLBACK.
|
||||
|
||||
Reference in new issue
Block a user