diff --git a/docs/3.3/Classes.html b/docs/3.3/Classes.html new file mode 100644 index 000000000..c4499fc14 --- /dev/null +++ b/docs/3.3/Classes.html @@ -0,0 +1,2049 @@ + + + + Classes Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Classes

+

The following classes are available globally.

+ +
+
+
+ +
    +
  • +
    + + + + AnyCursor + +
    +
    +
    +
    +
    +
    +

    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.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class AnyCursor<Element> : Cursor
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + Database + +
    +
    +
    +
    +
    +
    +

    A Database connection.

    + +

    You don’t create a database directly. Instead, you use a DatabaseQueue, or +a DatabasePool:

    +
    let dbQueue = DatabaseQueue(...)
    +
    +// The Database is the `db` in the closure:
    +try dbQueue.write { db in
    +    try Player(...).insert(db)
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class Database
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + DatabaseCollation + +
    +
    +
    +
    +
    +
    +

    A Collation is a string comparison function used by SQLite.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class DatabaseCollation
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + DatabaseFunction + +
    +
    +
    +
    +
    +
    +

    An SQL function or aggregate.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class DatabaseFunction : Hashable
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
+
+ +
+
+
    +
  • +
    + + + + AnyDatabaseReader + +
    +
    +
    +
    +
    +
    +

    A type-erased DatabaseReader

    + +

    Instances of AnyDatabaseReader forward their methods to an arbitrary +underlying database reader.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class AnyDatabaseReader : DatabaseReader
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
+
+ +
    +
  • +
    + + + + DatabaseValueCursor + +
    +
    +
    +
    +
    +
    +

    A cursor of database values extracted from a single column. +For example:

    +
    try dbQueue.read { db in
    +    let urls: DatabaseValueCursor<URL> = try URL.fetchCursor(db, "SELECT url FROM link")
    +    while let url = urls.next() { // URL
    +        print(url)
    +    }
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class DatabaseValueCursor<Value> : Cursor where Value : DatabaseValueConvertible
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    A cursor of optional database values extracted from a single column. +For example:

    +
    try dbQueue.read { db in
    +    let urls: NullableDatabaseValueCursor<URL> = try Optional<URL>.fetchCursor(db, "SELECT url FROM link")
    +    while let url = urls.next() { // URL?
    +        print(url)
    +    }
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class NullableDatabaseValueCursor<Value> : Cursor where Value : DatabaseValueConvertible
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + AnyDatabaseWriter + +
    +
    +
    +
    +
    +
    +

    A type-erased DatabaseWriter

    + +

    Instances of AnyDatabaseWriter forward their methods to an arbitrary +underlying database writer.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class AnyDatabaseWriter : DatabaseWriter
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + Row + +
    +
    +
    +
    +
    +
    +

    A database row.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class Row : Equatable, Hashable, RandomAccessCollection, ExpressibleByDictionaryLiteral, CustomStringConvertible, CustomDebugStringConvertible
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + RowCursor + +
    +
    +
    +
    +
    +
    +

    A cursor of database rows. For example:

    +
    try dbQueue.read { db in
    +    let rows: RowCursor = try Row.fetchCursor(db, "SELECT * FROM player")
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class RowCursor : Cursor
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + Statement + +
    +
    +
    +
    +
    +
    +

    A statement represents an SQL query.

    + +

    It is the base class of UpdateStatement that executes update statements, +and SelectStatement that fetches rows.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public class Statement
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + SelectStatement + +
    +
    +
    +
    +
    +
    +

    A subclass of Statement that fetches database rows.

    + +

    You create SelectStatement with the Database.makeSelectStatement() method:

    +
    try dbQueue.read { db in
    +    let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
    +    let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
    +    let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class SelectStatement : Statement
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + StatementCursor + +
    +
    +
    +
    +
    +
    +

    A cursor that iterates a database statement without producing any value. +For example:

    +
    try dbQueue.read { db in
    +    let statement = db.makeSelectStatement("SELECT * FROM player")
    +    let cursor: StatementCursor = statement.makeCursor()
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class StatementCursor : Cursor
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + UpdateStatement + +
    +
    +
    +
    +
    +
    +

    A subclass of Statement that executes SQL queries.

    + +

    You create UpdateStatement with the Database.makeUpdateStatement() method:

    +
    try dbQueue.inTransaction { db in
    +    let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)")
    +    try statement.execute(arguments: ["Arthur"])
    +    try statement.execute(arguments: ["Barbara"])
    +    return .commit
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class UpdateStatement : Statement
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    A cursor of database values extracted from a single column. +For example:

    +
    try dbQueue.read { db in
    +    let names: ColumnCursor<String> = try String.fetchCursor(db, "SELECT name FROM player")
    +    while let name = names.next() { // String
    +        print(name)
    +    }
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class FastDatabaseValueCursor<Value> : Cursor where Value : DatabaseValueConvertible, Value : StatementColumnConvertible
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    A cursor of optional database values extracted from a single column. +For example:

    +
    try dbQueue.read { db in
    +    let emails: NullableColumnCursor<String> = try Optional<String>.fetchCursor(db, "SELECT email FROM player")
    +    while let email = emails.next() { // String?
    +        print(email ?? "<NULL>")
    +    }
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class FastNullableDatabaseValueCursor<Value> : Cursor where Value : DatabaseValueConvertible, Value : StatementColumnConvertible
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + FTS3TableDefinition + +
    +
    +
    +
    +
    +
    +

    The FTS3TableDefinition class lets you define columns of a FTS3 virtual table.

    + +

    You don’t create instances of this class. Instead, you use the Database +create(virtualTable:using:) method:

    +
    try db.create(virtualTable: "document", using: FTS3()) { t in // t is FTS3TableDefinition
    +    t.column("content")
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class FTS3TableDefinition
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + FTS4TableDefinition + +
    +
    +
    +
    +
    +
    +

    The FTS4TableDefinition class lets you define columns of a FTS4 virtual table.

    + +

    You don’t create instances of this class. Instead, you use the Database +create(virtualTable:using:) method:

    +
    try db.create(virtualTable: "document", using: FTS4()) { t in // t is FTS4TableDefinition
    +    t.column("content")
    +}
    +
    + +

    See https://www.sqlite.org/fts3.html

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class FTS4TableDefinition
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + FTS4ColumnDefinition + +
    +
    +
    +
    +
    +
    +

    The FTS4ColumnDefinition class lets you refine a column of an FTS4 +virtual table.

    + +

    You get instances of this class when you create an FTS4 table:

    +
    try db.create(virtualTable: "document", using: FTS4()) { t in
    +    t.column("content")      // FTS4ColumnDefinition
    +}
    +
    + +

    See https://www.sqlite.org/fts3.html

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class FTS4ColumnDefinition
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + FTS5TableDefinition + +
    +
    +
    +
    +
    +
    +

    The FTS5TableDefinition class lets you define columns of a FTS5 virtual table.

    + +

    You don’t create instances of this class. Instead, you use the Database +create(virtualTable:using:) method:

    +
    try db.create(virtualTable: "document", using: FTS5()) { t in // t is FTS5TableDefinition
    +    t.column("content")
    +}
    +
    + +

    See https://www.sqlite.org/fts5.html

    + + See more +
    +
    +
    +
  • +
  • +
    + + + + FTS5ColumnDefinition + +
    +
    +
    +
    +
    +
    +

    The FTS5ColumnDefinition class lets you refine a column of an FTS5 +virtual table.

    + +

    You get instances of this class when you create an FTS5 table:

    +
    try db.create(virtualTable: "document", using: FTS5()) { t in
    +    t.column("content")      // FTS5ColumnDefinition
    +}
    +
    + +

    See https://www.sqlite.org/fts5.html

    + + See more +
    +
    +
    +
  • +
+
+
+ + +
+
+
    +
  • +
    + + + + TableDefinition + +
    +
    +
    +
    +
    +
    +

    The TableDefinition class lets you define table columns and constraints.

    + +

    You don’t create instances of this class. Instead, you use the Database +create(table:) method:

    +
    try db.create(table: "player") { t in // t is TableDefinition
    +    t.column(...)
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class TableDefinition
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + TableAlteration + +
    +
    +
    +
    +
    +
    +

    The TableAlteration class lets you alter database tables.

    + +

    You don’t create instances of this class. Instead, you use the Database +alter(table:) method:

    +
    try db.alter(table: "player") { t in // t is TableAlteration
    +    t.add(column: ...)
    +}
    +
    + +

    See https://www.sqlite.org/lang_altertable.html

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class TableAlteration
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ColumnDefinition + +
    +
    +
    +
    +
    +
    +

    The ColumnDefinition class lets you refine a table column.

    + +

    You get instances of this class when you create or alter a database table:

    +
    try db.create(table: "player") { t in
    +    t.column(...)      // ColumnDefinition
    +}
    +
    +try db.alter(table: "player") { t in
    +    t.add(column: ...) // ColumnDefinition
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html and +https://www.sqlite.org/lang_altertable.html

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class ColumnDefinition
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + RecordCursor + +
    +
    +
    +
    +
    +
    +

    A cursor of records. For example:

    +
    struct Player : FetchableRecord { ... }
    +try dbQueue.read { db in
    +    let players: RecordCursor<Player> = try Player.fetchCursor(db, "SELECT * FROM player")
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class RecordCursor<Record> : Cursor where Record : FetchableRecord
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
+
+
+ + + +

Record

+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/AnyCursor.html b/docs/3.3/Classes/AnyCursor.html new file mode 100644 index 000000000..86092b150 --- /dev/null +++ b/docs/3.3/Classes/AnyCursor.html @@ -0,0 +1,938 @@ + + + + AnyCursor Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

AnyCursor

+
+
+
public final class AnyCursor<Element> : Cursor
+ +
+
+

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.

+ +
+
+
+
    +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a cursor that wraps a base cursor but whose type depends only on +the base cursor’s element type

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init<C>(_ base: C) where Element == C.Element, C : Cursor
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(iterator:) + +
    +
    +
    +
    +
    +
    +

    Creates a cursor that wraps a base iterator but whose type depends only +on the base iterator’s element type

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public convenience init<I>(iterator: I) where Element == I.Element, I : IteratorProtocol
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a cursor that wraps a base sequence but whose type depends only +on the base sequence’s element type

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public convenience init<S>(_ s: S) where Element == S.Element, S : Sequence
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a cursor that wraps the given closure in its next() method

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ body: @escaping () throws -> Element?)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/AnyDatabaseReader.html b/docs/3.3/Classes/AnyDatabaseReader.html new file mode 100644 index 000000000..fa676b463 --- /dev/null +++ b/docs/3.3/Classes/AnyDatabaseReader.html @@ -0,0 +1,844 @@ + + + + AnyDatabaseReader Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

AnyDatabaseReader

+
+
+
public final class AnyDatabaseReader : DatabaseReader
+ +
+
+

A type-erased DatabaseReader

+ +

Instances of AnyDatabaseReader forward their methods to an arbitrary +underlying database reader.

+ +
+
+
+
    +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a database reader that wraps a base database reader.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ base: DatabaseReader)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/AnyDatabaseWriter.html b/docs/3.3/Classes/AnyDatabaseWriter.html new file mode 100644 index 000000000..28d8b0f8d --- /dev/null +++ b/docs/3.3/Classes/AnyDatabaseWriter.html @@ -0,0 +1,844 @@ + + + + AnyDatabaseWriter Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

AnyDatabaseWriter

+
+
+
public final class AnyDatabaseWriter : DatabaseWriter
+ +
+
+

A type-erased DatabaseWriter

+ +

Instances of AnyDatabaseWriter forward their methods to an arbitrary +underlying database writer.

+ +
+
+
+
    +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a database writer that wraps a base database writer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ base: DatabaseWriter)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/ColumnDefinition.html b/docs/3.3/Classes/ColumnDefinition.html new file mode 100644 index 000000000..0af1579a4 --- /dev/null +++ b/docs/3.3/Classes/ColumnDefinition.html @@ -0,0 +1,1461 @@ + + + + ColumnDefinition Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ColumnDefinition

+
+
+
public final class ColumnDefinition
+ +
+
+

The ColumnDefinition class lets you refine a table column.

+ +

You get instances of this class when you create or alter a database table:

+
try db.create(table: "player") { t in
+    t.column(...)      // ColumnDefinition
+}
+
+try db.alter(table: "player") { t in
+    t.add(column: ...) // ColumnDefinition
+}
+
+ +

See https://www.sqlite.org/lang_createtable.html and +https://www.sqlite.org/lang_altertable.html

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Adds a primary key constraint on the column.

    +
    try db.create(table: "player") { t in
    +    t.column("id", .integer).primaryKey()
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#primkeyconst and +https://www.sqlite.org/lang_createtable.html#rowid

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func primaryKey(onConflict conflictResolution: Database.ConflictResolution? = nil, autoincrement: Bool = false) -> Self
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + conflitResolution + + +
    +

    An optional conflict resolution +(see https://www.sqlite.org/lang_conflict.html).

    +
    +
    + + autoincrement + + +
    +

    If true, the primary key is autoincremented.

    +
    +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
  • +
    + + + + notNull(onConflict:) + +
    +
    +
    +
    +
    +
    +

    Adds a NOT NULL constraint on the column.

    +
    try db.create(table: "player") { t in
    +    t.column("name", .text).notNull()
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#notnullconst

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func notNull(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + conflitResolution + + +
    +

    An optional conflict resolution +(see https://www.sqlite.org/lang_conflict.html).

    +
    +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
  • +
    + + + + unique(onConflict:) + +
    +
    +
    +
    +
    +
    +

    Adds a UNIQUE constraint on the column.

    +
    try db.create(table: "player") { t in
    +    t.column("email", .text).unique()
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#uniqueconst

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func unique(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + conflitResolution + + +
    +

    An optional conflict resolution +(see https://www.sqlite.org/lang_conflict.html).

    +
    +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
  • +
    + + + + indexed() + +
    +
    +
    +
    +
    +
    +

    Adds an index of the column.

    +
    try db.create(table: "player") { t in
    +    t.column("email", .text).indexed()
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#uniqueconst

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func indexed() -> Self
    + +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
  • +
    + + + + check(_:) + +
    +
    +
    +
    +
    +
    +

    Adds a CHECK constraint on the column.

    +
    try db.create(table: "player") { t in
    +    t.column("name", .text).check { length($0) > 0 }
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#ckconst

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func check(_ condition: (Column) -> SQLExpressible) -> Self
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + condition + + +
    +

    A closure whose argument is an Column that +represents the defined column, and returns the expression to check.

    +
    +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
  • +
    + + + + check(sql:) + +
    +
    +
    +
    +
    +
    +

    Adds a CHECK constraint on the column.

    +
    try db.create(table: "player") { t in
    +    t.column("name", .text).check(sql: "LENGTH(name) > 0")
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#ckconst

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func check(sql: String) -> Self
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + sql + + +
    +

    An SQL snippet.

    +
    +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
  • +
    + + + + defaults(to:) + +
    +
    +
    +
    +
    +
    +

    Defines the default column value.

    +
    try db.create(table: "player") { t in
    +    t.column("name", .text).defaults(to: "Anonymous")
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#dfltval

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func defaults(to value: DatabaseValueConvertible) -> Self
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + value + + +
    +

    A DatabaseValueConvertible value.

    +
    +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
  • +
    + + + + defaults(sql:) + +
    +
    +
    +
    +
    +
    +

    Defines the default column value.

    +
    try db.create(table: "player") { t in
    +    t.column("creationDate", .DateTime).defaults(sql: "CURRENT_TIMESTAMP")
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#dfltval

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func defaults(sql: String) -> Self
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + sql + + +
    +

    An SQL snippet.

    +
    +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
  • +
    + + + + collate(_:) + +
    +
    +
    +
    +
    +
    +
    try db.create(table: "player") { t in
    +    t.column("email", .text).collate(.nocase)
    +}
    +
    + +

    See https://www.sqlite.org/datatype3.html#collation

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func collate(_ collation: Database.CollationName) -> Self
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + collation + + +
    +

    An Database.CollationName.

    +
    +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
  • +
    + + + + collate(_:) + +
    +
    +
    +
    +
    +
    +
    try db.create(table: "player") { t in
    +    t.column("name", .text).collate(.localizedCaseInsensitiveCompare)
    +}
    +
    + +

    See https://www.sqlite.org/datatype3.html#collation

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func collate(_ collation: DatabaseCollation) -> Self
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + collation + + +
    +

    A custom DatabaseCollation.

    +
    +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Defines a foreign key.

    +
    try db.create(table: "book") { t in
    +    t.column("authorId", .integer).references("author", onDelete: .cascade)
    +}
    +
    + +

    See https://www.sqlite.org/foreignkeys.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func references(_ table: String, column: String? = nil, onDelete deleteAction: Database.ForeignKeyAction? = nil, onUpdate updateAction: Database.ForeignKeyAction? = nil, deferred: Bool = false) -> Self
    + +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/Database.html b/docs/3.3/Classes/Database.html new file mode 100644 index 000000000..92ca30c96 --- /dev/null +++ b/docs/3.3/Classes/Database.html @@ -0,0 +1,3707 @@ + + + + Database Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Database

+
+
+
public final class Database
+ +
+
+

A Database connection.

+ +

You don’t create a database directly. Instead, you use a DatabaseQueue, or +a DatabasePool:

+
let dbQueue = DatabaseQueue(...)
+
+// The Database is the `db` in the closure:
+try dbQueue.write { db in
+    try Player(...).insert(db)
+}
+
+ +
+
+
+ + +
+
+ +
    +
  • +
    + + + + logError + +
    +
    +
    +
    +
    +
    +

    The error logging function.

    + +

    Quoting https://www.sqlite.org/errlog.html:

    + +
    +

    SQLite can be configured to invoke a callback function containing an +error code and a terse error message whenever anomalies occur. This +mechanism is very helpful in tracking obscure problems that occur +rarely and in the field. Application developers are encouraged to take +advantage of the error logging facility of SQLite in their products, +as it is very low CPU and memory cost but can be a huge aid +for debugging.

    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static var logError: Database.LogErrorFunction? { get set }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + configuration + +
    +
    +
    +
    +
    +
    +

    The database configuration

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let configuration: Configuration
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + lastInsertedRowID + +
    +
    +
    +
    +
    +
    +

    The rowID of the most recently inserted row.

    + +

    If no row has ever been inserted using this database connection, +returns zero.

    + +

    For more detailed information, see https://www.sqlite.org/c3ref/last_insert_rowid.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var lastInsertedRowID: Int64 { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + changesCount + +
    +
    +
    +
    +
    +
    +

    The number of rows modified, inserted or deleted by the most recent +successful INSERT, UPDATE or DELETE statement.

    + +

    For more detailed information, see https://www.sqlite.org/c3ref/changes.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var changesCount: Int { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + totalChangesCount + +
    +
    +
    +
    +
    +
    +

    The total number of rows modified, inserted or deleted by all successful +INSERT, UPDATE or DELETE statements since the database connection was +opened.

    + +

    For more detailed information, see https://www.sqlite.org/c3ref/total_changes.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var totalChangesCount: Int { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + isInsideTransaction + +
    +
    +
    +
    +
    +
    +

    True if the database connection is currently in a transaction.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var isInsideTransaction: Bool { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + clearSchemaCache() + +
    +
    +
    +
    +
    +
    +

    Clears the database schema cache.

    + +

    You may need to clear the cache manually if the database schema is +modified by another connection.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func clearSchemaCache()
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + tableExists(_:) + +
    +
    +
    +
    +
    +
    +

    Returns whether a table exists.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func tableExists(_ tableName: String) throws -> Bool
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns whether a table is an internal SQLite table.

    + +

    Those are tables whose name begins with sqlite_.

    + +

    For more information, see https://www.sqlite.org/fileformat2.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func isSQLiteInternalTable(_ tableName: String) -> Bool
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns whether a table is an internal GRDB table.

    + +

    Those are tables whose name begins with grdb_.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func isGRDBInternalTable(_ tableName: String) -> Bool
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + viewExists(_:) + +
    +
    +
    +
    +
    +
    +

    Returns whether a view exists.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func viewExists(_ viewName: String) throws -> Bool
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + triggerExists(_:) + +
    +
    +
    +
    +
    +
    +

    Returns whether a trigger exists.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func triggerExists(_ triggerName: String) throws -> Bool
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + primaryKey(_:) + +
    +
    +
    +
    +
    +
    +

    The primary key for table named tableName.

    + +

    All tables have a primary key, even when it is not explicit. When a +table has no explicit primary key, the result is the hidden +rowid column.

    +
    +

    Throws

    + A DatabaseError if table does not exist. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + indexes(on:) + +
    +
    +
    +
    +
    +
    +

    The indexes on table named tableName; returns the empty array if the +table does not exist.

    + +

    Note: SQLite does not define any index for INTEGER PRIMARY KEY columns: +this method does not return any index that represents this primary key.

    + +

    If you want to know if a set of columns uniquely identify a row, prefer +table(_:hasUniqueKey:) instead.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func indexes(on tableName: String) throws -> [IndexInfo]
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    True if a sequence of columns uniquely identifies a row, that is to say +if the columns are the primary key, or if there is a unique index on them.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func table<T>(_ tableName: String, hasUniqueKey columns: T) throws -> Bool where T : Sequence, T.Element == String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + foreignKeys(on:) + +
    +
    +
    +
    +
    +
    +

    The foreign keys defined on table named tableName.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func foreignKeys(on tableName: String) throws -> [ForeignKeyInfo]
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + columns(in:) + +
    +
    +
    +
    +
    +
    +

    The columns in the table named tableName

    +
    +

    Throws

    + A DatabaseError if table does not exist. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func columns(in tableName: String) throws -> [ColumnInfo]
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Returns a new prepared statement that can be reused.

    +
    let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
    +let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
    +let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
    +
    +
    +

    Throws

    + A DatabaseError whenever SQLite could not parse the sql query. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func makeSelectStatement(_ sql: String) throws -> SelectStatement
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + sql + + +
    +

    An SQL query.

    +
    +
    +
    +
    +

    Return Value

    +

    A SelectStatement.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns a prepared statement that can be reused.

    +
    let statement = try db.cachedSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
    +let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
    +let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
    +
    + +

    The returned statement may have already been used: it may or may not +contain values for its eventual arguments.

    +
    +

    Throws

    + A DatabaseError whenever SQLite could not parse the sql query. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func cachedSelectStatement(_ sql: String) throws -> SelectStatement
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + sql + + +
    +

    An SQL query.

    +
    +
    +
    +
    +

    Return Value

    +

    An UpdateStatement.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns a new prepared statement that can be reused.

    +
    let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)")
    +try statement.execute(arguments: ["Arthur"])
    +try statement.execute(arguments: ["Barbara"])
    +
    +
    +

    Throws

    + A DatabaseError whenever SQLite could not parse the sql query. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func makeUpdateStatement(_ sql: String) throws -> UpdateStatement
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + sql + + +
    +

    An SQL query.

    +
    +
    +
    +
    +

    Return Value

    +

    An UpdateStatement.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns a prepared statement that can be reused.

    +
    let statement = try db.cachedUpdateStatement("INSERT INTO player (name) VALUES (?)")
    +try statement.execute(arguments: ["Arthur"])
    +try statement.execute(arguments: ["Barbara"])
    +
    + +

    The returned statement may have already been used: it may or may not +contain values for its eventual arguments.

    +
    +

    Throws

    + A DatabaseError whenever SQLite could not parse the sql query. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func cachedUpdateStatement(_ sql: String) throws -> UpdateStatement
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + sql + + +
    +

    An SQL query.

    +
    +
    +
    +
    +

    Return Value

    +

    An UpdateStatement.

    +
    + +
    +
    +
  • +
  • +
    + + + + execute(_:arguments:) + +
    +
    +
    +
    +
    +
    +

    Executes one or several SQL statements, separated by semi-colons.

    +
    try db.execute(
    +    "INSERT INTO player (name) VALUES (:name)",
    +    arguments: ["name": "Arthur"])
    +
    +try db.execute("""
    +    INSERT INTO player (name) VALUES (?);
    +    INSERT INTO player (name) VALUES (?);
    +    INSERT INTO player (name) VALUES (?);
    +    """, arguments; ['Arthur', 'Barbara', 'Craig'])
    +
    + +

    This method may throw a DatabaseError.

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func execute(_ sql: String, arguments: StatementArguments? = nil) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(function:) + +
    +
    +
    +
    +
    +
    +

    Add or redefine an SQL function.

    +
    let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
    +    guard let int = Int.fromDatabaseValue(dbValues[0]) else {
    +        return nil
    +    }
    +    return int + 1
    +}
    +db.add(function: fn)
    +try Int.fetchOne(db, "SELECT succ(1)")! // 2
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func add(function: DatabaseFunction)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + remove(function:) + +
    +
    +
    +
    +
    +
    +

    Remove an SQL function.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func remove(function: DatabaseFunction)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(collation:) + +
    +
    +
    +
    +
    +
    +

    Add or redefine a collation.

    +
    let collation = DatabaseCollation("localized_standard") { (string1, string2) in
    +    return (string1 as NSString).localizedStandardCompare(string2)
    +}
    +db.add(collation: collation)
    +try db.execute("CREATE TABLE files (name TEXT COLLATE localized_standard")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func add(collation: DatabaseCollation)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + remove(collation:) + +
    +
    +
    +
    +
    +
    +

    Remove a collation.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func remove(collation: DatabaseCollation)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + inTransaction(_:_:) + +
    +
    +
    +
    +
    +
    +

    Executes a block inside a database transaction.

    +
    try dbQueue.inDatabase do {
    +    try db.inTransaction {
    +        try db.execute("INSERT ...")
    +        return .commit
    +    }
    +}
    +
    + +

    If the block throws an error, the transaction is rollbacked and the +error is rethrown.

    + +

    This method is not reentrant: you can’t nest transactions.

    +
    +

    Throws

    + The error thrown by the block. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func inTransaction(_ kind: TransactionKind? = nil, _ block: () throws -> TransactionCompletion) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + kind + + +
    +

    The transaction type (default nil). If nil, the transaction +type is configuration.defaultTransactionKind, which itself +defaults to .deferred. See https://www.sqlite.org/lang_transaction.html +for more information.

    +
    +
    + + block + + +
    +

    A block that executes SQL statements and return either +.commit or .rollback.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + inSavepoint(_:) + +
    +
    +
    +
    +
    +
    +

    Executes a block inside a savepoint.

    +
    try dbQueue.inDatabase do {
    +    try db.inSavepoint {
    +        try db.execute("INSERT ...")
    +        return .commit
    +    }
    +}
    +
    + +

    If the block throws an error, the savepoint is rollbacked and the +error is rethrown.

    + +

    This method is reentrant: you can nest savepoints.

    +
    +

    Throws

    + The error thrown by the block. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func inSavepoint(_ block: () throws -> TransactionCompletion) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + block + + +
    +

    A block that executes SQL statements and return +either .commit or .rollback.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + beginTransaction(_:) + +
    +
    +
    +
    +
    +
    +

    Begins a database transaction.

    +
    +

    Throws

    + The error thrown by the block. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func beginTransaction(_ kind: TransactionKind? = nil) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + kind + + +
    +

    The transaction type (default nil). If nil, the +transaction type is configuration.defaultTransactionKind, which itself +defaults to .deferred. See https://www.sqlite.org/lang_transaction.html +for more information.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + rollback() + +
    +
    +
    +
    +
    +
    +

    Rollbacks a database transaction.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func rollback() throws
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + commit() + +
    +
    +
    +
    +
    +
    +

    Commits a database transaction.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func commit() throws
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Add a transaction observer, so that it gets notified of +database changes.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func add(transactionObserver: TransactionObserver, extent: TransactionObservationExtent = .observerLifetime)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + transactionObserver + + +
    +

    A transaction observer.

    +
    +
    + + extent + + +
    +

    The duration of the observation. The default is +the observer lifetime (observation lasts until observer +is deallocated).

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Remove a transaction observer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func remove(transactionObserver: TransactionObserver)
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Registers a closure to be executed after the next or current +transaction completion.

    +
    try dbQueue.write { db in
    +    db.afterNextTransactionCommit { _ in
    +        print("success")
    +    }
    +    ...
    +} // prints "success"
    +
    + +

    If the transaction is rollbacked, the closure is not executed.

    + +

    If the transaction is committed, the closure is executed in a protected +dispatch queue, serialized will all database updates.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func afterNextTransactionCommit(_ closure: @escaping (Database) -> ())
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    The extent of a transaction observation

    + +

    See Database.add(transactionObserver:extent:)

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public enum TransactionObservationExtent
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Deletes the synchronization triggers for a synchronized FTS4 table

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func dropFTS4SynchronizationTriggers(forTable tableName: String) throws
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Creates a database table.

    +
    try db.create(table: "place") { t in
    +    t.autoIncrementedPrimaryKey("id")
    +    t.column("title", .text)
    +    t.column("favorite", .boolean).notNull().default(false)
    +    t.column("longitude", .double).notNull()
    +    t.column("latitude", .double).notNull()
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html and +https://www.sqlite.org/withoutrowid.html

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a database table.

    +
    try db.create(table: "place") { t in
    +    t.autoIncrementedPrimaryKey("id")
    +    t.column("title", .text)
    +    t.column("favorite", .boolean).notNull().default(false)
    +    t.column("longitude", .double).notNull()
    +    t.column("latitude", .double).notNull()
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html and +https://www.sqlite.org/withoutrowid.html

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @available(iOS 8.2, OSX 10.10, *)
    +public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, withoutRowID: Bool, body: (TableDefinition) -> Void) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + + + + + +
    + + name + + +
    +

    The table name.

    +
    +
    + + temporary + + +
    +

    If true, creates a temporary table.

    +
    +
    + + ifNotExists + + +
    +

    If false (the default), an error is thrown if the +table already exists. Otherwise, the table is created unless it +already exists.

    +
    +
    + + withoutRowID + + +
    +

    If true, uses WITHOUT ROWID optimization.

    +
    +
    + + body + + +
    +

    A closure that defines table columns and constraints.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a database table.

    +
    try db.create(table: "place") { t in
    +    t.autoIncrementedPrimaryKey("id")
    +    t.column("title", .text)
    +    t.column("favorite", .boolean).notNull().default(false)
    +    t.column("longitude", .double).notNull()
    +    t.column("latitude", .double).notNull()
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, body: (TableDefinition) -> Void) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + name + + +
    +

    The table name.

    +
    +
    + + temporary + + +
    +

    If true, creates a temporary table.

    +
    +
    + + ifNotExists + + +
    +

    If false (the default), an error is thrown if the +table already exists. Otherwise, the table is created unless it +already exists.

    +
    +
    + + body + + +
    +

    A closure that defines table columns and constraints.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + rename(table:to:) + +
    +
    +
    +
    +
    +
    +

    Renames a database table.

    + +

    See https://www.sqlite.org/lang_altertable.html

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func rename(table name: String, to newName: String) throws
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + alter(table:body:) + +
    +
    +
    +
    +
    +
    +

    Modifies a database table.

    +
    try db.alter(table: "player") { t in
    +    t.add(column: "url", .text)
    +}
    +
    + +

    See https://www.sqlite.org/lang_altertable.html

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func alter(table name: String, body: (TableAlteration) -> Void) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + name + + +
    +

    The table name.

    +
    +
    + + body + + +
    +

    A closure that defines table alterations.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + drop(table:) + +
    +
    +
    +
    +
    +
    +

    Deletes a database table.

    + +

    See https://www.sqlite.org/lang_droptable.html

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func drop(table name: String) throws
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates an index.

    +
    try db.create(index: "playerByEmail", on: "player", columns: ["email"])
    +
    + +

    SQLite can also index expressions (https://www.sqlite.org/expridx.html) +and use specific collations. To create such an index, use a raw SQL +query.

    +
    try db.execute("CREATE INDEX ...")
    +
    + +

    See https://www.sqlite.org/lang_createindex.html

    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates an index.

    +
    try db.create(index: "playerByEmail", on: "player", columns: ["email"])
    +
    + +

    SQLite can also index expressions (https://www.sqlite.org/expridx.html) +and use specific collations. To create such an index, use a raw SQL +query.

    +
    try db.execute("CREATE INDEX ...")
    +
    + +

    See https://www.sqlite.org/lang_createindex.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func create(index name: String, on table: String, columns: [String], unique: Bool = false, ifNotExists: Bool = false) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + + + + + +
    + + name + + +
    +

    The index name.

    +
    +
    + + table + + +
    +

    The name of the indexed table.

    +
    +
    + + columns + + +
    +

    The indexed columns.

    +
    +
    + + unique + + +
    +

    If true, creates a unique index.

    +
    +
    + + ifNotExists + + +
    +

    If false, no error is thrown if index already exists.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a partial index.

    +
    try db.create(index: "playerByEmail", on: "player", columns: ["email"], condition: Column("email") != nil)
    +
    + +

    See https://www.sqlite.org/lang_createindex.html, and +https://www.sqlite.org/partialindex.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @available(iOS 8.2, OSX 10.10, *)
    +public func create(index name: String, on table: String, columns: [String], unique: Bool = false, ifNotExists: Bool = false, condition: SQLExpressible) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + name + + +
    +

    The index name.

    +
    +
    + + table + + +
    +

    The name of the indexed table.

    +
    +
    + + columns + + +
    +

    The indexed columns.

    +
    +
    + + unique + + +
    +

    If true, creates a unique index.

    +
    +
    + + ifNotExists + + +
    +

    If false, no error is thrown if index already exists.

    +
    +
    + + condition + + +
    +

    The condition that indexed rows must verify.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + drop(index:) + +
    +
    +
    +
    +
    +
    +

    Deletes a database index.

    + +

    See https://www.sqlite.org/lang_dropindex.html

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func drop(index name: String) throws
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Creates a virtual database table.

    +
    try db.create(virtualTable: "vocabulary", using: "spellfix1")
    +
    + +

    See https://www.sqlite.org/lang_createtable.html

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func create(virtualTable name: String, ifNotExists: Bool = false, using module: String) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + name + + +
    +

    The table name.

    +
    +
    + + ifNotExists + + +
    +

    If false (the default), an error is thrown if the +table already exists. Otherwise, the table is created unless it +already exists.

    +
    +
    + + module + + +
    +

    The name of an SQLite virtual table module.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a virtual database table.

    +
    let module = ...
    +try db.create(virtualTable: "book", using: module) { t in
    +    ...
    +}
    +
    + +

    The type of the closure argument t depends on the type of the module +argument: refer to this module’s documentation.

    + +

    Use this method to create full-text tables using the FTS3, FTS4, or +FTS5 modules:

    +
    try db.create(virtualTable: "book", using: FTS4()) { t in
    +    t.column("title")
    +    t.column("author")
    +    t.column("body")
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func create<Module: VirtualTableModule>(virtualTable tableName: String, ifNotExists: Bool = false, using module: Module, _ body: ((Module.TableDefinition) -> Void)? = nil) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + name + + +
    +

    The table name.

    +
    +
    + + ifNotExists + + +
    +

    If false (the default), an error is thrown if the +table already exists. Otherwise, the table is created unless it +already exists.

    +
    +
    + + module + + +
    +

    a VirtualTableModule

    +
    +
    + + body + + +
    +

    An optional closure that defines the virtual table.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/Database/BusyMode.html b/docs/3.3/Classes/Database/BusyMode.html new file mode 100644 index 000000000..f3febd61c --- /dev/null +++ b/docs/3.3/Classes/Database/BusyMode.html @@ -0,0 +1,930 @@ + + + + BusyMode Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

BusyMode

+
+
+
public enum BusyMode
+ +
+
+

When there are several connections to a database, a connection may try +to access the database while it is locked by another connection.

+ +

The BusyMode enum describes the behavior of GRDB when such a situation +occurs:

+ +
    +
  • .immediateError: The SQLITE_BUSY error is immediately returned to the +connection that tries to access the locked database.

  • +
  • .timeout: The SQLITE_BUSY error will be returned only if the database +remains locked for more than the specified duration.

  • +
  • .callback: Perform your custom lock handling.

  • +
+ +

To set the busy mode of a database, use Configuration:

+
let configuration = Configuration(busyMode: .timeout(1))
+let dbQueue = DatabaseQueue(path: "...", configuration: configuration)
+
+ +

Relevant SQLite documentation:

+ + + +
+
+
+
    +
  • +
    + + + + immediateError + +
    +
    +
    +
    +
    +
    +

    The SQLITE_BUSY error is immediately returned to the connection that +tries to access the locked database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case immediateError
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + timeout + +
    +
    +
    +
    +
    +
    +

    The SQLITE_BUSY error will be returned only if the database remains +locked for more than the specified duration.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case timeout(TimeInterval)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + callback + +
    +
    +
    +
    +
    +
    +

    A custom callback that is called when a database is locked. +See https://www.sqlite.org/c3ref/busy_handler.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case callback(Database.BusyCallback)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/Database/CheckpointMode.html b/docs/3.3/Classes/Database/CheckpointMode.html new file mode 100644 index 000000000..cf5a85dc7 --- /dev/null +++ b/docs/3.3/Classes/Database/CheckpointMode.html @@ -0,0 +1,931 @@ + + + + CheckpointMode Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

CheckpointMode

+
+
+
public enum CheckpointMode : Int32
+ +
+
+

The available checkpoint modes.

+ +
+
+
+
    +
  • +
    + + + + passive + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case passive = 0
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + full + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case full = 1
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + restart + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case restart = 2
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + truncate + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case truncate = 3
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/Database/CollationName.html b/docs/3.3/Classes/Database/CollationName.html new file mode 100644 index 000000000..3f48fd86c --- /dev/null +++ b/docs/3.3/Classes/Database/CollationName.html @@ -0,0 +1,933 @@ + + + + CollationName Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

CollationName

+
+
+
public struct CollationName : RawRepresentable, Hashable
+ +
+
+

A built-in SQLite collation.

+ +

See https://www.sqlite.org/datatype3.html#collation

+ +
+
+
+
    +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ rawValue: String)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + binary + +
    +
    +
    +
    +
    +
    +

    The BINARY built-in SQL collation

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let binary: Database.CollationName
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + nocase + +
    +
    +
    +
    +
    +
    +

    The NOCASE built-in SQL collation

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let nocase: Database.CollationName
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + rtrim + +
    +
    +
    +
    +
    +
    +

    The RTRIM built-in SQL collation

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let rtrim: Database.CollationName
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/Database/ColumnType.html b/docs/3.3/Classes/Database/ColumnType.html new file mode 100644 index 000000000..9b5121252 --- /dev/null +++ b/docs/3.3/Classes/Database/ColumnType.html @@ -0,0 +1,1088 @@ + + + + ColumnType Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ColumnType

+
+
+
public struct ColumnType : RawRepresentable, Hashable
+ +
+
+

An SQL column type.

+
try db.create(table: "player") { t in
+    t.autoIncrementedPrimaryKey("id")
+    t.column("title", .text)
+}
+
+ +

See https://www.sqlite.org/datatype3.html

+ +
+
+
+
    +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ rawValue: String)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + text + +
    +
    +
    +
    +
    +
    +

    The TEXT SQL column type

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let text: Database.ColumnType
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + integer + +
    +
    +
    +
    +
    +
    +

    The INTEGER SQL column type

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let integer: Database.ColumnType
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + double + +
    +
    +
    +
    +
    +
    +

    The DOUBLE SQL column type

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let double: Database.ColumnType
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + numeric + +
    +
    +
    +
    +
    +
    +

    The NUMERIC SQL column type

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let numeric: Database.ColumnType
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + boolean + +
    +
    +
    +
    +
    +
    +

    The BOOLEAN SQL column type

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let boolean: Database.ColumnType
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + blob + +
    +
    +
    +
    +
    +
    +

    The BLOB SQL column type

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let blob: Database.ColumnType
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + date + +
    +
    +
    +
    +
    +
    +

    The DATE SQL column type

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let date: Database.ColumnType
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + datetime + +
    +
    +
    +
    +
    +
    +

    The DATETIME SQL column type

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let datetime: Database.ColumnType
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/Database/ConflictResolution.html b/docs/3.3/Classes/Database/ConflictResolution.html new file mode 100644 index 000000000..9c8ec8070 --- /dev/null +++ b/docs/3.3/Classes/Database/ConflictResolution.html @@ -0,0 +1,963 @@ + + + + ConflictResolution Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ConflictResolution

+
+
+
public enum ConflictResolution : String
+ +
+
+

An SQLite conflict resolution.

+ +

See https://www.sqlite.org/lang_conflict.html.

+ +
+
+
+
    +
  • +
    + + + + rollback + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case rollback = "ROLLBACK"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + abort + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case abort = "ABORT"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fail + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case fail = "FAIL"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ignore + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case ignore = "IGNORE"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + replace + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case replace = "REPLACE"
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/Database/ForeignKeyAction.html b/docs/3.3/Classes/Database/ForeignKeyAction.html new file mode 100644 index 000000000..1a0fff2cd --- /dev/null +++ b/docs/3.3/Classes/Database/ForeignKeyAction.html @@ -0,0 +1,933 @@ + + + + ForeignKeyAction Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ForeignKeyAction

+
+
+
public enum ForeignKeyAction : String
+ +
+
+

A foreign key action.

+ +

See https://www.sqlite.org/foreignkeys.html

+ +
+
+
+
    +
  • +
    + + + + cascade + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case cascade = "CASCADE"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + restrict + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case restrict = "RESTRICT"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + setNull + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case setNull = "SET NULL"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + setDefault + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case setDefault = "SET DEFAULT"
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/Database/TransactionCompletion.html b/docs/3.3/Classes/Database/TransactionCompletion.html new file mode 100644 index 000000000..9642fb09a --- /dev/null +++ b/docs/3.3/Classes/Database/TransactionCompletion.html @@ -0,0 +1,871 @@ + + + + TransactionCompletion Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

TransactionCompletion

+
+
+
public enum TransactionCompletion
+ +
+
+

The end of a transaction: Commit, or Rollback

+ +
+
+
+
    +
  • +
    + + + + commit + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case commit
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + rollback + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case rollback
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/Database/TransactionKind.html b/docs/3.3/Classes/Database/TransactionKind.html new file mode 100644 index 000000000..fcbf5a292 --- /dev/null +++ b/docs/3.3/Classes/Database/TransactionKind.html @@ -0,0 +1,901 @@ + + + + TransactionKind Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

TransactionKind

+
+
+
public enum TransactionKind : String
+ +
+
+

An SQLite transaction kind. See https://www.sqlite.org/lang_transaction.html

+ +
+
+
+
    +
  • +
    + + + + deferred + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case deferred = "DEFERRED"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + immediate + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case immediate = "IMMEDIATE"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + exclusive + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case exclusive = "EXCLUSIVE"
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/Database/TransactionObservationExtent.html b/docs/3.3/Classes/Database/TransactionObservationExtent.html new file mode 100644 index 000000000..ab3fff484 --- /dev/null +++ b/docs/3.3/Classes/Database/TransactionObservationExtent.html @@ -0,0 +1,903 @@ + + + + TransactionObservationExtent Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

TransactionObservationExtent

+
+
+
public enum TransactionObservationExtent
+ +
+
+

The extent of a transaction observation

+ +

See Database.add(transactionObserver:extent:)

+ +
+
+
+
    +
  • +
    + + + + observerLifetime + +
    +
    +
    +
    +
    +
    +

    Observation lasts until observer is deallocated

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case observerLifetime
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + nextTransaction + +
    +
    +
    +
    +
    +
    +

    Observation lasts until the next transaction

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case nextTransaction
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseLifetime + +
    +
    +
    +
    +
    +
    +

    Observation lasts until the database is closed

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case databaseLifetime
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/DatabaseCollation.html b/docs/3.3/Classes/DatabaseCollation.html new file mode 100644 index 000000000..34581dc52 --- /dev/null +++ b/docs/3.3/Classes/DatabaseCollation.html @@ -0,0 +1,1134 @@ + + + + DatabaseCollation Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseCollation

+
+
+
public final class DatabaseCollation
+ +
+
+

A Collation is a string comparison function used by SQLite.

+ +
+
+
+
    +
  • +
    + + + + name + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let name: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:function:) + +
    +
    +
    +
    +
    +
    +

    Creates a collation.

    +
    let collation = DatabaseCollation("localized_standard") { (string1, string2) in
    +    return (string1 as NSString).localizedStandardCompare(string2)
    +}
    +db.add(collation: collation)
    +try db.execute("CREATE TABLE file (name TEXT COLLATE localized_standard")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ name: String, function: @escaping (String, String) -> ComparisonResult)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + name + + +
    +

    The function name.

    +
    +
    + + function + + +
    +

    A function that compares two strings.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + unicodeCompare + +
    +
    +
    +
    +
    +
    +

    A collation, or SQL string comparison function, that compares strings +according to the the Swift built-in == and <= operators.

    + +

    This collation is automatically added by GRDB to your database +connections.

    + +

    You can use it when creating database tables:

    +
    let collationName = DatabaseCollation.caseInsensitiveCompare.name
    +dbQueue.execute(
    +    "CREATE TABLE players (" +
    +        "name TEXT COLLATE \(collationName)" +
    +    ")"
    +)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let unicodeCompare: DatabaseCollation
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    A collation, or SQL string comparison function, that compares strings +according to the the Swift built-in caseInsensitiveCompare(_:) method.

    + +

    This collation is automatically added by GRDB to your database +connections.

    + +

    You can use it when creating database tables:

    +
    let collationName = DatabaseCollation.caseInsensitiveCompare.name
    +dbQueue.execute(
    +    "CREATE TABLE players (" +
    +        "name TEXT COLLATE \(collationName)" +
    +    ")"
    +)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let caseInsensitiveCompare: DatabaseCollation
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    A collation, or SQL string comparison function, that compares strings +according to the the Swift built-in localizedCaseInsensitiveCompare(_:) method.

    + +

    This collation is automatically added by GRDB to your database +connections.

    + +

    You can use it when creating database tables:

    +
    let collationName = DatabaseCollation.localizedCaseInsensitiveCompare.name
    +dbQueue.execute(
    +    "CREATE TABLE players (" +
    +        "name TEXT COLLATE \(collationName)" +
    +    ")"
    +)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let localizedCaseInsensitiveCompare: DatabaseCollation
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + localizedCompare + +
    +
    +
    +
    +
    +
    +

    A collation, or SQL string comparison function, that compares strings +according to the the Swift built-in localizedCompare(_:) method.

    + +

    This collation is automatically added by GRDB to your database +connections.

    + +

    You can use it when creating database tables:

    +
    let collationName = DatabaseCollation.localizedCompare.name
    +dbQueue.execute(
    +    "CREATE TABLE players (" +
    +        "name TEXT COLLATE \(collationName)" +
    +    ")"
    +)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let localizedCompare: DatabaseCollation
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    A collation, or SQL string comparison function, that compares strings +according to the the Swift built-in localizedStandardCompare(_:) method.

    + +

    This collation is automatically added by GRDB to your database +connections.

    + +

    You can use it when creating database tables:

    +
    let collationName = DatabaseCollation.localizedStandardCompare.name
    +dbQueue.execute(
    +    "CREATE TABLE players (" +
    +        "name TEXT COLLATE \(collationName)" +
    +    ")"
    +)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let localizedStandardCompare: DatabaseCollation
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/DatabaseFunction.html b/docs/3.3/Classes/DatabaseFunction.html new file mode 100644 index 000000000..240a4bf7b --- /dev/null +++ b/docs/3.3/Classes/DatabaseFunction.html @@ -0,0 +1,1374 @@ + + + + DatabaseFunction Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseFunction

+
+
+
public final class DatabaseFunction : Hashable
+ +
+
+

An SQL function or aggregate.

+ +
+
+
+
    +
  • +
    + + + + name + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var name: String { get }
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns an SQL function.

    +
    let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
    +    guard let int = Int.fromDatabaseValue(dbValues[0]) else {
    +        return nil
    +    }
    +    return int + 1
    +}
    +db.add(function: fn)
    +try Int.fetchOne(db, "SELECT succ(1)")! // 2
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + name + + +
    +

    The function name.

    +
    +
    + + argumentCount + + +
    +

    The number of arguments of the function. If +omitted, or nil, the function accepts any number of arguments.

    +
    +
    + + pure + + +
    +

    Whether the function is pure, which means that its results +only depends on its inputs. When a function is pure, SQLite has +the opportunity to perform additional optimizations. Default value +is false.

    +
    +
    + + function + + +
    +

    A function that takes an array of DatabaseValue +arguments, and returns an optional DatabaseValueConvertible such +as Int, String, NSDate, etc. The array is guaranteed to have +exactly argumentCount elements, provided argumentCount is +not nil.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns an SQL aggregate function.

    +
    struct MySum : DatabaseAggregate {
    +    var sum: Int = 0
    +
    +    mutating func step(_ dbValues: [DatabaseValue]) {
    +        if let int = Int.fromDatabaseValue(dbValues[0]) {
    +            sum += int
    +        }
    +    }
    +
    +    func finalize() -> DatabaseValueConvertible? {
    +        return sum
    +    }
    +}
    +
    +let dbQueue = DatabaseQueue()
    +let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
    +dbQueue.add(function: fn)
    +try dbQueue.write { db in
    +    try db.execute("CREATE TABLE test(i)")
    +    try db.execute("INSERT INTO test(i) VALUES (1)")
    +    try db.execute("INSERT INTO test(i) VALUES (2)")
    +    try Int.fetchOne(db, "SELECT mysum(i) FROM test")! // 3
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init<Aggregate: DatabaseAggregate>(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, aggregate: Aggregate.Type)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + name + + +
    +

    The function name.

    +
    +
    + + argumentCount + + +
    +

    The number of arguments of the aggregate. If +omitted, or nil, the aggregate accepts any number of arguments.

    +
    +
    + + pure + + +
    +

    Whether the aggregate is pure, which means that its +results only depends on its inputs. When an aggregate is pure, +SQLite has the opportunity to perform additional optimizations. +Default value is false.

    +
    +
    + + aggregate + + +
    +

    A type that implements the DatabaseAggregate protocol. +For each step of the aggregation, its step method is called with +an array of DatabaseValue arguments. The array is guaranteed to +have exactly argumentCount elements, provided argumentCount is +not nil.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + capitalize + +
    +
    +
    +
    +
    +
    +

    An SQL function that returns the Swift built-in capitalized +String property.

    + +

    The function returns NULL for non-strings values.

    + +

    This function is automatically added by GRDB to your database +connections. It is the function used by the query interface’s +capitalized:

    +
    let nameColumn = Column("name")
    +let request = Player.select(nameColumn.capitalized)
    +let names = try String.fetchAll(dbQueue, request)   // [String]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let capitalize: DatabaseFunction
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + lowercase + +
    +
    +
    +
    +
    +
    +

    An SQL function that returns the Swift built-in lowercased +String property.

    + +

    The function returns NULL for non-strings values.

    + +

    This function is automatically added by GRDB to your database +connections. It is the function used by the query interface’s +lowercased:

    +
    let nameColumn = Column("name")
    +let request = Player.select(nameColumn.lowercased())
    +let names = try String.fetchAll(dbQueue, request)   // [String]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let lowercase: DatabaseFunction
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + uppercase + +
    +
    +
    +
    +
    +
    +

    An SQL function that returns the Swift built-in uppercased +String property.

    + +

    The function returns NULL for non-strings values.

    + +

    This function is automatically added by GRDB to your database +connections. It is the function used by the query interface’s +uppercased:

    +
    let nameColumn = Column("name")
    +let request = Player.select(nameColumn.uppercased())
    +let names = try String.fetchAll(dbQueue, request)   // [String]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let uppercase: DatabaseFunction
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + localizedCapitalize + +
    +
    +
    +
    +
    +
    +

    An SQL function that returns the Swift built-in +localizedCapitalized String property.

    + +

    The function returns NULL for non-strings values.

    + +

    This function is automatically added by GRDB to your database +connections. It is the function used by the query interface’s +localizedCapitalized:

    +
    let nameColumn = Column("name")
    +let request = Player.select(nameColumn.localizedCapitalized)
    +let names = try String.fetchAll(dbQueue, request)   // [String]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
    +public static let localizedCapitalize: DatabaseFunction
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + localizedLowercase + +
    +
    +
    +
    +
    +
    +

    An SQL function that returns the Swift built-in +localizedLowercased String property.

    + +

    The function returns NULL for non-strings values.

    + +

    This function is automatically added by GRDB to your database +connections. It is the function used by the query interface’s +localizedLowercased:

    +
    let nameColumn = Column("name")
    +let request = Player.select(nameColumn.localizedLowercased)
    +let names = try String.fetchAll(dbQueue, request)   // [String]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
    +public static let localizedLowercase: DatabaseFunction
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + localizedUppercase + +
    +
    +
    +
    +
    +
    +

    An SQL function that returns the Swift built-in +localizedUppercased String property.

    + +

    The function returns NULL for non-strings values.

    + +

    This function is automatically added by GRDB to your database +connections. It is the function used by the query interface’s +localizedUppercased:

    +
    let nameColumn = Column("name")
    +let request = Player.select(nameColumn.localizedUppercased)
    +let names = try String.fetchAll(dbQueue, request)   // [String]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
    +public static let localizedUppercase: DatabaseFunction
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/DatabasePool.html b/docs/3.3/Classes/DatabasePool.html new file mode 100644 index 000000000..d832f3eea --- /dev/null +++ b/docs/3.3/Classes/DatabasePool.html @@ -0,0 +1,1927 @@ + + + + DatabasePool Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabasePool

+
+
+
public final class DatabasePool : DatabaseWriter
+ +
+
+

A DatabasePool grants concurrent accesses to an SQLite database.

+ +
+
+
+ +
    +
  • +
    + + + + path + +
    +
    +
    +
    +
    +
    +

    The path to the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var path: String { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Opens the SQLite database at path path.

    +
    let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
    +
    + +

    Database connections get closed when the database pool gets deallocated.

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(path: String, configuration: Configuration = Configuration()) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + path + + +
    +

    The path to the database file.

    +
    +
    + + configuration + + +
    +

    A configuration.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+ +
    +
  • +
    + + + + releaseMemory() + +
    +
    +
    +
    +
    +
    +

    Free as much memory as possible.

    + +

    This method blocks the current thread until all database accesses are completed.

    + +

    See also setupMemoryManagement(application:)

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func releaseMemory()
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Listens to UIApplicationDidEnterBackgroundNotification and +UIApplicationDidReceiveMemoryWarningNotification in order to release +as much memory as possible.

    + +
      +
    • param application: The UIApplication that will start a background +task to let the database pool release its memory when the application +enters background.
    • +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func setupMemoryManagement(in application: UIApplication)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + read(_:) + +
    +
    +
    +
    +
    +
    +

    Synchronously executes a read-only block in a protected dispatch queue, +and returns its result. The block is wrapped in a deferred transaction.

    +
    let players = try dbPool.read { db in
    +    try Player.fetchAll(...)
    +}
    +
    + +

    The block is completely isolated. Eventual concurrent database updates +are not visible inside the block:

    +
    try dbPool.read { db in
    +    // Those two values are guaranteed to be equal, even if the
    +    // `wine` table is modified between the two requests:
    +    let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +    let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +}
    +
    +try dbPool.read { db in
    +    // Now this value may be different:
    +    let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +}
    +
    + +

    This method is not reentrant.

    +
    +

    Throws

    + The error thrown by the block, or any DatabaseError that would +happen while establishing the read access to the database. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func read<T>(_ block: (Database) throws -> T) throws -> T
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + block + + +
    +

    A block that accesses the database.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + unsafeRead(_:) + +
    +
    +
    +
    +
    +
    +

    Synchronously executes a read-only block in a protected dispatch queue, +and returns its result.

    + +

    The block argument is not isolated: eventual concurrent database updates +are visible inside the block:

    +
    try dbPool.unsafeRead { db in
    +    // Those two values may be different because some other thread
    +    // may have inserted or deleted a wine between the two requests:
    +    let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +    let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +}
    +
    + +

    Cursor iteration is safe, though:

    +
    try dbPool.unsafeRead { db in
    +    // No concurrent update can mess with this iteration:
    +    let rows = try Row.fetchCursor(db, "SELECT ...")
    +    while let row = try rows.next() { ... }
    +}
    +
    + +

    This method is not reentrant.

    +
    +

    Throws

    + The error thrown by the block, or any DatabaseError that would +happen while establishing the read access to the database. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + block + + +
    +

    A block that accesses the database.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Synchronously executes a read-only block in a protected dispatch queue, +and returns its result.

    + +

    The block argument is not isolated: eventual concurrent database updates +are visible inside the block:

    +
    try dbPool.unsafeReentrantRead { db in
    +    // Those two values may be different because some other thread
    +    // may have inserted or deleted a wine between the two requests:
    +    let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +    let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +}
    +
    + +

    Cursor iteration is safe, though:

    +
    try dbPool.unsafeReentrantRead { db in
    +    // No concurrent update can mess with this iteration:
    +    let rows = try Row.fetchCursor(db, "SELECT ...")
    +    while let row = try rows.next() { ... }
    +}
    +
    + +

    This method is reentrant. It is unsafe because it fosters dangerous +concurrency practices.

    +
    +

    Throws

    + The error thrown by the block, or any DatabaseError that would +happen while establishing the read access to the database. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + block + + +
    +

    A block that accesses the database.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Asynchronously executes a read-only block in a protected dispatch queue, +wrapped in a deferred transaction.

    + +

    This method must be called from the writing dispatch queue, outside of a +transaction. You’ll get a fatal error otherwise.

    + +

    The block argument is guaranteed to see the database in the last +committed state at the moment this method is called. Eventual concurrent +database updates are not visible inside the block.

    +
    try dbPool.write { db in
    +    try db.execute("DELETE FROM player")
    +    try dbPool.readFromCurrentState { db in
    +        // Guaranteed to be zero
    +        try Int.fetchOne(db, "SELECT COUNT(*) FROM player")!
    +    }
    +    try db.execute("INSERT INTO player ...")
    +}
    +
    + +

    This method blocks the current thread until the isolation guarantee has +been established, and before the block argument has run.

    +
    +

    Throws

    + The error thrown by the block, or any DatabaseError that would +happen while establishing the read access to the database. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + block + + +
    +

    A block that accesses the database.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + write(_:) + +
    +
    +
    +
    +
    +
    +

    Synchronously executes an update block in a protected dispatch queue, +wrapped inside a transaction, and returns the result of the block.

    + +

    Eventual concurrent database updates are postponed until the block +has executed.

    +
    try dbPool.write { db in
    +    try db.execute(...)
    +}
    +
    + +

    Eventual concurrent reads are guaranteed not to see any changes +performed in the block until they are all saved in the database.

    + +

    This method is not reentrant.

    +
    +

    Throws

    + The error thrown by the block, or by the wrapping transaction. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func write<T>(_ block: (Database) throws -> T) throws -> T
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Synchronously executes a block that takes a database connection, and +returns its result.

    + +

    Eventual concurrent database updates are postponed until the block +has executed.

    + +

    Eventual concurrent reads may see changes performed in the block before +the block completes.

    + +

    The block is guaranteed to be executed outside of a transaction.

    + +

    This method is not reentrant.

    +
    +

    Throws

    + The error thrown by the block. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func writeWithoutTransaction<T>(_ block: (Database) throws -> T) rethrows -> T
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Synchronously executes a block in a protected dispatch queue, wrapped +inside a transaction.

    + +

    Eventual concurrent database updates are postponed until the block +has executed.

    + +

    If the block throws an error, the transaction is rollbacked and the +error is rethrown. If the block returns .rollback, the transaction is +also rollbacked, but no error is thrown.

    +
    try dbPool.writeInTransaction { db in
    +    db.execute(...)
    +    return .commit
    +}
    +
    + +

    Eventual concurrent reads are guaranteed not to see any changes +performed in the block until they are all saved in the database.

    + +

    This method is not reentrant.

    +
    +

    Throws

    + The error thrown by the block, or any error establishing the +transaction. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + kind + + +
    +

    The transaction type (default nil). If nil, the transaction +type is configuration.defaultTransactionKind, which itself +defaults to .deferred. See https://www.sqlite.org/lang_transaction.html +for more information.

    +
    +
    + + block + + +
    +

    A block that executes SQL statements and return either +.commit or .rollback.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Synchronously executes an update block in a protected dispatch queue, +and returns its result.

    + +

    Eventual concurrent database updates are postponed until the block +has executed.

    +
    try dbPool.unsafeReentrantWrite { db in
    +    try db.execute(...)
    +}
    +
    + +

    Eventual concurrent reads may see changes performed in the block before +the block completes.

    + +

    This method is reentrant. It is unsafe because it fosters dangerous +concurrency practices.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(function:) + +
    +
    +
    +
    +
    +
    +

    Add or redefine an SQL function.

    +
    let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
    +    guard let int = Int.fromDatabaseValue(dbValues[0]) else {
    +        return nil
    +    }
    +    return int + 1
    +}
    +dbPool.add(function: fn)
    +try dbPool.read { db in
    +    try Int.fetchOne(db, "SELECT succ(1)") // 2
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func add(function: DatabaseFunction)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + remove(function:) + +
    +
    +
    +
    +
    +
    +

    Remove an SQL function.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func remove(function: DatabaseFunction)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(collation:) + +
    +
    +
    +
    +
    +
    +

    Add or redefine a collation.

    +
    let collation = DatabaseCollation("localized_standard") { (string1, string2) in
    +    return (string1 as NSString).localizedStandardCompare(string2)
    +}
    +dbPool.add(collation: collation)
    +try dbPool.write { db in
    +    try db.execute("CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD")
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func add(collation: DatabaseCollation)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + remove(collation:) + +
    +
    +
    +
    +
    +
    +

    Remove a collation.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func remove(collation: DatabaseCollation)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + makeSnapshot() + +
    +
    +
    +
    +
    +
    +

    Creates a database snapshot.

    + +

    The snapshot sees an unchanging database content, as it existed at the +moment it was created.

    + +

    When you want to control the latest committed changes seen by a +snapshot, create it from the pool’s writer protected dispatch queue:

    +
    let snapshot1 = try dbPool.write { db -> DatabaseSnapshot in
    +    try Player.deleteAll()
    +    return try dbPool.makeSnapshot()
    +}
    +// <- Other threads may modify the database here
    +let snapshot2 = try dbPool.makeSnapshot()
    +
    +try snapshot1.read { db in
    +    // Guaranteed to be zero
    +    try Player.fetchCount(db)
    +}
    +
    +try snapshot2.read { db in
    +    // Could be anything
    +    try Player.fetchCount(db)
    +}
    +
    + +

    It is forbidden to create a snapshot from the writer protected dispatch +queue when a transaction is opened, though, because it is likely a +programmer error:

    +
    try dbPool.write { db in
    +    try db.inTransaction {
    +        try Player.deleteAll()
    +        // fatal error: makeSnapshot() must not be called from inside a transaction
    +        let snapshot = try dbPool.makeSnapshot()
    +        return .commit
    +    }
    +}
    +
    + +

    To avoid this fatal error, create the snapshot before or after the +transaction:

    +
    try dbPool.writeWithoutTransaction { db in
    +    // OK
    +    let snapshot = try dbPool.makeSnapshot()
    +
    +    try db.inTransaction {
    +        try Player.deleteAll()
    +        return .commit
    +    }
    +
    +    // OK
    +    let snapshot = try dbPool.makeSnapshot()
    +}
    +
    + +

    You can create as many snapshots as you need, regardless of the maximum +number of reader connections in the pool.

    + +

    For more information, read about snapshot isolation at https://sqlite.org/isolation.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func makeSnapshot() throws -> DatabaseSnapshot
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Listens to UIApplicationDidEnterBackgroundNotification and +UIApplicationDidReceiveMemoryWarningNotification in order to release +as much memory as possible.

    + +
      +
    • param application: The UIApplication that will start a background +task to let the database pool release its memory when the application +enters background.
    • +
    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/DatabaseQueue.html b/docs/3.3/Classes/DatabaseQueue.html new file mode 100644 index 000000000..6a7e42d8a --- /dev/null +++ b/docs/3.3/Classes/DatabaseQueue.html @@ -0,0 +1,1628 @@ + + + + DatabaseQueue Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseQueue

+
+
+
public final class DatabaseQueue : DatabaseWriter
+ +
+
+

A DatabaseQueue serializes access to an SQLite database.

+ +
+
+
+ +
    +
  • +
    + + + + configuration + +
    +
    +
    +
    +
    +
    +

    The database configuration

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var configuration: Configuration { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + path + +
    +
    +
    +
    +
    +
    +

    The path to the database file; it is :memory: for in-memory databases.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var path: String { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Opens the SQLite database at path path.

    +
    let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
    +
    + +

    Database connections get closed when the database queue gets deallocated.

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(path: String, configuration: Configuration = Configuration()) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + path + + +
    +

    The path to the database file.

    +
    +
    + + configuration + + +
    +

    A configuration.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(configuration:) + +
    +
    +
    +
    +
    +
    +

    Opens an in-memory SQLite database.

    +
    let dbQueue = DatabaseQueue()
    +
    + +

    Database memory is released when the database queue gets deallocated.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(configuration: Configuration = Configuration())
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + configuration + + +
    +

    A configuration.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + releaseMemory() + +
    +
    +
    +
    +
    +
    +

    Free as much memory as possible.

    + +

    This method blocks the current thread until all database accesses are completed.

    + +

    See also setupMemoryManagement(application:)

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func releaseMemory()
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Listens to UIApplicationDidEnterBackgroundNotification and +UIApplicationDidReceiveMemoryWarningNotification in order to release +as much memory as possible.

    + +
      +
    • param application: The UIApplication that will start a background +task to let the database queue release its memory when the application +enters background.
    • +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func setupMemoryManagement(in application: UIApplication)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + read(_:) + +
    +
    +
    +
    +
    +
    +

    Synchronously executes a read-only block in a protected dispatch queue, +and returns its result.

    +
    let players = try dbQueue.read { db in
    +    try Player.fetchAll(db)
    +}
    +
    + +

    This method is not reentrant.

    + +

    Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and +SQLCipher), attempts to write in the database from this meethod throw a +DatabaseError of resultCode SQLITE_READONLY.

    +
    +

    Throws

    + The error thrown by the block. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func read<T>(_ block: (Database) throws -> T) rethrows -> T
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + block + + +
    +

    A block that accesses the database.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + write(_:) + +
    +
    +
    +
    +
    +
    +

    Synchronously executes a block in a protected dispatch queue, wrapped +inside a transaction.

    + +

    If the block throws an error, the transaction is rollbacked and the +error is rethrown.

    +
    try dbQueue.write { db in
    +    try Player(...).insert(db)
    +}
    +
    + +

    This method is not reentrant.

    +
    +

    Throws

    + An eventual database error, or the error thrown by the block. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func write<T>(_ block: (Database) throws -> T) throws -> T
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + block + + +
    +

    A block that executes SQL statements.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + inTransaction(_:_:) + +
    +
    +
    +
    +
    +
    +

    Synchronously executes a block in a protected dispatch queue, wrapped +inside a transaction.

    + +

    If the block throws an error, the transaction is rollbacked and the +error is rethrown. If the block returns .rollback, the transaction is +also rollbacked, but no error is thrown.

    +
    try dbQueue.inTransaction { db in
    +    try Player(...).insert(db)
    +    return .commit
    +}
    +
    + +

    This method is not reentrant.

    +
    +

    Throws

    + The error thrown by the block. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func inTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + kind + + +
    +

    The transaction type (default nil). If nil, the transaction +type is configuration.defaultTransactionKind, which itself +defaults to .deferred. See https://www.sqlite.org/lang_transaction.html +for more information.

    +
    +
    + + block + + +
    +

    A block that executes SQL statements and return either +.commit or .rollback.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + inDatabase(_:) + +
    +
    +
    +
    +
    +
    +

    Synchronously executes a block in a protected dispatch queue, and +returns its result.

    +
    // INSERT INTO player ...
    +let players = try dbQueue.inDatabase { db in
    +    try Player(...).insert(db)
    +}
    +
    + +

    This method is not reentrant.

    +
    +

    Throws

    + The error thrown by the block. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func inDatabase<T>(_ block: (Database) throws -> T) rethrows -> T
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + block + + +
    +

    A block that accesses the database.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Synchronously executes a block in a protected dispatch queue, and +returns its result.

    +
    // INSERT INTO player ...
    +try dbQueue.unsafeReentrantWrite { db in
    +    try Player(...).insert(db)
    +}
    +
    + +

    This method is reentrant. It is unsafe because it fosters dangerous +concurrency practices.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(function:) + +
    +
    +
    +
    +
    +
    +

    Add or redefine an SQL function.

    +
    let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
    +    guard let int = Int.fromDatabaseValue(dbValues[0]) else {
    +        return nil
    +    }
    +    return int + 1
    +}
    +dbQueue.add(function: fn)
    +try dbQueue.read { db in
    +    try Int.fetchOne(db, "SELECT succ(1)") // 2
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func add(function: DatabaseFunction)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + remove(function:) + +
    +
    +
    +
    +
    +
    +

    Remove an SQL function.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func remove(function: DatabaseFunction)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(collation:) + +
    +
    +
    +
    +
    +
    +

    Add or redefine a collation.

    +
    let collation = DatabaseCollation("localized_standard") { (string1, string2) in
    +    return (string1 as NSString).localizedStandardCompare(string2)
    +}
    +dbQueue.add(collation: collation)
    +try dbQueue.write { db in
    +    try db.execute("CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD")
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func add(collation: DatabaseCollation)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + remove(collation:) + +
    +
    +
    +
    +
    +
    +

    Remove a collation.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func remove(collation: DatabaseCollation)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Listens to UIApplicationDidEnterBackgroundNotification and +UIApplicationDidReceiveMemoryWarningNotification in order to release +as much memory as possible.

    + +
      +
    • param application: The UIApplication that will start a background +task to let the database queue release its memory when the application +enters background.
    • +
    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/DatabaseSnapshot.html b/docs/3.3/Classes/DatabaseSnapshot.html new file mode 100644 index 000000000..8492fe1ae --- /dev/null +++ b/docs/3.3/Classes/DatabaseSnapshot.html @@ -0,0 +1,1043 @@ + + + + DatabaseSnapshot Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseSnapshot

+
+
+
public class DatabaseSnapshot : DatabaseReader
+ +
+
+

A DatabaseSnapshot sees an unchanging database content, as it existed at the +moment it was created.

+ +

See DatabasePool.makeSnapshot()

+ +

For more information, read about snapshot isolation at https://sqlite.org/isolation.html

+ +
+
+
+ +
    +
  • +
    + + + + read(_:) + +
    +
    +
    +
    +
    +
    +

    Synchronously executes a read-only block that takes a database +connection, and returns its result.

    +
    let players = try snapshot.read { db in
    +    try Player.fetchAll(...)
    +}
    +
    +
    +

    Throws

    + The error thrown by the block. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func read<T>(_ block: (Database) throws -> T) rethrows -> T
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + block + + +
    +

    A block that accesses the database.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(function:) + +
    +
    +
    +
    +
    +
    +

    Add or redefine an SQL function.

    +
    let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
    +    guard let int = Int.fromDatabaseValue(dbValues[0]) else {
    +        return nil
    +    }
    +    return int + 1
    +}
    +snapshot.add(function: fn)
    +try snapshot.read { db in
    +    try Int.fetchOne(db, "SELECT succ(1)") // 2
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func add(function: DatabaseFunction)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + remove(function:) + +
    +
    +
    +
    +
    +
    +

    Remove an SQL function.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func remove(function: DatabaseFunction)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(collation:) + +
    +
    +
    +
    +
    +
    +

    Add or redefine a collation.

    +
    let collation = DatabaseCollation("localized_standard") { (string1, string2) in
    +    return (string1 as NSString).localizedStandardCompare(string2)
    +}
    +snapshot.add(collation: collation)
    +let files = try snapshot.read { db in
    +    try File.fetchAll(db, "SELECT * FROM file ORDER BY name COLLATE localized_standard")
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func add(collation: DatabaseCollation)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + remove(collation:) + +
    +
    +
    +
    +
    +
    +

    Remove a collation.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func remove(collation: DatabaseCollation)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/FTS3TableDefinition.html b/docs/3.3/Classes/FTS3TableDefinition.html new file mode 100644 index 000000000..041aaef04 --- /dev/null +++ b/docs/3.3/Classes/FTS3TableDefinition.html @@ -0,0 +1,907 @@ + + + + FTS3TableDefinition Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS3TableDefinition

+
+
+
public final class FTS3TableDefinition
+ +
+
+

The FTS3TableDefinition class lets you define columns of a FTS3 virtual table.

+ +

You don’t create instances of this class. Instead, you use the Database +create(virtualTable:using:) method:

+
try db.create(virtualTable: "document", using: FTS3()) { t in // t is FTS3TableDefinition
+    t.column("content")
+}
+
+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/FTS4ColumnDefinition.html b/docs/3.3/Classes/FTS4ColumnDefinition.html new file mode 100644 index 000000000..8c0fa2068 --- /dev/null +++ b/docs/3.3/Classes/FTS4ColumnDefinition.html @@ -0,0 +1,905 @@ + + + + FTS4ColumnDefinition Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS4ColumnDefinition

+
+
+
public final class FTS4ColumnDefinition
+ +
+
+

The FTS4ColumnDefinition class lets you refine a column of an FTS4 +virtual table.

+ +

You get instances of this class when you create an FTS4 table:

+
try db.create(virtualTable: "document", using: FTS4()) { t in
+    t.column("content")      // FTS4ColumnDefinition
+}
+
+ +

See https://www.sqlite.org/fts3.html

+ +
+
+
+
    +
  • +
    + + + + notIndexed() + +
    +
    +
    +
    +
    +
    +

    Excludes the column from the full-text index.

    +
    try db.create(virtualTable: "document", using: FTS4()) { t in
    +    t.column("a")
    +    t.column("b").notIndexed()
    +}
    +
    + +

    See https://www.sqlite.org/fts3.html#the_notindexed_option

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @available(iOS 8.2, OSX 10.10, *)
    +@discardableResult
    +public func notIndexed() -> Self
    + +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
  • +
    + + + + asLanguageId() + +
    +
    +
    +
    +
    +
    +

    Uses the column as the Int32 language id hidden column.

    +
    try db.create(virtualTable: "document", using: FTS4()) { t in
    +    t.column("a")
    +    t.column("lid").asLanguageId()
    +}
    +
    + +

    See https://www.sqlite.org/fts3.html#the_languageid_option

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func asLanguageId() -> Self
    + +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/FTS4TableDefinition.html b/docs/3.3/Classes/FTS4TableDefinition.html new file mode 100644 index 000000000..60e963eb5 --- /dev/null +++ b/docs/3.3/Classes/FTS4TableDefinition.html @@ -0,0 +1,1120 @@ + + + + FTS4TableDefinition Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS4TableDefinition

+
+
+
public final class FTS4TableDefinition
+ +
+
+

The FTS4TableDefinition class lets you define columns of a FTS4 virtual table.

+ +

You don’t create instances of this class. Instead, you use the Database +create(virtualTable:using:) method:

+
try db.create(virtualTable: "document", using: FTS4()) { t in // t is FTS4TableDefinition
+    t.column("content")
+}
+
+ +

See https://www.sqlite.org/fts3.html

+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/FTS5ColumnDefinition.html b/docs/3.3/Classes/FTS5ColumnDefinition.html new file mode 100644 index 000000000..8f0589172 --- /dev/null +++ b/docs/3.3/Classes/FTS5ColumnDefinition.html @@ -0,0 +1,840 @@ + + + + FTS5ColumnDefinition Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS5ColumnDefinition

+

The FTS5ColumnDefinition class lets you refine a column of an FTS5 +virtual table.

+ +

You get instances of this class when you create an FTS5 table:

+
try db.create(virtualTable: "document", using: FTS5()) { t in
+    t.column("content")      // FTS5ColumnDefinition
+}
+
+ +

See https://www.sqlite.org/fts5.html

+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/FTS5TableDefinition.html b/docs/3.3/Classes/FTS5TableDefinition.html new file mode 100644 index 000000000..ccf6c2d71 --- /dev/null +++ b/docs/3.3/Classes/FTS5TableDefinition.html @@ -0,0 +1,1007 @@ + + + + FTS5TableDefinition Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS5TableDefinition

+

The FTS5TableDefinition class lets you define columns of a FTS5 virtual table.

+ +

You don’t create instances of this class. Instead, you use the Database +create(virtualTable:using:) method:

+
try db.create(virtualTable: "document", using: FTS5()) { t in // t is FTS5TableDefinition
+    t.column("content")
+}
+
+ +

See https://www.sqlite.org/fts5.html

+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/FetchedRecordsController.html b/docs/3.3/Classes/FetchedRecordsController.html new file mode 100644 index 000000000..0aaaf3406 --- /dev/null +++ b/docs/3.3/Classes/FetchedRecordsController.html @@ -0,0 +1,1965 @@ + + + + FetchedRecordsController Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FetchedRecordsController

+
+
+
public final class FetchedRecordsController<Record> where Record : FetchableRecord
+ +
+
+

You use FetchedRecordsController to track changes in the results of an +SQLite request.

+ +

See https://github.com/groue/GRDB.swift#fetchedrecordscontroller for +more information.

+ +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Creates a fetched records controller initialized from a SQL query and +its eventual arguments.

    +
    let controller = FetchedRecordsController<Wine>(
    +    dbQueue,
    +    sql: "SELECT * FROM wine WHERE color = ? ORDER BY name",
    +    arguments: [Color.red],
    +    isSameRecord: { (wine1, wine2) in wine1.id == wine2.id })
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public convenience init(
    +    _ databaseWriter: DatabaseWriter,
    +    sql: String,
    +    arguments: StatementArguments? = nil,
    +    adapter: RowAdapter? = nil,
    +    queue: DispatchQueue = .main,
    +    isSameRecord: ((Record, Record) -> Bool)? = nil) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + databaseWriter + + +
    +

    A DatabaseWriter (DatabaseQueue, or DatabasePool)

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    + + queue + + +
    +

    A serial dispatch queue (defaults to the main queue)

    + +

    The fetched records controller tracking callbacks will be +notified of changes in this queue. The controller itself must be +used from this queue.

    +
    +
    + + isSameRecord + + +
    +

    Optional function that compares two records.

    + +

    This function should return true if the two records have the +same identity. For example, they have the same id.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a fetched records controller initialized from a fetch request +from the Query Interface.

    +
    let request = Wine.order(Column("name"))
    +let controller = FetchedRecordsController(
    +    dbQueue,
    +    request: request,
    +    isSameRecord: { (wine1, wine2) in wine1.id == wine2.id })
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public convenience init<Request>(
    +    _ databaseWriter: DatabaseWriter,
    +    request: Request,
    +    queue: DispatchQueue = .main,
    +    isSameRecord: ((Record, Record) -> Bool)? = nil) throws
    +    where Request: FetchRequest, Request.RowDecoder == Record
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + databaseWriter + + +
    +

    A DatabaseWriter (DatabaseQueue, or DatabasePool)

    +
    +
    + + request + + +
    +

    A fetch request.

    +
    +
    + + queue + + +
    +

    A serial dispatch queue (defaults to the main queue)

    + +

    The fetched records controller tracking callbacks will be +notified of changes in this queue. The controller itself must be +used from this queue.

    +
    +
    + + isSameRecord + + +
    +

    Optional function that compares two records.

    + +

    This function should return true if the two records have the +same identity. For example, they have the same id.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + performFetch() + +
    +
    +
    +
    +
    +
    +

    Executes the controller’s fetch request.

    + +

    After executing this method, you can access the the fetched objects with +the fetchedRecords property.

    + +

    This method must be used from the controller’s dispatch queue (the +main queue unless stated otherwise in the controller’s initializer).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func performFetch() throws
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + databaseWriter + +
    +
    +
    +
    +
    +
    +

    The database writer used to fetch records.

    + +

    The controller registers as a transaction observer in order to respond +to changes.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let databaseWriter: DatabaseWriter
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + queue + +
    +
    +
    +
    +
    +
    +

    The dispatch queue on which the controller must be used.

    + +

    Unless specified otherwise at initialization time, it is the main queue.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let queue: DispatchQueue
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + setRequest(_:) + +
    +
    +
    +
    +
    +
    +

    Updates the fetch request, and eventually notifies the tracking +callbacks if performFetch() has been called.

    + +

    This method must be used from the controller’s dispatch queue (the +main queue unless stated otherwise in the controller’s initializer).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func setRequest<Request>(_ request: Request) throws where Record == Request.RowDecoder, Request : FetchRequest
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Updates the fetch request, and eventually notifies the tracking +callbacks if performFetch() has been called.

    + +

    This method must be used from the controller’s dispatch queue (the +main queue unless stated otherwise in the controller’s initializer).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func setRequest(sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Registers changes notification callbacks.

    + +

    This method must be used from the controller’s dispatch queue (the +main queue unless stated otherwise in the controller’s initializer).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func trackChanges(
    +    willChange: ((FetchedRecordsController<Record>) -> ())? = nil,
    +    onChange: ((FetchedRecordsController<Record>, Record, FetchedRecordChange) -> ())? = nil,
    +    didChange: ((FetchedRecordsController<Record>) -> ())? = nil)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + willChange + + +
    +

    Invoked before records are updated.

    +
    +
    + + onChange + + +
    +

    Invoked for each record that has been added, +removed, moved, or updated.

    +
    +
    + + didChange + + +
    +

    Invoked after records have been updated.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Registers changes notification callbacks.

    + +

    This method must be used from the controller’s dispatch queue (the +main queue unless stated otherwise in the controller’s initializer).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func trackChanges<T>(
    +    fetchAlongside: @escaping (Database) throws -> T,
    +    willChange: ((FetchedRecordsController<Record>, _ fetchedAlongside: T) -> ())? = nil,
    +    onChange: ((FetchedRecordsController<Record>, Record, FetchedRecordChange) -> ())? = nil,
    +    didChange: ((FetchedRecordsController<Record>, _ fetchedAlongside: T) -> ())? = nil)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + fetchAlongside + + +
    +

    The value returned from this closure is given to +willChange and didChange callbacks, as their +fetchedAlongside argument. The closure is guaranteed to see the +database in the state it has just after eventual changes to the +fetched records have been performed. Use it in order to fetch +values that must be consistent with the fetched records.

    +
    +
    + + willChange + + +
    +

    Invoked before records are updated.

    +
    +
    + + onChange + + +
    +

    Invoked for each record that has been added, +removed, moved, or updated.

    +
    +
    + + didChange + + +
    +

    Invoked after records have been updated.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + trackErrors(_:) + +
    +
    +
    +
    +
    +
    +

    Registers an error callback.

    + +

    Whenever the controller could not look for changes after a transaction +has potentially modified the tracked request, this error handler is +called.

    + +

    The request observation is not stopped, though: future transactions may +successfully be handled, and the notified changes will then be based on +the last successful fetch.

    + +

    This method must be used from the controller’s dispatch queue (the +main queue unless stated otherwise in the controller’s initializer).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func trackErrors(_ errorHandler: @escaping (FetchedRecordsController<Record>, Error) -> ())
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Call this method when changes performed while the application is +in the background should be processed before the application enters the +suspended state.

    + +

    Whenever the tracked request is changed, the fetched records controller +sets up a background task using +UIApplication.beginBackgroundTask(expirationHandler:) which is ended +after the didChange callback has completed.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func allowBackgroundChangesTracking(in application: UIApplication)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchedRecords + +
    +
    +
    +
    +
    +
    +

    The fetched records.

    + +

    The value of this property is nil until performFetch() has been called.

    + +

    The records reflect the state of the database after the initial +call to performFetch, and after each database transaction that affects +the results of the fetch request.

    + +

    This property must be used from the controller’s dispatch queue (the +main queue unless stated otherwise in the controller’s initializer).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var fetchedRecords: [Record] { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Call this method when changes performed while the application is +in the background should be processed before the application enters the +suspended state.

    + +

    Whenever the tracked request is changed, the fetched records controller +sets up a background task using +UIApplication.beginBackgroundTask(expirationHandler:) which is ended +after the didChange callback has completed.

    + +
    +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Creates a fetched records controller initialized from a SQL query and +its eventual arguments.

    +
    let controller = FetchedRecordsController<Wine>(
    +    dbQueue,
    +    sql: "SELECT * FROM wine WHERE color = ? ORDER BY name",
    +    arguments: [Color.red])
    +
    + +

    The records are compared by primary key (single-column primary key, +compound primary key, or implicit rowid). For a database table which +has an id primary key, this initializer is equivalent to:

    +
    // Assuming the wine table has an `id` primary key:
    +let controller = FetchedRecordsController<Wine>(
    +    dbQueue,
    +    sql: "SELECT * FROM wine WHERE color = ? ORDER BY name",
    +    arguments: [Color.red],
    +    isSameRecord: { (wine1, wine2) in wine1.id == wine2.id })
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public convenience init(
    +    _ databaseWriter: DatabaseWriter,
    +    sql: String,
    +    arguments: StatementArguments? = nil,
    +    adapter: RowAdapter? = nil,
    +    queue: DispatchQueue = .main) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + + + + + +
    + + databaseWriter + + +
    +

    A DatabaseWriter (DatabaseQueue, or DatabasePool)

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    + + queue + + +
    +

    A serial dispatch queue (defaults to the main queue)

    + +

    The fetched records controller tracking callbacks will be +notified of changes in this queue. The controller itself must be +used from this queue.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a fetched records controller initialized from a fetch request +from the Query Interface.

    +
    let request = Wine.order(Column("name"))
    +let controller = FetchedRecordsController(
    +    dbQueue,
    +    request: request)
    +
    + +

    The records are compared by primary key (single-column primary key, +compound primary key, or implicit rowid). For a database table which +has an id primary key, this initializer is equivalent to:

    +
    // Assuming the wine table has an `id` primary key:
    +let controller = FetchedRecordsController<Wine>(
    +    dbQueue,
    +    request: request,
    +    isSameRecord: { (wine1, wine2) in wine1.id == wine2.id })
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public convenience init<Request>(
    +    _ databaseWriter: DatabaseWriter,
    +    request: Request,
    +    queue: DispatchQueue = .main) throws
    +    where Request: FetchRequest, Request.RowDecoder == Record
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + databaseWriter + + +
    +

    A DatabaseWriter (DatabaseQueue, or DatabasePool)

    +
    +
    + + request + + +
    +

    A fetch request.

    +
    +
    + + queue + + +
    +

    A serial dispatch queue (defaults to the main queue)

    + +

    The fetched records controller tracking callbacks will be +notified of changes in this queue. The controller itself must be +used from this queue.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + record(at:) + +
    +
    +
    +
    +
    +
    +

    Returns the object at the given index path.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func record(at indexPath: IndexPath) -> Record
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + indexPath + + +
    +

    An index path in the fetched records.

    + +

    If indexPath does not describe a valid index path in the fetched +records, a fatal error is raised.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + sections + +
    +
    +
    +
    +
    +
    +

    The sections for the fetched records.

    + +

    You typically use the sections array when implementing +UITableViewDataSource methods, such as numberOfSectionsInTableView.

    + +

    The sections array is never empty, even when there are no fetched +records. In this case, there is a single empty section.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var sections: [FetchedRecordsSectionInfo<Record>] { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + indexPath(for:) + +
    +
    +
    +
    +
    +
    +

    Returns the indexPath of a given record.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func indexPath(for record: Record) -> IndexPath?
    + +
    +
    +
    +

    Return Value

    +

    The index path of record in the fetched records, or nil +if record could not be found.

    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/Record.html b/docs/3.3/Classes/Record.html new file mode 100644 index 000000000..af2182d6f --- /dev/null +++ b/docs/3.3/Classes/Record.html @@ -0,0 +1,1657 @@ + + + + Record Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Record

+
+
+
open class Record : FetchableRecord, TableRecord, PersistableRecord
+ +
+
+

Record is a class that wraps a table row, or the result of any query. It is +designed to be subclassed.

+ +
+
+
+ +
    +
  • +
    + + + + init() + +
    +
    +
    +
    +
    +
    +

    Creates a Record.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init()
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(row:) + +
    +
    +
    +
    +
    +
    +

    Creates a Record from a row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    required public init(row: Row)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + databaseTableName + +
    +
    +
    +
    +
    +
    +

    The name of a database table.

    + +

    This table name is required by the insert, update, save, delete, +and exists methods.

    +
    class Player : Record {
    +    override class var databaseTableName: String {
    +        return "player"
    +    }
    +}
    +
    + +

    The implementation of the base class Record raises a fatal error.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    open class var databaseTableName: String { get }
    + +
    +
    +
    +

    Return Value

    +

    The name of a database table.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    The policy that handles SQLite conflicts when records are inserted +or updated.

    + +

    This property is optional: its default value uses the ABORT policy +for both insertions and updates, and has GRDB generate regular +INSERT and UPDATE queries.

    + +

    If insertions are resolved with .ignore policy, the +didInsert(with:for:) method is not called upon successful insertion, +even if a row was actually inserted without any conflict.

    + +

    See https://www.sqlite.org/lang_conflict.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    open class var persistenceConflictPolicy: PersistenceConflictPolicy { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseSelection + +
    +
    +
    +
    +
    +
    +

    The default request selection.

    + +

    Unless this method is overriden, requests select all columns:

    +
    // SELECT * FROM player
    +try Player.fetchAll(db)
    +
    + +

    You can override this property and provide an explicit list +of columns:

    +
    class RestrictedPlayer : Record {
    +    override static var databaseSelection: [SQLSelectable] {
    +        return [Column("id"), Column("name")]
    +    }
    +}
    +
    +// SELECT id, name FROM player
    +try RestrictedPlayer.fetchAll(db)
    +
    + +

    You can also add extra columns such as the rowid column:

    +
    class ExtendedPlayer : Player {
    +    override static var databaseSelection: [SQLSelectable] {
    +        return [AllColumns(), Column.rowID]
    +    }
    +}
    +
    +// SELECT *, rowid FROM player
    +try ExtendedPlayer.fetchAll(db)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    open class var databaseSelection: [SQLSelectable] { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + encode(to:) + +
    +
    +
    +
    +
    +
    +

    Defines the values persisted in the database.

    + +

    Store in the container argument all values that should be stored in +the columns of the database table (see Record.databaseTableName()).

    + +

    Primary key columns, if any, must be included.

    +
    class Player : Record {
    +    var id: Int64?
    +    var name: String?
    +
    +    override func encode(to container: inout PersistenceContainer) {
    +        container["id"] = id
    +        container["name"] = name
    +    }
    +}
    +
    + +

    The implementation of the base class Record does not store any value in +the container.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    open func encode(to container: inout PersistenceContainer)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + didInsert(with:for:) + +
    +
    +
    +
    +
    +
    +

    Notifies the record that it was succesfully inserted.

    + +

    Do not call this method directly: it is called for you, in a protected +dispatch queue, with the inserted RowID and the eventual +INTEGER PRIMARY KEY column name.

    + +

    The implementation of the base Record class does nothing.

    +
    class Player : Record {
    +    var id: Int64?
    +    var name: String?
    +
    +    func didInsert(with rowID: Int64, for column: String?) {
    +        id = rowID
    +    }
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    open func didInsert(with rowID: Int64, for column: String?)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + rowID + + +
    +

    The inserted rowID.

    +
    +
    + + column + + +
    +

    The name of the eventual INTEGER PRIMARY KEY column.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
+ + + +

Copy

+
+
+
    +
  • +
    + + + + copy() + +
    +
    +
    +
    +
    +
    +

    Returns a copy of self, initialized from all values encoded in the +encode(to:) method.

    + +

    The eventual primary key is copied, as well as the +hasDatabaseChanges flag.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    open func copy() -> Self
    + +
    +
    +
    +

    Return Value

    +

    A copy of self.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + hasDatabaseChanges + +
    +
    +
    +
    +
    +
    +

    A boolean that indicates whether the record has changes that have not +been saved.

    + +

    This flag is purely informative, and does not prevent insert(), +update(), and save() from performing their database queries.

    + +

    A record is edited if has been changed since last database +synchronization (fetch, update, insert). Comparison +is performed between values (values stored in the encode(to:) +method, and values loaded from the database). Property setters do not +trigger this flag.

    + +

    You can rely on the Record base class to compute this flag for you, or +you may set it to true or false when you know better. Setting it to +false does not prevent it from turning true on subsequent modifications +of the record.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var hasDatabaseChanges: Bool { get set }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseChanges + +
    +
    +
    +
    +
    +
    +

    A dictionary of changes that have not been saved.

    + +

    Its keys are column names, and values the old values that have been +changed since last fetching or saving of the record.

    + +

    Unless the record has actually been fetched or saved, the old values +are nil.

    + +

    See hasDatabaseChanges for more information.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseChanges: [String : DatabaseValue?] { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ + + +

CRUD

+
+
+
    +
  • +
    + + + + insert(_:) + +
    +
    +
    +
    +
    +
    +

    Executes an INSERT statement.

    + +

    On success, this method sets the hasDatabaseChanges flag to false.

    + +

    This method is guaranteed to have inserted a row in the database if it +returns without error.

    + +

    Records whose primary key is declared as INTEGER PRIMARY KEY have +their id automatically set after successful insertion, if it was nil +before the insertion.

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    open func insert(_ db: Database) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + update(_:columns:) + +
    +
    +
    +
    +
    +
    +

    Executes an UPDATE statement.

    + +

    On success, this method sets the hasDatabaseChanges flag to false.

    + +

    This method is guaranteed to have updated a row in the database if it +returns without error.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. +PersistenceError.recordNotFound is thrown if the primary key does not +match any row in the database and record could not be updated. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    open func update(_ db: Database, columns: Set<String>) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + columns + + +
    +

    The columns to update.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + updateChanges(_:) + +
    +
    +
    +
    +
    +
    +

    If the record has been changed, executes an UPDATE statement so that +those changes and only those changes are saved in the database.

    + +

    On success, this method sets the hasDatabaseChanges flag to false.

    + +

    This method is guaranteed to have saved the eventual changes in the +database if it returns without error.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. +PersistenceError.recordNotFound is thrown if the primary key does not +match any row in the database and record could not be updated. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +final public func updateChanges(_ db: Database) throws -> Bool
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + columns + + +
    +

    The columns to update.

    +
    +
    +
    +
    +

    Return Value

    +

    Whether the record had changes.

    +
    + +
    +
    +
  • +
  • +
    + + + + save(_:) + +
    +
    +
    +
    +
    +
    +

    Executes an INSERT or an UPDATE statement so that self is saved in +the database.

    + +

    If the record has a non-nil primary key and a matching row in the +database, this method performs an update.

    + +

    Otherwise, performs an insert.

    + +

    On success, this method sets the hasDatabaseChanges flag to false.

    + +

    This method is guaranteed to have inserted or updated a row in the +database if it returns without error.

    + +

    You can’t override this method. Instead, override insert(_:) +or update(_:columns:).

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs, or errors +thrown by update(). + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    final public func save(_ db: Database) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + delete(_:) + +
    +
    +
    +
    +
    +
    +

    Executes a DELETE statement.

    + +

    On success, this method sets the hasDatabaseChanges flag to true.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +open func delete(_ db: Database) throws -> Bool
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    Whether a database row was deleted.

    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/Row.html b/docs/3.3/Classes/Row.html new file mode 100644 index 000000000..9557b7a5d --- /dev/null +++ b/docs/3.3/Classes/Row.html @@ -0,0 +1,3207 @@ + + + + Row Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Row

+
+
+
public final class Row : Equatable, Hashable, RandomAccessCollection, ExpressibleByDictionaryLiteral, CustomStringConvertible, CustomDebugStringConvertible
+ +
+
+

A database row.

+ +
+
+
+
    +
  • +
    + + + + count + +
    +
    +
    +
    +
    +
    +

    The number of columns in the row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let count: Int
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + init() + +
    +
    +
    +
    +
    +
    +

    Creates an empty row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public convenience init()
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a row from a dictionary of values.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public convenience init(_ dictionary: [String : DatabaseValueConvertible?])
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a row from [AnyHashable: Any].

    + +

    The result is nil unless all dictionary keys are strings, and values +adopt DatabaseValueConvertible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public convenience init?(_ dictionary: [AnyHashable : Any])
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + copy() + +
    +
    +
    +
    +
    +
    +

    Returns an immutable copy of the row.

    + +

    For performance reasons, rows fetched from a cursor are reused during +the iteration of a query: make sure to make a copy of it whenever you +want to keep a specific one: row.copy().

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func copy() -> Row
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + columnNames + +
    +
    +
    +
    +
    +
    +

    The names of columns in the row.

    + +

    Columns appear in the same order as they occur as the .0 member +of column-value pairs in self.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var columnNames: LazyMapCollection<Row, String> { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + hasColumn(_:) + +
    +
    +
    +
    +
    +
    +

    Returns true if and only if the row has that column.

    + +

    This method is case-insensitive.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func hasColumn(_ columnName: String) -> Bool
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + containsNonNullValue + +
    +
    +
    +
    +
    +
    +

    Returns true if and only if one column contains a non-null value, or if +the row was fetched with a row adapter that defines a scoped row that +contains a non-null value.

    + +

    For example:

    +
    let row = try Row.fetchOne(db, "SELECT 'foo', 1")!
    +row.containsNonNullValue // true
    +
    +let row = try Row.fetchOne(db, "SELECT NULL, NULL")!
    +row.containsNonNullValue // false
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var containsNonNullValue: Bool { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + hasNull(atIndex:) + +
    +
    +
    +
    +
    +
    +

    Returns true if the row contains null at given index.

    + +

    Indexes span from 0 for the leftmost column to (row.count - 1) for the +righmost column.

    + +

    This method is equivalent to row[index] == nil, but may be preferred +in performance-critical code because it can avoid decoding database +values.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func hasNull(atIndex index: Int) -> Bool
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns Int64, Double, String, Data or nil, depending on the value +stored at the given index.

    + +

    Indexes span from 0 for the leftmost column to (row.count - 1) for the +righmost column.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript(index: Int) -> DatabaseValueConvertible? { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the value at given index, converted to the requested type.

    + +

    Indexes span from 0 for the leftmost column to (row.count - 1) for the +righmost column.

    + +

    If the SQLite value is NULL, the result is nil. Otherwise the SQLite +value is converted to the requested type Value. Should this conversion +fail, a fatal error is raised.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript<Value>(index: Int) -> Value? where Value : DatabaseValueConvertible { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the value at given index, converted to the requested type.

    + +

    Indexes span from 0 for the leftmost column to (row.count - 1) for the +righmost column.

    + +

    If the SQLite value is NULL, the result is nil. Otherwise the SQLite +value is converted to the requested type Value. Should this conversion +fail, a fatal error is raised.

    + +

    This method exists as an optimization opportunity for types that adopt +StatementColumnConvertible. It may trigger SQLite built-in conversions +(see https://www.sqlite.org/datatype3.html).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript<Value>(index: Int) -> Value? where Value : DatabaseValueConvertible, Value : StatementColumnConvertible { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the value at given index, converted to the requested type.

    + +

    Indexes span from 0 for the leftmost column to (row.count - 1) for the +righmost column.

    + +

    This method crashes if the fetched SQLite value is NULL, or if the +SQLite value can not be converted to Value.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript<Value>(index: Int) -> Value where Value : DatabaseValueConvertible { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the value at given index, converted to the requested type.

    + +

    Indexes span from 0 for the leftmost column to (row.count - 1) for the +righmost column.

    + +

    This method crashes if the fetched SQLite value is NULL, or if the +SQLite value can not be converted to Value.

    + +

    This method exists as an optimization opportunity for types that adopt +StatementColumnConvertible. It may trigger SQLite built-in conversions +(see https://www.sqlite.org/datatype3.html).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript<Value>(index: Int) -> Value where Value : DatabaseValueConvertible, Value : StatementColumnConvertible { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns Int64, Double, String, Data or nil, depending on the value +stored at the given column.

    + +

    Column name lookup is case-insensitive, and when several columns have +the same name, the leftmost column is considered.

    + +

    The result is nil if the row does not contain the column.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript(columnName: String) -> DatabaseValueConvertible? { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the value at given column, converted to the requested type.

    + +

    Column name lookup is case-insensitive, and when several columns have +the same name, the leftmost column is considered.

    + +

    If the column is missing or if the SQLite value is NULL, the result is +nil. Otherwise the SQLite value is converted to the requested type +Value. Should this conversion fail, a fatal error is raised.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript<Value>(columnName: String) -> Value? where Value : DatabaseValueConvertible { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the value at given column, converted to the requested type.

    + +

    Column name lookup is case-insensitive, and when several columns have +the same name, the leftmost column is considered.

    + +

    If the column is missing or if the SQLite value is NULL, the result is +nil. Otherwise the SQLite value is converted to the requested type +Value. Should this conversion fail, a fatal error is raised.

    + +

    This method exists as an optimization opportunity for types that adopt +StatementColumnConvertible. It may trigger SQLite built-in conversions +(see https://www.sqlite.org/datatype3.html).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript<Value>(columnName: String) -> Value? where Value : DatabaseValueConvertible, Value : StatementColumnConvertible { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the value at given column, converted to the requested type.

    + +

    Column name lookup is case-insensitive, and when several columns have +the same name, the leftmost column is considered.

    + +

    If the row does not contain the column, a fatal error is raised.

    + +

    This method crashes if the fetched SQLite value is NULL, or if the +SQLite value can not be converted to Value.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript<Value>(columnName: String) -> Value where Value : DatabaseValueConvertible { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the value at given column, converted to the requested type.

    + +

    Column name lookup is case-insensitive, and when several columns have +the same name, the leftmost column is considered.

    + +

    If the row does not contain the column, a fatal error is raised.

    + +

    This method crashes if the fetched SQLite value is NULL, or if the +SQLite value can not be converted to Value.

    + +

    This method exists as an optimization opportunity for types that adopt +StatementColumnConvertible. It may trigger SQLite built-in conversions +(see https://www.sqlite.org/datatype3.html).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript<Value>(columnName: String) -> Value where Value : DatabaseValueConvertible, Value : StatementColumnConvertible { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns Int64, Double, String, NSData or nil, depending on the value +stored at the given column.

    + +

    Column name lookup is case-insensitive, and when several columns have +the same name, the leftmost column is considered.

    + +

    The result is nil if the row does not contain the column.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript(column: ColumnExpression) -> DatabaseValueConvertible? { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the value at given column, converted to the requested type.

    + +

    Column name lookup is case-insensitive, and when several columns have +the same name, the leftmost column is considered.

    + +

    If the column is missing or if the SQLite value is NULL, the result is +nil. Otherwise the SQLite value is converted to the requested type +Value. Should this conversion fail, a fatal error is raised.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript<Value>(column: ColumnExpression) -> Value? where Value : DatabaseValueConvertible { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the value at given column, converted to the requested type.

    + +

    Column name lookup is case-insensitive, and when several columns have +the same name, the leftmost column is considered.

    + +

    If the column is missing or if the SQLite value is NULL, the result is +nil. Otherwise the SQLite value is converted to the requested type +Value. Should this conversion fail, a fatal error is raised.

    + +

    This method exists as an optimization opportunity for types that adopt +StatementColumnConvertible. It may trigger SQLite built-in conversions +(see https://www.sqlite.org/datatype3.html).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript<Value>(column: ColumnExpression) -> Value? where Value : DatabaseValueConvertible, Value : StatementColumnConvertible { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the value at given column, converted to the requested type.

    + +

    Column name lookup is case-insensitive, and when several columns have +the same name, the leftmost column is considered.

    + +

    If the row does not contain the column, a fatal error is raised.

    + +

    This method crashes if the fetched SQLite value is NULL, or if the +SQLite value can not be converted to Value.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript<Value>(column: ColumnExpression) -> Value where Value : DatabaseValueConvertible { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the value at given column, converted to the requested type.

    + +

    Column name lookup is case-insensitive, and when several columns have +the same name, the leftmost column is considered.

    + +

    If the row does not contain the column, a fatal error is raised.

    + +

    This method crashes if the fetched SQLite value is NULL, or if the +SQLite value can not be converted to Value.

    + +

    This method exists as an optimization opportunity for types that adopt +StatementColumnConvertible. It may trigger SQLite built-in conversions +(see https://www.sqlite.org/datatype3.html).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript<Value>(column: ColumnExpression) -> Value where Value : DatabaseValueConvertible, Value : StatementColumnConvertible { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + dataNoCopy(atIndex:) + +
    +
    +
    +
    +
    +
    +

    Returns the optional Data at given index.

    + +

    Indexes span from 0 for the leftmost column to (row.count - 1) for the +righmost column.

    + +

    If the SQLite value is NULL, the result is nil. If the SQLite value can +not be converted to Data, a fatal error is raised.

    + +

    The returned data does not owns its bytes: it must not be used longer +than the row’s lifetime.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func dataNoCopy(atIndex index: Int) -> Data?
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + dataNoCopy(named:) + +
    +
    +
    +
    +
    +
    +

    Returns the optional Data at given column.

    + +

    Column name lookup is case-insensitive, and when several columns have +the same name, the leftmost column is considered.

    + +

    If the column is missing or if the SQLite value is NULL, the result is +nil. If the SQLite value can not be converted to Data, a fatal error +is raised.

    + +

    The returned data does not owns its bytes: it must not be used longer +than the row’s lifetime.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func dataNoCopy(named columnName: String) -> Data?
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + dataNoCopy(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the optional NSData at given column.

    + +

    Column name lookup is case-insensitive, and when several columns have +the same name, the leftmost column is considered.

    + +

    If the column is missing or if the SQLite value is NULL, the result is +nil. If the SQLite value can not be converted to NSData, a fatal error +is raised.

    + +

    The returned data does not owns its bytes: it must not be used longer +than the row’s lifetime.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func dataNoCopy(_ column: ColumnExpression) -> Data?
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + databaseValues + +
    +
    +
    +
    +
    +
    +

    The database values in the row.

    + +

    Values appear in the same order as they occur as the .1 member +of column-value pairs in self.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValues: LazyMapCollection<Row, DatabaseValue> { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+
+ + + +

Scopes

+
+
+
    +
  • +
    + + + + scopes + +
    +
    +
    +
    +
    +
    +

    Returns a view on the scopes defined by row adapters.

    + +

    For example:

    +
    // Define a tree of nested scopes
    +let adapter = ScopeAdapter([
    +    "foo": RangeRowAdapter(0..<1),
    +    "bar": RangeRowAdapter(1..<2).addingScopes([
    +        "baz" : RangeRowAdapter(2..<3)])])
    +
    +// Fetch
    +let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
    +let row = try Row.fetchOne(db, sql, adapter: adapter)!
    +
    +row.scopes.count  // 2
    +row.scopes.names  // ["foo", "bar"]
    +
    +row.scopes["foo"] // [foo:1]
    +row.scopes["bar"] // [bar:2]
    +row.scopes["baz"] // nil
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var scopes: ScopesView { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + scopesTree + +
    +
    +
    +
    +
    +
    +

    Returns a view on the scopes tree defined by row adapters.

    + +

    For example:

    +
    // Define a tree of nested scopes
    +let adapter = ScopeAdapter([
    +    "foo": RangeRowAdapter(0..<1),
    +    "bar": RangeRowAdapter(1..<2).addingScopes([
    +        "baz" : RangeRowAdapter(2..<3)])])
    +
    +// Fetch
    +let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
    +let row = try Row.fetchOne(db, sql, adapter: adapter)!
    +
    +row.scopesTree.names  // ["foo", "bar", "baz"]
    +
    +row.scopesTree["foo"] // [foo:1]
    +row.scopesTree["bar"] // [bar:2]
    +row.scopesTree["baz"] // [baz:3]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var scopesTree: ScopesTreeView { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + unscoped + +
    +
    +
    +
    +
    +
    +

    Returns a copy of the row, without any scopes.

    + +

    This property can turn out useful when you want to test the content of +adapted rows, such as rows fetched from joined requests.

    +
    let row = ...
    +// Failure because row equality tests for row scopes:
    +XCTAssertEqual(row, ["id": 1, "name": "foo"])
    +// Success:
    +XCTAssertEqual(row.unscoped, ["id": 1, "name": "foo"])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var unscoped: Row { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + unadapted + +
    +
    +
    +
    +
    +
    +

    Return the raw row fetched from the database.

    + +

    This property can turn out useful when you debug the consumption of +adapted rows, such as rows fetched from joined requests.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var unadapted: Row { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Returns a cursor over rows fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT ...")
    +let rows = try Row.fetchCursor(statement) // RowCursor
    +while let row = try rows.next() { // Row
    +    let id: Int64 = row[0]
    +    let name: String = row[1]
    +}
    +
    + +

    Fetched rows are reused during the cursor iteration: don’t turn a row +cursor into an array with Array(rows) or rows.filter { ... } since +you would not get the distinct rows you expect. Use Row.fetchAll(...) +instead.

    + +

    For the same reason, make sure you make a copy whenever you extract a +row for later use: row.copy().

    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched rows.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns an array of rows fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT ...")
    +let rows = try Row.fetchAll(statement)
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An array of rows.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns a single row fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT ...")
    +let row = try Row.fetchOne(statement)
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row?
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An optional row.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Returns a cursor over rows fetched from an SQL query.

    +
    let rows = try Row.fetchCursor(db, "SELECT id, name FROM player") // RowCursor
    +while let row = try rows.next() { // Row
    +    let id: Int64 = row[0]
    +    let name: String = row[1]
    +}
    +
    + +

    Fetched rows are reused during the cursor iteration: don’t turn a row +cursor into an array with Array(rows) or rows.filter { ... } since +you would not get the distinct rows you expect. Use Row.fetchAll(...) +instead.

    + +

    For the same reason, make sure you make a copy whenever you extract a +row for later use: row.copy().

    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched rows.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns an array of rows fetched from an SQL query.

    +
    let rows = try Row.fetchAll(db, "SELECT ...")
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An array of rows.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns a single row fetched from an SQL query.

    +
    let row = try Row.fetchOne(db, "SELECT ...")
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row?
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An optional row.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:_:) + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over rows fetched from a fetch request.

    +
    let request = Player.all()
    +let rows = try Row.fetchCursor(db, request) // RowCursor
    +while let row = try rows.next() { // Row
    +    let id: Int64 = row["id"]
    +    let name: String = row["name"]
    +}
    +
    + +

    Fetched rows are reused during the cursor iteration: don’t turn a row +cursor into an array with Array(rows) or rows.filter { ... } since +you would not get the distinct rows you expect. Use Row.fetchAll(...) +instead.

    + +

    For the same reason, make sure you make a copy whenever you extract a +row for later use: row.copy().

    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor<R>(_ db: Database, _ request: R) throws -> RowCursor where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched rows.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:_:) + +
    +
    +
    +
    +
    +
    +

    Returns an array of rows fetched from a fetch request.

    +
    let request = Player.all()
    +let rows = try Row.fetchAll(db, request)
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll<R>(_ db: Database, _ request: R) throws -> [Row] where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of rows.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:_:) + +
    +
    +
    +
    +
    +
    +

    Returns a single row fetched from a fetch request.

    +
    let request = Player.filter(key: 1)
    +let row = try Row.fetchOne(db, request)
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne<R>(_ db: Database, _ request: R) throws -> Row? where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    An optional row.

    +
    + +
    +
    +
  • +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Creates a row initialized with elements. Column order is preserved, and +duplicated columns names are allowed.

    +
    let row: Row = ["foo": 1, "foo": "bar", "baz": nil]
    +print(row)
    +// Prints [foo:1 foo:"bar" baz:NULL]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public convenience init(dictionaryLiteral elements: (String, DatabaseValueConvertible?)...)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Accesses the (ColumnName, DatabaseValue) pair at given index.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript(position: RowIndex) -> (String, DatabaseValue) { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + ScopesView + +
    +
    +
    +
    +
    +
    +

    A view of the scopes defined by row adapters. It is a collection of +tuples made of a scope name and a scoped row, which behaves like a +dictionary.

    + +

    For example:

    +
    // Define a tree of nested scopes
    +let adapter = ScopeAdapter([
    +    "foo": RangeRowAdapter(0..<1),
    +    "bar": RangeRowAdapter(1..<2).addingScopes([
    +        "baz" : RangeRowAdapter(2..<3)])])
    +
    +// Fetch
    +let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
    +let row = try Row.fetchOne(db, sql, adapter: adapter)!
    +
    +row.scopes.count  // 2
    +row.scopes.names  // ["foo", "bar"]
    +
    +row.scopes["foo"] // [foo:1]
    +row.scopes["bar"] // [bar:2]
    +row.scopes["baz"] // nil
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct ScopesView : Collection
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + ScopesTreeView + +
    +
    +
    +
    +
    +
    +

    A view on the scopes tree defined by row adapters.

    + +

    For example:

    +
    // Define a tree of nested scopes
    +let adapter = ScopeAdapter([
    +    "foo": RangeRowAdapter(0..<1),
    +    "bar": RangeRowAdapter(1..<2).addingScopes([
    +        "baz" : RangeRowAdapter(2..<3)])])
    +
    +// Fetch
    +let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
    +let row = try Row.fetchOne(db, sql, adapter: adapter)!
    +
    +row.scopesTree.names  // ["foo", "bar", "baz"]
    +
    +row.scopesTree["foo"] // [foo:1]
    +row.scopesTree["bar"] // [bar:2]
    +row.scopesTree["baz"] // [baz:3]
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct ScopesTreeView
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/Row/ScopesTreeView.html b/docs/3.3/Classes/Row/ScopesTreeView.html new file mode 100644 index 000000000..529fd4941 --- /dev/null +++ b/docs/3.3/Classes/Row/ScopesTreeView.html @@ -0,0 +1,891 @@ + + + + ScopesTreeView Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ScopesTreeView

+
+
+
public struct ScopesTreeView
+ +
+
+

A view on the scopes tree defined by row adapters.

+ +

For example:

+
// Define a tree of nested scopes
+let adapter = ScopeAdapter([
+    "foo": RangeRowAdapter(0..<1),
+    "bar": RangeRowAdapter(1..<2).addingScopes([
+        "baz" : RangeRowAdapter(2..<3)])])
+
+// Fetch
+let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
+let row = try Row.fetchOne(db, sql, adapter: adapter)!
+
+row.scopesTree.names  // ["foo", "bar", "baz"]
+
+row.scopesTree["foo"] // [foo:1]
+row.scopesTree["bar"] // [bar:2]
+row.scopesTree["baz"] // [baz:3]
+
+ +
+
+
+
    +
  • +
    + + + + names + +
    +
    +
    +
    +
    +
    +

    The scopes defined on this row, recursively.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var names: Set<String> { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the row associated with the given scope, by performing a +breadth-first search in this row’s scopes and the scopes of its +scoped rows, recursively.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript(name: String) -> Row? { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/Row/ScopesView.html b/docs/3.3/Classes/Row/ScopesView.html new file mode 100644 index 000000000..e1424584c --- /dev/null +++ b/docs/3.3/Classes/Row/ScopesView.html @@ -0,0 +1,922 @@ + + + + ScopesView Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ScopesView

+
+
+
public struct ScopesView : Collection
+ +
+
+

A view of the scopes defined by row adapters. It is a collection of +tuples made of a scope name and a scoped row, which behaves like a +dictionary.

+ +

For example:

+
// Define a tree of nested scopes
+let adapter = ScopeAdapter([
+    "foo": RangeRowAdapter(0..<1),
+    "bar": RangeRowAdapter(1..<2).addingScopes([
+        "baz" : RangeRowAdapter(2..<3)])])
+
+// Fetch
+let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
+let row = try Row.fetchOne(db, sql, adapter: adapter)!
+
+row.scopes.count  // 2
+row.scopes.names  // ["foo", "bar"]
+
+row.scopes["foo"] // [foo:1]
+row.scopes["bar"] // [bar:2]
+row.scopes["baz"] // nil
+
+ +
+
+
+
    +
  • +
    + + + + Index + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public typealias Index = Dictionary<String, LayoutedRowAdapter>.Index
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + names + +
    +
    +
    +
    +
    +
    +

    The scopes defined on this row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var names: Dictionary<String, LayoutedRowAdapter>.Keys { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the row associated with the given scope, or nil if the +scope is not defined.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript(name: String) -> Row? { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/RowCursor.html b/docs/3.3/Classes/RowCursor.html new file mode 100644 index 000000000..a7a340865 --- /dev/null +++ b/docs/3.3/Classes/RowCursor.html @@ -0,0 +1,845 @@ + + + + RowCursor Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

RowCursor

+
+
+
public final class RowCursor : Cursor
+ +
+
+

A cursor of database rows. For example:

+
try dbQueue.read { db in
+    let rows: RowCursor = try Row.fetchCursor(db, "SELECT * FROM player")
+}
+
+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/SelectStatement.html b/docs/3.3/Classes/SelectStatement.html new file mode 100644 index 000000000..3674275d6 --- /dev/null +++ b/docs/3.3/Classes/SelectStatement.html @@ -0,0 +1,940 @@ + + + + SelectStatement Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

SelectStatement

+
+
+
public final class SelectStatement : Statement
+ +
+
+

A subclass of Statement that fetches database rows.

+ +

You create SelectStatement with the Database.makeSelectStatement() method:

+
try dbQueue.read { db in
+    let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
+    let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
+    let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
+}
+
+ +
+
+
+
    +
  • +
    + + + + databaseRegion + +
    +
    +
    +
    +
    +
    +

    The database region that the statement looks into.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public private(set) var databaseRegion: DatabaseRegion
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + columnCount + +
    +
    +
    +
    +
    +
    +

    The number of columns in the resulting rows.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var columnCount: Int { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + columnNames + +
    +
    +
    +
    +
    +
    +

    The column names, ordered from left to right.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public lazy var columnNames: [String] { get set }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + index(ofColumn:) + +
    +
    +
    +
    +
    +
    +

    Returns the index of the leftmost column named name, in a +case-insensitive way.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func index(ofColumn name: String) -> Int?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/Statement.html b/docs/3.3/Classes/Statement.html new file mode 100644 index 000000000..21e11e91c --- /dev/null +++ b/docs/3.3/Classes/Statement.html @@ -0,0 +1,976 @@ + + + + Statement Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Statement

+
+
+
public class Statement
+ +
+
+

A statement represents an SQL query.

+ +

It is the base class of UpdateStatement that executes update statements, +and SelectStatement that fetches rows.

+ +
+
+
+
    +
  • +
    + + + + sqliteStatement + +
    +
    +
    +
    +
    +
    +

    The raw SQLite statement, suitable for the SQLite C API.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let sqliteStatement: SQLiteStatement
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + sql + +
    +
    +
    +
    +
    +
    +

    The SQL query

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var sql: String { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/StatementCursor.html b/docs/3.3/Classes/StatementCursor.html new file mode 100644 index 000000000..787889293 --- /dev/null +++ b/docs/3.3/Classes/StatementCursor.html @@ -0,0 +1,847 @@ + + + + StatementCursor Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

StatementCursor

+
+
+
public final class StatementCursor : Cursor
+ +
+
+

A cursor that iterates a database statement without producing any value. +For example:

+
try dbQueue.read { db in
+    let statement = db.makeSelectStatement("SELECT * FROM player")
+    let cursor: StatementCursor = statement.makeCursor()
+}
+
+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/TableAlias.html b/docs/3.3/Classes/TableAlias.html new file mode 100644 index 000000000..03941d4b1 --- /dev/null +++ b/docs/3.3/Classes/TableAlias.html @@ -0,0 +1,905 @@ + + + + TableAlias Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

TableAlias

+
+
+
public class TableAlias : Hashable
+ +
+
+

Experimental

+ +

A TableAlias identifies a table in a request.

+ +
+
+
+
    +
  • +
    + + + + init(name:) + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(name: String? = nil)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a qualified value that is able to resolve ambiguities in +joined queries.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript(selectable: SQLSelectable) -> SQLSelectable { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a qualified expression that is able to resolve ambiguities in +joined queries.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript(expression: SQLExpression) -> SQLExpression { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/TableAlteration.html b/docs/3.3/Classes/TableAlteration.html new file mode 100644 index 000000000..e8cce7c4e --- /dev/null +++ b/docs/3.3/Classes/TableAlteration.html @@ -0,0 +1,893 @@ + + + + TableAlteration Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

TableAlteration

+
+
+
public final class TableAlteration
+ +
+
+

The TableAlteration class lets you alter database tables.

+ +

You don’t create instances of this class. Instead, you use the Database +alter(table:) method:

+
try db.alter(table: "player") { t in // t is TableAlteration
+    t.add(column: ...)
+}
+
+ +

See https://www.sqlite.org/lang_altertable.html

+ +
+
+
+
    +
  • +
    + + + + add(column:_:) + +
    +
    +
    +
    +
    +
    +

    Appends a column to the table.

    +
    try db.alter(table: "player") { t in
    +    t.add(column: "url", .text)
    +}
    +
    + +

    See https://www.sqlite.org/lang_altertable.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func add(column name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + name + + +
    +

    the column name.

    +
    +
    + + type + + +
    +

    the column type.

    +
    +
    +
    +
    +

    Return Value

    +

    An ColumnDefinition that allows you to refine the +column definition.

    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/TableDefinition.html b/docs/3.3/Classes/TableDefinition.html new file mode 100644 index 000000000..82d249f33 --- /dev/null +++ b/docs/3.3/Classes/TableDefinition.html @@ -0,0 +1,1348 @@ + + + + TableDefinition Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

TableDefinition

+
+
+
public final class TableDefinition
+ +
+
+

The TableDefinition class lets you define table columns and constraints.

+ +

You don’t create instances of this class. Instead, you use the Database +create(table:) method:

+
try db.create(table: "player") { t in // t is TableDefinition
+    t.column(...)
+}
+
+ +

See https://www.sqlite.org/lang_createtable.html

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Defines the auto-incremented primary key.

    +
    try db.create(table: "player") { t in
    +    t.autoIncrementedPrimaryKey("id")
    +}
    +
    + +

    The auto-incremented primary key is an integer primary key that +automatically generates unused values when you do not explicitly +provide one, and prevents the reuse of ids over the lifetime of +the database.

    + +

    It is the preferred way to define a numeric primary key.

    + +

    The fact that an auto-incremented primary key prevents the reuse of +ids is an excellent guard against data races that could happen when your +application processes ids in an asynchronous way. The auto-incremented +primary key provides the guarantee that a given id can’t reference a row +that is different from the one it used to be at the beginning of the +asynchronous process, even if this row gets deleted and a new one is +inserted in between.

    + +

    See https://www.sqlite.org/lang_createtable.html#primkeyconst and +https://www.sqlite.org/lang_createtable.html#rowid

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func autoIncrementedPrimaryKey(_ name: String, onConflict conflictResolution: Database.ConflictResolution? = nil) -> ColumnDefinition
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + conflitResolution + + +
    +

    An optional conflict resolution +(see https://www.sqlite.org/lang_conflict.html).

    +
    +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
  • +
    + + + + column(_:_:) + +
    +
    +
    +
    +
    +
    +

    Appends a table column.

    +
    try db.create(table: "player") { t in
    +    t.column("name", .text)
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#tablecoldef

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func column(_ name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + name + + +
    +

    the column name.

    +
    +
    + + type + + +
    +

    the eventual column type.

    +
    +
    +
    +
    +

    Return Value

    +

    An ColumnDefinition that allows you to refine the +column definition.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Defines the table primary key.

    +
    try db.create(table: "citizenship") { t in
    +    t.column("citizenID", .integer)
    +    t.column("countryCode", .text)
    +    t.primaryKey(["citizenID", "countryCode"])
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#primkeyconst and +https://www.sqlite.org/lang_createtable.html#rowid

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func primaryKey(_ columns: [String], onConflict conflictResolution: Database.ConflictResolution? = nil)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + columns + + +
    +

    The primary key columns.

    +
    +
    + + conflitResolution + + +
    +

    An optional conflict resolution +(see https://www.sqlite.org/lang_conflict.html).

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Adds a unique key.

    +
    try db.create(table: "place") { t in
    +    t.column("latitude", .double)
    +    t.column("longitude", .double)
    +    t.uniqueKey(["latitude", "longitude"])
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#uniqueconst

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func uniqueKey(_ columns: [String], onConflict conflictResolution: Database.ConflictResolution? = nil)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + columns + + +
    +

    The unique key columns.

    +
    +
    + + conflitResolution + + +
    +

    An optional conflict resolution +(see https://www.sqlite.org/lang_conflict.html).

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Adds a foreign key.

    +
    try db.create(table: "passport") { t in
    +    t.column("issueDate", .date)
    +    t.column("citizenID", .integer)
    +    t.column("countryCode", .text)
    +    t.foreignKey(["citizenID", "countryCode"], references: "citizenship", onDelete: .cascade)
    +}
    +
    + +

    See https://www.sqlite.org/foreignkeys.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func foreignKey(_ columns: [String], references table: String, columns destinationColumns: [String]? = nil, onDelete deleteAction: Database.ForeignKeyAction? = nil, onUpdate updateAction: Database.ForeignKeyAction? = nil, deferred: Bool = false)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + columns + + +
    +

    The foreign key columns.

    +
    +
    + + table + + +
    +

    The referenced table.

    +
    +
    + + destinationColumns + + +
    +

    The columns in the referenced table. If not +specified, the columns of the primary key of the referenced table +are used.

    +
    +
    + + deleteAction + + +
    +

    Optional action when the referenced row is deleted.

    +
    +
    + + updateAction + + +
    +

    Optional action when the referenced row is updated.

    +
    +
    + + deferred + + +
    +

    If true, defines a deferred foreign key constraint. +See https://www.sqlite.org/foreignkeys.html#fk_deferred.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + check(_:) + +
    +
    +
    +
    +
    +
    +

    Adds a CHECK constraint.

    +
    try db.create(table: "player") { t in
    +    t.column("personalPhone", .text)
    +    t.column("workPhone", .text)
    +    let personalPhone = Column("personalPhone")
    +    let workPhone = Column("workPhone")
    +    t.check(personalPhone != nil || workPhone != nil)
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#ckconst

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func check(_ condition: SQLExpressible)
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + condition + + +
    +

    The checked condition

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + check(sql:) + +
    +
    +
    +
    +
    +
    +

    Adds a CHECK constraint.

    +
    try db.create(table: "player") { t in
    +    t.column("personalPhone", .text)
    +    t.column("workPhone", .text)
    +    t.check(sql: "personalPhone IS NOT NULL OR workPhone IS NOT NULL")
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#ckconst

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func check(sql: String)
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + sql + + +
    +

    An SQL snippet

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Classes/UpdateStatement.html b/docs/3.3/Classes/UpdateStatement.html new file mode 100644 index 000000000..0cd822412 --- /dev/null +++ b/docs/3.3/Classes/UpdateStatement.html @@ -0,0 +1,874 @@ + + + + UpdateStatement Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

UpdateStatement

+
+
+
public final class UpdateStatement : Statement
+ +
+
+

A subclass of Statement that executes SQL queries.

+ +

You create UpdateStatement with the Database.makeUpdateStatement() method:

+
try dbQueue.inTransaction { db in
+    let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)")
+    try statement.execute(arguments: ["Arthur"])
+    try statement.execute(arguments: ["Barbara"])
+    return .commit
+}
+
+ +
+
+
+
    +
  • +
    + + + + execute(arguments:) + +
    +
    +
    +
    +
    +
    +

    Executes the SQL query.

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func execute(arguments: StatementArguments? = nil) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + arguments + + +
    +

    Statement arguments.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Enums.html b/docs/3.3/Enums.html new file mode 100644 index 000000000..5d4c14de7 --- /dev/null +++ b/docs/3.3/Enums.html @@ -0,0 +1,1129 @@ + + + + Enumerations Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Enumerations

+

The following enumerations are available globally.

+ +
+
+
+ +
    +
  • +
    + + + + DatabaseEventKind + +
    +
    +
    +
    +
    +
    +

    A kind of database event. See the TransactionObserver protocol for +more information.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public enum DatabaseEventKind
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    DatabaseDateDecodingStrategy specifies how FetchableRecord types that also +adopt the standard Decodable protocol decode their date properties.

    + +

    For example:

    +
    struct Player: FetchableRecord, Decodable {
    +    static let databaseDateDecodingStrategy: DatabaseDateDecodingStrategy = .timeIntervalSince1970
    +
    +    var name: String
    +    var registrationDate: Date // decoded from epoch timestamp
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public enum DatabaseDateDecodingStrategy
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + FetchedRecordChange + +
    +
    +
    +
    +
    +
    +

    A record change, given by a FetchedRecordsController to its change callback.

    + +

    The move and update events hold a changes dictionary, whose keys are +column names, and values the old values that have been changed.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public enum FetchedRecordChange
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + PersistenceError + +
    +
    +
    +
    +
    +
    +

    An error thrown by a type that adopts PersistableRecord.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public enum PersistenceError : Error, CustomStringConvertible
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    DatabaseDateEncodingStrategy specifies how PersistableRecord types that also +adopt the standard Encodable protocol encode their date properties.

    + +

    For example:

    +
    struct Player: PersistableRecord, Encodable {
    +    static let databaseDateEncodingStrategy: DatabaseDateEncodingStrategy = .timeIntervalSince1970
    +
    +    var name: String
    +    var registrationDate: Date // encoded as an epoch timestamp
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public enum DatabaseDateEncodingStrategy
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    DatabaseUUIDEncodingStrategy specifies how FetchableRecord types that also +adopt the standard Encodable protocol encode their UUID properties.

    + +

    For example:

    +
    struct Player: PersistableProtocol, Encodable {
    +    static let databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy = .string
    +
    +    // encoded in a string like "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
    +    var uuid: UUID
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public enum DatabaseUUIDEncodingStrategy
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Enums/DatabaseDateDecodingStrategy.html b/docs/3.3/Enums/DatabaseDateDecodingStrategy.html new file mode 100644 index 000000000..f0509a7a3 --- /dev/null +++ b/docs/3.3/Enums/DatabaseDateDecodingStrategy.html @@ -0,0 +1,1054 @@ + + + + DatabaseDateDecodingStrategy Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseDateDecodingStrategy

+
+
+
public enum DatabaseDateDecodingStrategy
+ +
+
+

DatabaseDateDecodingStrategy specifies how FetchableRecord types that also +adopt the standard Decodable protocol decode their date properties.

+ +

For example:

+
struct Player: FetchableRecord, Decodable {
+    static let databaseDateDecodingStrategy: DatabaseDateDecodingStrategy = .timeIntervalSince1970
+
+    var name: String
+    var registrationDate: Date // decoded from epoch timestamp
+}
+
+ +
+
+
+
    +
  • +
    + + + + deferredToDate + +
    +
    +
    +
    +
    +
    +

    The strategy that uses formatting from the Date structure.

    + +

    It decodes numeric values as a nunber of seconds since Epoch +(midnight UTC on January 1st, 1970).

    + +

    It decodes strings in the following formats, assuming UTC time zone. +Missing components are assumed to be zero:

    + +
      +
    • YYYY-MM-DD
    • +
    • YYYY-MM-DD HH:MM
    • +
    • YYYY-MM-DD HH:MM:SS
    • +
    • YYYY-MM-DD HH:MM:SS.SSS
    • +
    • YYYY-MM-DDTHH:MM
    • +
    • YYYY-MM-DDTHH:MM:SS
    • +
    • YYYY-MM-DDTHH:MM:SS.SSS
    • +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case deferredToDate
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Decodes numeric values as a number of seconds between the date and +midnight UTC on 1 January 2001

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case timeIntervalSinceReferenceDate
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + timeIntervalSince1970 + +
    +
    +
    +
    +
    +
    +

    Decodes numeric values as a number of seconds between the date and +midnight UTC on 1 January 1970

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case timeIntervalSince1970
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + millisecondsSince1970 + +
    +
    +
    +
    +
    +
    +

    Decodes numeric values as a number of milliseconds between the date and +midnight UTC on 1 January 1970

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case millisecondsSince1970
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + iso8601 + +
    +
    +
    +
    +
    +
    +

    Decodes dates according to the ISO 8601 standards

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case iso8601
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + formatted + +
    +
    +
    +
    +
    +
    +

    Decodes a String, according to the provided formatter

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case formatted(DateFormatter)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + custom + +
    +
    +
    +
    +
    +
    +

    Decodes according to the user-provided function.

    + +

    If the database value does not contain a suitable value, the function +must return nil (GRDB will interpret this nil result as a conversion +error, and react accordingly).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case custom((DatabaseValue) -> Date?)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Enums/DatabaseDateEncodingStrategy.html b/docs/3.3/Enums/DatabaseDateEncodingStrategy.html new file mode 100644 index 000000000..8c686e2b3 --- /dev/null +++ b/docs/3.3/Enums/DatabaseDateEncodingStrategy.html @@ -0,0 +1,1068 @@ + + + + DatabaseDateEncodingStrategy Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseDateEncodingStrategy

+
+
+
public enum DatabaseDateEncodingStrategy
+ +
+
+

DatabaseDateEncodingStrategy specifies how PersistableRecord types that also +adopt the standard Encodable protocol encode their date properties.

+ +

For example:

+
struct Player: PersistableRecord, Encodable {
+    static let databaseDateEncodingStrategy: DatabaseDateEncodingStrategy = .timeIntervalSince1970
+
+    var name: String
+    var registrationDate: Date // encoded as an epoch timestamp
+}
+
+ +
+
+
+
    +
  • +
    + + + + deferredToDate + +
    +
    +
    +
    +
    +
    +

    The strategy that uses formatting from the Date structure.

    + +

    It encodes dates using the format YYYY-MM-DD HH:MM:SS.SSS in the +UTC time zone.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case deferredToDate
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Encodes a Double: the number of seconds between the date and +midnight UTC on 1 January 2001

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case timeIntervalSinceReferenceDate
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + timeIntervalSince1970 + +
    +
    +
    +
    +
    +
    +

    Encodes a Double: the number of seconds between the date and +midnight UTC on 1 January 1970

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case timeIntervalSince1970
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + secondsSince1970 + +
    +
    +
    +
    +
    +
    +

    Encodes an Int64: the number of seconds between the date and +midnight UTC on 1 January 1970

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case secondsSince1970
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + millisecondsSince1970 + +
    +
    +
    +
    +
    +
    +

    Encodes an Int64: the number of milliseconds between the date and +midnight UTC on 1 January 1970

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case millisecondsSince1970
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + iso8601 + +
    +
    +
    +
    +
    +
    +

    Encodes dates according to the ISO 8601 and RFC 3339 standards

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case iso8601
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + formatted + +
    +
    +
    +
    +
    +
    +

    Encodes a String, according to the provided formatter

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case formatted(DateFormatter)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + custom + +
    +
    +
    +
    +
    +
    +

    Encodes the result of the user-provided function

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case custom((Date) -> DatabaseValueConvertible?)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Enums/DatabaseEventKind.html b/docs/3.3/Enums/DatabaseEventKind.html new file mode 100644 index 000000000..6e1fe63b6 --- /dev/null +++ b/docs/3.3/Enums/DatabaseEventKind.html @@ -0,0 +1,943 @@ + + + + DatabaseEventKind Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseEventKind

+
+
+
public enum DatabaseEventKind
+ +
+
+

A kind of database event. See the TransactionObserver protocol for +more information.

+ +
+
+
+
    +
  • +
    + + + + insert + +
    +
    +
    +
    +
    +
    +

    The insertion of a row in a database table

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case insert(tableName: String)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + delete + +
    +
    +
    +
    +
    +
    +

    The deletion of a row in a database table

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case delete(tableName: String)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + update + +
    +
    +
    +
    +
    +
    +

    The update of a set of columns in a database table

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case update(tableName: String, columnNames: Set<String>)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + tableName + +
    +
    +
    +
    +
    +
    +

    The impacted database table

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var tableName: String { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Enums/DatabaseUUIDEncodingStrategy.html b/docs/3.3/Enums/DatabaseUUIDEncodingStrategy.html new file mode 100644 index 000000000..d05b465d5 --- /dev/null +++ b/docs/3.3/Enums/DatabaseUUIDEncodingStrategy.html @@ -0,0 +1,883 @@ + + + + DatabaseUUIDEncodingStrategy Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseUUIDEncodingStrategy

+
+
+
public enum DatabaseUUIDEncodingStrategy
+ +
+
+

DatabaseUUIDEncodingStrategy specifies how FetchableRecord types that also +adopt the standard Encodable protocol encode their UUID properties.

+ +

For example:

+
struct Player: PersistableProtocol, Encodable {
+    static let databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy = .string
+
+    // encoded in a string like "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
+    var uuid: UUID
+}
+
+ +
+
+
+
    +
  • +
    + + + + deferredToUUID + +
    +
    +
    +
    +
    +
    +

    The strategy that uses formatting from the UUID type.

    + +

    It encodes UUIDs as 16-bytes data blobs.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case deferredToUUID
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + string + +
    +
    +
    +
    +
    +
    +

    Encodes UUIDs as strings such as E621E1F8-C36C-495A-93FC-0C247A3E6E5F

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case string
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Enums/FetchedRecordChange.html b/docs/3.3/Enums/FetchedRecordChange.html new file mode 100644 index 000000000..702d23825 --- /dev/null +++ b/docs/3.3/Enums/FetchedRecordChange.html @@ -0,0 +1,978 @@ + + + + FetchedRecordChange Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FetchedRecordChange

+
+
+
public enum FetchedRecordChange
+ +
+
+

A record change, given by a FetchedRecordsController to its change callback.

+ +

The move and update events hold a changes dictionary, whose keys are +column names, and values the old values that have been changed.

+ +
+
+
+
    +
  • +
    + + + + insertion + +
    +
    +
    +
    +
    +
    +

    An insertion event, at given indexPath.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case insertion(indexPath: IndexPath)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + deletion + +
    +
    +
    +
    +
    +
    +

    A deletion event, at given indexPath.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case deletion(indexPath: IndexPath)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + move + +
    +
    +
    +
    +
    +
    +

    A move event, from indexPath to newIndexPath. The changes are a +dictionary whose keys are column names, and values the old values that +have been changed.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case move(indexPath: IndexPath, newIndexPath: IndexPath, changes: [String : DatabaseValue])
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + update + +
    +
    +
    +
    +
    +
    +

    An update event, at given indexPath. The changes are a dictionary +whose keys are column names, and values the old values that have +been changed.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case update(indexPath: IndexPath, changes: [String : DatabaseValue])
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + description + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var description: String { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Enums/PersistenceError.html b/docs/3.3/Enums/PersistenceError.html new file mode 100644 index 000000000..845efc3ee --- /dev/null +++ b/docs/3.3/Enums/PersistenceError.html @@ -0,0 +1,842 @@ + + + + PersistenceError Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

PersistenceError

+
+
+
public enum PersistenceError : Error, CustomStringConvertible
+ +
+
+

An error thrown by a type that adopts PersistableRecord.

+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/Enums/SQLLogicalBinaryOperator.html b/docs/3.3/Enums/SQLLogicalBinaryOperator.html new file mode 100644 index 000000000..fd9fb2aa6 --- /dev/null +++ b/docs/3.3/Enums/SQLLogicalBinaryOperator.html @@ -0,0 +1,871 @@ + + + + SQLLogicalBinaryOperator Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

SQLLogicalBinaryOperator

+
+
+
public enum SQLLogicalBinaryOperator
+ +
+
+

Undocumented

+ +
+
+
+
    +
  • +
    + + + + and + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case and
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + or + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case or
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions.html b/docs/3.3/Extensions.html new file mode 100644 index 000000000..007ce9e7e --- /dev/null +++ b/docs/3.3/Extensions.html @@ -0,0 +1,1982 @@ + + + + Extensions Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Extensions

+

The following extensions are available globally.

+ +
+
+
+ +
    +
  • +
    + + + + Array + +
    +
    +
    +
    +
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Array<Element> : _DestructorSafeContainer
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + Sequence + +
    +
    +
    +
    +
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    protocol Sequence
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + Set + +
    +
    +
    +
    +
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Set<Element> where Element : Hashable
    + +
    +
    +
    +
    +
  • +
+
+
+ +
+
+ +
+
+ +
    +
  • +
    + + + + Optional + +
    +
    +
    +
    +
    +
    +

    Swift’s Optional comes with built-in methods that allow to fetch cursors +and arrays of optional DatabaseValueConvertible:

    +
    try Optional<String>.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String?
    +try Optional<String>.fetchAll(db, "SELECT name FROM ...", arguments:...)    // [String?]
    +
    +let statement = try db.makeSelectStatement("SELECT name FROM ...")
    +try Optional<String>.fetchCursor(statement, arguments:...) // Cursor of String?
    +try Optional<String>.fetchAll(statement, arguments:...)    // [String?]
    +
    + +

    DatabaseValueConvertible is adopted by Bool, Int, String, etc.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    enum Optional<Wrapped> : ExpressibleByNilLiteral
    + +
    +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + CGFloat + +
    +
    +
    +
    +
    +
    +

    CGFloat adopts DatabaseValueConvertible

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct CGFloat
    + +
    +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + Data + +
    +
    +
    +
    +
    +
    +

    Data is convertible to and from DatabaseValue.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessCollection, MutableCollection, RangeReplaceableCollection
    + +
    +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + NSDate + +
    +
    +
    +
    +
    +
    +

    NSDate is stored in the database using the format +yyyy-MM-dd HH:mm:ss.SSS, in the UTC time zone.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    class NSDate : NSObject, NSCopying, NSSecureCoding
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + Date + +
    +
    +
    +
    +
    +
    +

    Date is stored in the database using the format +yyyy-MM-dd HH:mm:ss.SSS, in the UTC time zone.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Date : ReferenceConvertible, Comparable, Equatable
    + +
    +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + NSData + +
    +
    +
    +
    +
    +
    +

    NSData is convertible to and from DatabaseValue.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding
    + +
    +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + NSNull + +
    +
    +
    +
    +
    +
    +

    NSNull adopts DatabaseValueConvertible

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    class NSNull : NSObject, NSCopying, NSSecureCoding
    + +
    +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + NSNumber + +
    +
    +
    +
    +
    +
    +

    NSNumber adopts DatabaseValueConvertible

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    class NSNumber : NSValue
    + +
    +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + NSString + +
    +
    +
    +
    +
    +
    +

    NSString adopts DatabaseValueConvertible

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    class NSString : NSObject, NSCopying, NSMutableCopying, NSSecureCoding
    + +
    +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + NSURL + +
    +
    +
    +
    +
    +
    +

    NSURL stores its absoluteString in the database.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    class NSURL : NSObject, NSSecureCoding, NSCopying
    + +
    +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + NSUUID + +
    +
    +
    +
    +
    +
    +

    NSUUID adopts DatabaseValueConvertible

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    class NSUUID : NSObject, NSCopying, NSSecureCoding
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + UUID + +
    +
    +
    +
    +
    +
    +

    UUID adopts DatabaseValueConvertible

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @available(OSX 10.8, iOS 6.0, *)
    +struct UUID : ReferenceConvertible, Hashable, Equatable, CustomStringConvertible
    + +
    +
    +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + Bool + +
    +
    +
    +
    +
    +
    +

    Bool adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Bool
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + Int + +
    +
    +
    +
    +
    +
    +

    Int adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Int : FixedWidthInteger, SignedInteger
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + Int8 + +
    +
    +
    +
    +
    +
    +

    Int8 adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Int8 : FixedWidthInteger, SignedInteger
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + Int16 + +
    +
    +
    +
    +
    +
    +

    Int16 adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Int16 : FixedWidthInteger, SignedInteger
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + Int32 + +
    +
    +
    +
    +
    +
    +

    Int32 adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Int32 : FixedWidthInteger, SignedInteger
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + Int64 + +
    +
    +
    +
    +
    +
    +

    Int64 adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Int64 : FixedWidthInteger, SignedInteger
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + UInt + +
    +
    +
    +
    +
    +
    +

    UInt adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct UInt : FixedWidthInteger, UnsignedInteger
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + UInt8 + +
    +
    +
    +
    +
    +
    +

    UInt8 adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct UInt8 : FixedWidthInteger, UnsignedInteger
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + UInt16 + +
    +
    +
    +
    +
    +
    +

    UInt16 adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct UInt16 : FixedWidthInteger, UnsignedInteger
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + UInt32 + +
    +
    +
    +
    +
    +
    +

    UInt32 adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct UInt32 : FixedWidthInteger, UnsignedInteger
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + UInt64 + +
    +
    +
    +
    +
    +
    +

    UInt64 adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct UInt64 : FixedWidthInteger, UnsignedInteger
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + Double + +
    +
    +
    +
    +
    +
    +

    Double adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Double
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + Float + +
    +
    +
    +
    +
    +
    +

    Float adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Float
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + String + +
    +
    +
    +
    +
    +
    +

    String adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct String
    + +
    +
    +
    +
    +
  • +
+
+
+ +
+
+ +
+
+ +
    +
  • +
    + + + + Range + +
    +
    +
    +
    +
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Range<Bound> where Bound : Comparable
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + ClosedRange + +
    +
    +
    +
    +
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct ClosedRange<Bound> where Bound : Comparable
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + CountableRange + +
    +
    +
    +
    +
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct CountableRange<Bound> where Bound : Strideable, Bound.Stride : SignedInteger
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + CountableClosedRange + +
    +
    +
    +
    +
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct CountableClosedRange<Bound> where Bound : Strideable, Bound.Stride : SignedInteger
    + +
    +
    +
    +
    +
  • +
+
+
+ + +
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/Array.html b/docs/3.3/Extensions/Array.html new file mode 100644 index 000000000..7d1798a8c --- /dev/null +++ b/docs/3.3/Extensions/Array.html @@ -0,0 +1,843 @@ + + + + Array Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Array

+
+
+
struct Array<Element> : _DestructorSafeContainer
+ +
+
+ +
+
+
+
    +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    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"]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init<C>(_ cursor: C) throws where Element == C.Element, C : Cursor
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/Bool.html b/docs/3.3/Extensions/Bool.html new file mode 100644 index 000000000..7609b4ff1 --- /dev/null +++ b/docs/3.3/Extensions/Bool.html @@ -0,0 +1,932 @@ + + + + Bool Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Bool

+
+
+
struct Bool
+ +
+
+

Bool adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a Bool initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Bool?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/CGFloat.html b/docs/3.3/Extensions/CGFloat.html new file mode 100644 index 000000000..f25ef9cdd --- /dev/null +++ b/docs/3.3/Extensions/CGFloat.html @@ -0,0 +1,871 @@ + + + + CGFloat Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

CGFloat

+
+
+
struct CGFloat
+ +
+
+

CGFloat adopts DatabaseValueConvertible

+ +
+
+
+
    +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a CGFloat initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> CGFloat?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/ClosedRange.html b/docs/3.3/Extensions/ClosedRange.html new file mode 100644 index 000000000..b2626bda7 --- /dev/null +++ b/docs/3.3/Extensions/ClosedRange.html @@ -0,0 +1,876 @@ + + + + ClosedRange Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ClosedRange

+
+
+
struct ClosedRange<Bound> where Bound : Comparable
+ +
+
+ +
+
+
+
    +
  • +
    + + + + contains(_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that checks the inclusion of an expression in a range.

    +
    // email BETWEEN 'A' AND 'B'
    +("A"..."B").contains(Column("email"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func contains(_ element: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + contains(_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that checks the inclusion of an expression in a range.

    +
    // email BETWEEN 'A' AND 'B' COLLATE NOCASE
    +("A"..."B").contains(Column("email").collating(.nocase))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func contains(_ element: SQLCollatedExpression) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/Column.html b/docs/3.3/Extensions/Column.html new file mode 100644 index 000000000..875e20977 --- /dev/null +++ b/docs/3.3/Extensions/Column.html @@ -0,0 +1,823 @@ + + + + Column Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Column

+ +
+
+
+
    +
  • +
    + + + + rank + +
    +
    +
    +
    +
    +
    +

    The FTS5 rank column

    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/CountableClosedRange.html b/docs/3.3/Extensions/CountableClosedRange.html new file mode 100644 index 000000000..dce75d259 --- /dev/null +++ b/docs/3.3/Extensions/CountableClosedRange.html @@ -0,0 +1,843 @@ + + + + CountableClosedRange Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

CountableClosedRange

+
+
+
struct CountableClosedRange<Bound> where Bound : Strideable, Bound.Stride : SignedInteger
+ +
+
+ +
+
+
+
    +
  • +
    + + + + contains(_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that checks the inclusion of an expression in a range.

    +
    // id BETWEEN 1 AND 10
    +(1...10).contains(Column("id"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func contains(_ element: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/CountableRange.html b/docs/3.3/Extensions/CountableRange.html new file mode 100644 index 000000000..9a9831ae8 --- /dev/null +++ b/docs/3.3/Extensions/CountableRange.html @@ -0,0 +1,843 @@ + + + + CountableRange Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

CountableRange

+
+
+
struct CountableRange<Bound> where Bound : Strideable, Bound.Stride : SignedInteger
+ +
+
+ +
+
+
+
    +
  • +
    + + + + contains(_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that checks the inclusion of an expression in a range.

    +
    // id BETWEEN 1 AND 9
    +(1..<10).contains(Column("id"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func contains(_ element: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/Data.html b/docs/3.3/Extensions/Data.html new file mode 100644 index 000000000..97645f9cb --- /dev/null +++ b/docs/3.3/Extensions/Data.html @@ -0,0 +1,901 @@ + + + + Data Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Data

+
+
+
struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessCollection, MutableCollection, RangeReplaceableCollection
+ +
+
+

Data is convertible to and from DatabaseValue.

+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/Database.html b/docs/3.3/Extensions/Database.html new file mode 100644 index 000000000..91630f2b1 --- /dev/null +++ b/docs/3.3/Extensions/Database.html @@ -0,0 +1,937 @@ + + + + Database Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Database

+ +
+
+
+ +
+
+
+ + + +

FTS5

+
+
+
    +
  • +
    + + + + add(tokenizer:) + +
    +
    +
    +
    +
    +
    +

    Add a custom FTS5 tokenizer.

    +
    class MyTokenizer : FTS5CustomTokenizer { ... }
    +db.add(tokenizer: MyTokenizer.self)
    +
    + +
    +
    +
    +
  • +
+
+
+
+ + + +

FTS5

+
+
+ +
+
+
+ + + +

FTS5

+
+
+
    +
  • +
    + + + + makeTokenizer(_:) + +
    +
    +
    +
    +
    +
    +

    Creates an FTS5 tokenizer, given its descriptor.

    +
    let unicode61 = try db.makeTokenizer(.unicode61())
    +
    + +

    It is a programmer error to use the tokenizer outside of a protected +database queue, or after the database has been closed.

    + +

    Use this method when you implement a custom wrapper tokenizer:

    +
    final class MyTokenizer : FTS5WrapperTokenizer {
    +    var wrappedTokenizer: FTS5Tokenizer
    +
    +    init(db: Database, arguments: [String]) throws {
    +        wrappedTokenizer = try db.makeTokenizer(.unicode61())
    +    }
    +}
    +
    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/DatabasePool.html b/docs/3.3/Extensions/DatabasePool.html new file mode 100644 index 000000000..45034336c --- /dev/null +++ b/docs/3.3/Extensions/DatabasePool.html @@ -0,0 +1,863 @@ + + + + DatabasePool Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabasePool

+ +
+
+
+ +
    +
  • +
    + + + + change(passphrase:) + +
    +
    +
    +
    +
    +
    +

    Changes the passphrase of an encrypted database

    + +
    +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(tokenizer:) + +
    +
    +
    +
    +
    +
    +

    Add a custom FTS5 tokenizer.

    +
    class MyTokenizer : FTS5CustomTokenizer { ... }
    +dbPool.add(tokenizer: MyTokenizer.self)
    +
    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/DatabaseQueue.html b/docs/3.3/Extensions/DatabaseQueue.html new file mode 100644 index 000000000..ffc7e7c09 --- /dev/null +++ b/docs/3.3/Extensions/DatabaseQueue.html @@ -0,0 +1,863 @@ + + + + DatabaseQueue Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseQueue

+ +
+
+
+ +
    +
  • +
    + + + + change(passphrase:) + +
    +
    +
    +
    +
    +
    +

    Changes the passphrase of an encrypted database

    + +
    +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(tokenizer:) + +
    +
    +
    +
    +
    +
    +

    Add a custom FTS5 tokenizer.

    +
    class MyTokenizer : FTS5CustomTokenizer { ... }
    +dbQueue.add(tokenizer: MyTokenizer.self)
    +
    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/Date.html b/docs/3.3/Extensions/Date.html new file mode 100644 index 000000000..9f25f9b8e --- /dev/null +++ b/docs/3.3/Extensions/Date.html @@ -0,0 +1,977 @@ + + + + Date Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Date

+
+
+
struct Date : ReferenceConvertible, Comparable, Equatable
+ +
+
+

Date is stored in the database using the format +yyyy-MM-dd HH:mm:ss.SSS, in the UTC time zone.

+ +
+
+
+
    +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a database value that contains the date encoded as +yyyy-MM-dd HH:mm:ss.SSS, in the UTC time zone.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a date initialized from dbValue, if possible.

    + +

    If database value contains a number, that number is interpreted as a +timeinterval since 00:00:00 UTC on 1 January 1970.

    + +

    If database value contains a string, that string is interpreted as a +SQLite date in the UTC time +zone. Nil is returned if the date string does not contain at least the +year, month and day components. Other components (minutes, etc.) +are set to zero if missing.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Date?
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(julianDay:) + +
    +
    +
    +
    +
    +
    +

    Creates a date from a Julian Day.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init?(julianDay: Double)
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/Double.html b/docs/3.3/Extensions/Double.html new file mode 100644 index 000000000..3017e6613 --- /dev/null +++ b/docs/3.3/Extensions/Double.html @@ -0,0 +1,932 @@ + + + + Double Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Double

+
+
+
struct Double
+ +
+
+

Double adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a Double initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Double?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/Float.html b/docs/3.3/Extensions/Float.html new file mode 100644 index 000000000..125cd0978 --- /dev/null +++ b/docs/3.3/Extensions/Float.html @@ -0,0 +1,932 @@ + + + + Float Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Float

+
+
+
struct Float
+ +
+
+

Float adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a Float initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Float?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/Int.html b/docs/3.3/Extensions/Int.html new file mode 100644 index 000000000..f4b069f20 --- /dev/null +++ b/docs/3.3/Extensions/Int.html @@ -0,0 +1,932 @@ + + + + Int Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Int

+
+
+
struct Int : FixedWidthInteger, SignedInteger
+ +
+
+

Int adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an Int initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/Int16.html b/docs/3.3/Extensions/Int16.html new file mode 100644 index 000000000..a7cc80d58 --- /dev/null +++ b/docs/3.3/Extensions/Int16.html @@ -0,0 +1,932 @@ + + + + Int16 Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Int16

+
+
+
struct Int16 : FixedWidthInteger, SignedInteger
+ +
+
+

Int16 adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an Int16 initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int16?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/Int32.html b/docs/3.3/Extensions/Int32.html new file mode 100644 index 000000000..832d17ea2 --- /dev/null +++ b/docs/3.3/Extensions/Int32.html @@ -0,0 +1,932 @@ + + + + Int32 Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Int32

+
+
+
struct Int32 : FixedWidthInteger, SignedInteger
+ +
+
+

Int32 adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an Int32 initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int32?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/Int64.html b/docs/3.3/Extensions/Int64.html new file mode 100644 index 000000000..1a25d8e19 --- /dev/null +++ b/docs/3.3/Extensions/Int64.html @@ -0,0 +1,932 @@ + + + + Int64 Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Int64

+
+
+
struct Int64 : FixedWidthInteger, SignedInteger
+ +
+
+

Int64 adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an Int64 initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int64?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/Int8.html b/docs/3.3/Extensions/Int8.html new file mode 100644 index 000000000..af282b1ab --- /dev/null +++ b/docs/3.3/Extensions/Int8.html @@ -0,0 +1,932 @@ + + + + Int8 Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Int8

+
+
+
struct Int8 : FixedWidthInteger, SignedInteger
+ +
+
+

Int8 adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an Int8 initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int8?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/NSData.html b/docs/3.3/Extensions/NSData.html new file mode 100644 index 000000000..8416534a8 --- /dev/null +++ b/docs/3.3/Extensions/NSData.html @@ -0,0 +1,872 @@ + + + + NSData Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

NSData

+
+
+
class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding
+ +
+
+

NSData is convertible to and from DatabaseValue.

+ +
+
+
+
    +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an NSData initialized from dbValue, if it contains +a Blob.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> `Self`?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/NSDate.html b/docs/3.3/Extensions/NSDate.html new file mode 100644 index 000000000..9388547db --- /dev/null +++ b/docs/3.3/Extensions/NSDate.html @@ -0,0 +1,882 @@ + + + + NSDate Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

NSDate

+
+
+
class NSDate : NSObject, NSCopying, NSSecureCoding
+ +
+
+

NSDate is stored in the database using the format +yyyy-MM-dd HH:mm:ss.SSS, in the UTC time zone.

+ +
+
+
+
    +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a database value that contains the date encoded as +yyyy-MM-dd HH:mm:ss.SSS, in the UTC time zone.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a date initialized from dbValue, if possible.

    + +

    If database value contains a number, that number is interpreted as a +timeinterval since 00:00:00 UTC on 1 January 1970.

    + +

    If database value contains a string, that string is interpreted as a +SQLite date in the UTC time +zone. Nil is returned if the date string does not contain at least the +year, month and day components. Other components (minutes, etc.) +are set to zero if missing.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> `Self`?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/NSNull.html b/docs/3.3/Extensions/NSNull.html new file mode 100644 index 000000000..bea335158 --- /dev/null +++ b/docs/3.3/Extensions/NSNull.html @@ -0,0 +1,871 @@ + + + + NSNull Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

NSNull

+
+
+
class NSNull : NSObject, NSCopying, NSSecureCoding
+ +
+
+

NSNull adopts DatabaseValueConvertible

+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/NSNumber.html b/docs/3.3/Extensions/NSNumber.html new file mode 100644 index 000000000..e53edea85 --- /dev/null +++ b/docs/3.3/Extensions/NSNumber.html @@ -0,0 +1,871 @@ + + + + NSNumber Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

NSNumber

+
+
+
class NSNumber : NSValue
+ +
+
+

NSNumber adopts DatabaseValueConvertible

+ +
+
+
+
    +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an NSNumber initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> `Self`?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/NSString.html b/docs/3.3/Extensions/NSString.html new file mode 100644 index 000000000..2634a38fb --- /dev/null +++ b/docs/3.3/Extensions/NSString.html @@ -0,0 +1,871 @@ + + + + NSString Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

NSString

+
+
+
class NSString : NSObject, NSCopying, NSMutableCopying, NSSecureCoding
+ +
+
+

NSString adopts DatabaseValueConvertible

+ +
+
+
+
    +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an NSString initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> `Self`?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/NSURL.html b/docs/3.3/Extensions/NSURL.html new file mode 100644 index 000000000..61e40c254 --- /dev/null +++ b/docs/3.3/Extensions/NSURL.html @@ -0,0 +1,872 @@ + + + + NSURL Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

NSURL

+
+
+
class NSURL : NSObject, NSSecureCoding, NSCopying
+ +
+
+

NSURL stores its absoluteString in the database.

+ +
+
+
+
    +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database. +(the URL’s absoluteString).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an NSURL initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> `Self`?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/NSUUID.html b/docs/3.3/Extensions/NSUUID.html new file mode 100644 index 000000000..a87a0dc48 --- /dev/null +++ b/docs/3.3/Extensions/NSUUID.html @@ -0,0 +1,869 @@ + + + + NSUUID Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

NSUUID

+
+
+
class NSUUID : NSObject, NSCopying, NSSecureCoding
+ +
+
+

NSUUID adopts DatabaseValueConvertible

+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/Optional.html b/docs/3.3/Extensions/Optional.html new file mode 100644 index 000000000..fa440d0c9 --- /dev/null +++ b/docs/3.3/Extensions/Optional.html @@ -0,0 +1,1923 @@ + + + + Optional Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Optional

+
+
+
enum Optional<Wrapped> : ExpressibleByNilLiteral
+ +
+
+

Swift’s Optional comes with built-in methods that allow to fetch cursors +and arrays of optional DatabaseValueConvertible:

+
try Optional<String>.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String?
+try Optional<String>.fetchAll(db, "SELECT name FROM ...", arguments:...)    // [String?]
+
+let statement = try db.makeSelectStatement("SELECT name FROM ...")
+try Optional<String>.fetchCursor(statement, arguments:...) // Cursor of String?
+try Optional<String>.fetchAll(statement, arguments:...)    // [String?]
+
+ +

DatabaseValueConvertible is adopted by Bool, Int, String, etc.

+ +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Returns a cursor over optional values fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT name FROM ...")
    +let names = try Optional<String>.fetchCursor(statement) // Cursor of String?
    +while let name = try names.next() { // String?
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped>
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched optional values.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns an array of optional values fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT name FROM ...")
    +let names = try Optional<String>.fetchAll(statement)  // [String?]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An array of optional values.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Returns a cursor over optional values fetched from an SQL query.

    +
    let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // Cursor of String?
    +while let name = try names.next() { // String?
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped>
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched optional values.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns an array of optional values fetched from an SQL query.

    +
    let names = try String.fetchAll(db, "SELECT name FROM ...") // [String?]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An array of optional values.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:_:) + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over optional values fetched from a fetch request.

    +
    let request = Player.select(Column("name"))
    +let names = try Optional<String>.fetchCursor(db, request) // Cursor of String?
    +while let name = try names.next() { // String?
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor<R>(_ db: Database, _ request: R) throws -> NullableDatabaseValueCursor<Wrapped> where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched optional values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:_:) + +
    +
    +
    +
    +
    +
    +

    Returns an array of optional values fetched from a fetch request.

    +
    let request = Player.select(Column("name"))
    +let names = try Optional<String>.fetchAll(db, request) // [String?]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll<R>(_ db: Database, _ request: R) throws -> [Wrapped?] where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of optional values.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Returns a cursor over optional values fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT name FROM ...")
    +let names = try Optional<String>.fetchCursor(statement) // Cursor of String?
    +while let name = try names.next() { // String?
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor<Wrapped>
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched optional values.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns an array of optional values fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT name FROM ...")
    +let names = try Optional<String>.fetchAll(statement)  // [String?]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An array of optional values.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Returns a cursor over optional values fetched from an SQL query.

    +
    let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // Cursor of String?
    +while let name = try names.next() { // String?
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor<Wrapped>
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched optional values.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns an array of optional values fetched from an SQL query.

    +
    let names = try String.fetchAll(db, "SELECT name FROM ...") // [String?]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An array of optional values.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:_:) + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over optional values fetched from a fetch request.

    +
    let request = Player.select(Column("name"))
    +let names = try Optional<String>.fetchCursor(db, request) // Cursor of String?
    +while let name = try names.next() { // String?
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor<R>(_ db: Database, _ request: R) throws -> FastNullableDatabaseValueCursor<Wrapped> where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched optional values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:_:) + +
    +
    +
    +
    +
    +
    +

    Returns an array of optional values fetched from a fetch request.

    +
    let request = Player.select(Column("name"))
    +let names = try Optional<String>.fetchAll(db, request) // [String?]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll<R>(_ db: Database, _ request: R) throws -> [Wrapped?] where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of optional values.

    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/QueryInterfaceRequest.html b/docs/3.3/Extensions/QueryInterfaceRequest.html new file mode 100644 index 000000000..ba84a2139 --- /dev/null +++ b/docs/3.3/Extensions/QueryInterfaceRequest.html @@ -0,0 +1,842 @@ + + + + QueryInterfaceRequest Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

QueryInterfaceRequest

+ +
+
+
+ +
    +
  • +
    + + + + matching(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a request with a full-text predicate added to the eventual +set of already applied predicates.

    +
    // SELECT * FROM book WHERE book MATCH '...'
    +var request = Book.all()
    +request = request.matching(pattern)
    +
    + +

    If the search pattern is nil, the request does not match any +database row.

    + +

    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.

    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/Range.html b/docs/3.3/Extensions/Range.html new file mode 100644 index 000000000..b3f8e3456 --- /dev/null +++ b/docs/3.3/Extensions/Range.html @@ -0,0 +1,876 @@ + + + + Range Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Range

+
+
+
struct Range<Bound> where Bound : Comparable
+ +
+
+ +
+
+
+
    +
  • +
    + + + + contains(_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that checks the inclusion of an expression in a range.

    +
    // email >= 'A' AND email < 'B'
    +("A"..<"B").contains(Column("email"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func contains(_ element: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + contains(_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that checks the inclusion of an expression in a range.

    +
    // email >= 'A' COLLATE NOCASE AND email < 'B' COLLATE NOCASE
    +("A"..<"B").contains(Column("email").collating(.nocase))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func contains(_ element: SQLCollatedExpression) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/SQLSpecificExpressible.html b/docs/3.3/Extensions/SQLSpecificExpressible.html new file mode 100644 index 000000000..119050a42 --- /dev/null +++ b/docs/3.3/Extensions/SQLSpecificExpressible.html @@ -0,0 +1,843 @@ + + + + SQLSpecificExpressible Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

SQLSpecificExpressible

+
+
+
public protocol SQLSpecificExpressible : SQLExpressible
+ +
+
+ +
+
+
+
    +
  • +
    + + + + like(_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression with the LIKE SQL operator.

    +
    // email LIKE '%@example.com"
    +Column("email").like("%@example.com")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func like(_ pattern: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/Sequence.html b/docs/3.3/Extensions/Sequence.html new file mode 100644 index 000000000..88a7dfdd3 --- /dev/null +++ b/docs/3.3/Extensions/Sequence.html @@ -0,0 +1,969 @@ + + + + Sequence Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Sequence

+
+
+
protocol Sequence
+ +
+
+ +
+
+
+
    +
  • +
    + + + + flatMap(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over the concatenated results of mapping transform +over self.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<AnyCursor<Iterator.Element>, SegmentOfResult>>
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + contains(_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that checks the inclusion of an expression in +a sequence.

    +
    // id IN (1,2,3)
    +[1, 2, 3].contains(Column("id"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func contains(_ element: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + contains(_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that checks the inclusion of an expression in +a sequence.

    +
    // name IN ('A', 'B') COLLATE NOCASE
    +["A", "B"].contains(Column("name").collating(.nocase))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func contains(_ element: SQLCollatedExpression) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + joined(operator:) + +
    +
    +
    +
    +
    +
    +

    Returns an expression by joining all elements with an SQL +logical operator.

    + +

    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))
    +
    + +

    When the sequence is empty, joined(operator: .and) returns true, +and joined(operator: .or) returns false:

    +
    // SELECT * FROM player WHERE 1
    +Player.filter([].joined(operator: .and))
    +
    +// SELECT * FROM player WHERE 0
    +Player.filter([].joined(operator: .or))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func joined(operator: SQLLogicalBinaryOperator) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/Set.html b/docs/3.3/Extensions/Set.html new file mode 100644 index 000000000..c25e3319c --- /dev/null +++ b/docs/3.3/Extensions/Set.html @@ -0,0 +1,843 @@ + + + + Set Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Set

+
+
+
struct Set<Element> where Element : Hashable
+ +
+
+ +
+
+
+
    +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a set containing the elements of a cursor.

    +
    let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'foo'")
    +let strings = try Set(cursor) // ["foo"]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init<C>(_ cursor: C) throws where Element == C.Element, C : Cursor
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/String.html b/docs/3.3/Extensions/String.html new file mode 100644 index 000000000..c033d242b --- /dev/null +++ b/docs/3.3/Extensions/String.html @@ -0,0 +1,969 @@ + + + + String Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

String

+
+
+
struct String
+ +
+
+

String adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a String initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> String?
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns the receiver, quoted for safe insertion as an identifier in an +SQL query.

    +
    db.execute("SELECT * FROM \(tableName.quotedDatabaseIdentifier)")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var quotedDatabaseIdentifier: String { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/TableRecord.html b/docs/3.3/Extensions/TableRecord.html new file mode 100644 index 000000000..dbfb4a96c --- /dev/null +++ b/docs/3.3/Extensions/TableRecord.html @@ -0,0 +1,836 @@ + + + + TableRecord Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

TableRecord

+ +
+
+
+ +
    +
  • +
    + + + + matching(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a QueryInterfaceRequest with a matching predicate.

    +
    // SELECT * FROM book WHERE book MATCH '...'
    +var request = Book.matching(pattern)
    +
    + +

    If the search pattern is nil, the request does not match any +database row.

    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/UInt.html b/docs/3.3/Extensions/UInt.html new file mode 100644 index 000000000..03c835216 --- /dev/null +++ b/docs/3.3/Extensions/UInt.html @@ -0,0 +1,932 @@ + + + + UInt Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

UInt

+
+
+
struct UInt : FixedWidthInteger, UnsignedInteger
+ +
+
+

UInt adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an Int initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/UInt16.html b/docs/3.3/Extensions/UInt16.html new file mode 100644 index 000000000..1da653a5b --- /dev/null +++ b/docs/3.3/Extensions/UInt16.html @@ -0,0 +1,932 @@ + + + + UInt16 Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

UInt16

+
+
+
struct UInt16 : FixedWidthInteger, UnsignedInteger
+ +
+
+

UInt16 adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an UInt16 initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt16?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/UInt32.html b/docs/3.3/Extensions/UInt32.html new file mode 100644 index 000000000..3a8b6bf33 --- /dev/null +++ b/docs/3.3/Extensions/UInt32.html @@ -0,0 +1,932 @@ + + + + UInt32 Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

UInt32

+
+
+
struct UInt32 : FixedWidthInteger, UnsignedInteger
+ +
+
+

UInt32 adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an UInt32 initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt32?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/UInt64.html b/docs/3.3/Extensions/UInt64.html new file mode 100644 index 000000000..487c6afb2 --- /dev/null +++ b/docs/3.3/Extensions/UInt64.html @@ -0,0 +1,932 @@ + + + + UInt64 Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

UInt64

+
+
+
struct UInt64 : FixedWidthInteger, UnsignedInteger
+ +
+
+

UInt64 adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an UInt64 initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt64?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/UInt8.html b/docs/3.3/Extensions/UInt8.html new file mode 100644 index 000000000..811677ddf --- /dev/null +++ b/docs/3.3/Extensions/UInt8.html @@ -0,0 +1,932 @@ + + + + UInt8 Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

UInt8

+
+
+
struct UInt8 : FixedWidthInteger, UnsignedInteger
+ +
+
+

UInt8 adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an UInt8 initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt8?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Extensions/UUID.html b/docs/3.3/Extensions/UUID.html new file mode 100644 index 000000000..43325c58b --- /dev/null +++ b/docs/3.3/Extensions/UUID.html @@ -0,0 +1,903 @@ + + + + UUID Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

UUID

+
+
+
@available(OSX 10.8, iOS 6.0, *)
+struct UUID : ReferenceConvertible, Hashable, Equatable, CustomStringConvertible
+ +
+
+

UUID adopts DatabaseValueConvertible

+ +
+
+
+ +
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/Functions.html b/docs/3.3/Functions.html new file mode 100644 index 000000000..c0abdcc19 --- /dev/null +++ b/docs/3.3/Functions.html @@ -0,0 +1,3512 @@ + + + + Functions Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Functions

+

The following functions are available globally.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns an array of row adapters that split a row according to the input +number of columns.

    + +

    For example:

    +
    let sql = "SELECT 1, 2,3,4, 5,6, 7,8"
    +//               <.><. . .><. .><. .>
    +let adapters = splittingRowAdapters([1, 3, 2])
    +let adapter = ScopeAdapter([
    +    "a": adapters[0],
    +    "b": adapters[1],
    +    "c": adapters[2],
    +    "d": adapters[3]])
    +let row = try Row.fetchOne(db, sql, adapter: adapter)
    +row.scopes["a"] // [1]
    +row.scopes["b"] // [2, 3, 4]
    +row.scopes["c"] // [5, 6]
    +row.scopes["d"] // [7, 8]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func splittingRowAdapters(columnCounts: [Int]) -> [RowAdapter]
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + abs(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an expression that evaluates the ABS SQL function.

    +
    // ABS(amount)
    +abs(Column("amount"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func abs(_ value: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + average(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an expression that evaluates the AVG SQL function.

    +
    // AVG(length)
    +average(Column("length"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func average(_ value: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + count(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an expression that evaluates the COUNT SQL function.

    +
    // COUNT(email)
    +count(Column("email"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func count(_ counted: SQLSelectable) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + count(distinct:) + +
    +
    +
    +
    +
    +
    +

    Returns an expression that evaluates the COUNT(DISTINCT) SQL function.

    +
    // COUNT(DISTINCT email)
    +count(distinct: Column("email"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func count(distinct value: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + ??(_:_:) + +
    +
    +
    +
    +
    +
    +

    Returns an expression that evaluates the IFNULL SQL function.

    +
    // IFNULL(name, 'Anonymous')
    +Column("name") ?? "Anonymous"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func ?? (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + length(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an expression that evaluates the LENGTH SQL function.

    +
    // LENGTH(name)
    +length(Column("name"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func length(_ value: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + max(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an expression that evaluates the MAX SQL function.

    +
    // MAX(score)
    +max(Column("score"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func max(_ value: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + min(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an expression that evaluates the MIN SQL function.

    +
    // MIN(score)
    +min(Column("score"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func min(_ value: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + sum(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an expression that evaluates the SUM SQL function.

    +
    // SUM(amount)
    +sum(Column("amount"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func sum(_ value: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + ==(_:_:) + +
    +
    +
    +
    +
    +
    +

    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
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func == (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ==(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the = SQL operator.

    +
    // name = 'Arthur' COLLATE NOCASE
    +Column("name").collating(.nocase) == "Arthur"
    +
    + +

    When the right operand is nil, IS NULL is used instead.

    +
    // name IS NULL
    +Column("name").collating(.nocase) == nil
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func == (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> 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
    +Column("validated") == true
    +
    +// NOT validated
    +Column("validated") == false
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func == (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ==(_:_:) + +
    +
    +
    +
    +
    +
    +

    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")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func == (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ==(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the = SQL operator.

    +
    // 'Arthur' = name COLLATE NOCASE
    +"Arthur" == Column("name").collating(.nocase)
    +
    + +

    When the left operand is nil, IS NULL is used instead.

    +
    // name IS NULL
    +nil == Column("name").collating(.nocase)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func == (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> 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")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func == (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ==(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the = SQL operator.

    +
    // email = login
    +Column("email") == Column("login")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func == (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> 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
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func != (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + !=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the <> SQL operator.

    +
    // name <> 'Arthur' COLLATE NOCASE
    +Column("name").collating(.nocase) != "Arthur"
    +
    + +

    When the right operand is nil, IS NOT NULL is used instead.

    +
    // name IS NOT NULL
    +Column("name").collating(.nocase) != nil
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func != (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + !=(_:_:) + +
    +
    +
    +
    +
    +
    +

    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
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func != (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + !=(_:_:) + +
    +
    +
    +
    +
    +
    +

    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")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func != (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + !=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the <> SQL operator.

    +
    // 'Arthur' <> name COLLATE NOCASE
    +"Arthur" != Column("name").collating(.nocase)
    +
    + +

    When the left operand is nil, IS NOT NULL is used instead.

    +
    // name IS NOT NULL
    +nil != Column("name").collating(.nocase)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func != (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + !=(_:_:) + +
    +
    +
    +
    +
    +
    +

    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")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func != (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + !=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the <> SQL operator.

    +
    // email <> login
    +Column("email") != Column("login")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func != (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ===(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the IS SQL operator.

    +
    // name IS 'Arthur'
    +Column("name") === "Arthur"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func === (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ===(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the IS SQL operator.

    +
    // name IS 'Arthur' COLLATE NOCASE
    +Column("name").collating(.nocase) === "Arthur"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func === (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ===(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the IS SQL operator.

    +
    // name IS 'Arthur'
    +"Arthur" === Column("name")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func === (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ===(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the IS SQL operator.

    +
    // name IS 'Arthur' COLLATE NOCASE
    +"Arthur" === Column("name").collating(.nocase)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func === (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ===(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the IS SQL operator.

    +
    // email IS login
    +Column("email") === Column("login")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func === (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + !==(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the IS NOT SQL operator.

    +
    // name IS NOT 'Arthur'
    +Column("name") !== "Arthur"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func !== (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + !==(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the IS NOT SQL operator.

    +
    // name IS NOT 'Arthur' COLLATE NOCASE
    +Column("name").collating(.nocase) !== "Arthur"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func !== (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + !==(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the IS NOT SQL operator.

    +
    // name IS NOT 'Arthur'
    +"Arthur" !== Column("name")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func !== (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + !==(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the IS NOT SQL operator.

    +
    // name IS NOT 'Arthur' COLLATE NOCASE
    +"Arthur" !== Column("name").collating(.nocase)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func !== (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + !==(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the IS NOT SQL operator.

    +
    // email IS NOT login
    +Column("email") !== Column("login")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func !== (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + <(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the < SQL operator.

    +
    // score < 18
    +Column("score") < 18
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func < (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + <(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the < SQL operator.

    +
    // name < 'Arthur' COLLATE NOCASE
    +Column("name").collating(.nocase) < "Arthur"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func < (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + <(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the < SQL operator.

    +
    // 18 < score
    +18 < Column("score")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func < (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + <(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the < SQL operator.

    +
    // 'Arthur' < name COLLATE NOCASE
    +"Arthur" < Column("name").collating(.nocase)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func < (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + <(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the < SQL operator.

    +
    // width < height
    +Column("width") < Column("height")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func < (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + <=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the <= SQL operator.

    +
    // score <= 18
    +Column("score") <= 18
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func <= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + <=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the <= SQL operator.

    +
    // name <= 'Arthur' COLLATE NOCASE
    +Column("name").collating(.nocase) <= "Arthur"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func <= (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + <=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the <= SQL operator.

    +
    // 18 <= score
    +18 <= Column("score")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func <= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + <=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the <= SQL operator.

    +
    // 'Arthur' <= name COLLATE NOCASE
    +"Arthur" <= Column("name").collating(.nocase)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func <= (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + <=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the <= SQL operator.

    +
    // width <= height
    +Column("width") <= Column("height")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func <= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + >(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the > SQL operator.

    +
    // score > 18
    +Column("score") > 18
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func > (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + >(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the > SQL operator.

    +
    // name > 'Arthur' COLLATE NOCASE
    +Column("name").collating(.nocase) > "Arthur"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func > (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + >(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the > SQL operator.

    +
    // 18 > score
    +18 > Column("score")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func > (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + >(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the > SQL operator.

    +
    // 'Arthur' > name COLLATE NOCASE
    +"Arthur" > Column("name").collating(.nocase)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func > (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + >(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the > SQL operator.

    +
    // width > height
    +Column("width") > Column("height")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func > (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + >=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the >= SQL operator.

    +
    // score >= 18
    +Column("score") >= 18
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func >= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + >=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the >= SQL operator.

    +
    // name >= 'Arthur' COLLATE NOCASE
    +Column("name").collating(.nocase) >= "Arthur"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func >= (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + >=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the >= SQL operator.

    +
    // 18 >= score
    +18 >= Column("score")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func >= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + >=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the >= SQL operator.

    +
    // 'Arthur' >= name COLLATE NOCASE
    +"Arthur" >= Column("name").collating(.nocase)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func >= (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + >=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the >= SQL operator.

    +
    // width >= height
    +Column("width") >= Column("height")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func >= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + *(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL arithmetic multiplication.

    +
    // width * 2
    +Column("width") * 2
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func * (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + *(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL arithmetic multiplication.

    +
    // 2 * width
    +2 * Column("width")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func * (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + *(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL arithmetic multiplication.

    +
    // width * height
    +Column("width") * Column("height")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func * (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + /(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL arithmetic division.

    +
    // width / 2
    +Column("width") / 2
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func / (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + /(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL arithmetic division.

    +
    // 2 / width
    +2 / Column("width")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func / (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + /(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL arithmetic division.

    +
    // width / height
    +Column("width") / Column("height")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func / (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + +(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL arithmetic addition.

    +
    // width + 2
    +Column("width") + 2
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func + (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + +(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL arithmetic addition.

    +
    // 2 + width
    +2 + Column("width")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func + (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + +(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL arithmetic addition.

    +
    // width + height
    +Column("width") + Column("height")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func + (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + -(_:) + +
    +
    +
    +
    +
    +
    +

    A negated SQL arithmetic expression.

    +
    // -width
    +-Column("width")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public prefix func - (value: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + -(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL arithmetic substraction.

    +
    // width - 2
    +Column("width") - 2
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func - (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + -(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL arithmetic substraction.

    +
    // 2 - width
    +2 - Column("width")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func - (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + -(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL arithmetic substraction.

    +
    // width - height
    +Column("width") - Column("height")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func - (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + &&(_:_:) + +
    +
    +
    +
    +
    +
    +

    A logical SQL expression with the AND SQL operator.

    +
    // favorite AND 0
    +Column("favorite") && false
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + &&(_:_:) + +
    +
    +
    +
    +
    +
    +

    A logical SQL expression with the AND SQL operator.

    +
    // 0 AND favorite
    +false && Column("favorite")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func && (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + &&(_:_:) + +
    +
    +
    +
    +
    +
    +

    A logical SQL expression with the AND SQL operator.

    +
    // email IS NOT NULL AND favorite
    +Column("email") != nil && Column("favorite")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func && (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ||(_:_:) + +
    +
    +
    +
    +
    +
    +

    A logical SQL expression with the OR SQL operator.

    +
    // favorite OR 1
    +Column("favorite") || true
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ||(_:_:) + +
    +
    +
    +
    +
    +
    +

    A logical SQL expression with the OR SQL operator.

    +
    // 0 OR favorite
    +true || Column("favorite")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func || (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ||(_:_:) + +
    +
    +
    +
    +
    +
    +

    A logical SQL expression with the OR SQL operator.

    +
    // email IS NULL OR hidden
    +Column("email") == nil || Column("hidden")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func || (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> 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")))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public prefix func ! (value: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ + + +

Public

+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Return as many question marks separated with commas as the count argument.

    +
    databaseQuestionMarks(count: 3) // "?,?,?"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func databaseQuestionMarks(count: Int) -> String
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Protocols.html b/docs/3.3/Protocols.html new file mode 100644 index 000000000..10bab949c --- /dev/null +++ b/docs/3.3/Protocols.html @@ -0,0 +1,1702 @@ + + + + Protocols Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Protocols

+

The following protocols are available globally.

+ +
+
+
+
+ + + +

Cursor

+
+
+
    +
  • +
    + + + + Cursor + +
    +
    +
    +
    +
    +
    +

    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 Sequence protocol: contains, dropFirst, +dropLast, drop(while:), enumerated, filter, first, flatMap, +forEach, joined, joined(separator:), max, max(by:), min, +min(by:), map, prefix, prefix(while:), reduce, reduce(into:), +suffix.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol Cursor : AnyObject
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + DatabaseAggregate + +
    +
    +
    +
    +
    +
    +

    The protocol for custom SQLite aggregates.

    + +

    For example:

    +
    struct MySum : DatabaseAggregate {
    +    var sum: Int = 0
    +
    +    mutating func step(_ dbValues: [DatabaseValue]) {
    +        if let int = Int.fromDatabaseValue(dbValues[0]) {
    +            sum += int
    +        }
    +    }
    +
    +    func finalize() -> DatabaseValueConvertible? {
    +        return sum
    +    }
    +}
    +
    +let dbQueue = DatabaseQueue()
    +let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
    +dbQueue.add(function: fn)
    +try dbQueue.write { db in
    +    try db.execute("CREATE TABLE test(i)")
    +    try db.execute("INSERT INTO test(i) VALUES (1)")
    +    try db.execute("INSERT INTO test(i) VALUES (2)")
    +    try Int.fetchOne(db, "SELECT mysum(i) FROM test")! // 3
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol DatabaseAggregate
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + DatabaseReader + +
    +
    +
    +
    +
    +
    +

    The protocol for all types that can fetch values from a database.

    + +

    It is adopted by DatabaseQueue and DatabasePool.

    + +

    The protocol comes with isolation guarantees that describe the behavior of +adopting types in a multithreaded application.

    + +

    Types that adopt the protocol can provide in practice stronger guarantees. +For example, DatabaseQueue provides a stronger isolation level +than DatabasePool.

    + +

    Warning: Isolation guarantees stand as long as there is no external +connection to the database. Should you have to cope with external +connections, protect yourself with transactions, and be ready to setup a +busy handler.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol DatabaseReader : AnyObject
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Types that adopt DatabaseValueConvertible can be initialized from +database values.

    + +

    The protocol comes with built-in methods that allow to fetch cursors, +arrays, or single values:

    +
    try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String
    +try String.fetchAll(db, "SELECT name FROM ...", arguments:...)    // [String]
    +try String.fetchOne(db, "SELECT name FROM ...", arguments:...)    // String?
    +
    +let statement = try db.makeSelectStatement("SELECT name FROM ...")
    +try String.fetchCursor(statement, arguments:...) // Cursor of String
    +try String.fetchAll(statement, arguments:...)    // [String]
    +try String.fetchOne(statement, arguments:...)    // String?
    +
    + +

    DatabaseValueConvertible is adopted by Bool, Int, String, etc.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol DatabaseValueConvertible : SQLExpressible
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + FetchRequest + +
    +
    +
    +
    +
    +
    +

    The protocol for all requests that run from a single select statement, and +tell how fetched rows should be interpreted.

    +
    struct Player: FetchableRecord { ... }
    +let request: ... // Some FetchRequest that fetches Player
    +try request.fetchCursor(db) // Cursor of Player
    +try request.fetchAll(db)    // [Player]
    +try request.fetchOne(db)    // Player?
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol FetchRequest
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + DatabaseWriter + +
    +
    +
    +
    +
    +
    +

    The protocol for all types that can update a database.

    + +

    It is adopted by DatabaseQueue and DatabasePool.

    + +

    The protocol comes with isolation guarantees that describe the behavior of +adopting types in a multithreaded application.

    + +

    Types that adopt the protocol can in practice provide stronger guarantees. +For example, DatabaseQueue provides a stronger isolation level +than DatabasePool.

    + +

    Warning: Isolation guarantees stand as long as there is no external +connection to the database. Should you have to cope with external +connections, protect yourself with transactions, and be ready to setup a +busy handler.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol DatabaseWriter : DatabaseReader
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + RowAdapter + +
    +
    +
    +
    +
    +
    +

    RowAdapter is a protocol that helps two incompatible row interfaces working +together.

    + +

    GRDB ships with four concrete types that adopt the RowAdapter protocol:

    + +
      +
    • ColumnMapping: renames row columns
    • +
    • SuffixRowAdapter: hides the first columns of a row
    • +
    • RangeRowAdapter: only exposes a range of columns
    • +
    • ScopeAdapter: groups several adapters together to define named scopes
    • +
    + +

    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, adapter: adapter)
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol RowAdapter
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    The StatementColumnConvertible protocol grants access to the low-level C +interface that extracts values from query results: +https://www.sqlite.org/c3ref/column_blob.html. It can bring performance +improvements.

    + +

    To use it, have a value type adopt both StatementColumnConvertible and +DatabaseValueConvertible. GRDB will then automatically apply the +optimization whenever direct access to SQLite is possible:

    +
    let rows = Row.fetchCursor(db, "SELECT ...")
    +while let row = try rows.next() {
    +    let int: Int = row[0]                 // there
    +}
    +let ints = Int.fetchAll(db, "SELECT ...") // there
    +struct Player {
    +    init(row: Row) {
    +        name = row["name"]                // there
    +        score = row["score"]              // there
    +    }
    +}
    +
    + +

    StatementColumnConvertible is already adopted by all Swift integer types, +Float, Double, String, and Bool.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol StatementColumnConvertible
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + TransactionObserver + +
    +
    +
    +
    +
    +
    +

    A transaction observer is notified of all changes and transactions committed +or rollbacked on a database.

    + +

    Adopting types must be a class.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol TransactionObserver : AnyObject
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
+
+ +
+
+
    +
  • +
    + + + + FTS5WrapperTokenizer + +
    +
    +
    +
    +
    +
    +

    The protocol for custom FTS5 tokenizers that wrap another tokenizer.

    + +

    Types that adopt FTS5WrapperTokenizer don’t have to implement the +low-level FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:).

    + +

    Instead, they process regular Swift strings.

    + +

    Here is the implementation for a trivial tokenizer that wraps the +built-in ascii tokenizer without any custom processing:

    +
    class TrivialAsciiTokenizer : FTS5WrapperTokenizer {
    +    static let name = "trivial"
    +    let wrappedTokenizer: FTS5Tokenizer
    +
    +    init(db: Database, arguments: [String]) throws {
    +        wrappedTokenizer = try db.makeTokenizer(.ascii())
    +    }
    +
    +    func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws {
    +        try tokenCallback(token, flags)
    +    }
    +}
    +
    + + See more +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + Association + +
    +
    +
    +
    +
    +
    +

    Experimental

    + +

    The base protocol for all associations that define a connection between two +record types.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol Association : DerivableRequest
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + TableRecord + +
    +
    +
    +
    +
    +
    +

    Types that adopt TableRecord declare a particular relationship with +a database table.

    + +

    Types that adopt both TableRecord and FetchableRecord are granted with +built-in methods that allow to fetch instances identified by key:

    +
    try Player.fetchOne(db, key: 123)  // Player?
    +try Citizenship.fetchOne(db, key: ["citizenId": 12, "countryId": 45]) // Citizenship?
    +
    + +

    TableRecord is adopted by Record.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol TableRecord
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + ColumnExpression + +
    +
    +
    +
    +
    +
    +

    Adopt the ColumnExpression protocol when you define a column type.

    + +

    You can, for example, define a String-based column enum:

    +
    enum Columns: String, ColumnExpression {
    +    case id, name, score
    +}
    +let arthur = try Player.filter(Columns.name == "Arthur").fetchOne(db)
    +
    + +

    You can also define a genuine column type:

    +
    struct MyColumn: ColumnExpression {
    +    var name: String
    +    var sqlType: String
    +}
    +let nameColumn = MyColumn(name: "name", sqlType: "VARCHAR")
    +let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db)
    +
    + +

    See https://github.com/groue/GRDB.swift#the-query-interface

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol ColumnExpression : SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+
    +
  • +
    + + + + VirtualTableModule + +
    +
    +
    +
    +
    +
    +

    The protocol for SQLite virtual table modules. It lets you define a DSL for +the Database.create(virtualTable:using:) method:

    +
    let module = ...
    +try db.create(virtualTable: "item", using: module) { t in
    +    ...
    +}
    +
    + +

    GRDB ships with three concrete classes that implement this protocol: FTS3, +FTS4 and FTS5.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol VirtualTableModule
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + FetchableRecord + +
    +
    +
    +
    +
    +
    +

    Types that adopt FetchableRecord can be initialized from a database Row.

    +
    let row = try Row.fetchOne(db, "SELECT ...")!
    +let player = Player(row)
    +
    + +

    The protocol comes with built-in methods that allow to fetch cursors, +arrays, or single records:

    +
    try Player.fetchCursor(db, "SELECT ...", arguments:...) // Cursor of Player
    +try Player.fetchAll(db, "SELECT ...", arguments:...)    // [Player]
    +try Player.fetchOne(db, "SELECT ...", arguments:...)    // Player?
    +
    +let statement = try db.makeSelectStatement("SELECT ...")
    +try Player.fetchCursor(statement, arguments:...) // Cursor of Player
    +try Player.fetchAll(statement, arguments:...)    // [Player]
    +try Player.fetchOne(statement, arguments:...)    // Player?
    +
    + +

    FetchableRecord is adopted by Record.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol FetchableRecord
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + PersistableRecord + +
    +
    +
    +
    +
    +
    +

    Types that adopt PersistableRecord can be inserted, updated, and deleted.

    + +

    This protocol is intented for types that don’t have an INTEGER PRIMARY KEY.

    + +

    Unlike MutablePersistableRecord, the insert() and save() methods are not +mutating methods.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol PersistableRecord : MutablePersistableRecord
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Protocols/Association.html b/docs/3.3/Protocols/Association.html new file mode 100644 index 000000000..539167c57 --- /dev/null +++ b/docs/3.3/Protocols/Association.html @@ -0,0 +1,1412 @@ + + + + Association Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Association

+
+
+
public protocol Association : DerivableRequest
+ +
+
+

Experimental

+ +

The base protocol for all associations that define a connection between two +record types.

+ +
+
+
+
    +
  • +
    + + + + OriginRowDecoder + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    associatedtype OriginRowDecoder
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + RowDecoder + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    associatedtype RowDecoder
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + key + +
    +
    +
    +
    +
    +
    +

    The association key defines how rows fetched from this association +should be consumed.

    + +

    For example:

    +
    struct Player: TableRecord {
    +    // The default key of this association is the name of the
    +    // database table for teams, let's say "team":
    +    static let team = belongsTo(Team.self)
    +}
    +print(Player.team.key) // Prints "team"
    +
    +// Consume rows:
    +let request = Player.including(required: Player.team)
    +for row in Row.fetchAll(db, request) {
    +    let team: Team = row["team"] // the association key
    +}
    +
    + +

    The key can be redefined with the forKey method:

    +
    let request = Player.including(required: Player.team.forKey("custom"))
    +for row in Row.fetchAll(db, request) {
    +    let team: Team = row["custom"]
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    var key: String { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + forKey(_:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Creates an association with the given key.

    + +

    This new key impacts how rows fetched from the resulting association +should be consumed:

    +
    struct Player: TableRecord {
    +    static let team = belongsTo(Team.self)
    +}
    +
    +// Consume rows:
    +let request = Player.including(required: Player.team.forKey("custom"))
    +for row in Row.fetchAll(db, request) {
    +    let team: Team = row["custom"]
    +}
    +
    + +
    +

    Default Implementation

    +
    +

    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)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func forKey(_ key: String) -> Self
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + select(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    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([Column("color")])
    +var request = Player.including(required: association)
    +
    + +

    Any previous selection is replaced:

    +
    // SELECT player.*, team.color
    +// FROM player
    +// JOIN team ON team.id = player.teamId
    +let association = Player.team
    +    .select([Column("id")])
    +    .select([Column("color")])
    +var request = Player.including(required: association)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func select(_ selection: [SQLSelectable]) -> Self
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + filter(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    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)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + order(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    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)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + reversed() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    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)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func reversed() -> Self
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + aliased(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    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"])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func aliased(_ alias: TableAlias) -> Self
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + including(optional:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates an association that includes another one. The columns of the +associated record are selected. The returned association does not +require that the associated database table contains a matching row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func including<A>(optional association: A) -> Self where A : Association, Self.RowDecoder == A.OriginRowDecoder
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + including(required:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates an association that includes another one. The columns of the +associated record are selected. The returned association requires +that the associated database table contains a matching row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func including<A>(required association: A) -> Self where A : Association, Self.RowDecoder == A.OriginRowDecoder
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + joining(optional:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates an association that joins another one. The columns of the +associated record are not selected. The returned association does not +require that the associated database table contains a matching row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func joining<A>(optional association: A) -> Self where A : Association, Self.RowDecoder == A.OriginRowDecoder
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + joining(required:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates an association that joins another one. The columns of the +associated record are not selected. The returned association requires +that the associated database table contains a matching row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func joining<A>(required association: A) -> Self where A : Association, Self.RowDecoder == A.OriginRowDecoder
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Protocols/ColumnExpression.html b/docs/3.3/Protocols/ColumnExpression.html new file mode 100644 index 000000000..06d1b87a8 --- /dev/null +++ b/docs/3.3/Protocols/ColumnExpression.html @@ -0,0 +1,911 @@ + + + + ColumnExpression Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ColumnExpression

+
+
+
public protocol ColumnExpression : SQLExpression
+ +
+
+

Adopt the ColumnExpression protocol when you define a column type.

+ +

You can, for example, define a String-based column enum:

+
enum Columns: String, ColumnExpression {
+    case id, name, score
+}
+let arthur = try Player.filter(Columns.name == "Arthur").fetchOne(db)
+
+ +

You can also define a genuine column type:

+
struct MyColumn: ColumnExpression {
+    var name: String
+    var sqlType: String
+}
+let nameColumn = MyColumn(name: "name", sqlType: "VARCHAR")
+let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db)
+
+ +

See https://github.com/groue/GRDB.swift#the-query-interface

+ +
+
+
+
    +
  • +
    + + + + name + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    The unqualified name of a database column.

    + +

    score is a valid unqualified name. player.score is not.

    + +
    +

    Default Implementation

    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    var name: String { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + match(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    A matching SQL expression with the MATCH SQL operator.

    +
    // content MATCH '...'
    +Column("content").match(pattern)
    +
    + +

    If the search pattern is nil, SQLite will evaluate the expression +to false.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func match(_ pattern: FTS3Pattern?) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Protocols/Cursor.html b/docs/3.3/Protocols/Cursor.html new file mode 100644 index 000000000..3b626c16a --- /dev/null +++ b/docs/3.3/Protocols/Cursor.html @@ -0,0 +1,2251 @@ + + + + Cursor Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Cursor

+
+
+
public protocol Cursor : AnyObject
+ +
+
+

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 Sequence protocol: contains, dropFirst, +dropLast, drop(while:), enumerated, filter, first, flatMap, +forEach, joined, joined(separator:), max, max(by:), min, +min(by:), map, prefix, prefix(while:), reduce, reduce(into:), +suffix.

+ +
+
+
+
    +
  • +
    + + + + Element + +
    +
    +
    +
    +
    +
    +

    The type of element traversed by the cursor.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    associatedtype Element
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + next() + +
    +
    +
    +
    +
    +
    +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func next() throws -> Element?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ + + +

Cursor

+
+
+
    +
  • +
    + + + + contains(where:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a Boolean value indicating whether the cursor contains an +element that satisfies the given predicate.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func contains(where predicate: (Element) throws -> Bool) throws -> Bool
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + 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.

    +
    +
    +
    +
    +

    Return Value

    +

    true if the cursor contains an element that satisfies +predicate; otherwise, false.

    +
    + +
    +
    +
  • +
  • +
    + + + + enumerated() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    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"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func enumerated() -> EnumeratedCursor<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + filter(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns the elements of the cursor that satisfy the given predicate.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func filter(_ isIncluded: @escaping (Element) throws -> Bool) -> FilterCursor<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + first(where:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns the first element of the cursor that satisfies the given +predicate or nil if no such element is found.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func first(where predicate: (Element) throws -> Bool) throws -> Element?
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + compactMap(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over the concatenated non-nil results of mapping +transform over this cursor.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func compactMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + flatMap(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func flatMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + drop(while:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor that skips any initial elements that satisfy +predicate.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func drop(while predicate: @escaping (Element) throws -> Bool) -> DropWhileCursor<Self>
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + predicate + + +
    +

    A closure that takes an element of the cursir as +its argument and returns true if the element should be skipped or +false otherwise. Once predicate returns false it will not be +called again.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + dropFirst(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor containing all but the given number of initial +elements.

    + +

    If the number of elements to drop exceeds the number of elements in +the cursor, the result is an empty cursor.

    +
    let numbers = AnyCursor([1, 2, 3, 4, 5])
    +try print(numbers.dropFirst(2))
    +// Prints "[3, 4, 5]"
    +try print(numbers.dropFirst(10))
    +// Prints "[]"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func dropFirst(_ n: Int) -> DropFirstCursor<Self>
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + n + + +
    +

    The number of elements to drop from the beginning of +the cursor. n must be greater than or equal to zero.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor starting after the specified number of +elements.

    +
    + +
    +
    +
  • +
  • +
    + + + + dropFirst() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor containing all but the first element of the cursor.

    + +

    The following example drops the first element from a cursor of integers.

    +
    let numbers = AnyCursor([1, 2, 3, 4, 5])
    +try print(numbers.dropFirst())
    +// Prints "[2, 3, 4, 5]"
    +
    + +

    If the cursor has no elements, the result is an empty cursor.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func dropFirst() -> DropFirstCursor<Self>
    + +
    +
    +
    +

    Return Value

    +

    A cursor starting after the first element of the cursor.

    +
    + +
    +
    +
  • +
  • +
    + + + + dropLast(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array containing all but the given number of final +elements.

    + +

    The cursor must be finite. If the number of elements to drop exceeds +the number of elements in the cursor, the result is an empty array.

    +
    let numbers = AnyCursor([1, 2, 3, 4, 5])
    +try print(numbers.dropLast(2))
    +// Prints "[1, 2, 3]"
    +try print(numbers.dropLast(10))
    +// Prints "[]"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func dropLast(_ n: Int) throws -> [Element]
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + n + + +
    +

    The number of elements to drop off the end of the +cursor. n must be greater than or equal to zero.

    +
    +
    +
    +
    +

    Return Value

    +

    An array leaving off the specified number of elements.

    +
    + +
    +
    +
  • +
  • +
    + + + + dropLast() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array containing all but the last element of the cursor.

    + +

    The following example drops the last element from a cursor of integers.

    +
    let numbers = AnyCursor([1, 2, 3, 4, 5])
    +try print(numbers.dropLast())
    +// Prints "[1, 2, 3, 4]"
    +
    + +

    If the cursor has no elements, the result is an empty cursor.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func dropLast() throws -> [Element]
    + +
    +
    +
    +

    Return Value

    +

    An array leaving off the last element of the cursor.

    +
    + +
    +
    +
  • +
  • +
    + + + + flatMap(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over the concatenated results of mapping transform +over self.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func flatMap<SegmentOfResult: Sequence>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, AnyCursor<SegmentOfResult.Element>>>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + flatMap(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over the concatenated results of mapping transform +over self.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, SegmentOfResult>>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + forEach(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Calls the given closure on each element in the cursor.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func forEach(_ body: (Element) throws -> Void) throws
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + map(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over the results of the transform function applied to +this cursor’s elements.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func map<T>(_ transform: @escaping (Element) throws -> T) -> MapCursor<Self, T>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + max(by:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns the maximum element in the cursor, using the given predicate as +the comparison between elements.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func max(by areInIncreasingOrder: (Element, Element) throws -> Bool) throws -> Element?
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + areInIncreasingOrder + + +
    +

    A predicate that returns true +if its first argument should be ordered before its second +argument; otherwise, false.

    +
    +
    +
    +
    +

    Return Value

    +

    The cursor’s maximum element, according to +areInIncreasingOrder. If the cursor has no elements, returns nil.

    +
    + +
    +
    +
  • +
  • +
    + + + + min(by:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns the minimum element in the cursor, using the given predicate as +the comparison between elements.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func min(by areInIncreasingOrder: (Element, Element) throws -> Bool) throws -> Element?
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + areInIncreasingOrder + + +
    +

    A predicate that returns true +if its first argument should be ordered before its second +argument; otherwise, false.

    +
    +
    +
    +
    +

    Return Value

    +

    The cursor’s minimum element, according to +areInIncreasingOrder. If the cursor has no elements, returns nil.

    +
    + +
    +
    +
  • +
  • +
    + + + + prefix(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor, up to the specified maximum length, containing the +initial elements of the cursor.

    + +

    If the maximum length exceeds the number of elements in the cursor, +the result contains all the elements in the cursor.

    +
    let numbers = AnyCursor([1, 2, 3, 4, 5])
    +try print(numbers.prefix(2))
    +// Prints "[1, 2]"
    +try print(numbers.prefix(10))
    +// Prints "[1, 2, 3, 4, 5]"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func prefix(_ maxLength: Int) -> PrefixCursor<Self>
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + maxLength + + +
    +

    The maximum number of elements to return. The +value of maxLength must be greater than or equal to zero.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor starting at the beginning of this cursor +with at most maxLength elements.

    +
    + +
    +
    +
  • +
  • +
    + + + + prefix(while:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor of the initial consecutive elements that satisfy +predicate.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func prefix(while predicate: @escaping (Element) throws -> Bool) -> PrefixWhileCursor<Self>
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + predicate + + +
    +

    A closure that takes an element of the cursor as +its argument and returns true if the element should be included or +false otherwise. Once predicate returns false it will not be +called again.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + reduce(_:_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns the result of calling the given combining closure with each +element of this cursor and an accumulating value.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func reduce<Result>(
    +    _ initialResult: Result,
    +    _ nextPartialResult: (Result, Element) throws -> Result)
    +    throws -> Result
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + reduce(into:_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns the result of calling the given combining closure with each +element of this cursor and an accumulating value.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func reduce<Result>(
    +    into initialResult: Result,
    +    _ updateAccumulatingResult: (inout Result, Element) throws -> Void)
    +    throws -> Result
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + suffix(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array, up to the given maximum length, containing the +final elements of the cursor.

    + +

    The cursor must be finite. If the maximum length exceeds the number of +elements in the cursor, the result contains all the elements in the +cursor.

    +
    let numbers = AnyCursor([1, 2, 3, 4, 5])
    +try print(numbers.suffix(2))
    +// Prints "[4, 5]"
    +try print(numbers.suffix(10))
    +// Prints "[1, 2, 3, 4, 5]"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func suffix(_ maxLength: Int) throws -> [Element]
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + maxLength + + +
    +

    The maximum number of elements to return. The +value of maxLength must be greater than or equal to zero.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + contains(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a Boolean value indicating whether the cursor contains the +given element.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func contains(_ element: Element) throws -> Bool
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + max() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns the maximum element in the cursor.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func max() throws -> Element?
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + areInIncreasingOrder + + +
    +

    A predicate that returns true +if its first argument should be ordered before its second +argument; otherwise, false.

    +
    +
    +
    +
    +

    Return Value

    +

    The cursor’s maximum element, according to +areInIncreasingOrder. If the cursor has no elements, returns +nil.

    +
    + +
    +
    +
  • +
  • +
    + + + + min() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns the minimum element in the cursor.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func min() throws -> Element?
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + areInIncreasingOrder + + +
    +

    A predicate that returns true +if its first argument should be ordered before its second +argument; otherwise, false.

    +
    +
    +
    +
    +

    Return Value

    +

    The cursor’s minimum element, according to +areInIncreasingOrder. If the cursor has no elements, returns +nil.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + joined() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns the elements of this cursor of cursors, concatenated.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func joined() -> FlattenCursor<Self>
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + joined() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns the elements of this cursor of sequences, concatenated.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func joined() -> FlattenCursor<MapCursor<Self, AnyCursor<Element.Element>>>
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + joined(separator:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns the elements of this cursor of sequences, concatenated.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func joined(separator: String = "") throws -> String
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Protocols/DatabaseAggregate.html b/docs/3.3/Protocols/DatabaseAggregate.html new file mode 100644 index 000000000..0f9a472b1 --- /dev/null +++ b/docs/3.3/Protocols/DatabaseAggregate.html @@ -0,0 +1,938 @@ + + + + DatabaseAggregate Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseAggregate

+
+
+
public protocol DatabaseAggregate
+ +
+
+

The protocol for custom SQLite aggregates.

+ +

For example:

+
struct MySum : DatabaseAggregate {
+    var sum: Int = 0
+
+    mutating func step(_ dbValues: [DatabaseValue]) {
+        if let int = Int.fromDatabaseValue(dbValues[0]) {
+            sum += int
+        }
+    }
+
+    func finalize() -> DatabaseValueConvertible? {
+        return sum
+    }
+}
+
+let dbQueue = DatabaseQueue()
+let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
+dbQueue.add(function: fn)
+try dbQueue.write { db in
+    try db.execute("CREATE TABLE test(i)")
+    try db.execute("INSERT INTO test(i) VALUES (1)")
+    try db.execute("INSERT INTO test(i) VALUES (2)")
+    try Int.fetchOne(db, "SELECT mysum(i) FROM test")! // 3
+}
+
+ +
+
+
+
    +
  • +
    + + + + init() + +
    +
    +
    +
    +
    +
    +

    Creates an aggregate.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    init()
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + step(_:) + +
    +
    +
    +
    +
    +
    +

    This method is called at each step of the aggregation.

    + +

    The dbValues argument contains as many values as given to the SQL +aggregate function.

    + +

    – One value + SELECT maxLength(name) FROM player

    + +

    – Two values + SELECT maxFullNameLength(firstName, lastName) FROM player

    + +

    This method is never called after the finalize() method has been called.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    mutating func step(_ dbValues: [DatabaseValue]) throws
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + finalize() + +
    +
    +
    +
    +
    +
    +

    Returns the final result

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func finalize() throws -> DatabaseValueConvertible?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Protocols/DatabaseReader.html b/docs/3.3/Protocols/DatabaseReader.html new file mode 100644 index 000000000..f6ebbd952 --- /dev/null +++ b/docs/3.3/Protocols/DatabaseReader.html @@ -0,0 +1,1278 @@ + + + + DatabaseReader Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseReader

+
+
+
public protocol DatabaseReader : AnyObject
+ +
+
+

The protocol for all types that can fetch values from a database.

+ +

It is adopted by DatabaseQueue and DatabasePool.

+ +

The protocol comes with isolation guarantees that describe the behavior of +adopting types in a multithreaded application.

+ +

Types that adopt the protocol can provide in practice stronger guarantees. +For example, DatabaseQueue provides a stronger isolation level +than DatabasePool.

+ +

Warning: Isolation guarantees stand as long as there is no external +connection to the database. Should you have to cope with external +connections, protect yourself with transactions, and be ready to setup a +busy handler.

+ +
+
+
+ +
    +
  • +
    + + + + read(_:) + +
    +
    +
    +
    +
    +
    +

    Synchronously executes a read-only block that takes a database +connection, and returns its result.

    + +

    Guarantee 1: the block argument is isolated. Eventual concurrent +database updates are not visible inside the block:

    +
    try reader.read { db in
    +    // Those two values are guaranteed to be equal, even if the
    +    // `wine` table is modified between the two requests:
    +    let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +    let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +}
    +
    +try reader.read { db in
    +    // Now this value may be different:
    +    let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +}
    +
    + +

    Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds +and SQLCipher, attempts to write in the database throw a DatabaseError +whose resultCode is SQLITE_READONLY.

    +
    +

    Throws

    + The error thrown by the block, or any DatabaseError that would +happen while establishing the read access to the database. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func read<T>(_ block: (Database) throws -> T) throws -> T
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + block + + +
    +

    A block that accesses the database.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + unsafeRead(_:) + +
    +
    +
    +
    +
    +
    +

    Synchronously executes a read-only block that takes a database +connection, and returns its result.

    + +

    The two guarantees of the safe read method are lifted:

    + +

    The block argument is not isolated: eventual concurrent database updates +are visible inside the block:

    +
    try reader.unsafeRead { db in
    +    // Those two values may be different because some other thread
    +    // may have inserted or deleted a wine between the two requests:
    +    let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +    let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +}
    +
    + +

    Cursor iterations are isolated, though:

    +
    try reader.unsafeRead { db in
    +    // No concurrent update can mess with this iteration:
    +    let rows = try Row.fetchCursor(db, "SELECT ...")
    +    while let row = try rows.next() { ... }
    +}
    +
    + +

    The block argument is not prevented from writing (DatabaseQueue, in +particular, will accept database modifications in unsafeRead).

    +
    +

    Throws

    + The error thrown by the block, or any DatabaseError that would +happen while establishing the read access to the database. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + block + + +
    +

    A block that accesses the database.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Synchronously executes a block that takes a database connection, and +returns its result.

    + +

    The two guarantees of the safe read method are lifted:

    + +

    The block argument is not isolated: eventual concurrent database updates +are visible inside the block:

    +
    try reader.unsafeReentrantRead { db in
    +    // Those two values may be different because some other thread
    +    // may have inserted or deleted a wine between the two requests:
    +    let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +    let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +}
    +
    + +

    Cursor iterations are isolated, though:

    +
    try reader.unsafeReentrantRead { db in
    +    // No concurrent update can mess with this iteration:
    +    let rows = try Row.fetchCursor(db, "SELECT ...")
    +    while let row = try rows.next() { ... }
    +}
    +
    + +

    The block argument is not prevented from writing (DatabaseQueue, in +particular, will accept database modifications in unsafeReentrantRead).

    +
    +

    Throws

    + The error thrown by the block, or any DatabaseError that would +happen while establishing the read access to the database. + +
    + +

    This method is reentrant. It should be avoided because it fosters +dangerous concurrency practices.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + block + + +
    +

    A block that accesses the database.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(function:) + +
    +
    +
    +
    +
    +
    +

    Add or redefine an SQL function.

    +
    let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
    +    guard let int = Int.fromDatabaseValue(dbValues[0]) else {
    +        return nil
    +    }
    +    return int + 1
    +}
    +reader.add(function: fn)
    +try reader.read { db in
    +    try Int.fetchOne(db, "SELECT succ(1)")! // 2
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func add(function: DatabaseFunction)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + remove(function:) + +
    +
    +
    +
    +
    +
    +

    Remove an SQL function.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func remove(function: DatabaseFunction)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(collation:) + +
    +
    +
    +
    +
    +
    +

    Add or redefine a collation.

    +
    let collation = DatabaseCollation("localized_standard") { (string1, string2) in
    +    return (string1 as NSString).localizedStandardCompare(string2)
    +}
    +reader.add(collation: collation)
    +try reader.execute("SELECT * FROM file ORDER BY name COLLATE localized_standard")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func add(collation: DatabaseCollation)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + remove(collation:) + +
    +
    +
    +
    +
    +
    +

    Remove a collation.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func remove(collation: DatabaseCollation)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ + + +

Backup

+
+
+
    +
  • +
    + + + + backup(to:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Copies the database contents into another database.

    + +

    The backup method blocks the current thread until the destination +database contains the same contents as the source database.

    + +

    When the source is a DatabasePool, concurrent writes can happen during +the backup. Those writes may, or may not, be reflected in the backup, +but they won’t trigger any error.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func backup(to writer: DatabaseWriter) throws
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Protocols/DatabaseValueConvertible.html b/docs/3.3/Protocols/DatabaseValueConvertible.html new file mode 100644 index 000000000..186073d65 --- /dev/null +++ b/docs/3.3/Protocols/DatabaseValueConvertible.html @@ -0,0 +1,2603 @@ + + + + DatabaseValueConvertible Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseValueConvertible

+
+
+
public protocol DatabaseValueConvertible : SQLExpressible
+ +
+
+

Types that adopt DatabaseValueConvertible can be initialized from +database values.

+ +

The protocol comes with built-in methods that allow to fetch cursors, +arrays, or single values:

+
try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String
+try String.fetchAll(db, "SELECT name FROM ...", arguments:...)    // [String]
+try String.fetchOne(db, "SELECT name FROM ...", arguments:...)    // String?
+
+let statement = try db.makeSelectStatement("SELECT name FROM ...")
+try String.fetchCursor(statement, arguments:...) // Cursor of String
+try String.fetchAll(statement, arguments:...)    // [String]
+try String.fetchOne(statement, arguments:...)    // String?
+
+ +

DatabaseValueConvertible is adopted by Bool, Int, String, etc.

+ +
+
+
+
    +
  • +
    + + + + databaseValue + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +

    Default Implementation

    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Returns a value initialized from dbValue, if possible.

    + +
    +

    Default Implementation

    +
    +

    Returns a value initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    static func fromDatabaseValue(_ dbValue: DatabaseValue) -> `Self`?
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over values fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT name FROM ...")
    +let names = try String.fetchCursor(statement) // Cursor of String
    +while let name = try names.next() { // String
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self>
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array of values fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT name FROM ...")
    +let names = try String.fetchAll(statement)  // [String]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An array.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a single value fetched from a prepared statement.

    + +

    The result is nil if the query returns no row, or if no value can be +extracted from the first row.

    +
    let statement = try db.makeSelectStatement("SELECT name FROM ...")
    +let name = try String.fetchOne(statement)   // String?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self?
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An optional value.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over values fetched from an SQL query.

    +
    let names = try String.fetchCursor(db, "SELECT name FROM ...") // Cursor of String
    +while let name = try name.next() { // String
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self>
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array of values fetched from an SQL query.

    +
    let names = try String.fetchAll(db, "SELECT name FROM ...") // [String]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An array.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a single value fetched from an SQL query.

    + +

    The result is nil if the query returns no row, or if no value can be +extracted from the first row.

    +
    let name = try String.fetchOne(db, "SELECT name FROM ...") // String?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self?
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An optional value.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over values fetched from a fetch request.

    +
    let request = Player.select(Column("name"))
    +let names = try String.fetchCursor(db, request) // Cursor of String
    +while let name = try name.next() { // String
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor<R>(_ db: Database, _ request: R) throws -> DatabaseValueCursor<Self> where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array of values fetched from a fetch request.

    +
    let request = Player.select(Column("name"))
    +let names = try String.fetchAll(db, request) // [String]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll<R>(_ db: Database, _ request: R) throws -> [Self] where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    An array.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a single value fetched from a fetch request.

    + +

    The result is nil if the query returns no row, or if no value can be +extracted from the first row.

    +
    let request = Player.filter(key: 1).select(Column("name"))
    +let name = try String.fetchOne(db, request) // String?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne<R>(_ db: Database, _ request: R) throws -> Self? where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    An optional value.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over values fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT name FROM ...")
    +let names = try String.fetchCursor(statement) // Cursor of String
    +while let name = try names.next() { // String
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor<Self>
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array of values fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT name FROM ...")
    +let names = try String.fetchAll(statement)  // [String]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An array of values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a single value fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT name FROM ...")
    +let name = try String.fetchOne(statement)   // String?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self?
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An optional value.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over values fetched from an SQL query.

    +
    let names = try String.fetchCursor(db, "SELECT name FROM ...") // Cursor of String
    +while let name = try names.next() { // String
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor<Self>
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array of values fetched from an SQL query.

    +
    let names = try String.fetchAll(db, "SELECT name FROM ...") // [String]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An array of values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a single value fetched from an SQL query.

    +
    let name = try String.fetchOne(db, "SELECT name FROM ...") // String?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self?
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An optional value.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over values fetched from a fetch request.

    +
    let request = Player.select(Column("name"))
    +let names = try String.fetchCursor(db, request) // Cursor of String
    +while let name = try names.next() { // String
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor<R>(_ db: Database, _ request: R) throws -> FastDatabaseValueCursor<Self> where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array of values fetched from a fetch request.

    +
    let request = Player.select(Column("name"))
    +let names = try String.fetchAll(db, request) // [String]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll<R>(_ db: Database, _ request: R) throws -> [Self] where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a single value fetched from a fetch request.

    +
    let request = Player.filter(key: 1).select(Column("name"))
    +let name = try String.fetchOne(db, request) // String?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne<R>(_ db: Database, _ request: R) throws -> Self? where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    An optional value.

    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Protocols/DatabaseWriter.html b/docs/3.3/Protocols/DatabaseWriter.html new file mode 100644 index 000000000..9764b7809 --- /dev/null +++ b/docs/3.3/Protocols/DatabaseWriter.html @@ -0,0 +1,1222 @@ + + + + DatabaseWriter Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseWriter

+
+
+
public protocol DatabaseWriter : DatabaseReader
+ +
+
+

The protocol for all types that can update a database.

+ +

It is adopted by DatabaseQueue and DatabasePool.

+ +

The protocol comes with isolation guarantees that describe the behavior of +adopting types in a multithreaded application.

+ +

Types that adopt the protocol can in practice provide stronger guarantees. +For example, DatabaseQueue provides a stronger isolation level +than DatabasePool.

+ +

Warning: Isolation guarantees stand as long as there is no external +connection to the database. Should you have to cope with external +connections, protect yourself with transactions, and be ready to setup a +busy handler.

+ +
+
+
+ +
    +
  • +
    + + + + write(_:) + +
    +
    +
    +
    +
    +
    +

    Synchronously executes a block that takes a database connection, and +returns its result.

    + +

    Eventual concurrent database updates are postponed until the block +has executed.

    + +

    Eventual concurrent reads are guaranteed not to see any changes +performed in the block until they are all saved in the database.

    + +

    The block may, or may not, be wrapped inside a transaction.

    + +

    This method is not reentrant.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func write<T>(_ block: (Database) throws -> T) throws -> T
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Synchronously executes a block that takes a database connection, and +returns its result.

    + +

    Eventual concurrent database updates are postponed until the block +has executed.

    + +

    Eventual concurrent reads may see changes performed in the block before +the block completes.

    + +

    The block is guaranteed to be executed outside of a transaction.

    + +

    This method is not reentrant.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func writeWithoutTransaction<T>(_ block: (Database) throws -> T) rethrows -> T
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Synchronously executes a block that takes a database connection, and +returns its result.

    + +

    Eventual concurrent database updates are postponed until the block +has executed.

    + +

    Eventual concurrent reads may see changes performed in the block before +the block completes.

    + +

    This method is reentrant. It should be avoided because it fosters +dangerous concurrency practices.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Synchronously or asynchronously executes a read-only block that takes a +database connection.

    + +

    This method must be called from a writing dispatch queue, outside of any +transaction. You’ll get a fatal error otherwise.

    + +

    The block argument is guaranteed to see the database in the last +committed state at the moment this method is called. Eventual concurrent +database updates are not visible inside the block.

    + +

    For example:

    +
    try writer.writeWithoutTransaction { db in
    +    try db.execute("DELETE FROM player")
    +    try writer.readFromCurrentState { db in
    +        // Guaranteed to be zero
    +        try Int.fetchOne(db, "SELECT COUNT(*) FROM player")!
    +    }
    +    try db.execute("INSERT INTO player ...")
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func readFromCurrentState(_ block: @escaping (Database) -> Void) throws
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(transactionObserver:extent:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Add a transaction observer, so that it gets notified of +database changes.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func add(transactionObserver: TransactionObserver, extent: Database.TransactionObservationExtent = .observerLifetime)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + transactionObserver + + +
    +

    A transaction observer.

    +
    +
    + + extent + + +
    +

    The duration of the observation. The default is +the observer lifetime (observation lasts until observer +is deallocated).

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + remove(transactionObserver:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Remove a transaction observer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func remove(transactionObserver: TransactionObserver)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + erase() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Erases the content of the database.

    +
    +

    Precondition

    + database is not accessed concurrently during the +execution of this method. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func erase() throws
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+
+ +
+
+ + + diff --git a/docs/3.3/Protocols/FTS5CustomTokenizer.html b/docs/3.3/Protocols/FTS5CustomTokenizer.html new file mode 100644 index 000000000..c2310d9bf --- /dev/null +++ b/docs/3.3/Protocols/FTS5CustomTokenizer.html @@ -0,0 +1,885 @@ + + + + FTS5CustomTokenizer Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS5CustomTokenizer

+

The protocol for custom FTS5 tokenizers.

+ +
+
+
+
    +
  • +
    + + + + name + +
    +
    +
    +
    +
    +
    +

    The name of the tokenizer; should uniquely identify your custom +tokenizer.

    + +
    +
    +
    +
  • +
  • +
    + + + + init(db:arguments:) + +
    +
    +
    +
    +
    +
    +

    Creates a custom tokenizer.

    + +

    The arguments parameter is an array of String built from the CREATE +VIRTUAL TABLE statement. In the example below, the arguments will +be ["arg1", "arg2"].

    +
    CREATE VIRTUAL TABLE document USING fts5(
    +    tokenize='custom arg1 arg2'
    +)
    +
    + +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + tokenizerDescriptor(arguments:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates an FTS5 tokenizer descriptor.

    +
    class MyTokenizer : FTS5CustomTokenizer { ... }
    +
    +db.create(virtualTable: "book", using: FTS5()) { t in
    +    let tokenizer = MyTokenizer.tokenizerDescriptor(arguments: ["unicode61", "remove_diacritics", "0"])
    +    t.tokenizer = tokenizer
    +}
    +
    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Protocols/FTS5Tokenizer.html b/docs/3.3/Protocols/FTS5Tokenizer.html new file mode 100644 index 000000000..16639ace1 --- /dev/null +++ b/docs/3.3/Protocols/FTS5Tokenizer.html @@ -0,0 +1,827 @@ + + + + FTS5Tokenizer Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS5Tokenizer

+

The protocol for FTS5 tokenizers

+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/Protocols/FTS5WrapperTokenizer.html b/docs/3.3/Protocols/FTS5WrapperTokenizer.html new file mode 100644 index 000000000..2a6d28968 --- /dev/null +++ b/docs/3.3/Protocols/FTS5WrapperTokenizer.html @@ -0,0 +1,909 @@ + + + + FTS5WrapperTokenizer Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS5WrapperTokenizer

+

The protocol for custom FTS5 tokenizers that wrap another tokenizer.

+ +

Types that adopt FTS5WrapperTokenizer don’t have to implement the +low-level FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:).

+ +

Instead, they process regular Swift strings.

+ +

Here is the implementation for a trivial tokenizer that wraps the +built-in ascii tokenizer without any custom processing:

+
class TrivialAsciiTokenizer : FTS5WrapperTokenizer {
+    static let name = "trivial"
+    let wrappedTokenizer: FTS5Tokenizer
+
+    init(db: Database, arguments: [String]) throws {
+        wrappedTokenizer = try db.makeTokenizer(.ascii())
+    }
+
+    func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws {
+        try tokenCallback(token, flags)
+    }
+}
+
+ +
+
+
+
    +
  • +
    + + + + wrappedTokenizer + +
    +
    +
    +
    +
    +
    +

    The wrapped tokenizer

    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Given a token produced by the wrapped tokenizer, notifies customized +tokens to the tokenCallback function.

    + +

    For example:

    +
    func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws {
    +    // pass through:
    +    try tokenCallback(token, flags)
    +}
    +
    + +

    When implementing the accept method, there are a two rules +to observe:

    + +
      +
    1. Errors thrown by the tokenCallback function must not be caught.

    2. +
    3. The input flags should be given unmodified to the tokenCallback +function, unless you union it with the .colocated flag when the +tokenizer produces synonyms (see +https://www.sqlite.org/fts5.html#synonym_support).

    4. +
    + +
    +
    +
    +
  • +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/Protocols/FetchRequest.html b/docs/3.3/Protocols/FetchRequest.html new file mode 100644 index 000000000..6ade87066 --- /dev/null +++ b/docs/3.3/Protocols/FetchRequest.html @@ -0,0 +1,2226 @@ + + + + FetchRequest Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FetchRequest

+
+
+
public protocol FetchRequest
+ +
+
+

The protocol for all requests that run from a single select statement, and +tell how fetched rows should be interpreted.

+
struct Player: FetchableRecord { ... }
+let request: ... // Some FetchRequest that fetches Player
+try request.fetchCursor(db) // Cursor of Player
+try request.fetchAll(db)    // [Player]
+try request.fetchOne(db)    // Player?
+
+ +
+
+
+
    +
  • +
    + + + + RowDecoder + +
    +
    +
    +
    +
    +
    +

    The type that tells how fetched database rows should be interpreted.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    associatedtype RowDecoder
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + prepare(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a tuple that contains a prepared statement that is ready to be +executed, and an eventual row adapter.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?)
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    A prepared statement and an eventual row adapter.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchCount(_:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Returns the number of rows fetched by the request.

    + +

    The default implementation builds a naive SQL query based on the +statement returned by the prepare method: +SELECT COUNT(*) FROM (...).

    + +

    Adopting types can refine this method in order to use more +efficient SQL.

    + +
    +

    Default Implementation

    +
    +

    Returns the number of rows fetched by the request.

    + +

    This default implementation builds a naive SQL query based on the +statement returned by the prepare method: SELECT COUNT(*) FROM (...).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func fetchCount(_ db: Database) throws -> Int
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseRegion(_:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Returns the database region that the request looks into.

    + +
    +

    Default Implementation

    +
    +

    Returns the database region that the request looks into.

    + +

    This default implementation returns a region built from the statement +returned by the prepare method.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func databaseRegion(_ db: Database) throws -> DatabaseRegion
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    A cursor over fetched values.

    +
    let request: ... // Some TypedRequest that fetches String
    +let strings = try request.fetchCursor(db) // Cursor of String
    +while let string = try strings.next() {   // String
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor<RowDecoder>
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    An array of fetched values.

    +
    let request: ... // Some TypedRequest that fetches String
    +let strings = try request.fetchAll(db) // [String]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchAll(_ db: Database) throws -> [RowDecoder]
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    The first fetched value.

    + +

    The result is nil if the request returns no row, or if no value can be +extracted from the first row.

    +
    let request: ... // Some TypedRequest that fetches String
    +let string = try request.fetchOne(db) // String?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchOne(_ db: Database) throws -> RowDecoder?
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    An optional value.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    A cursor over fetched optional values.

    +
    let request: ... // Some TypedRequest that fetches Optional<String>
    +let strings = try request.fetchCursor(db) // Cursor of String?
    +while let string = try strings.next() {   // String?
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor<RowDecoder._Wrapped>
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    An array of fetched optional values.

    +
    let request: ... // Some TypedRequest that fetches Optional<String>
    +let strings = try request.fetchAll(db) // [String?]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?]
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of values.

    +
    + +
    +
    +
  • +
+
+
+ + +
+
+ +
    +
  • +
    + + + + fetchCursor(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    A cursor over fetched rows.

    +
    let request: ... // Some TypedRequest that fetches Row
    +let rows = try request.fetchCursor(db) // RowCursor
    +while let row = try rows.next() {  // Row
    +    let id: Int64 = row[0]
    +    let name: String = row[1]
    +}
    +
    + +

    Fetched rows are reused during the cursor iteration: don’t turn a row +cursor into an array with Array(rows) or rows.filter { ... } since +you would not get the distinct rows you expect. Use Row.fetchAll(...) +instead.

    + +

    For the same reason, make sure you make a copy whenever you extract a +row for later use: row.copy().

    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchCursor(_ db: Database) throws -> RowCursor
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched rows.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    An array of fetched rows.

    +
    let request: ... // Some TypedRequest that fetches Row
    +let rows = try request.fetchAll(db)
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchAll(_ db: Database) throws -> [Row]
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of fetched rows.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    The first fetched row.

    +
    let request: ... // Some TypedRequest that fetches Row
    +let row = try request.fetchOne(db)
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchOne(_ db: Database) throws -> Row?
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    A,n optional rows.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    A cursor over fetched values.

    +
    let request: ... // Some TypedRequest that fetches String
    +let strings = try request.fetchCursor(db) // Cursor of String
    +while let string = try strings.next() {   // String
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchCursor(_ db: Database) throws -> FastDatabaseValueCursor<RowDecoder>
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    An array of fetched values.

    +
    let request: ... // Some TypedRequest that fetches String
    +let strings = try request.fetchAll(db) // [String]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchAll(_ db: Database) throws -> [RowDecoder]
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    The first fetched value.

    + +

    The result is nil if the request returns no row, or if no value can be +extracted from the first row.

    +
    let request: ... // Some TypedRequest that fetches String
    +let string = try request.fetchOne(db) // String?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchOne(_ db: Database) throws -> RowDecoder?
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    An optional value.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    A cursor over fetched optional values.

    +
    let request: ... // Some TypedRequest that fetches Optional<String>
    +let strings = try request.fetchCursor(db) // Cursor of String?
    +while let string = try strings.next() {   // String?
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchCursor(_ db: Database) throws -> FastNullableDatabaseValueCursor<RowDecoder._Wrapped>
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    An array of fetched optional values.

    +
    let request: ... // Some TypedRequest that fetches Optional<String>
    +let strings = try request.fetchAll(db) // [String?]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?]
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of values.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    A cursor over fetched records.

    +
    let request: ... // Some TypedRequest that fetches Player
    +let players = try request.fetchCursor(db) // Cursor of Player
    +while let player = try players.next() {   // Player
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchCursor(_ db: Database) throws -> RecordCursor<RowDecoder>
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    An array of fetched records.

    +
    let request: ... // Some TypedRequest that fetches Player
    +let players = try request.fetchAll(db) // [Player]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchAll(_ db: Database) throws -> [RowDecoder]
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    The first fetched record.

    +
    let request: ... // Some TypedRequest that fetches Player
    +let player = try request.fetchOne(db) // Player?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchOne(_ db: Database) throws -> RowDecoder?
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    An optional record.

    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Protocols/FetchableRecord.html b/docs/3.3/Protocols/FetchableRecord.html new file mode 100644 index 000000000..c9be0af33 --- /dev/null +++ b/docs/3.3/Protocols/FetchableRecord.html @@ -0,0 +1,2625 @@ + + + + FetchableRecord Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FetchableRecord

+
+
+
public protocol FetchableRecord
+ +
+
+

Types that adopt FetchableRecord can be initialized from a database Row.

+
let row = try Row.fetchOne(db, "SELECT ...")!
+let player = Player(row)
+
+ +

The protocol comes with built-in methods that allow to fetch cursors, +arrays, or single records:

+
try Player.fetchCursor(db, "SELECT ...", arguments:...) // Cursor of Player
+try Player.fetchAll(db, "SELECT ...", arguments:...)    // [Player]
+try Player.fetchOne(db, "SELECT ...", arguments:...)    // Player?
+
+let statement = try db.makeSelectStatement("SELECT ...")
+try Player.fetchCursor(statement, arguments:...) // Cursor of Player
+try Player.fetchAll(statement, arguments:...)    // [Player]
+try Player.fetchOne(statement, arguments:...)    // Player?
+
+ +

FetchableRecord is adopted by Record.

+ +
+
+
+ +
    +
  • +
    + + + + init(row:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Creates a record from row.

    + +

    For performance reasons, the row argument may be reused during the +iteration of a fetch query. If you want to keep the row for later use, +make sure to store a copy: self.row = row.copy().

    + +
    +

    Default Implementation

    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    init(row: Row)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + databaseDecodingUserInfo + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    When the FetchableRecord type also adopts the standard Decodable +protocol, you can use this dictionary to customize the decoding process +from database rows.

    + +

    For example:

    +
    // A key that holds a decoder's name
    +let decoderName = CodingUserInfoKey(rawValue: "decoderName")!
    +
    +// A FetchableRecord + Decodable record
    +struct Player: FetchableRecord, Decodable {
    +    // Customize the decoder name when decoding a database row
    +    static let databaseDecodingUserInfo: [CodingUserInfoKey: Any] = [decoderName: "Database"]
    +
    +    init(from decoder: Decoder) throws {
    +        // Print the decoder name
    +        print(decoder.userInfo[decoderName])
    +        ...
    +    }
    +}
    +
    +// prints "Database"
    +let player = try Player.fetchOne(db, ...)
    +
    +// prints "JSON"
    +let decoder = JSONDecoder()
    +decoder.userInfo = [decoderName: "JSON"]
    +let player = try decoder.decode(Player.self, from: ...)
    +
    + +
    +

    Default Implementation

    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    static var databaseDecodingUserInfo: [CodingUserInfoKey : Any] { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseJSONDecoder(for:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    When the FetchableRecord type also adopts the standard Decodable +protocol, this method controls the decoding process of nested properties +from JSON database columns.

    + +

    The default implementation returns a JSONDecoder with the +following properties:

    + +
      +
    • dataDecodingStrategy: .base64
    • +
    • dateDecodingStrategy: .millisecondsSince1970
    • +
    • nonConformingFloatDecodingStrategy: .throw
    • +
    + +

    You can override those defaults:

    +
    struct Achievement: Decodable {
    +    var name: String
    +    var date: Date
    +}
    +
    +struct Player: Decodable, FetchableRecord {
    +    // stored in a JSON column
    +    var achievements: [Achievement]
    +
    +    static func databaseJSONDecoder(for column: String) -> JSONDecoder {
    +        let decoder = JSONDecoder()
    +        decoder.dateDecodingStrategy = .iso8601
    +        return decoder
    +    }
    +}
    +
    + +
    +

    Default Implementation

    +
    +

    Returns a JSONDecoder with the following properties:

    + +
      +
    • dataDecodingStrategy: .base64
    • +
    • dateDecodingStrategy: .millisecondsSince1970
    • +
    • nonConformingFloatDecodingStrategy: .throw
    • +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    static func databaseJSONDecoder(for column: String) -> JSONDecoder
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseDateDecodingStrategy + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    When the FetchableRecord type also adopts the standard Decodable +protocol, this property controls the decoding of date properties.

    + +

    Default value is .deferredToDate

    + +

    For example:

    +
    struct Player: FetchableRecord, Decodable {
    +    static let databaseDateDecodingStrategy: DatabaseDateDecodingStrategy = .timeIntervalSince1970
    +
    +    var name: String
    +    var registrationDate: Date // decoded from epoch timestamp
    +}
    +
    + +
    +

    Default Implementation

    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    A cursor over all records fetched from the database.

    +
    // SELECT * FROM player
    +let players = try Player.fetchCursor(db) // Cursor of Player
    +while let player = try players.next() {  // Player
    +    ...
    +}
    +
    + +

    Records are iterated in the natural ordering of the table.

    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    + +

    The selection defaults to all columns. This default can be changed for +all requests by the TableRecord.databaseSelection property, or +for individual requests with the TableRecord.select method.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ db: Database) throws -> RecordCursor<Self>
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    An array of all records fetched from the database.

    +
    // SELECT * FROM player
    +let players = try Player.fetchAll(db) // [Player]
    +
    + +

    The selection defaults to all columns. This default can be changed for +all requests by the TableRecord.databaseSelection property, or +for individual requests with the TableRecord.select method.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ db: Database) throws -> [Self]
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    The first found record.

    +
    // SELECT * FROM player
    +let player = try Player.fetchOne(db) // Player?
    +
    + +

    The selection defaults to all columns. This default can be changed for +all requests by the TableRecord.databaseSelection property, or +for individual requests with the TableRecord.select method.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne(_ db: Database) throws -> Self?
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:keys:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over records, given their primary keys.

    +
    let players = try Player.fetchCursor(db, keys: [1, 2, 3]) // Cursor of Player
    +while let player = try players.next() { // Player
    +    ...
    +}
    +
    + +

    Records are iterated in unspecified order.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor<Sequence>(_ db: Database, keys: Sequence) throws -> RecordCursor<Self> where Sequence : Sequence, Sequence.Element : DatabaseValueConvertible
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + keys + + +
    +

    A sequence of primary keys.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:keys:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array of records, given their primary keys.

    +
    let players = try Player.fetchAll(db, keys: [1, 2, 3]) // [Player]
    +
    + +

    The order of records in the returned array is undefined.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll<Sequence>(_ db: Database, keys: Sequence) throws -> [Self] where Sequence : Sequence, Sequence.Element : DatabaseValueConvertible
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + keys + + +
    +

    A sequence of primary keys.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:key:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a single record given its primary key.

    +
    let player = try Player.fetchOne(db, key: 123) // Player?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne<PrimaryKeyType>(_ db: Database, key: PrimaryKeyType?) throws -> Self? where PrimaryKeyType : DatabaseValueConvertible
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + key + + +
    +

    A primary key value.

    +
    +
    +
    +
    +

    Return Value

    +

    An optional record.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:keys:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over records identified by the provided unique keys +(primary key or any key with a unique index on it).

    +
    let players = try Player.fetchCursor(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // Cursor of Player
    +while let player = try players.next() { // Player
    +    ...
    +}
    +
    + +

    Records are iterated in unspecified order.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ db: Database, keys: [[String : DatabaseValueConvertible?]]) throws -> RecordCursor<Self>
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + keys + + +
    +

    An array of key dictionaries.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:keys:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array of records identified by the provided unique keys +(primary key or any key with a unique index on it).

    +
    let players = try Player.fetchAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // [Player]
    +
    + +

    The order of records in the returned array is undefined.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ db: Database, keys: [[String : DatabaseValueConvertible?]]) throws -> [Self]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + keys + + +
    +

    An array of key dictionaries.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:key:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a single record identified by a unique key (the primary key or +any key with a unique index on it).

    +
    let player = try Player.fetchOne(db, key: ["name": Arthur"]) // Player?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne(_ db: Database, key: [String : DatabaseValueConvertible?]?) throws -> Self?
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + key + + +
    +

    A dictionary of values.

    +
    +
    +
    +
    +

    Return Value

    +

    An optional record.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    A cursor over records fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT * FROM player")
    +let players = try Player.fetchCursor(statement) // Cursor of Player
    +while let player = try players.next() { // Player
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor<Self>
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array of records fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT * FROM player")
    +let players = try Player.fetchAll(statement) // [Player]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An array of records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a single record fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT * FROM player")
    +let player = try Player.fetchOne(statement) // Player?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self?
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An optional record.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over records fetched from an SQL query.

    +
    let players = try Player.fetchCursor(db, "SELECT * FROM player") // Cursor of Player
    +while let player = try players.next() { // Player
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor<Self>
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array of records fetched from an SQL query.

    +
    let players = try Player.fetchAll(db, "SELECT * FROM player") // [Player]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An array of records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a single record fetched from an SQL query.

    +
    let player = try Player.fetchOne(db, "SELECT * FROM player") // Player?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self?
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An optional record.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over records fetched from a fetch request.

    +
    let request = try Player.all()
    +let players = try Player.fetchCursor(db, request) // Cursor of Player
    +while let player = try players.next() { // Player
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor<R>(_ db: Database, _ request: R) throws -> RecordCursor<Self> where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    a FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array of records fetched from a fetch request.

    +
    let request = try Player.all()
    +let players = try Player.fetchAll(db, request) // [Player]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll<R>(_ db: Database, _ request: R) throws -> [Self] where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    a FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a single record fetched from a fetch request.

    +
    let request = try Player.filter(key: 1)
    +let player = try Player.fetchOne(db, request) // Player?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne<R>(_ db: Database, _ request: R) throws -> Self? where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    a FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    An optional record.

    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Protocols/MutablePersistableRecord.html b/docs/3.3/Protocols/MutablePersistableRecord.html new file mode 100644 index 000000000..bddf524b6 --- /dev/null +++ b/docs/3.3/Protocols/MutablePersistableRecord.html @@ -0,0 +1,2648 @@ + + + + MutablePersistableRecord Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

MutablePersistableRecord

+
+
+
public protocol MutablePersistableRecord : TableRecord
+ +
+
+

Types that adopt MutablePersistableRecord can be inserted, updated, and deleted.

+ +
+
+
+
    +
  • +
    + + + + persistenceConflictPolicy + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    The policy that handles SQLite conflicts when records are inserted +or updated.

    + +

    This property is optional: its default value uses the ABORT policy +for both insertions and updates, and has GRDB generate regular +INSERT and UPDATE queries.

    + +

    If insertions are resolved with .ignore policy, the +didInsert(with:for:) method is not called upon successful insertion, +even if a row was actually inserted without any conflict.

    + +

    See https://www.sqlite.org/lang_conflict.html

    + +
    +

    Default Implementation

    +
    +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    static var persistenceConflictPolicy: PersistenceConflictPolicy { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + encode(to:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Defines the values persisted in the database.

    + +

    Store in the container argument all values that should be stored in +the columns of the database table (see databaseTableName()).

    + +

    Primary key columns, if any, must be included.

    +
    struct Player : MutablePersistableRecord {
    +    var id: Int64?
    +    var name: String?
    +
    +    func encode(to container: inout PersistenceContainer) {
    +        container["id"] = id
    +        container["name"] = name
    +    }
    +}
    +
    + +

    It is undefined behavior to set different values for the same column. +Column names are case insensitive, so defining both name and NAME +is considered undefined behavior.

    + +
    +

    Default Implementation

    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func encode(to container: inout PersistenceContainer)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + didInsert(with:for:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Notifies the record that it was succesfully inserted.

    + +

    Do not call this method directly: it is called for you, in a protected +dispatch queue, with the inserted RowID and the eventual +INTEGER PRIMARY KEY column name.

    + +

    This method is optional: the default implementation does nothing.

    +
    struct Player : MutablePersistableRecord {
    +    var id: Int64?
    +    var name: String?
    +
    +    mutating func didInsert(with rowID: Int64, for column: String?) {
    +        self.id = rowID
    +    }
    +}
    +
    + +
    +

    Default Implementation

    +
    +

    Notifies the record that it was succesfully inserted.

    + +

    The default implementation does nothing.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    mutating func didInsert(with rowID: Int64, for column: String?)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + rowID + + +
    +

    The inserted rowID.

    +
    +
    + + column + + +
    +

    The name of the eventual INTEGER PRIMARY KEY column.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
+ + + +

CRUD

+
+
+
    +
  • +
    + + + + insert(_:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Executes an INSERT statement.

    + +

    This method is guaranteed to have inserted a row in the database if it +returns without error.

    + +

    Upon successful insertion, the didInsert(with:for:) method +is called with the inserted RowID and the eventual INTEGER PRIMARY KEY +column name.

    + +

    This method has a default implementation, so your adopting types don’t +have to implement it. Yet your types can provide their own +implementation of insert(). In their implementation, it is recommended +that they invoke the performInsert() method.

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +

    Default Implementation

    +
    +

    Executes an INSERT statement.

    + +

    The default implementation for insert() invokes performInsert().

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    mutating func insert(_ db: Database) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + update(_:columns:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Executes an UPDATE statement.

    + +

    This method is guaranteed to have updated a row in the database if it +returns without error.

    + +

    This method has a default implementation, so your adopting types don’t +have to implement it. Yet your types can provide their own +implementation of update(). In their implementation, it is recommended +that they invoke the performUpdate() method.

    +
    +

    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. + +
    + +
    +

    Default Implementation

    +
    +

    Executes an UPDATE statement.

    +
    +

    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. + +
    +

    Executes an UPDATE statement.

    +
    +

    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. + +
    +

    Executes an UPDATE statement.

    +
    +

    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. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func update(_ db: Database, columns: Set<String>) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + columns + + +
    +

    The columns to update.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + save(_:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Executes an INSERT or an UPDATE statement so that self is saved in +the database.

    + +

    If the receiver has a non-nil primary key and a matching row in the +database, this method performs an update.

    + +

    Otherwise, performs an insert.

    + +

    This method is guaranteed to have inserted or updated a row in the +database if it returns without error.

    + +

    This method has a default implementation, so your adopting types don’t +have to implement it. Yet your types can provide their own +implementation of save(). In their implementation, it is recommended +that they invoke the performSave() method.

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs, or errors +thrown by update(). + +
    + +
    +

    Default Implementation

    +
    +

    Executes an INSERT or an UPDATE statement so that self is saved in +the database.

    + +

    The default implementation for save() invokes performSave().

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    mutating func save(_ db: Database) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + delete(_:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Executes a DELETE statement.

    + +

    This method has a default implementation, so your adopting types don’t +have to implement it. Yet your types can provide their own +implementation of delete(). In their implementation, it is recommended +that they invoke the performDelete() method.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +

    Default Implementation

    +
    +

    Executes a DELETE statement.

    + +

    The default implementation for delete() invokes performDelete().

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +func delete(_ db: Database) throws -> Bool
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    Whether a database row was deleted.

    +
    + +
    +
    +
  • +
  • +
    + + + + exists(_:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Returns true if and only if the primary key matches a row in +the database.

    + +

    This method has a default implementation, so your adopting types don’t +have to implement it. Yet your types can provide their own +implementation of exists(). In their implementation, it is recommended +that they invoke the performExists() method.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +

    Default Implementation

    +
    +

    Returns true if and only if the primary key matches a row in +the database.

    + +

    The default implementation for exists() invokes performExists().

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func exists(_ db: Database) throws -> Bool
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    Whether the primary key matches a row in the database.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + databaseEncodingUserInfo + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    When the PersistableRecord type also adopts the standard Encodable +protocol, you can use this dictionary to customize the encoding process +into database rows.

    + +

    For example:

    +
    // A key that holds a encoder's name
    +let encoderName = CodingUserInfoKey(rawValue: "encoderName")!
    +
    +// A PersistableRecord + Encodable record
    +struct Player: PersistableRecord, Encodable {
    +    // Customize the encoder name when encoding a database row
    +    static let databaseEncodingUserInfo: [CodingUserInfoKey: Any] = [encoderName: "Database"]
    +
    +    func encode(to encoder: Encoder) throws {
    +        // Print the encoder name
    +        print(encoder.userInfo[encoderName])
    +        ...
    +    }
    +}
    +
    +let player = Player(...)
    +
    +// prints "Database"
    +try player.insert(db)
    +
    +// prints "JSON"
    +let encoder = JSONEncoder()
    +encoder.userInfo = [encoderName: "JSON"]
    +let data = try encoder.encode(player)
    +
    + +
    +

    Default Implementation

    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    static var databaseEncodingUserInfo: [CodingUserInfoKey : Any] { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseJSONEncoder(for:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    When the PersistableRecord type also adopts the standard Encodable +protocol, this method controls the encoding process of nested properties +into JSON database columns.

    + +

    The default implementation returns a JSONEncoder with the +following properties:

    + +
      +
    • dataEncodingStrategy: .base64
    • +
    • dateEncodingStrategy: .millisecondsSince1970
    • +
    • nonConformingFloatEncodingStrategy: .throw
    • +
    • outputFormatting: .sortedKeys (iOS 11.0+, macOS 10.13+, watchOS 4.0+)
    • +
    + +

    You can override those defaults:

    +
    struct Achievement: Encodable {
    +    var name: String
    +    var date: Date
    +}
    +
    +struct Player: Encodable, PersistableRecord {
    +    // stored in a JSON column
    +    var achievements: [Achievement]
    +
    +    static func databaseJSONEncoder(for column: String) -> JSONEncoder {
    +        let encoder = JSONEncoder()
    +        encoder.dateEncodingStrategy = .iso8601
    +        return encoder
    +    }
    +}
    +
    + +
    +

    Default Implementation

    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    static func databaseJSONEncoder(for column: String) -> JSONEncoder
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseDateEncodingStrategy + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    When the PersistableRecord type also adopts the standard Encodable +protocol, this property controls the encoding of date properties.

    + +

    Default value is .deferredToDate

    + +

    For example:

    +
    struct Player: PersistableRecord, Encodable {
    +    static let databaseDateEncodingStrategy: DatabaseDateEncodingStrategy = .timeIntervalSince1970
    +
    +    var name: String
    +    var registrationDate: Date // encoded as an epoch timestamp
    +}
    +
    + +
    +

    Default Implementation

    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseUUIDEncodingStrategy + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    When the PersistableRecord type also adopts the standard Encodable +protocol, this property controls the encoding of UUID properties.

    + +

    Default value is .deferredToUUID

    + +

    For example:

    +
    struct Player: PersistableProtocol, Encodable {
    +    static let databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy = .string
    +
    +    // encoded in a string like "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
    +    var uuid: UUID
    +}
    +
    + +
    +

    Default Implementation

    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + request(for:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request that fetches the associated record(s).

    + +

    For example:

    +
    struct Team: {
    +    static let players = hasMany(Player.self)
    +    var players: QueryInterfaceRequest<Player> {
    +        return request(for: Team.players)
    +    }
    +}
    +
    +let team: Team = ...
    +let players = try team.players.fetchAll(db) // [Player]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func request<A>(for association: A) -> QueryInterfaceRequest<A.RowDecoder> where Self == A.OriginRowDecoder, A : Association
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+
+ + + +

CRUD

+
+
+
    +
  • +
    + + + + update(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Executes an UPDATE statement that updates all table columns.

    +
    +

    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. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func update(_ db: Database) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + updateChanges(_:from:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    If the record has differences from the other record, executes an UPDATE +statement so that those changes and only those changes are saved in +the database.

    + +

    This method is guaranteed to have saved the eventual changes in the +database if it returns without error.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. +PersistenceError.recordNotFound is thrown if the primary key does not +match any row in the database and record could not be updated. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func updateChanges(_ db: Database, from record: MutablePersistableRecord) throws -> Bool
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + columns + + +
    +

    The columns to update.

    +
    +
    +
    +
    +

    Return Value

    +

    Whether the record had changes.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + databaseEquals(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a boolean indicating whether this record and the other record +have the same database representation.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func databaseEquals(_ record: Self) -> Bool
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseChanges(from:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    A dictionary of values changed from the other record.

    + +

    Its keys are column names. Its values come from the other record.

    + +

    Note that this method is not symmetrical, not only in terms of values, +but also in terms of columns. When the two records don’t define the +same set of columns in their encode(to:) method, only the columns +defined by the receiver record are considered.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func databaseChanges(from record: MutablePersistableRecord) -> [String : DatabaseValue]
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + performInsert(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Don’t invoke this method directly: it is an internal method for types +that adopt MutablePersistableRecord.

    + +

    performInsert() provides the default implementation for insert(). Types +that adopt MutablePersistableRecord can invoke performInsert() in their +implementation of insert(). They should not provide their own +implementation of performInsert().

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public mutating func performInsert(_ db: Database) throws
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + performUpdate(_:columns:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Don’t invoke this method directly: it is an internal method for types +that adopt MutablePersistableRecord.

    + +

    performUpdate() provides the default implementation for update(). Types +that adopt MutablePersistableRecord can invoke performUpdate() in their +implementation of update(). They should not provide their own +implementation of performUpdate().

    +
    +

    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. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func performUpdate(_ db: Database, columns: Set<String>) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + columns + + +
    +

    The columns to update.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + performSave(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Don’t invoke this method directly: it is an internal method for types +that adopt MutablePersistableRecord.

    + +

    performSave() provides the default implementation for save(). Types +that adopt MutablePersistableRecord can invoke performSave() in their +implementation of save(). They should not provide their own +implementation of performSave().

    + +

    This default implementation forwards the job to update or insert.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public mutating func performSave(_ db: Database) throws
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + performDelete(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Don’t invoke this method directly: it is an internal method for types +that adopt MutablePersistableRecord.

    + +

    performDelete() provides the default implementation for deelte(). Types +that adopt MutablePersistableRecord can invoke performDelete() in +their implementation of delete(). They should not provide their own +implementation of performDelete().

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func performDelete(_ db: Database) throws -> Bool
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + performExists(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Don’t invoke this method directly: it is an internal method for types +that adopt MutablePersistableRecord.

    + +

    performExists() provides the default implementation for exists(). Types +that adopt MutablePersistableRecord can invoke performExists() in +their implementation of exists(). They should not provide their own +implementation of performExists().

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func performExists(_ db: Database) throws -> Bool
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + deleteAll(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Deletes all records; returns the number of deleted rows.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public static func deleteAll(_ db: Database) throws -> Int
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    The number of deleted rows

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + deleteAll(_:keys:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Delete records identified by their primary keys; returns the number of +deleted rows.

    +
    // 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])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public static func deleteAll<Sequence>(_ db: Database, keys: Sequence) throws -> Int where Sequence : Sequence, Sequence.Element : DatabaseValueConvertible
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + keys + + +
    +

    A sequence of primary keys.

    +
    +
    +
    +
    +

    Return Value

    +

    The number of deleted rows

    +
    + +
    +
    +
  • +
  • +
    + + + + deleteOne(_:key:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Delete a record, identified by its primary key; returns whether a +database row was deleted.

    +
    // DELETE FROM player WHERE id = 123
    +try Player.deleteOne(db, key: 123)
    +
    +// 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)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public static func deleteOne<PrimaryKeyType>(_ db: Database, key: PrimaryKeyType?) throws -> Bool where PrimaryKeyType : DatabaseValueConvertible
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + key + + +
    +

    A primary key value.

    +
    +
    +
    +
    +

    Return Value

    +

    Whether a database row was deleted.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + deleteAll(_:keys:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Delete records identified by the provided unique keys (primary key or +any key with a unique index on it); returns the number of deleted rows.

    +
    try Player.deleteAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public static func deleteAll(_ db: Database, keys: [[String : DatabaseValueConvertible?]]) throws -> Int
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + keys + + +
    +

    An array of key dictionaries.

    +
    +
    +
    +
    +

    Return Value

    +

    The number of deleted rows

    +
    + +
    +
    +
  • +
  • +
    + + + + deleteOne(_:key:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Delete a record, identified by a unique key (the primary key or any key +with a unique index on it); returns whether a database row was deleted.

    +
    Player.deleteOne(db, key: ["name": Arthur"])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public static func deleteOne(_ db: Database, key: [String : DatabaseValueConvertible?]) throws -> Bool
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + key + + +
    +

    A dictionary of values.

    +
    +
    +
    +
    +

    Return Value

    +

    Whether a database row was deleted.

    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Protocols/PersistableRecord.html b/docs/3.3/Protocols/PersistableRecord.html new file mode 100644 index 000000000..0bfae7c36 --- /dev/null +++ b/docs/3.3/Protocols/PersistableRecord.html @@ -0,0 +1,1143 @@ + + + + PersistableRecord Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

PersistableRecord

+
+
+
public protocol PersistableRecord : MutablePersistableRecord
+ +
+
+

Types that adopt PersistableRecord can be inserted, updated, and deleted.

+ +

This protocol is intented for types that don’t have an INTEGER PRIMARY KEY.

+ +

Unlike MutablePersistableRecord, the insert() and save() methods are not +mutating methods.

+ +
+
+
+
    +
  • +
    + + + + didInsert(with:for:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Notifies the record that it was succesfully inserted.

    + +

    Do not call this method directly: it is called for you, in a protected +dispatch queue, with the inserted RowID and the eventual +INTEGER PRIMARY KEY column name.

    + +

    This method is optional: the default implementation does nothing.

    + +

    If you need a mutating variant of this method, adopt the +MutablePersistableRecord protocol instead.

    + +
    +

    Default Implementation

    +
    +

    Notifies the record that it was succesfully inserted.

    + +

    The default implementation does nothing.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func didInsert(with rowID: Int64, for column: String?)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + rowID + + +
    +

    The inserted rowID.

    +
    +
    + + column + + +
    +

    The name of the eventual INTEGER PRIMARY KEY column.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + insert(_:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Executes an INSERT statement.

    + +

    This method is guaranteed to have inserted a row in the database if it +returns without error.

    + +

    Upon successful insertion, the didInsert(with:for:) method +is called with the inserted RowID and the eventual INTEGER PRIMARY KEY +column name.

    + +

    This method has a default implementation, so your adopting types don’t +have to implement it. Yet your types can provide their own +implementation of insert(). In their implementation, it is recommended +that they invoke the performInsert() method.

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +

    Default Implementation

    +
    +

    Executes an INSERT statement.

    + +

    The default implementation for insert() invokes performInsert().

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func insert(_ db: Database) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + save(_:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Executes an INSERT or an UPDATE statement so that self is saved in +the database.

    + +

    If the receiver has a non-nil primary key and a matching row in the +database, this method performs an update.

    + +

    Otherwise, performs an insert.

    + +

    This method is guaranteed to have inserted or updated a row in the +database if it returns without error.

    + +

    This method has a default implementation, so your adopting types don’t +have to implement it. Yet your types can provide their own +implementation of save(). In their implementation, it is recommended +that they invoke the performSave() method.

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs, or errors +thrown by update(). + +
    + +
    +

    Default Implementation

    +
    +

    Executes an INSERT or an UPDATE statement so that self is saved in +the database.

    + +

    The default implementation for save() invokes performSave().

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func save(_ db: Database) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + performInsert(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Don’t invoke this method directly: it is an internal method for types +that adopt PersistableRecord.

    + +

    performInsert() provides the default implementation for insert(). Types +that adopt PersistableRecord can invoke performInsert() in their +implementation of insert(). They should not provide their own +implementation of performInsert().

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func performInsert(_ db: Database) throws
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + performSave(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Don’t invoke this method directly: it is an internal method for types +that adopt PersistableRecord.

    + +

    performSave() provides the default implementation for save(). Types +that adopt PersistableRecord can invoke performSave() in their +implementation of save(). They should not provide their own +implementation of performSave().

    + +

    This default implementation forwards the job to update or insert.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func performSave(_ db: Database) throws
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Protocols/RowAdapter.html b/docs/3.3/Protocols/RowAdapter.html new file mode 100644 index 000000000..c8c64ec1d --- /dev/null +++ b/docs/3.3/Protocols/RowAdapter.html @@ -0,0 +1,939 @@ + + + + RowAdapter Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

RowAdapter

+
+
+
public protocol RowAdapter
+ +
+
+

RowAdapter is a protocol that helps two incompatible row interfaces working +together.

+ +

GRDB ships with four concrete types that adopt the RowAdapter protocol:

+ +
    +
  • ColumnMapping: renames row columns
  • +
  • SuffixRowAdapter: hides the first columns of a row
  • +
  • RangeRowAdapter: only exposes a range of columns
  • +
  • ScopeAdapter: groups several adapters together to define named scopes
  • +
+ +

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, adapter: adapter)
+
+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Experimental

    + +

    You never call this method directly. It is called for you whenever an +adapter has to be applied.

    + +

    The result is a value that adopts LayoutedRowAdapter, such as +LayoutedColumnMapping.

    + +

    For example:

    +
    // An adapter that turns any row to a row that contains a single
    +// column named "foo" whose value is the leftmost value of the
    +// base row.
    +struct FirstColumnAdapter : RowAdapter {
    +    func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
    +        return LayoutedColumnMapping(layoutColumns: [(0, "foo")])
    +    }
    +}
    +
    +// [foo:1]
    +try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: FirstColumnAdapter())
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + addingScopes(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an adapter based on self, with added scopes.

    + +

    If self already defines scopes, the added scopes replace +eventual existing scopes with the same name.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func addingScopes(_ scopes: [String : RowAdapter]) -> RowAdapter
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + scopes + + +
    +

    A dictionary that maps scope names to +row adapters.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Protocols/StatementColumnConvertible.html b/docs/3.3/Protocols/StatementColumnConvertible.html new file mode 100644 index 000000000..ffb955057 --- /dev/null +++ b/docs/3.3/Protocols/StatementColumnConvertible.html @@ -0,0 +1,907 @@ + + + + StatementColumnConvertible Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

StatementColumnConvertible

+
+
+
public protocol StatementColumnConvertible
+ +
+
+

The StatementColumnConvertible protocol grants access to the low-level C +interface that extracts values from query results: +https://www.sqlite.org/c3ref/column_blob.html. It can bring performance +improvements.

+ +

To use it, have a value type adopt both StatementColumnConvertible and +DatabaseValueConvertible. GRDB will then automatically apply the +optimization whenever direct access to SQLite is possible:

+
let rows = Row.fetchCursor(db, "SELECT ...")
+while let row = try rows.next() {
+    let int: Int = row[0]                 // there
+}
+let ints = Int.fetchAll(db, "SELECT ...") // there
+struct Player {
+    init(row: Row) {
+        name = row["name"]                // there
+        score = row["score"]              // there
+    }
+}
+
+ +

StatementColumnConvertible is already adopted by all Swift integer types, +Float, Double, String, and Bool.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Initializes a value from a raw SQLite statement pointer.

    + +

    For example, here is the how Int64 adopts StatementColumnConvertible:

    +
    extension Int64: StatementColumnConvertible {
    +    init(sqliteStatement: SQLiteStatement, index: Int32) {
    +        self = sqlite3_column_int64(sqliteStatement, index)
    +    }
    +}
    +
    + +

    This initializer is never called for NULL database values: don’t perform +any extra check.

    + +

    See https://www.sqlite.org/c3ref/column_blob.html for more information.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Protocols/TableRecord.html b/docs/3.3/Protocols/TableRecord.html new file mode 100644 index 000000000..e8e1c1301 --- /dev/null +++ b/docs/3.3/Protocols/TableRecord.html @@ -0,0 +1,2528 @@ + + + + TableRecord Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

TableRecord

+
+
+
public protocol TableRecord
+ +
+
+

Types that adopt TableRecord declare a particular relationship with +a database table.

+ +

Types that adopt both TableRecord and FetchableRecord are granted with +built-in methods that allow to fetch instances identified by key:

+
try Player.fetchOne(db, key: 123)  // Player?
+try Citizenship.fetchOne(db, key: ["citizenId": 12, "countryId": 45]) // Citizenship?
+
+ +

TableRecord is adopted by Record.

+ +
+
+
+
    +
  • +
    + + + + databaseTableName + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    The name of the database table used to build requests.

    +
    struct Player : TableRecord {
    +    static var databaseTableName = "player"
    +}
    +
    +// SELECT * FROM player
    +try Player.fetchAll(db)
    +
    + +
    +

    Default Implementation

    +
    +

    The default name of the database table used to build requests.

    + +
      +
    • Player -> player
    • +
    • Place -> place
    • +
    • PostalAddress -> postalAddress
    • +
    • HTTPRequest -> httpRequest
    • +
    • TOEFL -> toefl
    • +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    static var databaseTableName: String { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseSelection + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    The default request selection.

    + +

    Unless said otherwise, requests select all columns:

    +
    // SELECT * FROM player
    +try Player.fetchAll(db)
    +
    + +

    You can provide a custom implementation and provide an explicit list +of columns:

    +
    struct RestrictedPlayer : TableRecord {
    +    static var databaseTableName = "player"
    +    static var databaseSelection = [Column("id"), Column("name")]
    +}
    +
    +// 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: [SQLSelectable] = [AllColumns(), Column.rowID]
    +}
    +
    +// SELECT *, rowid FROM player
    +try ExtendedPlayer.fetchAll(db)
    +
    + +
    +

    Default Implementation

    +
    +

    Default value: [AllColumns()].

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    static var databaseSelection: [SQLSelectable] { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + belongsTo(_:key:using:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a Belongs To association between Self and the +destination type.

    +
    struct Author: TableRecord { ... }
    +struct Book: TableRecord {
    +    static let author = belongsTo(Author.self)
    +}
    +
    + +

    The association will let you define requests that load both the source +and the destination type:

    +
    // A request for all books with their authors:
    +let request = Book.including(optional: Book.author)
    +
    + +

    To consume those requests, define a type that adopts both the +FetchableRecord and Decodable protocols:

    +
    struct BookInfo: FetchableRecord, Decodable {
    +    var book: Book
    +    var author: Author?
    +}
    +
    +let bookInfos = try dbQueue.read { db in
    +    return try BookInfo.fetchAll(db, request)
    +}
    +for bookInfo in bookInfos {
    +    print("\(bookInfo.book.title) by \(bookInfo.author.name)")
    +}
    +
    + +

    It is recommended that you define, alongside the association, a property +with the same name:

    +
    struct Book: TableRecord {
    +    static let author = belongsTo(Author.self)
    +    var author: QueryInterfaceRequest<Author> {
    +        return request(for: Book.author)
    +    }
    +}
    +
    + +

    This property will let you navigate from the source type to the +destination type:

    +
    try dbQueue.read { db in
    +    let book: Book = ...
    +    let author = try book.author.fetchOne(db) // Author?
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func belongsTo<Destination>(
    +    _ destination: Destination.Type,
    +    key: String? = nil,
    +    using foreignKey: ForeignKey? = nil)
    +    -> BelongsToAssociation<Self, Destination>
    +    where Destination: TableRecord
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + destination + + +
    +

    The record type at the other side of the association.

    +
    +
    + + key + + +
    +

    An eventual decoding key for the association. By default, it +is destination.databaseTableName.

    +
    +
    + + foreignKey + + +
    +

    An eventual foreign key. You need to provide an +explicit foreign key when GRDB can’t infer one from the database +schema. This happens when the schema does not define any foreign +key to the destination table, or when the schema defines several +foreign keys to the destination table.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + hasMany(_:key:using:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a Has many association between Self and the +destination type.

    +
    struct Book: TableRecord { ... }
    +struct Author: TableRecord {
    +    static let books = hasMany(Book.self)
    +}
    +
    + +

    The association will let you define requests that load both the source +and the destination type:

    +
    // A request for all (author, book) pairs:
    +let request = Author.including(required: Author.books)
    +
    + +

    To consume those requests, define a type that adopts both the +FetchableRecord and Decodable protocols:

    +
    struct Authorship: FetchableRecord, Decodable {
    +    var author: Author
    +    var book: Book
    +}
    +
    +let authorships = try dbQueue.read { db in
    +    return try Authorship.fetchAll(db, request)
    +}
    +for authorship in authorships {
    +    print("\(authorship.author.name) wrote \(authorship.book.title)")
    +}
    +
    + +

    It is recommended that you define, alongside the association, a property +with the same name:

    +
    struct Author: TableRecord {
    +    static let books = hasMany(Book.self)
    +    var books: QueryInterfaceRequest<Book> {
    +        return request(for: Author.books)
    +    }
    +}
    +
    + +

    This property will let you navigate from the source type to the +destination type:

    +
    try dbQueue.read { db in
    +    let author: Author = ...
    +    let books = try author.books.fetchAll(db) // [Book]
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func hasMany<Destination>(
    +    _ destination: Destination.Type,
    +    key: String? = nil,
    +    using foreignKey: ForeignKey? = nil)
    +    -> HasManyAssociation<Self, Destination>
    +    where Destination: TableRecord
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + destination + + +
    +

    The record type at the other side of the association.

    +
    +
    + + key + + +
    +

    An eventual decoding key for the association. By default, it +is destination.databaseTableName.

    +
    +
    + + foreignKey + + +
    +

    An eventual foreign key. You need to provide an +explicit foreign key when GRDB can’t infer one from the database +schema. This happens when the schema does not define any foreign +key from the destination table, or when the schema defines several +foreign keys from the destination table.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + hasOne(_:key:using:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a Has one association between Self and the +destination type.

    +
    struct Demographics: TableRecord { ... }
    +struct Country: TableRecord {
    +    static let demographics = hasOne(Demographics.self)
    +}
    +
    + +

    The association will let you define requests that load both the source +and the destination type:

    +
    // A request for all countries with their demographic profile:
    +let request = Country.including(optional: Country.demographics)
    +
    + +

    To consume those requests, define a type that adopts both the +FetchableRecord and Decodable protocols:

    +
    struct CountryInfo: FetchableRecord, Decodable {
    +    var country: Country
    +    var demographics: Demographics?
    +}
    +
    +let countryInfos = try dbQueue.read { db in
    +    return try CountryInfo.fetchAll(db, request)
    +}
    +for countryInfo in countryInfos {
    +    print("\(countryInfo.country.name) has \(countryInfo.demographics.population) citizens")
    +}
    +
    + +

    It is recommended that you define, alongside the association, a property +with the same name:

    +
    struct Country: TableRecord {
    +    static let demographics = hasOne(Demographics.self)
    +    var demographics: QueryInterfaceRequest<Demographics> {
    +        return request(for: Country.demographics)
    +    }
    +}
    +
    + +

    This property will let you navigate from the source type to the +destination type:

    +
    try dbQueue.read { db in
    +    let country: Country = ...
    +    let demographics = try country.demographics.fetchOne(db) // Demographics?
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func hasOne<Destination>(
    +    _ destination: Destination.Type,
    +    key: String? = nil,
    +    using foreignKey: ForeignKey? = nil)
    +    -> HasOneAssociation<Self, Destination>
    +    where Destination: TableRecord
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + destination + + +
    +

    The record type at the other side of the association.

    +
    +
    + + key + + +
    +

    An eventual decoding key for the association. By default, it +is destination.databaseTableName.

    +
    +
    + + foreignKey + + +
    +

    An eventual foreign key. You need to provide an +explicit foreign key when GRDB can’t infer one from the database +schema. This happens when the schema does not define any foreign +key from the destination table, or when the schema defines several +foreign keys from the destination table.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + matching(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a QueryInterfaceRequest with a matching predicate.

    +
    // SELECT * FROM book WHERE book MATCH '...'
    +var request = Book.matching(pattern)
    +
    + +

    If the search pattern is nil, the request does not match any +database row.

    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + including(optional:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request that includes an association. The columns of the +associated record are selected. The returned association does not +require that the associated database table contains a matching row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func including<A>(optional association: A) -> QueryInterfaceRequest<Self> where Self == A.OriginRowDecoder, A : Association
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + including(required:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request that includes an association. The columns of the +associated record are selected. The returned association requires +that the associated database table contains a matching row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func including<A>(required association: A) -> QueryInterfaceRequest<Self> where Self == A.OriginRowDecoder, A : Association
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + joining(optional:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request that includes an association. The columns of the +associated record are not selected. The returned association does not +require that the associated database table contains a matching row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func joining<A>(optional association: A) -> QueryInterfaceRequest<Self> where Self == A.OriginRowDecoder, A : Association
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + joining(required:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request that includes an association. The columns of the +associated record are not selected. The returned association requires +that the associated database table contains a matching row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func joining<A>(required association: A) -> QueryInterfaceRequest<Self> where Self == A.OriginRowDecoder, A : Association
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + all() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request which fetches all records.

    +
    // SELECT * FROM player
    +let request = Player.all()
    +
    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func all() -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + none() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request which fetches no record.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func none() -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + select(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request which selects selection.

    +
    // SELECT id, email FROM player
    +let request = Player.select(Column("id"), Column("email"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func select(_ selection: SQLSelectable...) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + select(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request which selects selection.

    +
    // SELECT id, email FROM player
    +let request = Player.select([Column("id"), Column("email")])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + select(sql:arguments:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request which selects sql.

    +
    // SELECT id, email FROM player
    +let request = Player.select(sql: "id, email")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func select(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + select(_:as:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request which selects selection, and fetches values of +type type.

    +
    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)
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func select<RowDecoder>(_ selection: [SQLSelectable], as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + select(_:as:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request which selects selection, and fetches values of +type type.

    +
    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)
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func select<RowDecoder>(_ selection: SQLSelectable..., as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + select(sql:arguments:as:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request which selects sql, and fetches values of +type type.

    +
    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)
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func select<RowDecoder>(sql: String, arguments: StatementArguments? = nil, as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + filter(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request with the provided predicate.

    +
    // SELECT * FROM player WHERE email = 'arthur@example.com'
    +let request = Player.filter(Column("email") == "arthur@example.com")
    +
    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func filter(_ predicate: SQLExpressible) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + filter(key:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request with the provided primary key predicate.

    +
    // SELECT * FROM player WHERE id = 1
    +let request = Player.filter(key: 1)
    +
    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func filter<PrimaryKeyType>(key: PrimaryKeyType?) -> QueryInterfaceRequest<Self> where PrimaryKeyType : DatabaseValueConvertible
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + filter(keys:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request with the provided primary key predicate.

    +
    // SELECT * FROM player WHERE id IN (1, 2, 3)
    +let request = Player.filter(keys: [1, 2, 3])
    +
    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func filter<Sequence>(keys: Sequence) -> QueryInterfaceRequest<Self> where Sequence : Sequence, Sequence.Element : DatabaseValueConvertible
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + filter(key:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request with the provided primary key predicate.

    +
    // SELECT * FROM passport WHERE personId = 1 AND countryCode = 'FR'
    +let request = Passport.filter(key: ["personId": 1, "countryCode": "FR"])
    +
    + +

    When executed, this request raises a fatal error if there is no unique +index on the key columns.

    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func filter(key: [String : DatabaseValueConvertible?]?) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + filter(keys:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request with the provided primary key predicate.

    +
    // SELECT * FROM passport WHERE (personId = 1 AND countryCode = 'FR') OR ...
    +let request = Passport.filter(keys: [["personId": 1, "countryCode": "FR"], ...])
    +
    + +

    When executed, this request raises a fatal error if there is no unique +index on the key columns.

    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func filter(keys: [[String : DatabaseValueConvertible?]]) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + filter(sql:arguments:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request with the provided predicate.

    +
    // SELECT * FROM player WHERE email = 'arthur@example.com'
    +let request = Player.filter(sql: "email = ?", arguments: ["arthur@example.com"])
    +
    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func filter(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + order(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request sorted according to the +provided orderings.

    +
    // SELECT * FROM player ORDER BY name
    +let request = Player.order(Column("name"))
    +
    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + order(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request sorted according to the +provided orderings.

    +
    // SELECT * FROM player ORDER BY name
    +let request = Player.order([Column("name")])
    +
    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + orderByPrimaryKey() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request sorted by primary key.

    +
    // SELECT * FROM player ORDER BY id
    +let request = Player.orderByPrimaryKey()
    +
    +// SELECT * FROM country ORDER BY code
    +let request = Country.orderByPrimaryKey()
    +
    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func orderByPrimaryKey() -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + order(sql:arguments:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request sorted according to sql.

    +
    // SELECT * FROM player ORDER BY name
    +let request = Player.order(sql: "name")
    +
    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func order(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + limit(_:offset:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request which fetches limit rows, starting at +offset.

    +
    // SELECT * FROM player LIMIT 1
    +let request = Player.limit(1)
    +
    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + aliased(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request that allows you to define expressions that target +a specific database table.

    + +

    In the example below, the team.avgScore < player.score condition in +the ON clause could be not achieved without table aliases.

    +
    struct Player: TableRecord {
    +    static let team = belongsTo(Team.self)
    +}
    +
    +// SELECT player.*, team.*
    +// JOIN team ON ... AND team.avgScore < player.score
    +let playerAlias = TableAlias()
    +let request = Player
    +    .aliased(playerAlias)
    +    .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func aliased(_ alias: TableAlias) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCount(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    The number of records.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCount(_ db: Database) throws -> Int
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + selectionSQL(alias:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    The selection as an SQL String.

    + +

    For example:

    +
    struct Player: TableRecord {
    +    static let databaseTableName = "player"
    +}
    +
    +// SELECT "player".* FROM player
    +let sql = "SELECT \(Player.selectionSQL()) FROM player"
    +
    +// SELECT "p".* FROM player AS p
    +let sql = "SELECT \(Player.selectionSQL(alias: "p")) FROM player p"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func selectionSQL(alias: String? = nil) -> String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + numberOfSelectedColumns(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns the number of selected columns.

    + +

    For example:

    +
    struct Player: TableRecord {
    +    static let databaseTableName = "player"
    +}
    +
    +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)
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func numberOfSelectedColumns(_ db: Database) throws -> Int
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Protocols/TransactionObserver.html b/docs/3.3/Protocols/TransactionObserver.html new file mode 100644 index 000000000..785978d28 --- /dev/null +++ b/docs/3.3/Protocols/TransactionObserver.html @@ -0,0 +1,1135 @@ + + + + TransactionObserver Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

TransactionObserver

+
+
+
public protocol TransactionObserver : AnyObject
+ +
+
+

A transaction observer is notified of all changes and transactions committed +or rollbacked on a database.

+ +

Adopting types must be a class.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Filters database changes that should be notified the the +databaseDidChange(with:) method.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Notifies a database change (insert, update, or delete).

    + +

    The change is pending until the current transaction ends. See +databaseWillCommit, databaseDidCommit and databaseDidRollback.

    + +

    This method is called in a protected dispatch queue, serialized will all +database updates.

    + +

    The event is only valid for the duration of this method call. If you +need to keep it longer, store a copy: event.copy()

    + +

    The observer has an opportunity to stop receiving further change events +from the current transaction by calling the +stopObservingDatabaseChangesUntilNextTransaction() method.

    +
    +

    Warning

    + this method must not change the database. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func databaseDidChange(with event: DatabaseEvent)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseWillCommit() + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    When a transaction is about to be committed, the transaction observer +has an opportunity to rollback pending changes by throwing an error.

    + +

    This method is called on the database queue.

    +
    +

    Warning

    +

    this method must not change the database.

    + +
    +
    +

    Throws

    +

    An eventual error that rollbacks pending changes.

    + +
    + +
    +

    Default Implementation

    +
    +

    Default implementation does nothing

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func databaseWillCommit() throws
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseDidCommit(_:) + +
    +
    +
    +
    +
    +
    +

    Database changes have been committed.

    + +

    This method is called on the database queue. It can change the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func databaseDidCommit(_ db: Database)
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Database changes have been rollbacked.

    + +

    This method is called on the database queue. It can change the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func databaseDidRollback(_ db: Database)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseWillChange(with:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Notifies before a database change (insert, update, or delete) +with change information (initial / final values for the row’s +columns). (Called before databaseDidChangeWithEvent.)

    + +

    The change is pending until the end of the current transaction, +and you always get a second chance to get basic event information in +the databaseDidChangeWithEvent callback.

    + +

    This callback is mostly useful for calculating detailed change +information for a row, and provides the initial / final values.

    + +

    This method is called in a protected dispatch queue, serialized will all +database updates.

    + +

    The event is only valid for the duration of this method call. If you +need to keep it longer, store a copy: event.copy()

    +
    +

    Warning

    + this method must not change the database. + +
    + +

    Availability Info

    + +

    Requires SQLite 3.13.0 + +Compiled with option SQLITE_ENABLE_PREUPDATE_HOOK

    + +

    As of OSX 10.11.5, and iOS 9.3.2, the built-in SQLite library +does not have this enabled, so you’ll need to compile your own +copy using GRDBCustomSQLite. See https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md

    + +

    The databaseDidChangeWithEvent callback is always available, +and may provide most/all of what you need. +(For example, FetchedRecordsController is built without databaseWillChange)

    + +
    +

    Default Implementation

    +
    +

    Default implementation does nothing

    + +
    +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + stopObservingDatabaseChangesUntilNextTransaction() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    After this method has been called, the databaseDidChange(with:) +method won’t be called until the next transaction.

    + +

    For example:

    +
    class PlayerObserver: TransactionObserver {
    +    var playerTableWasModified = false
    +
    +    func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
    +        return eventKind.tableName == "player"
    +    }
    +
    +    func databaseDidChange(with event: DatabaseEvent) {
    +        playerTableWasModified = true
    +
    +        // It is pointless to keep on tracking further changes:
    +        stopObservingDatabaseChangesUntilNextTransaction()
    +    }
    +}
    +
    +
    +

    Precondition

    + This method must be called from databaseDidChange(with:). + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func stopObservingDatabaseChangesUntilNextTransaction()
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Protocols/VirtualTableModule.html b/docs/3.3/Protocols/VirtualTableModule.html new file mode 100644 index 000000000..165b159ff --- /dev/null +++ b/docs/3.3/Protocols/VirtualTableModule.html @@ -0,0 +1,981 @@ + + + + VirtualTableModule Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

VirtualTableModule

+
+
+
public protocol VirtualTableModule
+ +
+
+

The protocol for SQLite virtual table modules. It lets you define a DSL for +the Database.create(virtualTable:using:) method:

+
let module = ...
+try db.create(virtualTable: "item", using: module) { t in
+    ...
+}
+
+ +

GRDB ships with three concrete classes that implement this protocol: FTS3, +FTS4 and FTS5.

+ +
+
+
+
    +
  • +
    + + + + TableDefinition + +
    +
    +
    +
    +
    +
    +

    The type of the closure argument in the +Database.create(virtualTable:using:) method:

    +
    try db.create(virtualTable: "item", using: module) { t in
    +    // t is TableDefinition
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    associatedtype TableDefinition
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + moduleName + +
    +
    +
    +
    +
    +
    +

    The name of the module.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    var moduleName: String { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + makeTableDefinition() + +
    +
    +
    +
    +
    +
    +

    Returns a table definition that is passed as the closure argument in the +Database.create(virtualTable:using:) method:

    +
    try db.create(virtualTable: "item", using: module) { t in
    +    // t is the result of makeTableDefinition()
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func makeTableDefinition() -> TableDefinition
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns the module arguments for the CREATE VIRTUAL TABLE query.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func moduleArguments(for definition: TableDefinition, in db: Database) throws -> [String]
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Execute any relevant database statement after the virtual table has +been created.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func database(_ db: Database, didCreate tableName: String, using definition: TableDefinition) throws
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs.html b/docs/3.3/Structs.html new file mode 100644 index 000000000..1b2d2b307 --- /dev/null +++ b/docs/3.3/Structs.html @@ -0,0 +1,2911 @@ + + + + Structures Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Structures

+

The following structures are available globally.

+ +
+
+
+
    +
  • +
    + + + + Configuration + +
    +
    +
    +
    +
    +
    +

    Configuration for a DatabaseQueue or DatabasePool.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct Configuration
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + ColumnInfo + +
    +
    +
    +
    +
    +
    +

    A column of a database table.

    + +

    This type closely matches the information returned by the +table_info pragma.

    +
    > CREATE TABLE player (
    +    id INTEGER PRIMARY KEY,
    +    firstName TEXT,
    +    lastName TEXT)
    +> PRAGMA table_info("player")
    +cid   name   type     notnull   dflt_value  pk
    +----  -----  -------  --------  ----------  ---
    +0     id     INTEGER  0         NULL        1
    +1     name   TEXT     0         NULL        0
    +2     score  INTEGER  0         NULL        0
    +
    + +

    See Database.columns(in:) and https://www.sqlite.org/pragma.html#pragma_table_info

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct ColumnInfo : FetchableRecord
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + IndexInfo + +
    +
    +
    +
    +
    +
    +

    An index on a database table.

    + +

    See Database.indexes(on:)

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct IndexInfo
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + PrimaryKeyInfo + +
    +
    +
    +
    +
    +
    +

    Primary keys are returned from the Database.primaryKey(_:) method.

    + +

    When the table’s primary key is the rowid:

    +
    // CREATE TABLE item (name TEXT)
    +let pk = try db.primaryKey("item")
    +pk.columns     // ["rowid"]
    +pk.rowIDColumn // nil
    +pk.isRowID     // true
    +
    +// CREATE TABLE citizen (
    +//   id INTEGER PRIMARY KEY,
    +//   name TEXT
    +// )
    +let pk = try db.primaryKey("citizen")!
    +pk.columns     // ["id"]
    +pk.rowIDColumn // "id"
    +pk.isRowID     // true
    +
    + +

    When the table’s primary key is not the rowid:

    +
    // CREATE TABLE country (
    +//   isoCode TEXT NOT NULL PRIMARY KEY
    +//   name TEXT
    +// )
    +let pk = db.primaryKey("country")!
    +pk.columns     // ["isoCode"]
    +pk.rowIDColumn // nil
    +pk.isRowID     // false
    +
    +// CREATE TABLE citizenship (
    +//   citizenID INTEGER NOT NULL REFERENCES citizen(id)
    +//   countryIsoCode TEXT NOT NULL REFERENCES country(isoCode)
    +//   PRIMARY KEY (citizenID, countryIsoCode)
    +// )
    +let pk = db.primaryKey("citizenship")!
    +pk.columns     // ["citizenID", "countryIsoCode"]
    +pk.rowIDColumn // nil
    +pk.isRowID     // false
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct PrimaryKeyInfo
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ForeignKeyInfo + +
    +
    +
    +
    +
    +
    +

    You get foreign keys from table names, with the +foreignKeys(on:) method.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct ForeignKeyInfo
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + ResultCode + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + DatabaseError + +
    +
    +
    +
    +
    +
    +

    DatabaseError wraps an SQLite error.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct DatabaseError : Error, CustomStringConvertible, CustomNSError
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + DatabaseRegion + +
    +
    +
    +
    +
    +
    +

    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.

    + +

    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 (identified by +their rowids):

    +
    |Table1 |   |Table2 |   |Table3 |   |Table4 |   |Table5 |
    +|-------|   |-------|   |-------|   |-------|   |-------|
    +|x|x|x|x|   |x| | | |   |x|x|x|x|   |x|x| |x|   | | | | |
    +|x|x|x|x|   |x| | | |   | | | | |   | | | | |   | |x| | |
    +|x|x|x|x|   |x| | | |   | | | | |   |x|x| |x|   | | | | |
    +|x|x|x|x|   |x| | | |   | | | | |   | | | | |   | | | | |
    +
    + +

    You don’t create a database region directly. Instead, you use one of +those methods:

    + +
      +
    • SelectStatement.databaseRegion:

      + +

      let statement = db.makeSelectStatement(SELECT name, score FROM player) +print(statement.databaseRegion) +// prints player(name,score)

    • +
    • FetchRequest.databaseRegion(_:)

      + +

      let request = Player.filter(key: 1) +try print(request.databaseRegion(db)) +// prints player(*)[1]

    • +
    + +

    Database regions returned by requests can be more precise than regions +returned by select statements. Especially, regions returned by statements +don’t know about rowids:

    +
    // A plain statement
    +let statement = db.makeSelectStatement("SELECT * FROM player WHERE id = 1")
    +statement.databaseRegion       // "player(*)"
    +
    +// A query interface request that executes the same statement:
    +let request = Player.filter(key: 1)
    +try request.databaseRegion(db) // "player(*)[1]"
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct DatabaseRegion : CustomStringConvertible, Equatable
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+ + +
+
+ +
    +
  • +
    + + + + AnyFetchRequest + +
    +
    +
    +
    +
    +
    +

    A type-erased FetchRequest.

    + +

    An AnyFetchRequest forwards its operations to an underlying request, +hiding its specifics.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct AnyFetchRequest<T> : FetchRequest
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+ +
    +
  • +
    + + + + RowIndex + +
    +
    +
    +
    +
    +
    +

    Indexes to (ColumnName, DatabaseValue) pairs in a database row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct RowIndex : Comparable, Strideable
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + EmptyRowAdapter + +
    +
    +
    +
    +
    +
    +

    EmptyRowAdapter is a row adapter that hides all columns.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct EmptyRowAdapter : RowAdapter
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ColumnMapping + +
    +
    +
    +
    +
    +
    +

    ColumnMapping is a row adapter that maps column names.

    +
    let adapter = ColumnMapping(["foo": "bar"])
    +let sql = "SELECT 'foo' AS foo, 'bar' AS bar, 'baz' AS baz"
    +
    +// [foo:"bar"]
    +try Row.fetchOne(db, sql, adapter: adapter)
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct ColumnMapping : RowAdapter
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SuffixRowAdapter + +
    +
    +
    +
    +
    +
    +

    SuffixRowAdapter is a row adapter that hides the first columns in a row.

    +
    let adapter = SuffixRowAdapter(fromIndex: 2)
    +let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
    +
    +// [baz:3]
    +try Row.fetchOne(db, sql, adapter: adapter)
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct SuffixRowAdapter : RowAdapter
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + RangeRowAdapter + +
    +
    +
    +
    +
    +
    +

    RangeRowAdapter is a row adapter that only exposes a range of columns.

    +
    let adapter = RangeRowAdapter(1..<3)
    +let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz, 4 as qux"
    +
    +// [bar:2 baz:3]
    +try Row.fetchOne(db, sql, adapter: adapter)
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct RangeRowAdapter : RowAdapter
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ScopeAdapter + +
    +
    +
    +
    +
    +
    +

    ScopeAdapter is a row adapter that lets you define scopes on rows.

    +
    // Two adapters
    +let fooAdapter = ColumnMapping(["value": "foo"])
    +let barAdapter = ColumnMapping(["value": "bar"])
    +
    +// Define scopes
    +let adapter = ScopeAdapter([
    +    "foo": fooAdapter,
    +    "bar": barAdapter])
    +
    +// Fetch
    +let sql = "SELECT 'foo' AS foo, 'bar' AS bar"
    +let row = try Row.fetchOne(db, sql, adapter: adapter)!
    +
    +// Scoped rows:
    +if let fooRow = row.scopes["foo"] {
    +    fooRow["value"]    // "foo"
    +}
    +if let barRow = row.scopes["bar"] {
    +    barRow["value"]    // "bar"
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct ScopeAdapter : RowAdapter
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + StatementArguments + +
    +
    +
    +
    +
    +
    +

    StatementArguments provide values to argument placeholders in raw +SQL queries.

    + +

    Placeholders can take several forms (see https://www.sqlite.org/lang_expr.html#varparam +for more information):

    + +
      +
    • ?NNN (e.g. ?2): the NNN-th argument (starts at 1)
    • +
    • ?: the N-th argument, where N is one greater than the largest argument +number already assigned
    • +
    • :AAAA (e.g. :name): named argument

    • +
    • $AAAA (e.g. $name): named argument

    • +
    +

    Positional Arguments

    + +

    To fill question marks placeholders, feed StatementArguments with an array:

    +
    db.execute(
    +    "INSERT ... (?, ?)",
    +    arguments: StatementArguments(["Arthur", 41]))
    +
    +// Array literals are automatically converted:
    +db.execute(
    +    "INSERT ... (?, ?)",
    +    arguments: ["Arthur", 41])
    +
    +

    Named Arguments

    + +

    To fill named arguments, feed StatementArguments with a dictionary:

    +
    db.execute(
    +    "INSERT ... (:name, :score)",
    +    arguments: StatementArguments(["name": "Arthur", "score": 41]))
    +
    +// Dictionary literals are automatically converted:
    +db.execute(
    +    "INSERT ... (:name, :score)",
    +    arguments: ["name": "Arthur", "score": 41])
    +
    +

    Concatenating Arguments

    + +

    Several arguments can be concatenated and mixed with the +append(contentsOf:) method and the +, &+, += operators:

    +
    var arguments: StatementArguments = ["Arthur"]
    +arguments += [41]
    +db.execute("INSERT ... (?, ?)", arguments: arguments)
    +
    + +

    + and += operators consider that overriding named arguments is a +programmer error:

    +
    var arguments: StatementArguments = ["name": "Arthur"]
    +arguments += ["name": "Barbara"]
    +// fatal error: already defined statement argument: name
    +
    + +

    &+ and append(contentsOf:) allow overriding named arguments:

    +
    var arguments: StatementArguments = ["name": "Arthur"]
    +arguments = arguments &+ ["name": "Barbara"]
    +print(arguments)
    +// Prints ["name": "Barbara"]
    +
    +

    Mixed Arguments

    + +

    It is possible to mix named and positional arguments. Yet this is usually +confusing, and it is best to avoid this practice:

    +
    let sql = "SELECT ?2 AS two, :foo AS foo, ?1 AS one, :foo AS foo2, :bar AS bar"
    +var arguments: StatementArguments = [1, 2, "bar"] + ["foo": "foo"]
    +let row = try Row.fetchOne(db, sql, arguments: arguments)!
    +print(row)
    +// Prints [two:2 foo:"foo" one:1 foo2:"foo" bar:"bar"]
    +
    + +

    Mixed arguments exist as a support for requests like the following:

    +
    let players = try Player
    +    .filter(sql: "team = :team", arguments: ["team": "Blue"])
    +    .filter(sql: "score > ?", arguments: [1000])
    +    .fetchAll(db)
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct StatementArguments : CustomStringConvertible, Equatable, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
+
+ + +
+
+
    +
  • +
    + + + + FTS3 + +
    +
    +
    +
    +
    +
    +

    FTS3 lets you define fts3 virtual tables.

    +
    // CREATE VIRTUAL TABLE document USING fts3(content)
    +try db.create(virtualTable: "document", using: FTS3()) { t in
    +    t.column("content")
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct FTS3 : VirtualTableModule
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + FTS3Pattern + +
    +
    +
    +
    +
    +
    +

    A full text pattern that can query FTS3 and FTS4 virtual tables.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct FTS3Pattern
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
+
+ +
+
+
    +
  • +
    + + + + FTS5 + +
    +
    +
    +
    +
    +
    +

    FTS5 lets you define fts5 virtual tables.

    +
    // CREATE VIRTUAL TABLE document USING fts5(content)
    +try db.create(virtualTable: "document", using: FTS5()) { t in
    +    t.column("content")
    +}
    +
    + +

    See https://www.sqlite.org/fts5.html

    + + See more +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + FTS5Pattern + +
    +
    +
    +
    +
    +
    +

    A full text pattern that can query FTS5 virtual tables.

    + + See more +
    +
    +
    +
  • +
+
+
+ +
+
+ +
+
+ +
+
+
    +
  • +
    + + + + DatabaseMigrator + +
    +
    +
    +
    +
    +
    +

    A DatabaseMigrator registers and applies database migrations.

    + +

    Migrations are named blocks of SQL statements that are guaranteed to be +applied in order, once and only once.

    + +

    When a user upgrades your application, only non-applied migration are run.

    + +

    Usage:

    +
    var migrator = DatabaseMigrator()
    +
    +// 1st migration
    +migrator.registerMigration("createLibrary") { db in
    +    try db.create(table: "author") { t in
    +        t.autoIncrementedPrimaryKey("id")
    +        t.column("creationDate", .datetime)
    +        t.column("name", .text).notNull()
    +    }
    +
    +    try db.create(table: "book") { t in
    +        t.autoIncrementedPrimaryKey("id")
    +        t.column("authorId", .integer)
    +            .notNull()
    +            .references("author", onDelete: .cascade)
    +        t.column("title", .text).notNull()
    +    }
    +}
    +
    +// 2nd migration
    +migrator.registerMigration("AddBirthYearToAuthors") { db in
    +    try db.alter(table: "author") { t
    +        t.add(column: "birthYear", .integer)
    +    }
    +}
    +
    +// Migrations for future versions will be inserted here:
    +//
    +// // 3rd migration
    +// migrator.registerMigration("...") { db in
    +//     ...
    +// }
    +
    +try migrator.migrate(dbQueue)
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct DatabaseMigrator
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + BelongsToAssociation + +
    +
    +
    +
    +
    +
    +

    The BelongsTo association 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)
    +    ...
    +}
    +
    + +

    A BelongsTo associations 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.

    + +

    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)
    +}
    +
    + +
      +
    1. The author table has a primary key.
    2. +
    3. The book.authorId column is used to link a book to the author it +belongs to.
    4. +
    5. Make the book.authorId column not null if you want SQLite to guarantee +that all books have an author.
    6. +
    7. Create an index on the book.authorId column in order to ease the +selection of an author’s books.
    8. +
    9. Create a foreign key from book.authorId column to authors.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. +See https://sqlite.org/foreignkeys.html#fk_actions for more information.
    10. +
    + +

    The example above uses auto-incremented primary keys. But generally +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 +missing foreign key:

    +
    struct Book: FetchableRecord, TableRecord {
    +    static let author = belongsTo(Author.self, using: ForeignKey(...))
    +}
    +
    + +

    See ForeignKey for more information.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct BelongsToAssociation<Origin, Destination> : Association
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + ForeignKey + +
    +
    +
    +
    +
    +
    +

    A ForeignKey helps building associations when GRDB can’t infer a foreign +key from the database schema.

    + +

    Sometimes the database schema does not define any foreign key between two +tables. And sometimes, there are several foreign keys from a table +to another:

    +
    | Table book   |       | Table person |
    +| ------------ |       | ------------ |
    +| id           |   +-->• id           |
    +| authorId     •---+   | name         |
    +| translatorId •---+
    +| title        |
    +
    + +

    When this happens, associations can’t be automatically inferred from the +database schema. GRDB will complain with a fatal error such as Ambiguous +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:

    +
    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)
    +}
    +
    + +

    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]))
    +}
    +
    + +

    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:

    +
    struct Book: TableRecord {
    +    static let authorForeignKey = ForeignKey(["authorId"], to: ["id"]))
    +    static let author = belongsTo(Person.self, using: authorForeignKey)
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct ForeignKey
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + HasManyAssociation + +
    +
    +
    +
    +
    +
    +

    The HasMany association 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)
    +    ...
    +}
    +
    + +

    HasMany associations 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.

    + +

    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)
    +}
    +
    + +
      +
    1. The author table has a primary key.
    2. +
    3. The book.authorId column is used to link a book to the author it +belongs to.
    4. +
    5. Make the book.authorId column not null if you want SQLite to guarantee +that all books have an author.
    6. +
    7. Create an index on the book.authorId column in order to ease the +selection of an author’s books.
    8. +
    9. Create a foreign key from book.authorId column to authors.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. +See https://sqlite.org/foreignkeys.html#fk_actions for more information.
    10. +
    + +

    The example above uses auto-incremented primary keys. But generally +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 +missing foreign key:

    +
    struct Author: TableRecord {
    +    static let books = hasMany(Book.self, using: ForeignKey(...))
    +}
    +
    + +

    See ForeignKey for more information.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct HasManyAssociation<Origin, Destination> : Association
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + HasOneAssociation + +
    +
    +
    +
    +
    +
    +

    The HasOne association 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.

    + +

    For example, if your application has one database table for countries, and +another for their demographic profiles, you’d declare the association +this way:

    +
    struct Demographics: TableRecord { ... }
    +struct Country: TableRecord {
    +    static let demographics = hasOne(Demographics.self)
    +    ...
    +}
    +
    + +

    HasOne associations 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.

    + +

    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)
    +}
    +
    + +
      +
    1. The country table has a primary key.
    2. +
    3. The demographics.countryCode column is used to link a demographic +profile to the country it belongs to.
    4. +
    5. Make the demographics.countryCode column not null if you want SQLite to +guarantee that all profiles are linked to a country.
    6. +
    7. Create a unique index on the demographics.countryCode column in order to +guarantee the unicity of any country’s profile.
    8. +
    9. 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.
    10. +
    + +

    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:

    +
    struct Country: FetchableRecord, TableRecord {
    +    static let demographics = hasOne(Demographics.self, using: ForeignKey(...))
    +}
    +
    + +

    See ForeignKey for more information.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct HasOneAssociation<Origin, Destination> : Association
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
+
+ +
+
+ +
    +
  • +
    + + + + SQLExpressionLiteral + +
    +
    +
    +
    +
    +
    +

    Experimental

    + +

    SQLExpressionLiteral is an expression built from a raw SQL snippet.

    +
    SQLExpressionLiteral("1 + 2")
    +
    + +

    The SQL literal may contain ? and colon-prefixed arguments:

    +
    SQLExpressionLiteral("? + ?", arguments: [1, 2])
    +SQLExpressionLiteral(":one + :two", arguments: ["one": 1, "two": 2])
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct SQLExpressionLiteral : SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+ +
    +
  • +
    + + + + AllColumns + +
    +
    +
    +
    +
    +
    +

    AllColumns is the * in SELECT *.

    + +

    You use AllColumns in your custom implementation of +TableRecord.databaseSelection.

    + +

    For example:

    +
    struct Player : TableRecord {
    +    static var databaseTableName = "player"
    +    static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
    +}
    +
    +// SELECT *, rowid FROM player
    +let request = Player.all()
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct AllColumns
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+ +
    +
  • +
    + + + + PersistenceContainer + +
    +
    +
    +
    +
    +
    +

    Use persistence containers in the encode(to:) method of your +encodable records:

    +
    struct Player : MutablePersistableRecord {
    +    var id: Int64?
    +    var name: String?
    +
    +    func encode(to container: inout PersistenceContainer) {
    +        container["id"] = id
    +        container["name"] = name
    +    }
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct PersistenceContainer
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/AdaptedFetchRequest.html b/docs/3.3/Structs/AdaptedFetchRequest.html new file mode 100644 index 000000000..575db0880 --- /dev/null +++ b/docs/3.3/Structs/AdaptedFetchRequest.html @@ -0,0 +1,840 @@ + + + + AdaptedFetchRequest Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

AdaptedFetchRequest

+
+
+
public struct AdaptedFetchRequest<Base> : FetchRequest where Base : FetchRequest
+ +
+
+

An adapted request.

+ +
+
+
+
    +
  • +
    + + + + RowDecoder + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public typealias RowDecoder = Base.RowDecoder
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/AllColumns.html b/docs/3.3/Structs/AllColumns.html new file mode 100644 index 000000000..1237fe745 --- /dev/null +++ b/docs/3.3/Structs/AllColumns.html @@ -0,0 +1,854 @@ + + + + AllColumns Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

AllColumns

+
+
+
public struct AllColumns
+ +
+
+

AllColumns is the * in SELECT *.

+ +

You use AllColumns in your custom implementation of +TableRecord.databaseSelection.

+ +

For example:

+
struct Player : TableRecord {
+    static var databaseTableName = "player"
+    static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
+}
+
+// SELECT *, rowid FROM player
+let request = Player.all()
+
+ +
+
+
+
    +
  • +
    + + + + init() + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init()
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/AnyFetchRequest.html b/docs/3.3/Structs/AnyFetchRequest.html new file mode 100644 index 000000000..64c25f0e4 --- /dev/null +++ b/docs/3.3/Structs/AnyFetchRequest.html @@ -0,0 +1,904 @@ + + + + AnyFetchRequest Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

AnyFetchRequest

+
+
+
public struct AnyFetchRequest<T> : FetchRequest
+ +
+
+

A type-erased FetchRequest.

+ +

An AnyFetchRequest forwards its operations to an underlying request, +hiding its specifics.

+ +
+
+
+
    +
  • +
    + + + + RowDecoder + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public typealias RowDecoder = T
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a request that wraps and forwards operations to request.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init<Request>(_ request: Request) where Request : FetchRequest
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a request whose prepare() method wraps and forwards +operations the argument closure.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?))
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/BelongsToAssociation.html b/docs/3.3/Structs/BelongsToAssociation.html new file mode 100644 index 000000000..8d1084e6d --- /dev/null +++ b/docs/3.3/Structs/BelongsToAssociation.html @@ -0,0 +1,930 @@ + + + + BelongsToAssociation Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

BelongsToAssociation

+
+
+
public struct BelongsToAssociation<Origin, Destination> : Association
+ +
+
+

The BelongsTo association 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)
+    ...
+}
+
+ +

A BelongsTo associations 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.

+ +

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)
+}
+
+ +
    +
  1. The author table has a primary key.
  2. +
  3. The book.authorId column is used to link a book to the author it +belongs to.
  4. +
  5. Make the book.authorId column not null if you want SQLite to guarantee +that all books have an author.
  6. +
  7. Create an index on the book.authorId column in order to ease the +selection of an author’s books.
  8. +
  9. Create a foreign key from book.authorId column to authors.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. +See https://sqlite.org/foreignkeys.html#fk_actions for more information.
  10. +
+ +

The example above uses auto-incremented primary keys. But generally +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 +missing foreign key:

+
struct Book: FetchableRecord, TableRecord {
+    static let author = belongsTo(Author.self, using: ForeignKey(...))
+}
+
+ +

See ForeignKey for more information.

+ +
+
+
+
    +
  • +
    + + + + key + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var key: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + forKey(_:) + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func forKey(_ key: String) -> BelongsToAssociation<Origin, Destination>
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/Column.html b/docs/3.3/Structs/Column.html new file mode 100644 index 000000000..0dc64da98 --- /dev/null +++ b/docs/3.3/Structs/Column.html @@ -0,0 +1,906 @@ + + + + Column Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Column

+
+
+
public struct Column : ColumnExpression
+ +
+
+

A column in a database table.

+ +

When you need to introduce your own column type, don’t wrap a Column. +Instead, adopt the ColumnExpression protocol.

+ +

See https://github.com/groue/GRDB.swift#the-query-interface

+ +
+
+
+
    +
  • +
    + + + + rowID + +
    +
    +
    +
    +
    +
    +

    The hidden rowID column

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let rowID: Column
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + name + +
    +
    +
    +
    +
    +
    +

    The name of the column

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var name: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a column given its name.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ name: String)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/ColumnInfo.html b/docs/3.3/Structs/ColumnInfo.html new file mode 100644 index 000000000..ba96a4caf --- /dev/null +++ b/docs/3.3/Structs/ColumnInfo.html @@ -0,0 +1,1012 @@ + + + + ColumnInfo Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ColumnInfo

+
+
+
public struct ColumnInfo : FetchableRecord
+ +
+
+

A column of a database table.

+ +

This type closely matches the information returned by the +table_info pragma.

+
> CREATE TABLE player (
+    id INTEGER PRIMARY KEY,
+    firstName TEXT,
+    lastName TEXT)
+> PRAGMA table_info("player")
+cid   name   type     notnull   dflt_value  pk
+----  -----  -------  --------  ----------  ---
+0     id     INTEGER  0         NULL        1
+1     name   TEXT     0         NULL        0
+2     score  INTEGER  0         NULL        0
+
+ +

See Database.columns(in:) and https://www.sqlite.org/pragma.html#pragma_table_info

+ +
+
+
+
    +
  • +
    + + + + name + +
    +
    +
    +
    +
    +
    +

    The column name

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let name: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + type + +
    +
    +
    +
    +
    +
    +

    The column data type

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let type: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + isNotNull + +
    +
    +
    +
    +
    +
    +

    True if and only if the column is constrained to be not null.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let isNotNull: Bool
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + defaultValueSQL + +
    +
    +
    +
    +
    +
    +

    The SQL snippet that defines the default value, if any.

    + +

    When nil, the column has no default value.

    + +

    When not nil, it contains an SQL string that defines an expression. That +expression may be a literal, as 1, or 'foo'. It may also contain a +non-constant expression such as CURRENT_TIMESTAMP.

    + +

    For example:

    +
    try db.execute("""
    +    CREATE TABLE player(
    +        id INTEGER PRIMARY KEY,
    +        name TEXT DEFAULT 'Anonymous',
    +        score INT DEFAULT 0,
    +        creationDate DATE DEFAULT CURRENT_TIMESTAMP
    +    )
    +    """)
    +let columnInfos = try db.columns(in: "player")
    +columnInfos[0].defaultValueSQL // nil
    +columnInfos[1].defaultValueSQL // "'Anoynymous'"
    +columnInfos[2].defaultValueSQL // "0"
    +columnInfos[3].defaultValueSQL // "CURRENT_TIMESTAMP"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let defaultValueSQL: String?
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + primaryKeyIndex + +
    +
    +
    +
    +
    +
    +

    Zero for columns that are not part of the primary key.

    + +

    Before SQLite 3.7.16, it is 1 for columns that are part of the +primary key.

    + +

    Starting from SQLite 3.7.16, it is the one-based index of the column in +the primary key for columns that are part of the primary key.

    + +

    References:

    + + + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let primaryKeyIndex: Int
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/ColumnMapping.html b/docs/3.3/Structs/ColumnMapping.html new file mode 100644 index 000000000..f7cdda5c8 --- /dev/null +++ b/docs/3.3/Structs/ColumnMapping.html @@ -0,0 +1,848 @@ + + + + ColumnMapping Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ColumnMapping

+
+
+
public struct ColumnMapping : RowAdapter
+ +
+
+

ColumnMapping is a row adapter that maps column names.

+
let adapter = ColumnMapping(["foo": "bar"])
+let sql = "SELECT 'foo' AS foo, 'bar' AS bar, 'baz' AS baz"
+
+// [foo:"bar"]
+try Row.fetchOne(db, sql, adapter: adapter)
+
+ +
+
+
+
    +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a ColumnMapping with a dictionary from mapped column names to +column names in a base row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ mapping: [String : String])
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/Configuration.html b/docs/3.3/Structs/Configuration.html new file mode 100644 index 000000000..be5a7243b --- /dev/null +++ b/docs/3.3/Structs/Configuration.html @@ -0,0 +1,1244 @@ + + + + Configuration Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Configuration

+
+
+
public struct Configuration
+ +
+
+

Configuration for a DatabaseQueue or DatabasePool.

+ +
+
+
+ +
    +
  • +
    + + + + foreignKeysEnabled + +
    +
    +
    +
    +
    +
    +

    If true, foreign key constraints are checked.

    + +

    Default: true

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var foreignKeysEnabled: Bool
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + readonly + +
    +
    +
    +
    +
    +
    +

    If true, database modifications are disallowed.

    + +

    Default: false

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var readonly: Bool
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + label + +
    +
    +
    +
    +
    +
    +

    The database label.

    + +

    You can query this label at runtime:

    +
    var configuration = Configuration()
    +configuration.label = "MyDatabase"
    +let dbQueue = try DatabaseQueue(path: ..., configuration: configuration)
    +
    +try dbQueue.read { db in
    +    print(db.configuration.label) // Prints "MyDatabase"
    +}
    +
    + +

    The database label is also used to name the various dispatch queues +created by GRDB, visible in debugging sessions and crash logs. However +those dispatch queue labels are intended for debugging only. Their +format may change between GRDB releases. Applications should not depend +on the GRDB dispatch queue labels.

    + +

    If the database label is nil, the current GRDB implementation uses the +following dispatch queue labels:

    + +
      +
    • GRDB.DatabaseQueue: the (unique) dispatch queue of a DatabaseQueue
    • +
    • GRDB.DatabasePool.writer: the (unique) writer dispatch queue of +a DatabasePool
    • +
    • GRDB.DatabasePool.reader.N, where N is 1, 2, …: one of the reader +dispatch queue(s) of a DatabasePool. N grows with the number of SQLite +connections: it may get bigger than the maximum number of concurrent +readers, as SQLite connections get closed and new ones are opened.
    • +
    • GRDB.DatabasePool.snapshot.N: the dispatch queue of a +DatabaseSnapshot. N grows with the number of snapshots.
    • +
    + +

    If the database label is not nil, for example MyDatabase, the current +GRDB implementation uses the following dispatch queue labels:

    + +
      +
    • MyDatabase: the (unique) dispatch queue of a DatabaseQueue
    • +
    • MyDatabase.writer: the (unique) writer dispatch queue of +a DatabasePool
    • +
    • MyDatabase.reader.N, where N is 1, 2, …: one of the reader +dispatch queue(s) of a DatabasePool. N grows with the number of SQLite +connections: it may get bigger than the maximum number of concurrent +readers, as SQLite connections get closed and new ones are opened.
    • +
    • MyDatabase.snapshot.N: the dispatch queue of a +DatabaseSnapshot. N grows with the number of snapshots.
    • +
    + +

    The default label is nil.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var label: String?
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + trace + +
    +
    +
    +
    +
    +
    +

    A function that is called on every statement executed by the database.

    + +

    Default: nil

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var trace: TraceFunction?
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + passphrase + +
    +
    +
    +
    +
    +
    +

    The passphrase for encrypted database.

    + +

    Default: nil

    + +
    +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    The default kind of transaction.

    + +

    Default: deferred

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var defaultTransactionKind: Database.TransactionKind
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    If false, it is a programmer error to leave a transaction opened at the +end of a database access block.

    + +

    For example:

    +
    let dbQueue = DatabaseQueue()
    +
    +// fatal error: A transaction has been left opened at the end of a database access
    +try dbQueue.inDatabase { db in
    +    try db.beginTransaction()
    +}
    +
    + +

    If true, one can leave opened transaction at the end of database access +blocks:

    +
    var config = Configuration()
    +config.allowsUnsafeTransactions = true
    +let dbQueue = DatabaseQueue(configuration: config)
    +
    +try dbQueue.inDatabase { db in
    +    try db.beginTransaction()
    +}
    +
    +try dbQueue.inDatabase { db in
    +    try db.commit()
    +}
    +
    + +

    This configuration flag has no effect on DatabasePool readers: those +never allow leaving a transaction opened at the end of a read access.

    + +

    Default: false

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var allowsUnsafeTransactions: Bool
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+ +
    +
  • +
    + + + + init() + +
    +
    +
    +
    +
    +
    +

    Creates a factory configuration

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init()
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/DatabaseDateComponents.html b/docs/3.3/Structs/DatabaseDateComponents.html new file mode 100644 index 000000000..8843387b7 --- /dev/null +++ b/docs/3.3/Structs/DatabaseDateComponents.html @@ -0,0 +1,1119 @@ + + + + DatabaseDateComponents Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseDateComponents

+
+
+
public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumnConvertible
+ +
+
+

DatabaseDateComponents reads and stores DateComponents in the database.

+ +
+
+
+
    +
  • +
    + + + + Format + +
    +
    +
    +
    +
    +
    +

    The available formats for reading and storing date components.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public enum Format : String
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + dateComponents + +
    +
    +
    +
    +
    +
    +

    The date components

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let dateComponents: DateComponents
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + format + +
    +
    +
    +
    +
    +
    +

    The database format

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let format: Format
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:format:) + +
    +
    +
    +
    +
    +
    +

    Creates a DatabaseDateComponents from a DateComponents and a format.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ dateComponents: DateComponents, format: Format)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + dateComponents + + +
    +

    An optional DateComponents.

    +
    +
    + + format + + +
    +

    The format used for storing the date components in +the database.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a DatabaseDateComponents if dbValue contains a +valid date.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> DatabaseDateComponents?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/DatabaseDateComponents/Format.html b/docs/3.3/Structs/DatabaseDateComponents/Format.html new file mode 100644 index 000000000..74c946614 --- /dev/null +++ b/docs/3.3/Structs/DatabaseDateComponents/Format.html @@ -0,0 +1,1027 @@ + + + + Format Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Format

+
+
+
public enum Format : String
+ +
+
+

The available formats for reading and storing date components.

+ +
+
+
+
    +
  • +
    + + + + YMD + +
    +
    +
    +
    +
    +
    +

    The format yyyy-MM-dd.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case YMD = "yyyy-MM-dd"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + YMD_HM + +
    +
    +
    +
    +
    +
    +

    The format yyyy-MM-dd HH:mm.

    + +

    This format is lexically comparable with SQLite’s CURRENT_TIMESTAMP.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case YMD_HM = "yyyy-MM-dd HH:mm"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + YMD_HMS + +
    +
    +
    +
    +
    +
    +

    The format yyyy-MM-dd HH:mm:ss.

    + +

    This format is lexically comparable with SQLite’s CURRENT_TIMESTAMP.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case YMD_HMS = "yyyy-MM-dd HH:mm:ss"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + YMD_HMSS + +
    +
    +
    +
    +
    +
    +

    The format yyyy-MM-dd HH:mm:ss.SSS.

    + +

    This format is lexically comparable with SQLite’s CURRENT_TIMESTAMP.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case YMD_HMSS = "yyyy-MM-dd HH:mm:ss.SSS"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + HM + +
    +
    +
    +
    +
    +
    +

    The format HH:mm.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case HM = "HH:mm"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + HMS + +
    +
    +
    +
    +
    +
    +

    The format HH:mm:ss.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case HMS = "HH:mm:ss"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + HMSS + +
    +
    +
    +
    +
    +
    +

    The format HH:mm:ss.SSS.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case HMSS = "HH:mm:ss.SSS"
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/DatabaseError.html b/docs/3.3/Structs/DatabaseError.html new file mode 100644 index 000000000..36d1d0abc --- /dev/null +++ b/docs/3.3/Structs/DatabaseError.html @@ -0,0 +1,983 @@ + + + + DatabaseError Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseError

+
+
+
public struct DatabaseError : Error, CustomStringConvertible, CustomNSError
+ +
+
+

DatabaseError wraps an SQLite error.

+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/DatabaseEvent.html b/docs/3.3/Structs/DatabaseEvent.html new file mode 100644 index 000000000..2e0640f25 --- /dev/null +++ b/docs/3.3/Structs/DatabaseEvent.html @@ -0,0 +1,999 @@ + + + + DatabaseEvent Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseEvent

+
+
+
public struct DatabaseEvent
+ +
+
+

A database event, notified to TransactionObserver.

+ +
+
+
+
    +
  • +
    + + + + Kind + +
    +
    +
    +
    +
    +
    +

    An event kind

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public enum Kind : Int32
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + kind + +
    +
    +
    +
    +
    +
    +

    The event kind

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let kind: Kind
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseName + +
    +
    +
    +
    +
    +
    +

    The database name

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseName: String { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + tableName + +
    +
    +
    +
    +
    +
    +

    The table name

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var tableName: String { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + rowID + +
    +
    +
    +
    +
    +
    +

    The rowID of the changed row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let rowID: Int64
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + copy() + +
    +
    +
    +
    +
    +
    +

    Returns an event that can be stored:

    +
    class MyObserver: TransactionObserver {
    +    var events: [DatabaseEvent]
    +    func databaseDidChange(with event: DatabaseEvent) {
    +        events.append(event.copy())
    +    }
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func copy() -> DatabaseEvent
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/DatabaseEvent/Kind.html b/docs/3.3/Structs/DatabaseEvent/Kind.html new file mode 100644 index 000000000..7de72780a --- /dev/null +++ b/docs/3.3/Structs/DatabaseEvent/Kind.html @@ -0,0 +1,901 @@ + + + + Kind Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Kind

+
+
+
public enum Kind : Int32
+ +
+
+

An event kind

+ +
+
+
+
    +
  • +
    + + + + insert + +
    +
    +
    +
    +
    +
    +

    SQLITE_INSERT

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case insert = 18
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + delete + +
    +
    +
    +
    +
    +
    +

    SQLITE_DELETE

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case delete = 9
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + update + +
    +
    +
    +
    +
    +
    +

    SQLITE_UPDATE

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case update = 23
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/DatabaseMigrator.html b/docs/3.3/Structs/DatabaseMigrator.html new file mode 100644 index 000000000..58b48ef86 --- /dev/null +++ b/docs/3.3/Structs/DatabaseMigrator.html @@ -0,0 +1,1186 @@ + + + + DatabaseMigrator Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseMigrator

+
+
+
public struct DatabaseMigrator
+ +
+
+

A DatabaseMigrator registers and applies database migrations.

+ +

Migrations are named blocks of SQL statements that are guaranteed to be +applied in order, once and only once.

+ +

When a user upgrades your application, only non-applied migration are run.

+ +

Usage:

+
var migrator = DatabaseMigrator()
+
+// 1st migration
+migrator.registerMigration("createLibrary") { db in
+    try db.create(table: "author") { t in
+        t.autoIncrementedPrimaryKey("id")
+        t.column("creationDate", .datetime)
+        t.column("name", .text).notNull()
+    }
+
+    try db.create(table: "book") { t in
+        t.autoIncrementedPrimaryKey("id")
+        t.column("authorId", .integer)
+            .notNull()
+            .references("author", onDelete: .cascade)
+        t.column("title", .text).notNull()
+    }
+}
+
+// 2nd migration
+migrator.registerMigration("AddBirthYearToAuthors") { db in
+    try db.alter(table: "author") { t
+        t.add(column: "birthYear", .integer)
+    }
+}
+
+// Migrations for future versions will be inserted here:
+//
+// // 3rd migration
+// migrator.registerMigration("...") { db in
+//     ...
+// }
+
+try migrator.migrate(dbQueue)
+
+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    When the eraseDatabaseOnSchemaChange flag is true, the migrator will +automatically wipe out the full database content, and recreate the whole +database from scratch, if it detects that a migration has changed its +definition.

    + +

    This flag can destroy your precious users’ data!

    + +

    But it may be useful in two situations:

    + +
      +
    1. During application development, as you are still designing +migrations, and the schema changes often.

      + +

      In this case, it is recommended that you make sure this flag does +not ship in the distributed application, in order to avoid undesired +data loss:

      +
      var migrator = DatabaseMigrator()
      +#if DEBUG
      +// Speed up development by nuking the database when migrations change
      +migrator.eraseDatabaseOnSchemaChange = true
      +#endif
      +
    2. +
    3. When the database content can easily be recreated, such as a cache +for some downloaded data.

    4. +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var eraseDatabaseOnSchemaChange: Bool
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init() + +
    +
    +
    +
    +
    +
    +

    A new migrator.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init()
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Registers a migration.

    +
    migrator.registerMigration("createAuthors") { db in
    +    try db.create(table: "author") { t in
    +        t.autoIncrementedPrimaryKey("id")
    +        t.column("creationDate", .datetime)
    +        t.column("name", .text).notNull()
    +    }
    +}
    +
    +
    +

    Precondition

    + No migration with the same same as already been registered. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public mutating func registerMigration(_ identifier: String, migrate: @escaping (Database) throws -> Void)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + identifier + + +
    +

    The migration identifier.

    +
    +
    + + block + + +
    +

    The migration block that performs SQL statements.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public mutating func registerMigrationWithDeferredForeignKeyCheck(_ identifier: String, migrate: @escaping (Database) throws -> Void)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + migrate(_:) + +
    +
    +
    +
    +
    +
    +

    Iterate migrations in the same order as they were registered. If a +migration has not yet been applied, its block is executed in +a transaction.

    +
    +

    Throws

    + An eventual error thrown by the registered migration blocks. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func migrate(_ writer: DatabaseWriter) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A DatabaseWriter (DatabaseQueue or DatabasePool) where +migrations should apply.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + migrate(_:upTo:) + +
    +
    +
    +
    +
    +
    +

    Iterate migrations in the same order as they were registered, up to the +provided target. If a migration has not yet been applied, its block is +executed in a transaction.

    +
  • targetIdentifier: The identifier of a registered migration.
  • +
    +

    Throws

    + An eventual error thrown by the registered migration blocks. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A DatabaseWriter (DatabaseQueue or DatabasePool) where +migrations should apply.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns the set of applied migration identifiers.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func appliedMigrations(in reader: DatabaseReader) throws -> Set<String>
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/DatabasePreUpdateEvent.html b/docs/3.3/Structs/DatabasePreUpdateEvent.html new file mode 100644 index 000000000..41ed19b6a --- /dev/null +++ b/docs/3.3/Structs/DatabasePreUpdateEvent.html @@ -0,0 +1,1081 @@ + + + + DatabasePreUpdateEvent Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabasePreUpdateEvent

+ +
+
+
+
    +
  • +
    + + + + Kind + +
    +
    +
    +
    +
    +
    +

    An event kind

    + + See more +
    +
    +
    +
  • +
  • +
    + + + + kind + +
    +
    +
    +
    +
    +
    +

    The event kind

    + +
    +
    +
    +
  • +
  • +
    + + + + databaseName + +
    +
    +
    +
    +
    +
    +

    The database name

    + +
    +
    +
    +
  • +
  • +
    + + + + tableName + +
    +
    +
    +
    +
    +
    +

    The table name

    + +
    +
    +
    +
  • +
  • +
    + + + + count + +
    +
    +
    +
    +
    +
    +

    The number of columns in the row that is being inserted, updated, or deleted.

    + +
    +
    +
    +
  • +
  • +
    + + + + depth + +
    +
    +
    +
    +
    +
    +

    1 for inserts, updates, or deletes invoked by top-level triggers; +2 for changes resulting from triggers called by top-level triggers; +… and so forth

    + +
    +
    +
    +
  • +
  • +
    + + + + initialRowID + +
    +
    +
    +
    +
    +
    +

    The initial rowID of the row being changed for .Update and .Delete changes, +and nil for .Insert changes.

    + +
    +
    +
    +
  • +
  • +
    + + + + finalRowID + +
    +
    +
    +
    +
    +
    +

    The final rowID of the row being changed for .Update and .Insert changes, +and nil for .Delete changes.

    + +
    +
    +
    +
  • +
  • +
    + + + + initialDatabaseValues + +
    +
    +
    +
    +
    +
    +

    The initial database values in the row.

    + +

    Values appear in the same order as the columns in the table.

    + +

    The result is nil if the event is an .Insert event.

    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns the initial DatabaseValue at given index.

    + +

    Indexes span from 0 for the leftmost column to (row.count - 1) for the +righmost column.

    + +

    The result is nil if the event is an .Insert event.

    + +
    +
    +
    +
  • +
  • +
    + + + + finalDatabaseValues + +
    +
    +
    +
    +
    +
    +

    The final database values in the row.

    + +

    Values appear in the same order as the columns in the table.

    + +

    The result is nil if the event is a .Delete event.

    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns the final DatabaseValue at given index.

    + +

    Indexes span from 0 for the leftmost column to (row.count - 1) for the +righmost column.

    + +

    The result is nil if the event is a .Delete event.

    + +
    +
    +
    +
  • +
  • +
    + + + + copy() + +
    +
    +
    +
    +
    +
    +

    Returns an event that can be stored:

    +
    class MyObserver: TransactionObserver {
    +    var events: [DatabasePreUpdateEvent]
    +    func databaseWillChange(with event: DatabasePreUpdateEvent) {
    +        events.append(event.copy())
    +    }
    +}
    +
    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/DatabasePreUpdateEvent/Kind.html b/docs/3.3/Structs/DatabasePreUpdateEvent/Kind.html new file mode 100644 index 000000000..bfd205a68 --- /dev/null +++ b/docs/3.3/Structs/DatabasePreUpdateEvent/Kind.html @@ -0,0 +1,862 @@ + + + + Kind Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Kind

+

An event kind

+ +
+
+
+
    +
  • +
    + + + + insert + +
    +
    +
    +
    +
    +
    +

    SQLITE_INSERT

    + +
    +
    +
    +
  • +
  • +
    + + + + delete + +
    +
    +
    +
    +
    +
    +

    SQLITE_DELETE

    + +
    +
    +
    +
  • +
  • +
    + + + + update + +
    +
    +
    +
    +
    +
    +

    SQLITE_UPDATE

    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/DatabaseRegion.html b/docs/3.3/Structs/DatabaseRegion.html new file mode 100644 index 000000000..b876d8c1a --- /dev/null +++ b/docs/3.3/Structs/DatabaseRegion.html @@ -0,0 +1,1082 @@ + + + + DatabaseRegion Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseRegion

+
+
+
public struct DatabaseRegion : CustomStringConvertible, Equatable
+ +
+
+

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.

+ +

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 (identified by +their rowids):

+
|Table1 |   |Table2 |   |Table3 |   |Table4 |   |Table5 |
+|-------|   |-------|   |-------|   |-------|   |-------|
+|x|x|x|x|   |x| | | |   |x|x|x|x|   |x|x| |x|   | | | | |
+|x|x|x|x|   |x| | | |   | | | | |   | | | | |   | |x| | |
+|x|x|x|x|   |x| | | |   | | | | |   |x|x| |x|   | | | | |
+|x|x|x|x|   |x| | | |   | | | | |   | | | | |   | | | | |
+
+ +

You don’t create a database region directly. Instead, you use one of +those methods:

+ +
    +
  • SelectStatement.databaseRegion:

    + +

    let statement = db.makeSelectStatement(SELECT name, score FROM player) +print(statement.databaseRegion) +// prints player(name,score)

  • +
  • FetchRequest.databaseRegion(_:)

    + +

    let request = Player.filter(key: 1) +try print(request.databaseRegion(db)) +// prints player(*)[1]

  • +
+ +

Database regions returned by requests can be more precise than regions +returned by select statements. Especially, regions returned by statements +don’t know about rowids:

+
// A plain statement
+let statement = db.makeSelectStatement("SELECT * FROM player WHERE id = 1")
+statement.databaseRegion       // "player(*)"
+
+// A query interface request that executes the same statement:
+let request = Player.filter(key: 1)
+try request.databaseRegion(db) // "player(*)[1]"
+
+ +
+
+
+
    +
  • +
    + + + + isEmpty + +
    +
    +
    +
    +
    +
    +

    Returns whether the region is empty.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var isEmpty: Bool { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fullDatabase + +
    +
    +
    +
    +
    +
    +

    The region that covers the full database: all columns and all rows +from all tables.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let fullDatabase: DatabaseRegion
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init() + +
    +
    +
    +
    +
    +
    +

    The empty database region

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init()
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + union(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the union of this region and the given one.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func union(_ other: DatabaseRegion) -> DatabaseRegion
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + formUnion(_:) + +
    +
    +
    +
    +
    +
    +

    Inserts the given region into this region

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public mutating func formUnion(_ other: DatabaseRegion)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Returns whether the content in the region would be impacted if the +database were modified by an event of this kind.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func isModified(byEventsOfKind eventKind: DatabaseEventKind) -> Bool
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + isModified(by:) + +
    +
    +
    +
    +
    +
    +

    Returns whether the content in the region is impacted by this event.

    +
    +

    Precondition

    + event has been filtered by the same region +in the TransactionObserver.observes(eventsOfKind:) method, by calling +region.isModified(byEventsOfKind:) + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func isModified(by event: DatabaseEvent) -> Bool
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/DatabaseValue.html b/docs/3.3/Structs/DatabaseValue.html new file mode 100644 index 000000000..39c1f4e31 --- /dev/null +++ b/docs/3.3/Structs/DatabaseValue.html @@ -0,0 +1,1263 @@ + + + + DatabaseValue Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseValue

+
+
+
public struct DatabaseValue : Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLExpression
+ +
+
+

DatabaseValue is the intermediate type between SQLite and your values.

+ +

See https://www.sqlite.org/datatype3.html

+ +
+
+
+
    +
  • +
    + + + + storage + +
    +
    +
    +
    +
    +
    +

    The SQLite storage

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let storage: Storage
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + null + +
    +
    +
    +
    +
    +
    +

    The NULL DatabaseValue.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let null: DatabaseValue
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + Storage + +
    +
    +
    +
    +
    +
    +

    An SQLite storage (NULL, INTEGER, REAL, TEXT, BLOB).

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public enum Storage : Equatable
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(value:) + +
    +
    +
    +
    +
    +
    +

    Creates a DatabaseValue from Any.

    + +

    The result is nil unless object adopts DatabaseValueConvertible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init?(value: Any)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + isNull + +
    +
    +
    +
    +
    +
    +

    Returns true if databaseValue is NULL.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var isNull: Bool { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + ==(_:_:) + +
    +
    +
    +
    +
    +
    +

    Returns whether two DatabaseValues are equal.

    +
    1.databaseValue == "foo".databaseValue // false
    +1.databaseValue == 1.databaseValue     // true
    +
    + +

    When comparing integers and doubles, the result is true if and only +values are equal, and if converting one type to the other does +not lose information:

    +
    1.databaseValue == 1.0.databaseValue   // true
    +
    + +

    For a comparison that distinguishes integer and doubles, compare +storages instead:

    +
    1.databaseValue.storage == 1.0.databaseValue.storage // false
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func == (lhs: DatabaseValue, rhs: DatabaseValue) -> Bool
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Converts the database value to the type T.

    +
    let dbValue = "foo".databaseValue
    +let string = dbValue.losslessConvert() as String // "foo"
    +
    + +

    Conversion is successful if and only if T.fromDatabaseValue returns a +non-nil value.

    + +

    This method crashes with a fatal error when conversion fails.

    +
    let dbValue = "foo".databaseValue
    +let int = dbValue.losslessConvert() as Int // fatalError
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil) -> T where T : DatabaseValueConvertible
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sql + + +
    +

    Optional SQL statement that enhances the eventual +conversion error

    +
    +
    + + arguments + + +
    +

    Optional statement arguments that enhances the eventual +conversion error

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Converts the database value to the type Optional.

    +
    let dbValue = "foo".databaseValue
    +let string = dbValue.losslessConvert() as String? // "foo"
    +let null = DatabaseValue.null.losslessConvert() as String? // nil
    +
    + +

    Conversion is successful if and only if T.fromDatabaseValue returns a +non-nil value.

    + +

    This method crashes with a fatal error when conversion fails.

    +
    let dbValue = "foo".databaseValue
    +let int = dbValue.losslessConvert() as Int? // fatalError
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil) -> T? where T : DatabaseValueConvertible
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sql + + +
    +

    Optional SQL statement that enhances the eventual +conversion error

    +
    +
    + + arguments + + +
    +

    Optional statement arguments that enhances the eventual +conversion error

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns self

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the database value

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> DatabaseValue?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/DatabaseValue/Storage.html b/docs/3.3/Structs/DatabaseValue/Storage.html new file mode 100644 index 000000000..a52692a08 --- /dev/null +++ b/docs/3.3/Structs/DatabaseValue/Storage.html @@ -0,0 +1,1025 @@ + + + + Storage Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Storage

+
+
+
public enum Storage : Equatable
+ +
+
+

An SQLite storage (NULL, INTEGER, REAL, TEXT, BLOB).

+ +
+
+
+
    +
  • +
    + + + + null + +
    +
    +
    +
    +
    +
    +

    The NULL storage class.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case null
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + int64 + +
    +
    +
    +
    +
    +
    +

    The INTEGER storage class, wrapping an Int64.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case int64(Int64)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + double + +
    +
    +
    +
    +
    +
    +

    The REAL storage class, wrapping a Double.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case double(Double)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + string + +
    +
    +
    +
    +
    +
    +

    The TEXT storage class, wrapping a String.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case string(String)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + blob + +
    +
    +
    +
    +
    +
    +

    The BLOB storage class, wrapping Data.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case blob(Data)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + value + +
    +
    +
    +
    +
    +
    +

    Returns Int64, Double, String, Data or nil.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var value: DatabaseValueConvertible? { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ==(_:_:) + +
    +
    +
    +
    +
    +
    +

    Return true if the storages are identical.

    + +

    Unlike DatabaseValue equality that considers the integer 1 to be +equal to the 1.0 double (as SQLite does), int64 and double storages +are never equal.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func == (lhs: Storage, rhs: Storage) -> Bool
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/EmptyRowAdapter.html b/docs/3.3/Structs/EmptyRowAdapter.html new file mode 100644 index 000000000..2fd4a7070 --- /dev/null +++ b/docs/3.3/Structs/EmptyRowAdapter.html @@ -0,0 +1,841 @@ + + + + EmptyRowAdapter Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

EmptyRowAdapter

+
+
+
public struct EmptyRowAdapter : RowAdapter
+ +
+
+

EmptyRowAdapter is a row adapter that hides all columns.

+ +
+
+
+
    +
  • +
    + + + + init() + +
    +
    +
    +
    +
    +
    +

    Creates an EmptyRowAdapter

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init()
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/FTS3.html b/docs/3.3/Structs/FTS3.html new file mode 100644 index 000000000..25f0f59a2 --- /dev/null +++ b/docs/3.3/Structs/FTS3.html @@ -0,0 +1,989 @@ + + + + FTS3 Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS3

+
+
+
public struct FTS3 : VirtualTableModule
+ +
+
+

FTS3 lets you define fts3 virtual tables.

+
// CREATE VIRTUAL TABLE document USING fts3(content)
+try db.create(virtualTable: "document", using: FTS3()) { t in
+    t.column("content")
+}
+
+ +
+
+
+
    +
  • +
    + + + + init() + +
    +
    +
    +
    +
    +
    +

    Creates a FTS3 module suitable for the Database +create(virtualTable:using:) method.

    +
    // CREATE VIRTUAL TABLE document USING fts3(content)
    +try db.create(virtualTable: "document", using: FTS3()) { t in
    +    t.column("content")
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init()
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + moduleName + +
    +
    +
    +
    +
    +
    +

    The virtual table module name

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let moduleName: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + makeTableDefinition() + +
    +
    +
    +
    +
    +
    +

    Reserved; part of the VirtualTableModule protocol.

    + +

    See Database.create(virtualTable:using:)

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func makeTableDefinition() -> FTS3TableDefinition
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Reserved; part of the VirtualTableModule protocol.

    + +

    See Database.create(virtualTable:using:)

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func moduleArguments(for definition: FTS3TableDefinition, in db: Database) -> [String]
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Reserved; part of the VirtualTableModule protocol.

    + +

    See Database.create(virtualTable:using:)

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func database(_ db: Database, didCreate tableName: String, using definition: FTS3TableDefinition)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/FTS3Pattern.html b/docs/3.3/Structs/FTS3Pattern.html new file mode 100644 index 000000000..3398a0e5b --- /dev/null +++ b/docs/3.3/Structs/FTS3Pattern.html @@ -0,0 +1,1173 @@ + + + + FTS3Pattern Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS3Pattern

+
+
+
public struct FTS3Pattern
+ +
+
+

A full text pattern that can query FTS3 and FTS4 virtual tables.

+ +
+
+
+
    +
  • +
    + + + + rawPattern + +
    +
    +
    +
    +
    +
    +

    The raw pattern string. Guaranteed to be a valid FTS3/4 pattern.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let rawPattern: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(rawPattern:) + +
    +
    +
    +
    +
    +
    +

    Creates a pattern from a raw pattern string; throws DatabaseError on +invalid syntax.

    + +

    The pattern syntax is documented at https://www.sqlite.org/fts3.html#full_text_index_queries

    +
    try FTS3Pattern(rawPattern: "and") // OK
    +try FTS3Pattern(rawPattern: "AND") // malformed MATCH expression: [AND]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(rawPattern: String) throws
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a pattern that matches any token found in the input string; +returns nil if no pattern could be built.

    +
    FTS3Pattern(matchingAnyTokenIn: "")        // nil
    +FTS3Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar
    +
    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a pattern that matches all tokens found in the input string; +returns nil if no pattern could be built.

    +
    FTS3Pattern(matchingAllTokensIn: "")        // nil
    +FTS3Pattern(matchingAllTokensIn: "foo bar") // foo bar
    +
    + +
    +
    +
    +
  • +
  • +
    + + + + init(matchingPhrase:) + +
    +
    +
    +
    +
    +
    +

    Creates a pattern that matches a contiguous string; returns nil if no +pattern could be built.

    +
    FTS3Pattern(matchingPhrase: "")        // nil
    +FTS3Pattern(matchingPhrase: "foo bar") // "foo bar"
    +
    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a pattern that matches any token found in the input string; +returns nil if no pattern could be built.

    +
    FTS3Pattern(matchingAnyTokenIn: "")        // nil
    +FTS3Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @available(iOS 8.2, OSX 10.10, *)
    +public init?(matchingAnyTokenIn string: String)
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + string + + +
    +

    The string to turn into an FTS3 pattern

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a pattern that matches all tokens found in the input string; +returns nil if no pattern could be built.

    +
    FTS3Pattern(matchingAllTokensIn: "")        // nil
    +FTS3Pattern(matchingAllTokensIn: "foo bar") // foo bar
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @available(iOS 8.2, OSX 10.10, *)
    +public init?(matchingAllTokensIn string: String)
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + string + + +
    +

    The string to turn into an FTS3 pattern

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(matchingPhrase:) + +
    +
    +
    +
    +
    +
    +

    Creates a pattern that matches a contiguous string; returns nil if no +pattern could be built.

    +
    FTS3Pattern(matchingPhrase: "")        // nil
    +FTS3Pattern(matchingPhrase: "foo bar") // "foo bar"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @available(iOS 8.2, OSX 10.10, *)
    +public init?(matchingPhrase string: String)
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + string + + +
    +

    The string to turn into an FTS3 pattern

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an FTS3Pattern initialized from dbValue, if it contains +a suitable value.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> FTS3Pattern?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/FTS3TokenizerDescriptor.html b/docs/3.3/Structs/FTS3TokenizerDescriptor.html new file mode 100644 index 000000000..1578b6e20 --- /dev/null +++ b/docs/3.3/Structs/FTS3TokenizerDescriptor.html @@ -0,0 +1,997 @@ + + + + FTS3TokenizerDescriptor Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS3TokenizerDescriptor

+
+
+
public struct FTS3TokenizerDescriptor
+ +
+
+

An FTS3 tokenizer, suitable for FTS3 and FTS4 table definitions:

+
db.create(virtualTable: "book", using: FTS4()) { t in
+    t.tokenizer = .simple // FTS3TokenizerDescriptor
+}
+
+ +

See https://www.sqlite.org/fts3.html#tokenizer

+ +
+
+
+
    +
  • +
    + + + + simple + +
    +
    +
    +
    +
    +
    +

    The simple tokenizer.

    +
    db.create(virtualTable: "book", using: FTS4()) { t in
    +    t.tokenizer = .simple
    +}
    +
    + +

    See https://www.sqlite.org/fts3.html#tokenizer

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let simple: FTS3TokenizerDescriptor
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + porter + +
    +
    +
    +
    +
    +
    +

    The porter tokenizer.

    +
    db.create(virtualTable: "book", using: FTS4()) { t in
    +    t.tokenizer = .porter
    +}
    +
    + +

    See https://www.sqlite.org/fts3.html#tokenizer

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let porter: FTS3TokenizerDescriptor
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    The unicode61 tokenizer.

    +
    db.create(virtualTable: "book", using: FTS4()) { t in
    +    t.tokenizer = .unicode61()
    +}
    +
    + +

    See https://www.sqlite.org/fts3.html#tokenizer

    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    The unicode61 tokenizer.

    +
    db.create(virtualTable: "book", using: FTS4()) { t in
    +    t.tokenizer = .unicode61()
    +}
    +
    + +

    See https://www.sqlite.org/fts3.html#tokenizer

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @available(iOS 8.2, OSX 10.10, *)
    +public static func unicode61(removeDiacritics: Bool = true, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS3TokenizerDescriptor
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + removeDiacritics + + +
    +

    If true (the default), then SQLite will strip +diacritics from latin characters.

    +
    +
    + + separators + + +
    +

    Unless empty (the default), SQLite will consider these +characters as token separators.

    +
    +
    + + tokenCharacters + + +
    +

    Unless empty (the default), SQLite will consider +these characters as token characters.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/FTS4.html b/docs/3.3/Structs/FTS4.html new file mode 100644 index 000000000..400d2822c --- /dev/null +++ b/docs/3.3/Structs/FTS4.html @@ -0,0 +1,993 @@ + + + + FTS4 Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS4

+
+
+
public struct FTS4 : VirtualTableModule
+ +
+
+

FTS4 lets you define fts4 virtual tables.

+
// CREATE VIRTUAL TABLE document USING fts4(content)
+try db.create(virtualTable: "document", using: FTS4()) { t in
+    t.column("content")
+}
+
+ +

See https://www.sqlite.org/fts3.html

+ +
+
+
+
    +
  • +
    + + + + init() + +
    +
    +
    +
    +
    +
    +

    Creates a FTS4 module suitable for the Database +create(virtualTable:using:) method.

    +
    // CREATE VIRTUAL TABLE document USING fts4(content)
    +try db.create(virtualTable: "document", using: FTS4()) { t in
    +    t.column("content")
    +}
    +
    + +

    See https://www.sqlite.org/fts3.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init()
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + moduleName + +
    +
    +
    +
    +
    +
    +

    The virtual table module name

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let moduleName: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + makeTableDefinition() + +
    +
    +
    +
    +
    +
    +

    Reserved; part of the VirtualTableModule protocol.

    + +

    See Database.create(virtualTable:using:)

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func makeTableDefinition() -> FTS4TableDefinition
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Reserved; part of the VirtualTableModule protocol.

    + +

    See Database.create(virtualTable:using:)

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func moduleArguments(for definition: FTS4TableDefinition, in db: Database) -> [String]
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Reserved; part of the VirtualTableModule protocol.

    + +

    See Database.create(virtualTable:using:)

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func database(_ db: Database, didCreate tableName: String, using definition: FTS4TableDefinition) throws
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/FTS5.html b/docs/3.3/Structs/FTS5.html new file mode 100644 index 000000000..a3b077024 --- /dev/null +++ b/docs/3.3/Structs/FTS5.html @@ -0,0 +1,928 @@ + + + + FTS5 Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS5

+

FTS5 lets you define fts5 virtual tables.

+
// CREATE VIRTUAL TABLE document USING fts5(content)
+try db.create(virtualTable: "document", using: FTS5()) { t in
+    t.column("content")
+}
+
+ +

See https://www.sqlite.org/fts5.html

+ +
+
+
+
    +
  • +
    + + + + init() + +
    +
    +
    +
    +
    +
    +

    Creates a FTS5 module suitable for the Database +create(virtualTable:using:) method.

    +
    // CREATE VIRTUAL TABLE document USING fts5(content)
    +try db.create(virtualTable: "document", using: FTS5()) { t in
    +    t.column("content")
    +}
    +
    + +

    See https://www.sqlite.org/fts5.html

    + +
    +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + moduleName + +
    +
    +
    +
    +
    +
    +

    The virtual table module name

    + +
    +
    +
    +
  • +
  • +
    + + + + makeTableDefinition() + +
    +
    +
    +
    +
    +
    +

    Don’t use this method.

    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Don’t use this method.

    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Reserved; part of the VirtualTableModule protocol.

    + +

    See Database.create(virtualTable:using:)

    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/FTS5Pattern.html b/docs/3.3/Structs/FTS5Pattern.html new file mode 100644 index 000000000..59bd4bede --- /dev/null +++ b/docs/3.3/Structs/FTS5Pattern.html @@ -0,0 +1,959 @@ + + + + FTS5Pattern Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS5Pattern

+

A full text pattern that can query FTS5 virtual tables.

+ +
+
+
+
    +
  • +
    + + + + rawPattern + +
    +
    +
    +
    +
    +
    +

    The raw pattern string. Guaranteed to be a valid FTS5 pattern.

    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a pattern that matches any token found in the input string; +returns nil if no pattern could be built.

    +
    FTS5Pattern(matchingAnyTokenIn: "")        // nil
    +FTS5Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar
    +
    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a pattern that matches all tokens found in the input string; +returns nil if no pattern could be built.

    +
    FTS5Pattern(matchingAllTokensIn: "")        // nil
    +FTS5Pattern(matchingAllTokensIn: "foo bar") // foo bar
    +
    + +
    +
    +
    +
  • +
  • +
    + + + + init(matchingPhrase:) + +
    +
    +
    +
    +
    +
    +

    Creates a pattern that matches a contiguous string; returns nil if no +pattern could be built.

    +
    FTS5Pattern(matchingPhrase: "")        // nil
    +FTS5Pattern(matchingPhrase: "foo bar") // "foo bar"
    +
    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a pattern that matches a contiguous string prefix; returns +nil if no pattern could be built.

    +
    FTS5Pattern(matchingPrefixPhrase: "")        // nil
    +FTS5Pattern(matchingPrefixPhrase: "foo bar") // ^"foo bar"
    +
    + +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an FTS5Pattern initialized from dbValue, if it +contains a suitable value.

    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/FTS5TokenFlags.html b/docs/3.3/Structs/FTS5TokenFlags.html new file mode 100644 index 000000000..18d902d08 --- /dev/null +++ b/docs/3.3/Structs/FTS5TokenFlags.html @@ -0,0 +1,862 @@ + + + + FTS5TokenFlags Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS5TokenFlags

+

Flags that tell SQLite how to register a token.

+ +

See https://www.sqlite.org/fts5.html#custom_tokenizers

+ +
+
+
+
    +
  • +
    + + + + rawValue + +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
  • +
  • +
    + + + + init(rawValue:) + +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
  • +
  • +
    + + + + colocated + +
    +
    +
    +
    +
    +
    +

    FTS5_TOKEN_COLOCATED

    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/FTS5Tokenization.html b/docs/3.3/Structs/FTS5Tokenization.html new file mode 100644 index 000000000..c1ca843b1 --- /dev/null +++ b/docs/3.3/Structs/FTS5Tokenization.html @@ -0,0 +1,919 @@ + + + + FTS5Tokenization Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS5Tokenization

+

The reason why FTS5 is requesting tokenization.

+ +

See https://www.sqlite.org/fts5.html#custom_tokenizers

+ +
+
+
+
    +
  • +
    + + + + rawValue + +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
  • +
  • +
    + + + + init(rawValue:) + +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
  • +
  • +
    + + + + query + +
    +
    +
    +
    +
    +
    +

    FTS5_TOKENIZE_QUERY

    + +
    +
    +
    +
  • +
  • +
    + + + + prefix + +
    +
    +
    +
    +
    +
    +

    FTS5_TOKENIZE_PREFIX

    + +
    +
    +
    +
  • +
  • +
    + + + + document + +
    +
    +
    +
    +
    +
    +

    FTS5_TOKENIZE_DOCUMENT

    + +
    +
    +
    +
  • +
  • +
    + + + + aux + +
    +
    +
    +
    +
    +
    +

    FTS5_TOKENIZE_AUX

    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/FTS5TokenizerDescriptor.html b/docs/3.3/Structs/FTS5TokenizerDescriptor.html new file mode 100644 index 000000000..b0f3628af --- /dev/null +++ b/docs/3.3/Structs/FTS5TokenizerDescriptor.html @@ -0,0 +1,934 @@ + + + + FTS5TokenizerDescriptor Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS5TokenizerDescriptor

+

An FTS5 tokenizer, suitable for FTS5 table definitions:

+
db.create(virtualTable: "book", using: FTS5()) { t in
+    t.tokenizer = .unicode61() // FTS5TokenizerDescriptor
+}
+
+ +

See https://www.sqlite.org/fts5.html#tokenizers

+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/FetchedRecordsSectionInfo.html b/docs/3.3/Structs/FetchedRecordsSectionInfo.html new file mode 100644 index 000000000..23b3c27b4 --- /dev/null +++ b/docs/3.3/Structs/FetchedRecordsSectionInfo.html @@ -0,0 +1,871 @@ + + + + FetchedRecordsSectionInfo Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FetchedRecordsSectionInfo

+
+
+
public struct FetchedRecordsSectionInfo<Record> where Record : FetchableRecord
+ +
+
+

A section given by a FetchedRecordsController.

+ +
+
+
+
    +
  • +
    + + + + numberOfRecords + +
    +
    +
    +
    +
    +
    +

    The number of records (rows) in the section.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var numberOfRecords: Int { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + records + +
    +
    +
    +
    +
    +
    +

    The array of records in the section.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var records: [Record] { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/ForeignKey.html b/docs/3.3/Structs/ForeignKey.html new file mode 100644 index 000000000..48439b7f5 --- /dev/null +++ b/docs/3.3/Structs/ForeignKey.html @@ -0,0 +1,1019 @@ + + + + ForeignKey Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ForeignKey

+
+
+
public struct ForeignKey
+ +
+
+

A ForeignKey helps building associations when GRDB can’t infer a foreign +key from the database schema.

+ +

Sometimes the database schema does not define any foreign key between two +tables. And sometimes, there are several foreign keys from a table +to another:

+
| Table book   |       | Table person |
+| ------------ |       | ------------ |
+| id           |   +-->• id           |
+| authorId     •---+   | name         |
+| translatorId •---+
+| title        |
+
+ +

When this happens, associations can’t be automatically inferred from the +database schema. GRDB will complain with a fatal error such as Ambiguous +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:

+
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)
+}
+
+ +

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]))
+}
+
+ +

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:

+
struct Book: TableRecord {
+    static let authorForeignKey = ForeignKey(["authorId"], to: ["id"]))
+    static let author = belongsTo(Person.self, using: authorForeignKey)
+}
+
+ +
+
+
+
    +
  • +
    + + + + init(_:to:) + +
    +
    +
    +
    +
    +
    +

    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)
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ originColumns: [String], to destinationColumns: [String]? = nil)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + originColumns + + +
    +

    The columns at the origin of the foreign key.

    +
    +
    + + destinationColumns + + +
    +

    The columns at the destination of the +foreign key. When nil (the default), GRDB automatically uses the +primary key.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:to:) + +
    +
    +
    +
    +
    +
    +

    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)
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ originColumns: [ColumnExpression], to destinationColumns: [ColumnExpression]? = nil)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + originColumns + + +
    +

    The columns at the origin of the foreign key.

    +
    +
    + + destinationColumns + + +
    +

    The columns at the destination of the +foreign key. When nil (the default), GRDB automatically uses the +primary key.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/ForeignKeyInfo.html b/docs/3.3/Structs/ForeignKeyInfo.html new file mode 100644 index 000000000..b783e99ea --- /dev/null +++ b/docs/3.3/Structs/ForeignKeyInfo.html @@ -0,0 +1,932 @@ + + + + ForeignKeyInfo Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ForeignKeyInfo

+
+
+
public struct ForeignKeyInfo
+ +
+
+

You get foreign keys from table names, with the +foreignKeys(on:) method.

+ +
+
+
+
    +
  • +
    + + + + destinationTable + +
    +
    +
    +
    +
    +
    +

    The name of the destination table

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let destinationTable: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + mapping + +
    +
    +
    +
    +
    +
    +

    The column to column mapping

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let mapping: [(origin: String, destination: String)]
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + originColumns + +
    +
    +
    +
    +
    +
    +

    The origin columns

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var originColumns: [String] { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + destinationColumns + +
    +
    +
    +
    +
    +
    +

    The destination columns

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var destinationColumns: [String] { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/HasManyAssociation.html b/docs/3.3/Structs/HasManyAssociation.html new file mode 100644 index 000000000..f558e11b9 --- /dev/null +++ b/docs/3.3/Structs/HasManyAssociation.html @@ -0,0 +1,930 @@ + + + + HasManyAssociation Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

HasManyAssociation

+
+
+
public struct HasManyAssociation<Origin, Destination> : Association
+ +
+
+

The HasMany association 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)
+    ...
+}
+
+ +

HasMany associations 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.

+ +

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)
+}
+
+ +
    +
  1. The author table has a primary key.
  2. +
  3. The book.authorId column is used to link a book to the author it +belongs to.
  4. +
  5. Make the book.authorId column not null if you want SQLite to guarantee +that all books have an author.
  6. +
  7. Create an index on the book.authorId column in order to ease the +selection of an author’s books.
  8. +
  9. Create a foreign key from book.authorId column to authors.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. +See https://sqlite.org/foreignkeys.html#fk_actions for more information.
  10. +
+ +

The example above uses auto-incremented primary keys. But generally +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 +missing foreign key:

+
struct Author: TableRecord {
+    static let books = hasMany(Book.self, using: ForeignKey(...))
+}
+
+ +

See ForeignKey for more information.

+ +
+
+
+
    +
  • +
    + + + + key + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var key: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + forKey(_:) + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func forKey(_ key: String) -> HasManyAssociation<Origin, Destination>
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/HasOneAssociation.html b/docs/3.3/Structs/HasOneAssociation.html new file mode 100644 index 000000000..4fd5f1f7e --- /dev/null +++ b/docs/3.3/Structs/HasOneAssociation.html @@ -0,0 +1,932 @@ + + + + HasOneAssociation Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

HasOneAssociation

+
+
+
public struct HasOneAssociation<Origin, Destination> : Association
+ +
+
+

The HasOne association 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.

+ +

For example, if your application has one database table for countries, and +another for their demographic profiles, you’d declare the association +this way:

+
struct Demographics: TableRecord { ... }
+struct Country: TableRecord {
+    static let demographics = hasOne(Demographics.self)
+    ...
+}
+
+ +

HasOne associations 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.

+ +

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)
+}
+
+ +
    +
  1. The country table has a primary key.
  2. +
  3. The demographics.countryCode column is used to link a demographic +profile to the country it belongs to.
  4. +
  5. Make the demographics.countryCode column not null if you want SQLite to +guarantee that all profiles are linked to a country.
  6. +
  7. Create a unique index on the demographics.countryCode column in order to +guarantee the unicity of any country’s profile.
  8. +
  9. 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.
  10. +
+ +

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:

+
struct Country: FetchableRecord, TableRecord {
+    static let demographics = hasOne(Demographics.self, using: ForeignKey(...))
+}
+
+ +

See ForeignKey for more information.

+ +
+
+
+
    +
  • +
    + + + + key + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var key: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + forKey(_:) + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func forKey(_ key: String) -> HasOneAssociation<Origin, Destination>
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/IndexInfo.html b/docs/3.3/Structs/IndexInfo.html new file mode 100644 index 000000000..d567f4b0a --- /dev/null +++ b/docs/3.3/Structs/IndexInfo.html @@ -0,0 +1,903 @@ + + + + IndexInfo Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

IndexInfo

+
+
+
public struct IndexInfo
+ +
+
+

An index on a database table.

+ +

See Database.indexes(on:)

+ +
+
+
+
    +
  • +
    + + + + name + +
    +
    +
    +
    +
    +
    +

    The name of the index

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let name: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + columns + +
    +
    +
    +
    +
    +
    +

    The indexed columns

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let columns: [String]
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + isUnique + +
    +
    +
    +
    +
    +
    +

    True if the index is unique

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let isUnique: Bool
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/PersistenceConflictPolicy.html b/docs/3.3/Structs/PersistenceConflictPolicy.html new file mode 100644 index 000000000..110f7c526 --- /dev/null +++ b/docs/3.3/Structs/PersistenceConflictPolicy.html @@ -0,0 +1,906 @@ + + + + PersistenceConflictPolicy Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

PersistenceConflictPolicy

+
+
+
public struct PersistenceConflictPolicy
+ +
+
+

The MutablePersistableRecord protocol uses this type in order to handle SQLite +conflicts when records are inserted or updated.

+ +

See MutablePersistableRecord.persistenceConflictPolicy.

+ +

See https://www.sqlite.org/lang_conflict.html

+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/PersistenceContainer.html b/docs/3.3/Structs/PersistenceContainer.html new file mode 100644 index 000000000..77628f1f8 --- /dev/null +++ b/docs/3.3/Structs/PersistenceContainer.html @@ -0,0 +1,890 @@ + + + + PersistenceContainer Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

PersistenceContainer

+
+
+
public struct PersistenceContainer
+ +
+
+

Use persistence containers in the encode(to:) method of your +encodable records:

+
struct Player : MutablePersistableRecord {
+    var id: Int64?
+    var name: String?
+
+    func encode(to container: inout PersistenceContainer) {
+        container["id"] = id
+        container["name"] = name
+    }
+}
+
+ +
+
+
+
    +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Accesses the value associated with the given column.

    + +

    It is undefined behavior to set different values for the same column. +Column names are case insensitive, so defining both name and NAME +is considered undefined behavior.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript(column: String) -> DatabaseValueConvertible? { get set }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Accesses the value associated with the given column.

    + +

    It is undefined behavior to set different values for the same column. +Column names are case insensitive, so defining both name and NAME +is considered undefined behavior.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript(column: ColumnExpression) -> DatabaseValueConvertible? { get set }
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/PrimaryKeyInfo.html b/docs/3.3/Structs/PrimaryKeyInfo.html new file mode 100644 index 000000000..868ba6747 --- /dev/null +++ b/docs/3.3/Structs/PrimaryKeyInfo.html @@ -0,0 +1,939 @@ + + + + PrimaryKeyInfo Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

PrimaryKeyInfo

+
+
+
public struct PrimaryKeyInfo
+ +
+
+

Primary keys are returned from the Database.primaryKey(_:) method.

+ +

When the table’s primary key is the rowid:

+
// CREATE TABLE item (name TEXT)
+let pk = try db.primaryKey("item")
+pk.columns     // ["rowid"]
+pk.rowIDColumn // nil
+pk.isRowID     // true
+
+// CREATE TABLE citizen (
+//   id INTEGER PRIMARY KEY,
+//   name TEXT
+// )
+let pk = try db.primaryKey("citizen")!
+pk.columns     // ["id"]
+pk.rowIDColumn // "id"
+pk.isRowID     // true
+
+ +

When the table’s primary key is not the rowid:

+
// CREATE TABLE country (
+//   isoCode TEXT NOT NULL PRIMARY KEY
+//   name TEXT
+// )
+let pk = db.primaryKey("country")!
+pk.columns     // ["isoCode"]
+pk.rowIDColumn // nil
+pk.isRowID     // false
+
+// CREATE TABLE citizenship (
+//   citizenID INTEGER NOT NULL REFERENCES citizen(id)
+//   countryIsoCode TEXT NOT NULL REFERENCES country(isoCode)
+//   PRIMARY KEY (citizenID, countryIsoCode)
+// )
+let pk = db.primaryKey("citizenship")!
+pk.columns     // ["citizenID", "countryIsoCode"]
+pk.rowIDColumn // nil
+pk.isRowID     // false
+
+ +
+
+
+
    +
  • +
    + + + + columns + +
    +
    +
    +
    +
    +
    +

    The columns in the primary key; this array is never empty.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var columns: [String] { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + rowIDColumn + +
    +
    +
    +
    +
    +
    +

    When not nil, the name of the column that contains the INTEGER PRIMARY KEY.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var rowIDColumn: String? { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + isRowID + +
    +
    +
    +
    +
    +
    +

    When true, the primary key is the rowid:

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var isRowID: Bool { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/QueryInterfaceRequest.html b/docs/3.3/Structs/QueryInterfaceRequest.html new file mode 100644 index 000000000..11297137e --- /dev/null +++ b/docs/3.3/Structs/QueryInterfaceRequest.html @@ -0,0 +1,1623 @@ + + + + QueryInterfaceRequest Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

QueryInterfaceRequest

+
+
+
public struct QueryInterfaceRequest<T>
+ +
+
+

A QueryInterfaceRequest describes an SQL query.

+ +

See https://github.com/groue/GRDB.swift#the-query-interface

+ +
+
+
+ +
    +
  • +
    + + + + matching(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a request with a full-text predicate added to the eventual +set of already applied predicates.

    +
    // SELECT * FROM book WHERE book MATCH '...'
    +var request = Book.all()
    +request = request.matching(pattern)
    +
    + +

    If the search pattern is nil, the request does not match any +database row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest<T>
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + including(optional:) + +
    +
    +
    +
    +
    +
    +

    Creates a request that includes an association. The columns of the +associated record are selected. The returned association does not +require that the associated database table contains a matching row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func including<A>(optional association: A) -> QueryInterfaceRequest<RowDecoder> where T == A.OriginRowDecoder, A : Association
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + including(required:) + +
    +
    +
    +
    +
    +
    +

    Creates a request that includes an association. The columns of the +associated record are selected. The returned association requires +that the associated database table contains a matching row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func including<A>(required association: A) -> QueryInterfaceRequest<RowDecoder> where T == A.OriginRowDecoder, A : Association
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + joining(optional:) + +
    +
    +
    +
    +
    +
    +

    Creates a request that includes an association. The columns of the +associated record are not selected. The returned association does not +require that the associated database table contains a matching row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func joining<A>(optional association: A) -> QueryInterfaceRequest<RowDecoder> where T == A.OriginRowDecoder, A : Association
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + joining(required:) + +
    +
    +
    +
    +
    +
    +

    Creates a request that includes an association. The columns of the +associated record are not selected. The returned association requires +that the associated database table contains a matching row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func joining<A>(required association: A) -> QueryInterfaceRequest<RowDecoder> where T == A.OriginRowDecoder, A : Association
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + RowDecoder + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public typealias RowDecoder = T
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + select(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a request which selects selection.

    +
    // SELECT id, email FROM player
    +var request = Player.all()
    +request = request.select([Column("id"), Column("email")])
    +
    + +

    Any previous selection is replaced:

    +
    // SELECT email FROM player
    +request
    +    .select([Column("id")])
    +    .select([Column("email")])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest<T>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + select(_:as:) + +
    +
    +
    +
    +
    +
    +

    Creates a request which selects selection, and fetches values of +type type.

    +
    try dbQueue.read { db in
    +    // SELECT max(score) FROM player
    +    let request = Player.all().select([max(Column("score"))], as: Int.self)
    +    let maxScore: Int? = try request.fetchOne(db)
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func select<RowDecoder>(_ selection: [SQLSelectable], as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + select(_:as:) + +
    +
    +
    +
    +
    +
    +

    Creates a request which selects selection, and fetches values of +type type.

    +
    try dbQueue.read { db in
    +    // SELECT max(score) FROM player
    +    let request = Player.all().select(max(Column("score")), as: Int.self)
    +    let maxScore: Int? = try request.fetchOne(db)
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func select<RowDecoder>(_ selection: SQLSelectable..., as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder>
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a request which selects sql, and fetches values of +type type.

    +
    try dbQueue.read { db in
    +    // SELECT max(score) FROM player
    +    let request = Player.all().select(sql: "max(score)", as: Int.self)
    +    let maxScore: Int? = try request.fetchOne(db)
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func select<RowDecoder>(sql: String, arguments: StatementArguments? = nil, as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + distinct() + +
    +
    +
    +
    +
    +
    +

    Creates a request which returns distinct rows.

    +
    // SELECT DISTINCT * FROM player
    +var request = Player.all()
    +request = request.distinct()
    +
    +// SELECT DISTINCT name FROM player
    +var request = Player.select(Column("name"))
    +request = request.distinct()
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func distinct() -> QueryInterfaceRequest<T>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + filter(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a request with the provided predicate promise added to the +eventual set of already applied predicates.

    +
    // SELECT * FROM player WHERE 1
    +var request = Player.all()
    +request = request.filter { db in true }
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest<T>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + group(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a request grouped according to expressions.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func group(_ expressions: [SQLExpressible]) -> QueryInterfaceRequest<T>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + having(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a request with the provided predicate added to the +eventual set of already applied predicates.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func having(_ predicate: SQLExpressible) -> QueryInterfaceRequest<T>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + order(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a request with the provided orderings promise.

    +
    // SELECT * FROM player ORDER BY name
    +var request = Player.all()
    +request = request.order { _ in [Column("name")] }
    +
    + +

    Any previous ordering is replaced:

    +
    // SELECT * FROM player ORDER BY name
    +request
    +    .order{ _ in [Column("email")] }
    +    .reversed()
    +    .order{ _ in [Column("name")] }
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceRequest<T>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + reversed() + +
    +
    +
    +
    +
    +
    +

    Creates a request that reverses applied orderings.

    +
    // SELECT * FROM player ORDER BY name DESC
    +var request = Player.all().order(Column("name"))
    +request = request.reversed()
    +
    + +

    If no ordering was applied, the returned request is identical.

    +
    // SELECT * FROM player
    +var request = Player.all()
    +request = request.reversed()
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func reversed() -> QueryInterfaceRequest<T>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + limit(_:offset:) + +
    +
    +
    +
    +
    +
    +

    Creates a request which fetches limit rows, starting at offset.

    +
    // SELECT * FROM player LIMIT 1
    +var request = Player.all()
    +request = request.limit(1)
    +
    + +

    Any previous limit is replaced.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest<T>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + aliased(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a request that allows you to define expressions that target +a specific database table.

    + +

    In the example below, the team.avgScore < player.score condition in +the ON clause could be not achieved without table aliases.

    +
    struct Player: TableRecord {
    +    static let team = belongsTo(Team.self)
    +}
    +
    +// SELECT player.*, team.*
    +// JOIN team ON ... AND team.avgScore < player.score
    +let playerAlias = TableAlias()
    +let request = Player
    +    .all()
    +    .aliased(playerAlias)
    +    .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + asRequest(of:) + +
    +
    +
    +
    +
    +
    +

    Creates a request bound to type Target.

    + +

    The returned request can fetch if the type Target is fetchable (Row, +value, record).

    +
    // Int?
    +let maxScore = try Player
    +    .select(max(scoreColumn))
    +    .asRequest(of: Int.self)    // <--
    +    .fetchOne(db)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func asRequest<Target>(of type: Target.Type) -> QueryInterfaceRequest<Target>
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + type + + +
    +

    The fetched type Target

    +
    +
    +
    +
    +

    Return Value

    +

    A typed request bound to type Target.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + deleteAll(_:) + +
    +
    +
    +
    +
    +
    +

    Deletes matching rows; returns the number of deleted rows.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func deleteAll(_ db: Database) throws -> Int
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    The number of deleted rows

    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/RangeRowAdapter.html b/docs/3.3/Structs/RangeRowAdapter.html new file mode 100644 index 000000000..7cac78269 --- /dev/null +++ b/docs/3.3/Structs/RangeRowAdapter.html @@ -0,0 +1,877 @@ + + + + RangeRowAdapter Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

RangeRowAdapter

+
+
+
public struct RangeRowAdapter : RowAdapter
+ +
+
+

RangeRowAdapter is a row adapter that only exposes a range of columns.

+
let adapter = RangeRowAdapter(1..<3)
+let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz, 4 as qux"
+
+// [bar:2 baz:3]
+try Row.fetchOne(db, sql, adapter: adapter)
+
+ +
+
+
+
    +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a RangeRowAdapter that only exposes a range of columns.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ range: CountableRange<Int>)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a RangeRowAdapter that only exposes a range of columns.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ range: CountableClosedRange<Int>)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/ResultCode.html b/docs/3.3/Structs/ResultCode.html new file mode 100644 index 000000000..0ae7cef71 --- /dev/null +++ b/docs/3.3/Structs/ResultCode.html @@ -0,0 +1,3552 @@ + + + + ResultCode Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ResultCode

+
+
+
public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
+ +
+
+

Undocumented

+ +
+
+
+
    +
  • +
    + + + + rawValue + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let rawValue: Int32
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(rawValue:) + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(rawValue: Int32)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + primaryResultCode + +
    +
    +
    +
    +
    +
    +

    A result code limited to the least significant 8 bits of the receiver. +See https://www.sqlite.org/rescode.html for more information.

    +
    let resultCode = .SQLITE_CONSTRAINT_FOREIGNKEY
    +resultCode.primaryResultCode == .SQLITE_CONSTRAINT // true
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var primaryResultCode: ResultCode { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ~=(_:_:) + +
    +
    +
    +
    +
    +
    +

    Returns true if the code on the left matches the code on the right.

    + +

    Primary result codes match themselves and their extended result codes, +while extended result codes match only themselves:

    +
    switch error.extendedResultCode {
    +case .SQLITE_CONSTRAINT_FOREIGNKEY: // foreign key constraint error
    +case .SQLITE_CONSTRAINT:            // any other constraint error
    +default:                            // any other database error
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func ~= (pattern: ResultCode, code: ResultCode) -> Bool
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_OK + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_OK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_ERROR + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_ERROR: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_INTERNAL + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_INTERNAL: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_PERM + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_PERM: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_ABORT + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_ABORT: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_BUSY + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_BUSY: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_LOCKED + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_LOCKED: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_NOMEM + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_NOMEM: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_READONLY + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_READONLY: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_INTERRUPT + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_INTERRUPT: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_CORRUPT + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CORRUPT: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_NOTFOUND + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_NOTFOUND: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_FULL + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_FULL: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_CANTOPEN + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CANTOPEN: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_PROTOCOL + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_PROTOCOL: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_EMPTY + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_EMPTY: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_SCHEMA + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_SCHEMA: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_TOOBIG + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_TOOBIG: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_CONSTRAINT + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CONSTRAINT: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_MISMATCH + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_MISMATCH: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_MISUSE + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_MISUSE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_NOLFS + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_NOLFS: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_AUTH + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_AUTH: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_FORMAT + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_FORMAT: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_RANGE + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_RANGE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_NOTADB + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_NOTADB: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_NOTICE + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_NOTICE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_WARNING + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_WARNING: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_ROW + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_ROW: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_DONE + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_DONE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_READ + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_READ: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_SHORT_READ: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_WRITE + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_WRITE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_FSYNC + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_FSYNC: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_DIR_FSYNC: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_TRUNCATE + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_TRUNCATE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_FSTAT + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_FSTAT: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_UNLOCK + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_UNLOCK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_RDLOCK + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_RDLOCK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_DELETE + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_DELETE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_BLOCKED + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_BLOCKED: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_NOMEM + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_NOMEM: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_ACCESS + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_ACCESS: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_CHECKRESERVEDLOCK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_LOCK + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_LOCK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_CLOSE + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_CLOSE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_DIR_CLOSE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_SHMOPEN + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_SHMOPEN: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_SHMSIZE + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_SHMSIZE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_SHMLOCK + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_SHMLOCK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_SHMMAP + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_SHMMAP: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_SEEK + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_SEEK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_DELETE_NOENT: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_MMAP + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_MMAP: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_GETTEMPPATH: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_CONVPATH + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_CONVPATH: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_VNODE + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_VNODE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_AUTH + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_AUTH: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_LOCKED_SHAREDCACHE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_BUSY_RECOVERY + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_BUSY_RECOVERY: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_BUSY_SNAPSHOT + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_BUSY_SNAPSHOT: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CANTOPEN_NOTEMPDIR: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_CANTOPEN_ISDIR + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CANTOPEN_ISDIR: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CANTOPEN_FULLPATH: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CANTOPEN_CONVPATH: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_CORRUPT_VTAB + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CORRUPT_VTAB: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_READONLY_RECOVERY: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_READONLY_CANTLOCK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_READONLY_ROLLBACK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_READONLY_DBMOVED: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_ABORT_ROLLBACK + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_ABORT_ROLLBACK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CONSTRAINT_CHECK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CONSTRAINT_COMMITHOOK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CONSTRAINT_FOREIGNKEY: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CONSTRAINT_FUNCTION: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CONSTRAINT_NOTNULL: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CONSTRAINT_PRIMARYKEY: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CONSTRAINT_TRIGGER: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CONSTRAINT_UNIQUE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CONSTRAINT_VTAB: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CONSTRAINT_ROWID: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_NOTICE_RECOVER_WAL: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_NOTICE_RECOVER_ROLLBACK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_WARNING_AUTOINDEX: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_AUTH_USER + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_AUTH_USER: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_OK_LOAD_PERMANENTLY: ResultCode
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/SQLExpressionLiteral.html b/docs/3.3/Structs/SQLExpressionLiteral.html new file mode 100644 index 000000000..a707998db --- /dev/null +++ b/docs/3.3/Structs/SQLExpressionLiteral.html @@ -0,0 +1,921 @@ + + + + SQLExpressionLiteral Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

SQLExpressionLiteral

+
+
+
public struct SQLExpressionLiteral : SQLExpression
+ +
+
+

Experimental

+ +

SQLExpressionLiteral is an expression built from a raw SQL snippet.

+
SQLExpressionLiteral("1 + 2")
+
+ +

The SQL literal may contain ? and colon-prefixed arguments:

+
SQLExpressionLiteral("? + ?", arguments: [1, 2])
+SQLExpressionLiteral(":one + :two", arguments: ["one": 1, "two": 2])
+
+ +
+
+
+
    +
  • +
    + + + + sql + +
    +
    +
    +
    +
    +
    +

    Experimental

    + +

    The SQL literal

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let sql: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + arguments + +
    +
    +
    +
    +
    +
    +

    Experimental

    + +

    Eventual arguments that feed the ? and colon-prefixed arguments in the +SQL literal

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let arguments: StatementArguments?
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:arguments:) + +
    +
    +
    +
    +
    +
    +

    Experimental

    + +

    Creates an SQL literal expression.

    +
    SQLExpressionLiteral("1 + 2")
    +SQLExpressionLiteral("? + ?", arguments: [1, 2])
    +SQLExpressionLiteral(":one + :two", arguments: ["one": 1, "two": 2])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ sql: String, arguments: StatementArguments? = nil)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/SQLFunctionName.html b/docs/3.3/Structs/SQLFunctionName.html new file mode 100644 index 000000000..81a14b630 --- /dev/null +++ b/docs/3.3/Structs/SQLFunctionName.html @@ -0,0 +1,1096 @@ + + + + SQLFunctionName Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

SQLFunctionName

+
+
+
public struct SQLFunctionName : Hashable
+ +
+
+

Experimental

+ +

SQLFunctionName is an SQL function name.

+ +
+
+
+ +
    +
  • +
    + + + + abs + +
    +
    +
    +
    +
    +
    +

    The ABS function name

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let abs: SQLFunctionName
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + avg + +
    +
    +
    +
    +
    +
    +

    The AVG function name

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let avg: SQLFunctionName
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + ifNull + +
    +
    +
    +
    +
    +
    +

    The IFNULL function name

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let ifNull: SQLFunctionName
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + length + +
    +
    +
    +
    +
    +
    +

    The LENGTH function name

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let length: SQLFunctionName
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + max + +
    +
    +
    +
    +
    +
    +

    The MAX function name

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let max: SQLFunctionName
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + min + +
    +
    +
    +
    +
    +
    +

    The MIN function name

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let min: SQLFunctionName
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + sum + +
    +
    +
    +
    +
    +
    +

    The SUM function name

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let sum: SQLFunctionName
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/SQLRequest.html b/docs/3.3/Structs/SQLRequest.html new file mode 100644 index 000000000..597edca19 --- /dev/null +++ b/docs/3.3/Structs/SQLRequest.html @@ -0,0 +1,1102 @@ + + + + SQLRequest Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

SQLRequest

+
+
+
public struct SQLRequest<T> : FetchRequest
+ +
+
+

A FetchRequest built from raw SQL.

+ +
+
+
+
    +
  • +
    + + + + RowDecoder + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public typealias RowDecoder = T
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + sql + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var sql: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + arguments + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var arguments: StatementArguments?
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + adapter + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var adapter: RowAdapter?
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a request from an SQL string, optional arguments, and +optional row adapter.

    +
    let request = SQLRequest("SELECT * FROM player")
    +let request = SQLRequest("SELECT * FROM player WHERE id = ?", arguments: [1])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter.

    +
    +
    + + cached + + +
    +

    Defaults to false. If true, the request reuses a cached +prepared statement.

    +
    +
    +
    +
    +

    Return Value

    +

    A SQLRequest

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates an SQL request from any other fetch request.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init<Request: FetchRequest>(_ db: Database, request: Request, cached: Bool = false) throws where Request.RowDecoder == RowDecoder
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A request.

    +
    +
    + + cached + + +
    +

    Defaults to false. If true, the request reuses a cached +prepared statement.

    +
    +
    +
    +
    +

    Return Value

    +

    An SQLRequest

    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/ScopeAdapter.html b/docs/3.3/Structs/ScopeAdapter.html new file mode 100644 index 000000000..ff191b3b8 --- /dev/null +++ b/docs/3.3/Structs/ScopeAdapter.html @@ -0,0 +1,965 @@ + + + + ScopeAdapter Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ScopeAdapter

+
+
+
public struct ScopeAdapter : RowAdapter
+ +
+
+

ScopeAdapter is a row adapter that lets you define scopes on rows.

+
// Two adapters
+let fooAdapter = ColumnMapping(["value": "foo"])
+let barAdapter = ColumnMapping(["value": "bar"])
+
+// Define scopes
+let adapter = ScopeAdapter([
+    "foo": fooAdapter,
+    "bar": barAdapter])
+
+// Fetch
+let sql = "SELECT 'foo' AS foo, 'bar' AS bar"
+let row = try Row.fetchOne(db, sql, adapter: adapter)!
+
+// Scoped rows:
+if let fooRow = row.scopes["foo"] {
+    fooRow["value"]    // "foo"
+}
+if let barRow = row.scopes["bar"] {
+    barRow["value"]    // "bar"
+}
+
+ +
+
+
+
    +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates an adapter that preserves row contents and add scoped rows.

    + +

    For example:

    +
    let adapter = ScopeAdapter(["suffix": SuffixRowAdapter(fromIndex: 1)])
    +let row = try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: adapter)!
    +row                  // [1, 2, 3]
    +row.scopes["suffix"] // [2, 3]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ scopes: [String : RowAdapter])
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + scopes + + +
    +

    A dictionary that maps scope names to +row adapters.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(base:scopes:) + +
    +
    +
    +
    +
    +
    +

    Creates an adapter based on the base adapter, and add scoped rows.

    + +

    For example:

    +
    let baseAdapter = RangeRowAdapter(0..<1)
    +let adapter = ScopeAdapter(base: baseAdapter, scopes: ["suffix": SuffixRowAdapter(fromIndex: 1)])
    +let row = try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: adapter)!
    +row                   // [1]
    +row.scopes["initial"] // [2, 3]
    +
    + +

    If the base adapter already defines scopes, the given scopes replace +eventual existing scopes with the same name.

    + +

    This initializer is equivalent to baseAdapter.addingScopes(scopes).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(base: RowAdapter, scopes: [String : RowAdapter])
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + base + + +
    +

    A dictionary that maps scope names to +row adapters.

    +
    +
    + + scopes + + +
    +

    A dictionary that maps scope names to +row adapters.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/StatementArguments.html b/docs/3.3/Structs/StatementArguments.html new file mode 100644 index 000000000..8d1a76700 --- /dev/null +++ b/docs/3.3/Structs/StatementArguments.html @@ -0,0 +1,1610 @@ + + + + StatementArguments Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

StatementArguments

+
+
+
public struct StatementArguments : CustomStringConvertible, Equatable, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral
+ +
+
+

StatementArguments provide values to argument placeholders in raw +SQL queries.

+ +

Placeholders can take several forms (see https://www.sqlite.org/lang_expr.html#varparam +for more information):

+ +
    +
  • ?NNN (e.g. ?2): the NNN-th argument (starts at 1)
  • +
  • ?: the N-th argument, where N is one greater than the largest argument +number already assigned
  • +
  • :AAAA (e.g. :name): named argument

  • +
  • $AAAA (e.g. $name): named argument

  • +
+

Positional Arguments

+ +

To fill question marks placeholders, feed StatementArguments with an array:

+
db.execute(
+    "INSERT ... (?, ?)",
+    arguments: StatementArguments(["Arthur", 41]))
+
+// Array literals are automatically converted:
+db.execute(
+    "INSERT ... (?, ?)",
+    arguments: ["Arthur", 41])
+
+

Named Arguments

+ +

To fill named arguments, feed StatementArguments with a dictionary:

+
db.execute(
+    "INSERT ... (:name, :score)",
+    arguments: StatementArguments(["name": "Arthur", "score": 41]))
+
+// Dictionary literals are automatically converted:
+db.execute(
+    "INSERT ... (:name, :score)",
+    arguments: ["name": "Arthur", "score": 41])
+
+

Concatenating Arguments

+ +

Several arguments can be concatenated and mixed with the +append(contentsOf:) method and the +, &+, += operators:

+
var arguments: StatementArguments = ["Arthur"]
+arguments += [41]
+db.execute("INSERT ... (?, ?)", arguments: arguments)
+
+ +

+ and += operators consider that overriding named arguments is a +programmer error:

+
var arguments: StatementArguments = ["name": "Arthur"]
+arguments += ["name": "Barbara"]
+// fatal error: already defined statement argument: name
+
+ +

&+ and append(contentsOf:) allow overriding named arguments:

+
var arguments: StatementArguments = ["name": "Arthur"]
+arguments = arguments &+ ["name": "Barbara"]
+print(arguments)
+// Prints ["name": "Barbara"]
+
+

Mixed Arguments

+ +

It is possible to mix named and positional arguments. Yet this is usually +confusing, and it is best to avoid this practice:

+
let sql = "SELECT ?2 AS two, :foo AS foo, ?1 AS one, :foo AS foo2, :bar AS bar"
+var arguments: StatementArguments = [1, 2, "bar"] + ["foo": "foo"]
+let row = try Row.fetchOne(db, sql, arguments: arguments)!
+print(row)
+// Prints [two:2 foo:"foo" one:1 foo2:"foo" bar:"bar"]
+
+ +

Mixed arguments exist as a support for requests like the following:

+
let players = try Player
+    .filter(sql: "team = :team", arguments: ["team": "Blue"])
+    .filter(sql: "score > ?", arguments: [1000])
+    .fetchAll(db)
+
+ +
+
+
+
    +
  • +
    + + + + isEmpty + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var isEmpty: Bool { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates statement arguments from a sequence of optional values.

    +
    let values: [DatabaseValueConvertible?] = ["foo", 1, nil]
    +db.execute("INSERT ... (?,?,?)", arguments: StatementArguments(values))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init<Sequence>(_ sequence: Sequence) where Sequence : Sequence, Sequence.Element == DatabaseValueConvertible?
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + sequence + + +
    +

    A sequence of DatabaseValueConvertible values.

    +
    +
    +
    +
    +

    Return Value

    +

    A StatementArguments.

    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates statement arguments from a sequence of optional values.

    +
    let values: [String] = ["foo", "bar"]
    +db.execute("INSERT ... (?,?)", arguments: StatementArguments(values))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init<Sequence>(_ sequence: Sequence) where Sequence : Sequence, Sequence.Element : DatabaseValueConvertible
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + sequence + + +
    +

    A sequence of DatabaseValueConvertible values.

    +
    +
    +
    +
    +

    Return Value

    +

    A StatementArguments.

    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates statement arguments from any array. The result is nil unless all +array elements adopt DatabaseValueConvertible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init?(_ array: [Any])
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + array + + +
    +

    An array

    +
    +
    +
    +
    +

    Return Value

    +

    A StatementArguments.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates statement arguments from a sequence of (key, value) dictionary, +such as a dictionary.

    +
    let values: [String: DatabaseValueConvertible?] = ["firstName": nil, "lastName": "Miller"]
    +db.execute("INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ dictionary: [String : DatabaseValueConvertible?])
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + sequence + + +
    +

    A sequence of (key, value) pairs

    +
    +
    +
    +
    +

    Return Value

    +

    A StatementArguments.

    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates statement arguments from a sequence of (key, value) pairs, such +as a dictionary.

    +
    let values: [String: DatabaseValueConvertible?] = ["firstName": nil, "lastName": "Miller"]
    +db.execute("INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init<Sequence>(_ sequence: Sequence) where Sequence : Sequence, Sequence.Element == (String, DatabaseValueConvertible?)
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + sequence + + +
    +

    A sequence of (key, value) pairs

    +
    +
    +
    +
    +

    Return Value

    +

    A StatementArguments.

    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates statement arguments from [AnyHashable: Any].

    + +

    The result is nil unless all dictionary keys are strings, and values +adopt DatabaseValueConvertible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init?(_ dictionary: [AnyHashable : Any])
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + dictionary + + +
    +

    A dictionary.

    +
    +
    +
    +
    +

    Return Value

    +

    A StatementArguments.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + append(contentsOf:) + +
    +
    +
    +
    +
    +
    +

    Extends statement arguments with other arguments.

    + +

    Positional arguments (provided as arrays) are concatenated:

    +
    var arguments: StatementArguments = [1]
    +arguments.append(contentsOf: [2, 3])
    +print(arguments)
    +// Prints [1, 2, 3]
    +
    + +

    Named arguments (provided as dictionaries) are updated:

    +
    var arguments: StatementArguments = ["foo": 1]
    +arguments.append(contentsOf: ["bar": 2])
    +print(arguments)
    +// Prints ["foo": 1, "bar": 2]
    +
    + +

    Arguments that were replaced, if any, are returned:

    +
    var arguments: StatementArguments = ["foo": 1, "bar": 2]
    +let replacedValues = arguments.append(contentsOf: ["foo": 3])
    +print(arguments)
    +// Prints ["foo": 3, "bar": 2]
    +print(replacedValues)
    +// Prints ["foo": 1]
    +
    + +

    You can mix named and positional arguments (see documentation of +the StatementArguments type for more information about mixed arguments):

    +
    var arguments: StatementArguments = ["foo": 1]
    +arguments.append(contentsOf: [2, 3])
    +print(arguments)
    +// Prints ["foo": 1, 2, 3]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public mutating func append(contentsOf arguments: StatementArguments) -> [String : DatabaseValue]
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + +(_:_:) + +
    +
    +
    +
    +
    +
    +

    Creates a new StatementArguments by extending the left-hand size +arguments with the right-hand side arguments.

    + +

    Positional arguments (provided as arrays) are concatenated:

    +
    let arguments: StatementArguments = [1] + [2, 3]
    +print(arguments)
    +// Prints [1, 2, 3]
    +
    + +

    Named arguments (provided as dictionaries) are updated:

    +
    let arguments: StatementArguments = ["foo": 1] + ["bar": 2]
    +print(arguments)
    +// Prints ["foo": 1, "bar": 2]
    +
    + +

    You can mix named and positional arguments (see documentation of +the StatementArguments type for more information about mixed arguments):

    +
    let arguments: StatementArguments = ["foo": 1] + [2, 3]
    +print(arguments)
    +// Prints ["foo": 1, 2, 3]
    +
    + +

    If the arguments on the right-hand side has named parameters that are +already defined on the left, a fatal error is raised:

    +
    let arguments: StatementArguments = ["foo": 1] + ["foo": 2]
    +// fatal error: already defined statement argument: foo
    +
    + +

    This fatal error can be avoided with the &+ operator, or the +append(contentsOf:) method.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func + (lhs: StatementArguments, rhs: StatementArguments) -> StatementArguments
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + &+(_:_:) + +
    +
    +
    +
    +
    +
    +

    Creates a new StatementArguments by extending the left-hand size +arguments with the right-hand side arguments.

    + +

    Positional arguments (provided as arrays) are concatenated:

    +
    let arguments: StatementArguments = [1] &+ [2, 3]
    +print(arguments)
    +// Prints [1, 2, 3]
    +
    + +

    Named arguments (provided as dictionaries) are updated:

    +
    let arguments: StatementArguments = ["foo": 1] &+ ["bar": 2]
    +print(arguments)
    +// Prints ["foo": 1, "bar": 2]
    +
    + +

    You can mix named and positional arguments (see documentation of +the StatementArguments type for more information about mixed arguments):

    +
    let arguments: StatementArguments = ["foo": 1] &+ [2, 3]
    +print(arguments)
    +// Prints ["foo": 1, 2, 3]
    +
    + +

    If a named arguments is defined in both arguments, the right-hand +side wins:

    +
    let arguments: StatementArguments = ["foo": 1] &+ ["foo": 2]
    +print(arguments)
    +// Prints ["foo": 2]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func &+ (lhs: StatementArguments, rhs: StatementArguments) -> StatementArguments
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + +=(_:_:) + +
    +
    +
    +
    +
    +
    +

    Extends the left-hand size arguments with the right-hand side arguments.

    + +

    Positional arguments (provided as arrays) are concatenated:

    +
    var arguments: StatementArguments = [1]
    +arguments += [2, 3]
    +print(arguments)
    +// Prints [1, 2, 3]
    +
    + +

    Named arguments (provided as dictionaries) are updated:

    +
    var arguments: StatementArguments = ["foo": 1]
    +arguments += ["bar": 2]
    +print(arguments)
    +// Prints ["foo": 1, "bar": 2]
    +
    + +

    You can mix named and positional arguments (see documentation of +the StatementArguments type for more information about mixed arguments):

    +
    var arguments: StatementArguments = ["foo": 1]
    +arguments.append(contentsOf: [2, 3])
    +print(arguments)
    +// Prints ["foo": 1, 2, 3]
    +
    + +

    If the arguments on the right-hand side has named parameters that are +already defined on the left, a fatal error is raised:

    +
    var arguments: StatementArguments = ["foo": 1]
    +arguments += ["foo": 2]
    +// fatal error: already defined statement argument: foo
    +
    + +

    This fatal error can be avoided with the &+ operator, or the +append(contentsOf:) method.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func += (lhs: inout StatementArguments, rhs: StatementArguments)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + init(arrayLiteral:) + +
    +
    +
    +
    +
    +
    +

    Returns a StatementArguments from an array literal:

    +
    db.selectRows("SELECT ...", arguments: ["Arthur", 41])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(arrayLiteral elements: DatabaseValueConvertible?...)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Returns a StatementArguments from a dictionary literal:

    +
    db.selectRows("SELECT ...", arguments: ["name": "Arthur", "score": 41])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(dictionaryLiteral elements: (String, DatabaseValueConvertible?)...)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Structs/SuffixRowAdapter.html b/docs/3.3/Structs/SuffixRowAdapter.html new file mode 100644 index 000000000..e8f911ae9 --- /dev/null +++ b/docs/3.3/Structs/SuffixRowAdapter.html @@ -0,0 +1,850 @@ + + + + SuffixRowAdapter Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

SuffixRowAdapter

+
+
+
public struct SuffixRowAdapter : RowAdapter
+ +
+
+

SuffixRowAdapter is a row adapter that hides the first columns in a row.

+
let adapter = SuffixRowAdapter(fromIndex: 2)
+let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
+
+// [baz:3]
+try Row.fetchOne(db, sql, adapter: adapter)
+
+ +
+
+
+
    +
  • +
    + + + + init(fromIndex:) + +
    +
    +
    +
    +
    +
    +

    Creates a SuffixRowAdapter that hides all columns before the +provided index.

    + +

    If index is 0, the layout row is identical to the base row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(fromIndex index: Int)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/Typealiases.html b/docs/3.3/Typealiases.html new file mode 100644 index 000000000..63f18f1c8 --- /dev/null +++ b/docs/3.3/Typealiases.html @@ -0,0 +1,1017 @@ + + + + Type Aliases Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Type Aliases

+

The following type aliases are available globally.

+ +
+
+
+
    +
  • +
    + + + + TraceFunction + +
    +
    +
    +
    +
    +
    +

    A tracing function that takes an SQL string.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public typealias TraceFunction = (String) -> Void
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + SQLiteConnection + +
    +
    +
    +
    +
    +
    +

    A raw SQLite connection, suitable for the SQLite C API.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public typealias SQLiteConnection = OpaquePointer
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + SQLiteStatement + +
    +
    +
    +
    +
    +
    +

    A raw SQLite statement, suitable for the SQLite C API.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public typealias SQLiteStatement = OpaquePointer
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
+
+
    +
  • +
    + + + + FTS5TokenCallback + +
    +
    +
    +
    +
    +
    +

    A low-level SQLite function that lets FTS5Tokenizer notify tokens.

    + +

    See FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:)

    + +
    +
    +
    +
  • +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    A function that lets FTS5WrapperTokenizer notify tokens.

    + +

    See FTS5WrapperTokenizer.accept(token:flags:tokenCallback:)

    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/badge.svg b/docs/3.3/badge.svg new file mode 100644 index 000000000..b28dab66c --- /dev/null +++ b/docs/3.3/badge.svg @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + documentation + + + documentation + + + 89% + + + 89% + + + diff --git a/docs/3.3/css/highlight.css b/docs/3.3/css/highlight.css new file mode 100644 index 000000000..d0db0e13b --- /dev/null +++ b/docs/3.3/css/highlight.css @@ -0,0 +1,200 @@ +/* Credit to https://gist.github.com/wataru420/2048287 */ +.highlight { + /* Comment */ + /* Error */ + /* Keyword */ + /* Operator */ + /* Comment.Multiline */ + /* Comment.Preproc */ + /* Comment.Single */ + /* Comment.Special */ + /* Generic.Deleted */ + /* Generic.Deleted.Specific */ + /* Generic.Emph */ + /* Generic.Error */ + /* Generic.Heading */ + /* Generic.Inserted */ + /* Generic.Inserted.Specific */ + /* Generic.Output */ + /* Generic.Prompt */ + /* Generic.Strong */ + /* Generic.Subheading */ + /* Generic.Traceback */ + /* Keyword.Constant */ + /* Keyword.Declaration */ + /* Keyword.Pseudo */ + /* Keyword.Reserved */ + /* Keyword.Type */ + /* Literal.Number */ + /* Literal.String */ + /* Name.Attribute */ + /* Name.Builtin */ + /* Name.Class */ + /* Name.Constant */ + /* Name.Entity */ + /* Name.Exception */ + /* Name.Function */ + /* Name.Namespace */ + /* Name.Tag */ + /* Name.Variable */ + /* Operator.Word */ + /* Text.Whitespace */ + /* Literal.Number.Float */ + /* Literal.Number.Hex */ + /* Literal.Number.Integer */ + /* Literal.Number.Oct */ + /* Literal.String.Backtick */ + /* Literal.String.Char */ + /* Literal.String.Doc */ + /* Literal.String.Double */ + /* Literal.String.Escape */ + /* Literal.String.Heredoc */ + /* Literal.String.Interpol */ + /* Literal.String.Other */ + /* Literal.String.Regex */ + /* Literal.String.Single */ + /* Literal.String.Symbol */ + /* Name.Builtin.Pseudo */ + /* Name.Variable.Class */ + /* Name.Variable.Global */ + /* Name.Variable.Instance */ + /* Literal.Number.Integer.Long */ } + .highlight .c { + color: #999988; + font-style: italic; } + .highlight .err { + color: #a61717; + background-color: #e3d2d2; } + .highlight .k { + color: #000000; + font-weight: bold; } + .highlight .o { + color: #000000; + font-weight: bold; } + .highlight .cm { + color: #999988; + font-style: italic; } + .highlight .cp { + color: #999999; + font-weight: bold; } + .highlight .c1 { + color: #999988; + font-style: italic; } + .highlight .cs { + color: #999999; + font-weight: bold; + font-style: italic; } + .highlight .gd { + color: #000000; + background-color: #ffdddd; } + .highlight .gd .x { + color: #000000; + background-color: #ffaaaa; } + .highlight .ge { + color: #000000; + font-style: italic; } + .highlight .gr { + color: #aa0000; } + .highlight .gh { + color: #999999; } + .highlight .gi { + color: #000000; + background-color: #ddffdd; } + .highlight .gi .x { + color: #000000; + background-color: #aaffaa; } + .highlight .go { + color: #888888; } + .highlight .gp { + color: #555555; } + .highlight .gs { + font-weight: bold; } + .highlight .gu { + color: #aaaaaa; } + .highlight .gt { + color: #aa0000; } + .highlight .kc { + color: #000000; + font-weight: bold; } + .highlight .kd { + color: #000000; + font-weight: bold; } + .highlight .kp { + color: #000000; + font-weight: bold; } + .highlight .kr { + color: #000000; + font-weight: bold; } + .highlight .kt { + color: #445588; } + .highlight .m { + color: #009999; } + .highlight .s { + color: #d14; } + .highlight .na { + color: #008080; } + .highlight .nb { + color: #0086B3; } + .highlight .nc { + color: #445588; + font-weight: bold; } + .highlight .no { + color: #008080; } + .highlight .ni { + color: #800080; } + .highlight .ne { + color: #990000; + font-weight: bold; } + .highlight .nf { + color: #990000; } + .highlight .nn { + color: #555555; } + .highlight .nt { + color: #000080; } + .highlight .nv { + color: #008080; } + .highlight .ow { + color: #000000; + font-weight: bold; } + .highlight .w { + color: #bbbbbb; } + .highlight .mf { + color: #009999; } + .highlight .mh { + color: #009999; } + .highlight .mi { + color: #009999; } + .highlight .mo { + color: #009999; } + .highlight .sb { + color: #d14; } + .highlight .sc { + color: #d14; } + .highlight .sd { + color: #d14; } + .highlight .s2 { + color: #d14; } + .highlight .se { + color: #d14; } + .highlight .sh { + color: #d14; } + .highlight .si { + color: #d14; } + .highlight .sx { + color: #d14; } + .highlight .sr { + color: #009926; } + .highlight .s1 { + color: #d14; } + .highlight .ss { + color: #990073; } + .highlight .bp { + color: #999999; } + .highlight .vc { + color: #008080; } + .highlight .vg { + color: #008080; } + .highlight .vi { + color: #008080; } + .highlight .il { + color: #009999; } diff --git a/docs/3.3/css/jazzy.css b/docs/3.3/css/jazzy.css new file mode 100644 index 000000000..d62828260 --- /dev/null +++ b/docs/3.3/css/jazzy.css @@ -0,0 +1,337 @@ +html, body, div, span, h1, h3, h4, p, a, code, em, img, ul, li, table, tbody, tr, td { + background: transparent; + border: 0; + margin: 0; + outline: 0; + padding: 0; + vertical-align: baseline; } + +body { + background-color: #f2f2f2; + font-family: Helvetica, freesans, Arial, sans-serif; + font-size: 14px; + -webkit-font-smoothing: subpixel-antialiased; + word-wrap: break-word; } + +h1, h2, h3 { + margin-top: 0.8em; + margin-bottom: 0.3em; + font-weight: 100; + color: black; } + +h1 { + font-size: 2.5em; } + +h2 { + font-size: 2em; + border-bottom: 1px solid #e2e2e2; } + +h4 { + font-size: 13px; + line-height: 1.5; + margin-top: 21px; } + +h5 { + font-size: 1.1em; } + +h6 { + font-size: 1.1em; + color: #777; } + +.section-name { + color: gray; + display: block; + font-family: Helvetica; + font-size: 22px; + font-weight: 100; + margin-bottom: 15px; } + +pre, code { + font: 0.95em Menlo, monospace; + color: #777; + word-wrap: normal; } + +p code, li code { + background-color: #eee; + padding: 2px 4px; + border-radius: 4px; } + +a { + color: #0088cc; + text-decoration: none; } + +ul { + padding-left: 15px; } + +li { + line-height: 1.8em; } + +img { + max-width: 100%; } + +blockquote { + margin-left: 0; + padding: 0 10px; + border-left: 4px solid #ccc; } + +.content-wrapper { + margin: 0 auto; + width: 980px; } + +header { + font-size: 0.85em; + line-height: 26px; + background-color: #414141; + position: fixed; + width: 100%; + z-index: 1; } + header img { + padding-right: 6px; + vertical-align: -4px; + height: 16px; } + header a { + color: #fff; } + header p { + float: left; + color: #999; } + header .header-right { + float: right; + margin-left: 16px; } + +#breadcrumbs { + background-color: #f2f2f2; + height: 27px; + padding-top: 17px; + position: fixed; + width: 100%; + z-index: 1; + margin-top: 26px; } + #breadcrumbs #carat { + height: 10px; + margin: 0 5px; } + +.sidebar { + background-color: #f9f9f9; + border: 1px solid #e2e2e2; + overflow-y: auto; + overflow-x: hidden; + position: fixed; + top: 70px; + bottom: 0; + width: 230px; + word-wrap: normal; } + +.nav-groups { + list-style-type: none; + background: #fff; + padding-left: 0; } + +.nav-group-name { + border-bottom: 1px solid #e2e2e2; + font-size: 1.1em; + font-weight: 100; + padding: 15px 0 15px 20px; } + .nav-group-name > a { + color: #333; } + +.nav-group-tasks { + margin-top: 5px; } + +.nav-group-task { + font-size: 0.9em; + list-style-type: none; + white-space: nowrap; } + .nav-group-task a { + color: #888; } + +.main-content { + background-color: #fff; + border: 1px solid #e2e2e2; + margin-left: 246px; + position: absolute; + overflow: hidden; + padding-bottom: 60px; + top: 70px; + width: 734px; } + .main-content p, .main-content a, .main-content code, .main-content em, .main-content ul, .main-content table, .main-content blockquote { + margin-bottom: 1em; } + .main-content p { + line-height: 1.8em; } + .main-content section .section:first-child { + margin-top: 0; + padding-top: 0; } + .main-content section .task-group-section .task-group:first-of-type { + padding-top: 10px; } + .main-content section .task-group-section .task-group:first-of-type .section-name { + padding-top: 15px; } + .main-content section .heading:before { + content: ""; + display: block; + padding-top: 70px; + margin: -70px 0 0; } + +.section { + padding: 0 25px; } + +.highlight { + background-color: #eee; + padding: 10px 12px; + border: 1px solid #e2e2e2; + border-radius: 4px; + overflow-x: auto; } + +.declaration .highlight { + overflow-x: initial; + padding: 0 40px 40px 0; + margin-bottom: -25px; + background-color: transparent; + border: none; } + +.section-name { + margin: 0; + margin-left: 18px; } + +.task-group-section { + padding-left: 6px; + border-top: 1px solid #e2e2e2; } + +.task-group { + padding-top: 0px; } + +.task-name-container a[name]:before { + content: ""; + display: block; + padding-top: 70px; + margin: -70px 0 0; } + +.item { + padding-top: 8px; + width: 100%; + list-style-type: none; } + .item a[name]:before { + content: ""; + display: block; + padding-top: 70px; + margin: -70px 0 0; } + .item code { + background-color: transparent; + padding: 0; } + .item .token { + padding-left: 3px; + margin-left: 15px; + font-size: 11.9px; } + .item .declaration-note { + font-size: .85em; + color: gray; + font-style: italic; } + +.pointer-container { + border-bottom: 1px solid #e2e2e2; + left: -23px; + padding-bottom: 13px; + position: relative; + width: 110%; } + +.pointer { + background: #f9f9f9; + border-left: 1px solid #e2e2e2; + border-top: 1px solid #e2e2e2; + height: 12px; + left: 21px; + top: -7px; + -webkit-transform: rotate(45deg); + -moz-transform: rotate(45deg); + -o-transform: rotate(45deg); + transform: rotate(45deg); + position: absolute; + width: 12px; } + +.height-container { + display: none; + left: -25px; + padding: 0 25px; + position: relative; + width: 100%; + overflow: hidden; } + .height-container .section { + background: #f9f9f9; + border-bottom: 1px solid #e2e2e2; + left: -25px; + position: relative; + width: 100%; + padding-top: 10px; + padding-bottom: 5px; } + +.aside, .language { + padding: 6px 12px; + margin: 12px 0; + border-left: 5px solid #dddddd; + overflow-y: hidden; } + .aside .aside-title, .language .aside-title { + font-size: 9px; + letter-spacing: 2px; + text-transform: uppercase; + padding-bottom: 0; + margin: 0; + color: #aaa; + -webkit-user-select: none; } + .aside p:last-child, .language p:last-child { + margin-bottom: 0; } + +.language { + border-left: 5px solid #cde9f4; } + .language .aside-title { + color: #4b8afb; } + +.aside-warning { + border-left: 5px solid #ff6666; } + .aside-warning .aside-title { + color: #ff0000; } + +.graybox { + border-collapse: collapse; + width: 100%; } + .graybox p { + margin: 0; + word-break: break-word; + min-width: 50px; } + .graybox td { + border: 1px solid #e2e2e2; + padding: 5px 25px 5px 10px; + vertical-align: middle; } + .graybox tr td:first-of-type { + text-align: right; + padding: 7px; + vertical-align: top; + word-break: normal; + width: 40px; } + +.slightly-smaller { + font-size: 0.9em; } + +#footer { + position: absolute; + bottom: 10px; + margin-left: 25px; } + #footer p { + margin: 0; + color: #aaa; + font-size: 0.8em; } + +html.dash header, html.dash #breadcrumbs, html.dash .sidebar { + display: none; } +html.dash .main-content { + width: 980px; + margin-left: 0; + border: none; + width: 100%; + top: 0; + padding-bottom: 0; } +html.dash .height-container { + display: block; } +html.dash .item .token { + margin-left: 0; } +html.dash .content-wrapper { + width: auto; } +html.dash #footer { + position: static; } diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Info.plist b/docs/3.3/docsets/GRDB.docset/Contents/Info.plist new file mode 100644 index 000000000..3208ceda9 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Info.plist @@ -0,0 +1,20 @@ + + + + + CFBundleIdentifier + com.jazzy.grdb + CFBundleName + GRDB + DocSetPlatformFamily + grdb + isDashDocset + + dashIndexFilePath + index.html + isJavaScriptEnabled + + DashDocSetFamily + dashtoc + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes.html new file mode 100644 index 000000000..c4499fc14 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes.html @@ -0,0 +1,2049 @@ + + + + Classes Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Classes

+

The following classes are available globally.

+ +
+
+
+ +
    +
  • +
    + + + + AnyCursor + +
    +
    +
    +
    +
    +
    +

    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.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class AnyCursor<Element> : Cursor
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + Database + +
    +
    +
    +
    +
    +
    +

    A Database connection.

    + +

    You don’t create a database directly. Instead, you use a DatabaseQueue, or +a DatabasePool:

    +
    let dbQueue = DatabaseQueue(...)
    +
    +// The Database is the `db` in the closure:
    +try dbQueue.write { db in
    +    try Player(...).insert(db)
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class Database
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + DatabaseCollation + +
    +
    +
    +
    +
    +
    +

    A Collation is a string comparison function used by SQLite.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class DatabaseCollation
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + DatabaseFunction + +
    +
    +
    +
    +
    +
    +

    An SQL function or aggregate.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class DatabaseFunction : Hashable
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
+
+ +
+
+
    +
  • +
    + + + + AnyDatabaseReader + +
    +
    +
    +
    +
    +
    +

    A type-erased DatabaseReader

    + +

    Instances of AnyDatabaseReader forward their methods to an arbitrary +underlying database reader.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class AnyDatabaseReader : DatabaseReader
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
+
+ +
    +
  • +
    + + + + DatabaseValueCursor + +
    +
    +
    +
    +
    +
    +

    A cursor of database values extracted from a single column. +For example:

    +
    try dbQueue.read { db in
    +    let urls: DatabaseValueCursor<URL> = try URL.fetchCursor(db, "SELECT url FROM link")
    +    while let url = urls.next() { // URL
    +        print(url)
    +    }
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class DatabaseValueCursor<Value> : Cursor where Value : DatabaseValueConvertible
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    A cursor of optional database values extracted from a single column. +For example:

    +
    try dbQueue.read { db in
    +    let urls: NullableDatabaseValueCursor<URL> = try Optional<URL>.fetchCursor(db, "SELECT url FROM link")
    +    while let url = urls.next() { // URL?
    +        print(url)
    +    }
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class NullableDatabaseValueCursor<Value> : Cursor where Value : DatabaseValueConvertible
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + AnyDatabaseWriter + +
    +
    +
    +
    +
    +
    +

    A type-erased DatabaseWriter

    + +

    Instances of AnyDatabaseWriter forward their methods to an arbitrary +underlying database writer.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class AnyDatabaseWriter : DatabaseWriter
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + Row + +
    +
    +
    +
    +
    +
    +

    A database row.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class Row : Equatable, Hashable, RandomAccessCollection, ExpressibleByDictionaryLiteral, CustomStringConvertible, CustomDebugStringConvertible
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + RowCursor + +
    +
    +
    +
    +
    +
    +

    A cursor of database rows. For example:

    +
    try dbQueue.read { db in
    +    let rows: RowCursor = try Row.fetchCursor(db, "SELECT * FROM player")
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class RowCursor : Cursor
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + Statement + +
    +
    +
    +
    +
    +
    +

    A statement represents an SQL query.

    + +

    It is the base class of UpdateStatement that executes update statements, +and SelectStatement that fetches rows.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public class Statement
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + SelectStatement + +
    +
    +
    +
    +
    +
    +

    A subclass of Statement that fetches database rows.

    + +

    You create SelectStatement with the Database.makeSelectStatement() method:

    +
    try dbQueue.read { db in
    +    let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
    +    let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
    +    let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class SelectStatement : Statement
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + StatementCursor + +
    +
    +
    +
    +
    +
    +

    A cursor that iterates a database statement without producing any value. +For example:

    +
    try dbQueue.read { db in
    +    let statement = db.makeSelectStatement("SELECT * FROM player")
    +    let cursor: StatementCursor = statement.makeCursor()
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class StatementCursor : Cursor
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + UpdateStatement + +
    +
    +
    +
    +
    +
    +

    A subclass of Statement that executes SQL queries.

    + +

    You create UpdateStatement with the Database.makeUpdateStatement() method:

    +
    try dbQueue.inTransaction { db in
    +    let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)")
    +    try statement.execute(arguments: ["Arthur"])
    +    try statement.execute(arguments: ["Barbara"])
    +    return .commit
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class UpdateStatement : Statement
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    A cursor of database values extracted from a single column. +For example:

    +
    try dbQueue.read { db in
    +    let names: ColumnCursor<String> = try String.fetchCursor(db, "SELECT name FROM player")
    +    while let name = names.next() { // String
    +        print(name)
    +    }
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class FastDatabaseValueCursor<Value> : Cursor where Value : DatabaseValueConvertible, Value : StatementColumnConvertible
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    A cursor of optional database values extracted from a single column. +For example:

    +
    try dbQueue.read { db in
    +    let emails: NullableColumnCursor<String> = try Optional<String>.fetchCursor(db, "SELECT email FROM player")
    +    while let email = emails.next() { // String?
    +        print(email ?? "<NULL>")
    +    }
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class FastNullableDatabaseValueCursor<Value> : Cursor where Value : DatabaseValueConvertible, Value : StatementColumnConvertible
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + FTS3TableDefinition + +
    +
    +
    +
    +
    +
    +

    The FTS3TableDefinition class lets you define columns of a FTS3 virtual table.

    + +

    You don’t create instances of this class. Instead, you use the Database +create(virtualTable:using:) method:

    +
    try db.create(virtualTable: "document", using: FTS3()) { t in // t is FTS3TableDefinition
    +    t.column("content")
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class FTS3TableDefinition
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + FTS4TableDefinition + +
    +
    +
    +
    +
    +
    +

    The FTS4TableDefinition class lets you define columns of a FTS4 virtual table.

    + +

    You don’t create instances of this class. Instead, you use the Database +create(virtualTable:using:) method:

    +
    try db.create(virtualTable: "document", using: FTS4()) { t in // t is FTS4TableDefinition
    +    t.column("content")
    +}
    +
    + +

    See https://www.sqlite.org/fts3.html

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class FTS4TableDefinition
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + FTS4ColumnDefinition + +
    +
    +
    +
    +
    +
    +

    The FTS4ColumnDefinition class lets you refine a column of an FTS4 +virtual table.

    + +

    You get instances of this class when you create an FTS4 table:

    +
    try db.create(virtualTable: "document", using: FTS4()) { t in
    +    t.column("content")      // FTS4ColumnDefinition
    +}
    +
    + +

    See https://www.sqlite.org/fts3.html

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class FTS4ColumnDefinition
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + FTS5TableDefinition + +
    +
    +
    +
    +
    +
    +

    The FTS5TableDefinition class lets you define columns of a FTS5 virtual table.

    + +

    You don’t create instances of this class. Instead, you use the Database +create(virtualTable:using:) method:

    +
    try db.create(virtualTable: "document", using: FTS5()) { t in // t is FTS5TableDefinition
    +    t.column("content")
    +}
    +
    + +

    See https://www.sqlite.org/fts5.html

    + + See more +
    +
    +
    +
  • +
  • +
    + + + + FTS5ColumnDefinition + +
    +
    +
    +
    +
    +
    +

    The FTS5ColumnDefinition class lets you refine a column of an FTS5 +virtual table.

    + +

    You get instances of this class when you create an FTS5 table:

    +
    try db.create(virtualTable: "document", using: FTS5()) { t in
    +    t.column("content")      // FTS5ColumnDefinition
    +}
    +
    + +

    See https://www.sqlite.org/fts5.html

    + + See more +
    +
    +
    +
  • +
+
+
+ + +
+
+
    +
  • +
    + + + + TableDefinition + +
    +
    +
    +
    +
    +
    +

    The TableDefinition class lets you define table columns and constraints.

    + +

    You don’t create instances of this class. Instead, you use the Database +create(table:) method:

    +
    try db.create(table: "player") { t in // t is TableDefinition
    +    t.column(...)
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class TableDefinition
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + TableAlteration + +
    +
    +
    +
    +
    +
    +

    The TableAlteration class lets you alter database tables.

    + +

    You don’t create instances of this class. Instead, you use the Database +alter(table:) method:

    +
    try db.alter(table: "player") { t in // t is TableAlteration
    +    t.add(column: ...)
    +}
    +
    + +

    See https://www.sqlite.org/lang_altertable.html

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class TableAlteration
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ColumnDefinition + +
    +
    +
    +
    +
    +
    +

    The ColumnDefinition class lets you refine a table column.

    + +

    You get instances of this class when you create or alter a database table:

    +
    try db.create(table: "player") { t in
    +    t.column(...)      // ColumnDefinition
    +}
    +
    +try db.alter(table: "player") { t in
    +    t.add(column: ...) // ColumnDefinition
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html and +https://www.sqlite.org/lang_altertable.html

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class ColumnDefinition
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + RecordCursor + +
    +
    +
    +
    +
    +
    +

    A cursor of records. For example:

    +
    struct Player : FetchableRecord { ... }
    +try dbQueue.read { db in
    +    let players: RecordCursor<Player> = try Player.fetchCursor(db, "SELECT * FROM player")
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public final class RecordCursor<Record> : Cursor where Record : FetchableRecord
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
+
+
+ + + +

Record

+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/AnyCursor.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/AnyCursor.html new file mode 100644 index 000000000..86092b150 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/AnyCursor.html @@ -0,0 +1,938 @@ + + + + AnyCursor Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

AnyCursor

+
+
+
public final class AnyCursor<Element> : Cursor
+ +
+
+

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.

+ +
+
+
+
    +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a cursor that wraps a base cursor but whose type depends only on +the base cursor’s element type

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init<C>(_ base: C) where Element == C.Element, C : Cursor
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(iterator:) + +
    +
    +
    +
    +
    +
    +

    Creates a cursor that wraps a base iterator but whose type depends only +on the base iterator’s element type

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public convenience init<I>(iterator: I) where Element == I.Element, I : IteratorProtocol
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a cursor that wraps a base sequence but whose type depends only +on the base sequence’s element type

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public convenience init<S>(_ s: S) where Element == S.Element, S : Sequence
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a cursor that wraps the given closure in its next() method

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ body: @escaping () throws -> Element?)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/AnyDatabaseReader.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/AnyDatabaseReader.html new file mode 100644 index 000000000..fa676b463 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/AnyDatabaseReader.html @@ -0,0 +1,844 @@ + + + + AnyDatabaseReader Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

AnyDatabaseReader

+
+
+
public final class AnyDatabaseReader : DatabaseReader
+ +
+
+

A type-erased DatabaseReader

+ +

Instances of AnyDatabaseReader forward their methods to an arbitrary +underlying database reader.

+ +
+
+
+
    +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a database reader that wraps a base database reader.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ base: DatabaseReader)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/AnyDatabaseWriter.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/AnyDatabaseWriter.html new file mode 100644 index 000000000..28d8b0f8d --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/AnyDatabaseWriter.html @@ -0,0 +1,844 @@ + + + + AnyDatabaseWriter Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

AnyDatabaseWriter

+
+
+
public final class AnyDatabaseWriter : DatabaseWriter
+ +
+
+

A type-erased DatabaseWriter

+ +

Instances of AnyDatabaseWriter forward their methods to an arbitrary +underlying database writer.

+ +
+
+
+
    +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a database writer that wraps a base database writer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ base: DatabaseWriter)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/ColumnDefinition.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/ColumnDefinition.html new file mode 100644 index 000000000..0af1579a4 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/ColumnDefinition.html @@ -0,0 +1,1461 @@ + + + + ColumnDefinition Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ColumnDefinition

+
+
+
public final class ColumnDefinition
+ +
+
+

The ColumnDefinition class lets you refine a table column.

+ +

You get instances of this class when you create or alter a database table:

+
try db.create(table: "player") { t in
+    t.column(...)      // ColumnDefinition
+}
+
+try db.alter(table: "player") { t in
+    t.add(column: ...) // ColumnDefinition
+}
+
+ +

See https://www.sqlite.org/lang_createtable.html and +https://www.sqlite.org/lang_altertable.html

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Adds a primary key constraint on the column.

    +
    try db.create(table: "player") { t in
    +    t.column("id", .integer).primaryKey()
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#primkeyconst and +https://www.sqlite.org/lang_createtable.html#rowid

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func primaryKey(onConflict conflictResolution: Database.ConflictResolution? = nil, autoincrement: Bool = false) -> Self
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + conflitResolution + + +
    +

    An optional conflict resolution +(see https://www.sqlite.org/lang_conflict.html).

    +
    +
    + + autoincrement + + +
    +

    If true, the primary key is autoincremented.

    +
    +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
  • +
    + + + + notNull(onConflict:) + +
    +
    +
    +
    +
    +
    +

    Adds a NOT NULL constraint on the column.

    +
    try db.create(table: "player") { t in
    +    t.column("name", .text).notNull()
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#notnullconst

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func notNull(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + conflitResolution + + +
    +

    An optional conflict resolution +(see https://www.sqlite.org/lang_conflict.html).

    +
    +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
  • +
    + + + + unique(onConflict:) + +
    +
    +
    +
    +
    +
    +

    Adds a UNIQUE constraint on the column.

    +
    try db.create(table: "player") { t in
    +    t.column("email", .text).unique()
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#uniqueconst

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func unique(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + conflitResolution + + +
    +

    An optional conflict resolution +(see https://www.sqlite.org/lang_conflict.html).

    +
    +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
  • +
    + + + + indexed() + +
    +
    +
    +
    +
    +
    +

    Adds an index of the column.

    +
    try db.create(table: "player") { t in
    +    t.column("email", .text).indexed()
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#uniqueconst

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func indexed() -> Self
    + +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
  • +
    + + + + check(_:) + +
    +
    +
    +
    +
    +
    +

    Adds a CHECK constraint on the column.

    +
    try db.create(table: "player") { t in
    +    t.column("name", .text).check { length($0) > 0 }
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#ckconst

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func check(_ condition: (Column) -> SQLExpressible) -> Self
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + condition + + +
    +

    A closure whose argument is an Column that +represents the defined column, and returns the expression to check.

    +
    +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
  • +
    + + + + check(sql:) + +
    +
    +
    +
    +
    +
    +

    Adds a CHECK constraint on the column.

    +
    try db.create(table: "player") { t in
    +    t.column("name", .text).check(sql: "LENGTH(name) > 0")
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#ckconst

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func check(sql: String) -> Self
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + sql + + +
    +

    An SQL snippet.

    +
    +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
  • +
    + + + + defaults(to:) + +
    +
    +
    +
    +
    +
    +

    Defines the default column value.

    +
    try db.create(table: "player") { t in
    +    t.column("name", .text).defaults(to: "Anonymous")
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#dfltval

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func defaults(to value: DatabaseValueConvertible) -> Self
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + value + + +
    +

    A DatabaseValueConvertible value.

    +
    +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
  • +
    + + + + defaults(sql:) + +
    +
    +
    +
    +
    +
    +

    Defines the default column value.

    +
    try db.create(table: "player") { t in
    +    t.column("creationDate", .DateTime).defaults(sql: "CURRENT_TIMESTAMP")
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#dfltval

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func defaults(sql: String) -> Self
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + sql + + +
    +

    An SQL snippet.

    +
    +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
  • +
    + + + + collate(_:) + +
    +
    +
    +
    +
    +
    +
    try db.create(table: "player") { t in
    +    t.column("email", .text).collate(.nocase)
    +}
    +
    + +

    See https://www.sqlite.org/datatype3.html#collation

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func collate(_ collation: Database.CollationName) -> Self
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + collation + + +
    +

    An Database.CollationName.

    +
    +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
  • +
    + + + + collate(_:) + +
    +
    +
    +
    +
    +
    +
    try db.create(table: "player") { t in
    +    t.column("name", .text).collate(.localizedCaseInsensitiveCompare)
    +}
    +
    + +

    See https://www.sqlite.org/datatype3.html#collation

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func collate(_ collation: DatabaseCollation) -> Self
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + collation + + +
    +

    A custom DatabaseCollation.

    +
    +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Defines a foreign key.

    +
    try db.create(table: "book") { t in
    +    t.column("authorId", .integer).references("author", onDelete: .cascade)
    +}
    +
    + +

    See https://www.sqlite.org/foreignkeys.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func references(_ table: String, column: String? = nil, onDelete deleteAction: Database.ForeignKeyAction? = nil, onUpdate updateAction: Database.ForeignKeyAction? = nil, deferred: Bool = false) -> Self
    + +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database.html new file mode 100644 index 000000000..92ca30c96 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database.html @@ -0,0 +1,3707 @@ + + + + Database Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Database

+
+
+
public final class Database
+ +
+
+

A Database connection.

+ +

You don’t create a database directly. Instead, you use a DatabaseQueue, or +a DatabasePool:

+
let dbQueue = DatabaseQueue(...)
+
+// The Database is the `db` in the closure:
+try dbQueue.write { db in
+    try Player(...).insert(db)
+}
+
+ +
+
+
+ + +
+
+ +
    +
  • +
    + + + + logError + +
    +
    +
    +
    +
    +
    +

    The error logging function.

    + +

    Quoting https://www.sqlite.org/errlog.html:

    + +
    +

    SQLite can be configured to invoke a callback function containing an +error code and a terse error message whenever anomalies occur. This +mechanism is very helpful in tracking obscure problems that occur +rarely and in the field. Application developers are encouraged to take +advantage of the error logging facility of SQLite in their products, +as it is very low CPU and memory cost but can be a huge aid +for debugging.

    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static var logError: Database.LogErrorFunction? { get set }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + configuration + +
    +
    +
    +
    +
    +
    +

    The database configuration

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let configuration: Configuration
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + lastInsertedRowID + +
    +
    +
    +
    +
    +
    +

    The rowID of the most recently inserted row.

    + +

    If no row has ever been inserted using this database connection, +returns zero.

    + +

    For more detailed information, see https://www.sqlite.org/c3ref/last_insert_rowid.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var lastInsertedRowID: Int64 { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + changesCount + +
    +
    +
    +
    +
    +
    +

    The number of rows modified, inserted or deleted by the most recent +successful INSERT, UPDATE or DELETE statement.

    + +

    For more detailed information, see https://www.sqlite.org/c3ref/changes.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var changesCount: Int { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + totalChangesCount + +
    +
    +
    +
    +
    +
    +

    The total number of rows modified, inserted or deleted by all successful +INSERT, UPDATE or DELETE statements since the database connection was +opened.

    + +

    For more detailed information, see https://www.sqlite.org/c3ref/total_changes.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var totalChangesCount: Int { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + isInsideTransaction + +
    +
    +
    +
    +
    +
    +

    True if the database connection is currently in a transaction.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var isInsideTransaction: Bool { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + clearSchemaCache() + +
    +
    +
    +
    +
    +
    +

    Clears the database schema cache.

    + +

    You may need to clear the cache manually if the database schema is +modified by another connection.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func clearSchemaCache()
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + tableExists(_:) + +
    +
    +
    +
    +
    +
    +

    Returns whether a table exists.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func tableExists(_ tableName: String) throws -> Bool
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns whether a table is an internal SQLite table.

    + +

    Those are tables whose name begins with sqlite_.

    + +

    For more information, see https://www.sqlite.org/fileformat2.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func isSQLiteInternalTable(_ tableName: String) -> Bool
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns whether a table is an internal GRDB table.

    + +

    Those are tables whose name begins with grdb_.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func isGRDBInternalTable(_ tableName: String) -> Bool
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + viewExists(_:) + +
    +
    +
    +
    +
    +
    +

    Returns whether a view exists.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func viewExists(_ viewName: String) throws -> Bool
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + triggerExists(_:) + +
    +
    +
    +
    +
    +
    +

    Returns whether a trigger exists.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func triggerExists(_ triggerName: String) throws -> Bool
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + primaryKey(_:) + +
    +
    +
    +
    +
    +
    +

    The primary key for table named tableName.

    + +

    All tables have a primary key, even when it is not explicit. When a +table has no explicit primary key, the result is the hidden +rowid column.

    +
    +

    Throws

    + A DatabaseError if table does not exist. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + indexes(on:) + +
    +
    +
    +
    +
    +
    +

    The indexes on table named tableName; returns the empty array if the +table does not exist.

    + +

    Note: SQLite does not define any index for INTEGER PRIMARY KEY columns: +this method does not return any index that represents this primary key.

    + +

    If you want to know if a set of columns uniquely identify a row, prefer +table(_:hasUniqueKey:) instead.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func indexes(on tableName: String) throws -> [IndexInfo]
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    True if a sequence of columns uniquely identifies a row, that is to say +if the columns are the primary key, or if there is a unique index on them.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func table<T>(_ tableName: String, hasUniqueKey columns: T) throws -> Bool where T : Sequence, T.Element == String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + foreignKeys(on:) + +
    +
    +
    +
    +
    +
    +

    The foreign keys defined on table named tableName.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func foreignKeys(on tableName: String) throws -> [ForeignKeyInfo]
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + columns(in:) + +
    +
    +
    +
    +
    +
    +

    The columns in the table named tableName

    +
    +

    Throws

    + A DatabaseError if table does not exist. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func columns(in tableName: String) throws -> [ColumnInfo]
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Returns a new prepared statement that can be reused.

    +
    let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
    +let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
    +let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
    +
    +
    +

    Throws

    + A DatabaseError whenever SQLite could not parse the sql query. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func makeSelectStatement(_ sql: String) throws -> SelectStatement
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + sql + + +
    +

    An SQL query.

    +
    +
    +
    +
    +

    Return Value

    +

    A SelectStatement.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns a prepared statement that can be reused.

    +
    let statement = try db.cachedSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
    +let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
    +let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
    +
    + +

    The returned statement may have already been used: it may or may not +contain values for its eventual arguments.

    +
    +

    Throws

    + A DatabaseError whenever SQLite could not parse the sql query. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func cachedSelectStatement(_ sql: String) throws -> SelectStatement
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + sql + + +
    +

    An SQL query.

    +
    +
    +
    +
    +

    Return Value

    +

    An UpdateStatement.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns a new prepared statement that can be reused.

    +
    let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)")
    +try statement.execute(arguments: ["Arthur"])
    +try statement.execute(arguments: ["Barbara"])
    +
    +
    +

    Throws

    + A DatabaseError whenever SQLite could not parse the sql query. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func makeUpdateStatement(_ sql: String) throws -> UpdateStatement
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + sql + + +
    +

    An SQL query.

    +
    +
    +
    +
    +

    Return Value

    +

    An UpdateStatement.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns a prepared statement that can be reused.

    +
    let statement = try db.cachedUpdateStatement("INSERT INTO player (name) VALUES (?)")
    +try statement.execute(arguments: ["Arthur"])
    +try statement.execute(arguments: ["Barbara"])
    +
    + +

    The returned statement may have already been used: it may or may not +contain values for its eventual arguments.

    +
    +

    Throws

    + A DatabaseError whenever SQLite could not parse the sql query. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func cachedUpdateStatement(_ sql: String) throws -> UpdateStatement
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + sql + + +
    +

    An SQL query.

    +
    +
    +
    +
    +

    Return Value

    +

    An UpdateStatement.

    +
    + +
    +
    +
  • +
  • +
    + + + + execute(_:arguments:) + +
    +
    +
    +
    +
    +
    +

    Executes one or several SQL statements, separated by semi-colons.

    +
    try db.execute(
    +    "INSERT INTO player (name) VALUES (:name)",
    +    arguments: ["name": "Arthur"])
    +
    +try db.execute("""
    +    INSERT INTO player (name) VALUES (?);
    +    INSERT INTO player (name) VALUES (?);
    +    INSERT INTO player (name) VALUES (?);
    +    """, arguments; ['Arthur', 'Barbara', 'Craig'])
    +
    + +

    This method may throw a DatabaseError.

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func execute(_ sql: String, arguments: StatementArguments? = nil) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(function:) + +
    +
    +
    +
    +
    +
    +

    Add or redefine an SQL function.

    +
    let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
    +    guard let int = Int.fromDatabaseValue(dbValues[0]) else {
    +        return nil
    +    }
    +    return int + 1
    +}
    +db.add(function: fn)
    +try Int.fetchOne(db, "SELECT succ(1)")! // 2
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func add(function: DatabaseFunction)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + remove(function:) + +
    +
    +
    +
    +
    +
    +

    Remove an SQL function.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func remove(function: DatabaseFunction)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(collation:) + +
    +
    +
    +
    +
    +
    +

    Add or redefine a collation.

    +
    let collation = DatabaseCollation("localized_standard") { (string1, string2) in
    +    return (string1 as NSString).localizedStandardCompare(string2)
    +}
    +db.add(collation: collation)
    +try db.execute("CREATE TABLE files (name TEXT COLLATE localized_standard")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func add(collation: DatabaseCollation)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + remove(collation:) + +
    +
    +
    +
    +
    +
    +

    Remove a collation.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func remove(collation: DatabaseCollation)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + inTransaction(_:_:) + +
    +
    +
    +
    +
    +
    +

    Executes a block inside a database transaction.

    +
    try dbQueue.inDatabase do {
    +    try db.inTransaction {
    +        try db.execute("INSERT ...")
    +        return .commit
    +    }
    +}
    +
    + +

    If the block throws an error, the transaction is rollbacked and the +error is rethrown.

    + +

    This method is not reentrant: you can’t nest transactions.

    +
    +

    Throws

    + The error thrown by the block. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func inTransaction(_ kind: TransactionKind? = nil, _ block: () throws -> TransactionCompletion) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + kind + + +
    +

    The transaction type (default nil). If nil, the transaction +type is configuration.defaultTransactionKind, which itself +defaults to .deferred. See https://www.sqlite.org/lang_transaction.html +for more information.

    +
    +
    + + block + + +
    +

    A block that executes SQL statements and return either +.commit or .rollback.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + inSavepoint(_:) + +
    +
    +
    +
    +
    +
    +

    Executes a block inside a savepoint.

    +
    try dbQueue.inDatabase do {
    +    try db.inSavepoint {
    +        try db.execute("INSERT ...")
    +        return .commit
    +    }
    +}
    +
    + +

    If the block throws an error, the savepoint is rollbacked and the +error is rethrown.

    + +

    This method is reentrant: you can nest savepoints.

    +
    +

    Throws

    + The error thrown by the block. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func inSavepoint(_ block: () throws -> TransactionCompletion) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + block + + +
    +

    A block that executes SQL statements and return +either .commit or .rollback.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + beginTransaction(_:) + +
    +
    +
    +
    +
    +
    +

    Begins a database transaction.

    +
    +

    Throws

    + The error thrown by the block. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func beginTransaction(_ kind: TransactionKind? = nil) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + kind + + +
    +

    The transaction type (default nil). If nil, the +transaction type is configuration.defaultTransactionKind, which itself +defaults to .deferred. See https://www.sqlite.org/lang_transaction.html +for more information.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + rollback() + +
    +
    +
    +
    +
    +
    +

    Rollbacks a database transaction.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func rollback() throws
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + commit() + +
    +
    +
    +
    +
    +
    +

    Commits a database transaction.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func commit() throws
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Add a transaction observer, so that it gets notified of +database changes.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func add(transactionObserver: TransactionObserver, extent: TransactionObservationExtent = .observerLifetime)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + transactionObserver + + +
    +

    A transaction observer.

    +
    +
    + + extent + + +
    +

    The duration of the observation. The default is +the observer lifetime (observation lasts until observer +is deallocated).

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Remove a transaction observer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func remove(transactionObserver: TransactionObserver)
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Registers a closure to be executed after the next or current +transaction completion.

    +
    try dbQueue.write { db in
    +    db.afterNextTransactionCommit { _ in
    +        print("success")
    +    }
    +    ...
    +} // prints "success"
    +
    + +

    If the transaction is rollbacked, the closure is not executed.

    + +

    If the transaction is committed, the closure is executed in a protected +dispatch queue, serialized will all database updates.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func afterNextTransactionCommit(_ closure: @escaping (Database) -> ())
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    The extent of a transaction observation

    + +

    See Database.add(transactionObserver:extent:)

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public enum TransactionObservationExtent
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Deletes the synchronization triggers for a synchronized FTS4 table

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func dropFTS4SynchronizationTriggers(forTable tableName: String) throws
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Creates a database table.

    +
    try db.create(table: "place") { t in
    +    t.autoIncrementedPrimaryKey("id")
    +    t.column("title", .text)
    +    t.column("favorite", .boolean).notNull().default(false)
    +    t.column("longitude", .double).notNull()
    +    t.column("latitude", .double).notNull()
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html and +https://www.sqlite.org/withoutrowid.html

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a database table.

    +
    try db.create(table: "place") { t in
    +    t.autoIncrementedPrimaryKey("id")
    +    t.column("title", .text)
    +    t.column("favorite", .boolean).notNull().default(false)
    +    t.column("longitude", .double).notNull()
    +    t.column("latitude", .double).notNull()
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html and +https://www.sqlite.org/withoutrowid.html

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @available(iOS 8.2, OSX 10.10, *)
    +public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, withoutRowID: Bool, body: (TableDefinition) -> Void) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + + + + + +
    + + name + + +
    +

    The table name.

    +
    +
    + + temporary + + +
    +

    If true, creates a temporary table.

    +
    +
    + + ifNotExists + + +
    +

    If false (the default), an error is thrown if the +table already exists. Otherwise, the table is created unless it +already exists.

    +
    +
    + + withoutRowID + + +
    +

    If true, uses WITHOUT ROWID optimization.

    +
    +
    + + body + + +
    +

    A closure that defines table columns and constraints.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a database table.

    +
    try db.create(table: "place") { t in
    +    t.autoIncrementedPrimaryKey("id")
    +    t.column("title", .text)
    +    t.column("favorite", .boolean).notNull().default(false)
    +    t.column("longitude", .double).notNull()
    +    t.column("latitude", .double).notNull()
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, body: (TableDefinition) -> Void) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + name + + +
    +

    The table name.

    +
    +
    + + temporary + + +
    +

    If true, creates a temporary table.

    +
    +
    + + ifNotExists + + +
    +

    If false (the default), an error is thrown if the +table already exists. Otherwise, the table is created unless it +already exists.

    +
    +
    + + body + + +
    +

    A closure that defines table columns and constraints.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + rename(table:to:) + +
    +
    +
    +
    +
    +
    +

    Renames a database table.

    + +

    See https://www.sqlite.org/lang_altertable.html

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func rename(table name: String, to newName: String) throws
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + alter(table:body:) + +
    +
    +
    +
    +
    +
    +

    Modifies a database table.

    +
    try db.alter(table: "player") { t in
    +    t.add(column: "url", .text)
    +}
    +
    + +

    See https://www.sqlite.org/lang_altertable.html

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func alter(table name: String, body: (TableAlteration) -> Void) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + name + + +
    +

    The table name.

    +
    +
    + + body + + +
    +

    A closure that defines table alterations.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + drop(table:) + +
    +
    +
    +
    +
    +
    +

    Deletes a database table.

    + +

    See https://www.sqlite.org/lang_droptable.html

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func drop(table name: String) throws
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates an index.

    +
    try db.create(index: "playerByEmail", on: "player", columns: ["email"])
    +
    + +

    SQLite can also index expressions (https://www.sqlite.org/expridx.html) +and use specific collations. To create such an index, use a raw SQL +query.

    +
    try db.execute("CREATE INDEX ...")
    +
    + +

    See https://www.sqlite.org/lang_createindex.html

    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates an index.

    +
    try db.create(index: "playerByEmail", on: "player", columns: ["email"])
    +
    + +

    SQLite can also index expressions (https://www.sqlite.org/expridx.html) +and use specific collations. To create such an index, use a raw SQL +query.

    +
    try db.execute("CREATE INDEX ...")
    +
    + +

    See https://www.sqlite.org/lang_createindex.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func create(index name: String, on table: String, columns: [String], unique: Bool = false, ifNotExists: Bool = false) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + + + + + +
    + + name + + +
    +

    The index name.

    +
    +
    + + table + + +
    +

    The name of the indexed table.

    +
    +
    + + columns + + +
    +

    The indexed columns.

    +
    +
    + + unique + + +
    +

    If true, creates a unique index.

    +
    +
    + + ifNotExists + + +
    +

    If false, no error is thrown if index already exists.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a partial index.

    +
    try db.create(index: "playerByEmail", on: "player", columns: ["email"], condition: Column("email") != nil)
    +
    + +

    See https://www.sqlite.org/lang_createindex.html, and +https://www.sqlite.org/partialindex.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @available(iOS 8.2, OSX 10.10, *)
    +public func create(index name: String, on table: String, columns: [String], unique: Bool = false, ifNotExists: Bool = false, condition: SQLExpressible) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + name + + +
    +

    The index name.

    +
    +
    + + table + + +
    +

    The name of the indexed table.

    +
    +
    + + columns + + +
    +

    The indexed columns.

    +
    +
    + + unique + + +
    +

    If true, creates a unique index.

    +
    +
    + + ifNotExists + + +
    +

    If false, no error is thrown if index already exists.

    +
    +
    + + condition + + +
    +

    The condition that indexed rows must verify.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + drop(index:) + +
    +
    +
    +
    +
    +
    +

    Deletes a database index.

    + +

    See https://www.sqlite.org/lang_dropindex.html

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func drop(index name: String) throws
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Creates a virtual database table.

    +
    try db.create(virtualTable: "vocabulary", using: "spellfix1")
    +
    + +

    See https://www.sqlite.org/lang_createtable.html

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func create(virtualTable name: String, ifNotExists: Bool = false, using module: String) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + name + + +
    +

    The table name.

    +
    +
    + + ifNotExists + + +
    +

    If false (the default), an error is thrown if the +table already exists. Otherwise, the table is created unless it +already exists.

    +
    +
    + + module + + +
    +

    The name of an SQLite virtual table module.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a virtual database table.

    +
    let module = ...
    +try db.create(virtualTable: "book", using: module) { t in
    +    ...
    +}
    +
    + +

    The type of the closure argument t depends on the type of the module +argument: refer to this module’s documentation.

    + +

    Use this method to create full-text tables using the FTS3, FTS4, or +FTS5 modules:

    +
    try db.create(virtualTable: "book", using: FTS4()) { t in
    +    t.column("title")
    +    t.column("author")
    +    t.column("body")
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func create<Module: VirtualTableModule>(virtualTable tableName: String, ifNotExists: Bool = false, using module: Module, _ body: ((Module.TableDefinition) -> Void)? = nil) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + name + + +
    +

    The table name.

    +
    +
    + + ifNotExists + + +
    +

    If false (the default), an error is thrown if the +table already exists. Otherwise, the table is created unless it +already exists.

    +
    +
    + + module + + +
    +

    a VirtualTableModule

    +
    +
    + + body + + +
    +

    An optional closure that defines the virtual table.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/BusyMode.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/BusyMode.html new file mode 100644 index 000000000..f3febd61c --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/BusyMode.html @@ -0,0 +1,930 @@ + + + + BusyMode Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

BusyMode

+
+
+
public enum BusyMode
+ +
+
+

When there are several connections to a database, a connection may try +to access the database while it is locked by another connection.

+ +

The BusyMode enum describes the behavior of GRDB when such a situation +occurs:

+ +
    +
  • .immediateError: The SQLITE_BUSY error is immediately returned to the +connection that tries to access the locked database.

  • +
  • .timeout: The SQLITE_BUSY error will be returned only if the database +remains locked for more than the specified duration.

  • +
  • .callback: Perform your custom lock handling.

  • +
+ +

To set the busy mode of a database, use Configuration:

+
let configuration = Configuration(busyMode: .timeout(1))
+let dbQueue = DatabaseQueue(path: "...", configuration: configuration)
+
+ +

Relevant SQLite documentation:

+ + + +
+
+
+
    +
  • +
    + + + + immediateError + +
    +
    +
    +
    +
    +
    +

    The SQLITE_BUSY error is immediately returned to the connection that +tries to access the locked database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case immediateError
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + timeout + +
    +
    +
    +
    +
    +
    +

    The SQLITE_BUSY error will be returned only if the database remains +locked for more than the specified duration.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case timeout(TimeInterval)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + callback + +
    +
    +
    +
    +
    +
    +

    A custom callback that is called when a database is locked. +See https://www.sqlite.org/c3ref/busy_handler.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case callback(Database.BusyCallback)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/CheckpointMode.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/CheckpointMode.html new file mode 100644 index 000000000..cf5a85dc7 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/CheckpointMode.html @@ -0,0 +1,931 @@ + + + + CheckpointMode Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

CheckpointMode

+
+
+
public enum CheckpointMode : Int32
+ +
+
+

The available checkpoint modes.

+ +
+
+
+
    +
  • +
    + + + + passive + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case passive = 0
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + full + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case full = 1
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + restart + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case restart = 2
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + truncate + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case truncate = 3
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/CollationName.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/CollationName.html new file mode 100644 index 000000000..3f48fd86c --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/CollationName.html @@ -0,0 +1,933 @@ + + + + CollationName Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

CollationName

+
+
+
public struct CollationName : RawRepresentable, Hashable
+ +
+
+

A built-in SQLite collation.

+ +

See https://www.sqlite.org/datatype3.html#collation

+ +
+
+
+
    +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ rawValue: String)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + binary + +
    +
    +
    +
    +
    +
    +

    The BINARY built-in SQL collation

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let binary: Database.CollationName
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + nocase + +
    +
    +
    +
    +
    +
    +

    The NOCASE built-in SQL collation

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let nocase: Database.CollationName
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + rtrim + +
    +
    +
    +
    +
    +
    +

    The RTRIM built-in SQL collation

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let rtrim: Database.CollationName
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/ColumnType.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/ColumnType.html new file mode 100644 index 000000000..9b5121252 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/ColumnType.html @@ -0,0 +1,1088 @@ + + + + ColumnType Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ColumnType

+
+
+
public struct ColumnType : RawRepresentable, Hashable
+ +
+
+

An SQL column type.

+
try db.create(table: "player") { t in
+    t.autoIncrementedPrimaryKey("id")
+    t.column("title", .text)
+}
+
+ +

See https://www.sqlite.org/datatype3.html

+ +
+
+
+
    +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ rawValue: String)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + text + +
    +
    +
    +
    +
    +
    +

    The TEXT SQL column type

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let text: Database.ColumnType
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + integer + +
    +
    +
    +
    +
    +
    +

    The INTEGER SQL column type

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let integer: Database.ColumnType
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + double + +
    +
    +
    +
    +
    +
    +

    The DOUBLE SQL column type

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let double: Database.ColumnType
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + numeric + +
    +
    +
    +
    +
    +
    +

    The NUMERIC SQL column type

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let numeric: Database.ColumnType
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + boolean + +
    +
    +
    +
    +
    +
    +

    The BOOLEAN SQL column type

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let boolean: Database.ColumnType
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + blob + +
    +
    +
    +
    +
    +
    +

    The BLOB SQL column type

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let blob: Database.ColumnType
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + date + +
    +
    +
    +
    +
    +
    +

    The DATE SQL column type

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let date: Database.ColumnType
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + datetime + +
    +
    +
    +
    +
    +
    +

    The DATETIME SQL column type

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let datetime: Database.ColumnType
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/ConflictResolution.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/ConflictResolution.html new file mode 100644 index 000000000..9c8ec8070 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/ConflictResolution.html @@ -0,0 +1,963 @@ + + + + ConflictResolution Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ConflictResolution

+
+
+
public enum ConflictResolution : String
+ +
+
+

An SQLite conflict resolution.

+ +

See https://www.sqlite.org/lang_conflict.html.

+ +
+
+
+
    +
  • +
    + + + + rollback + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case rollback = "ROLLBACK"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + abort + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case abort = "ABORT"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fail + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case fail = "FAIL"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ignore + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case ignore = "IGNORE"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + replace + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case replace = "REPLACE"
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/ForeignKeyAction.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/ForeignKeyAction.html new file mode 100644 index 000000000..1a0fff2cd --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/ForeignKeyAction.html @@ -0,0 +1,933 @@ + + + + ForeignKeyAction Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ForeignKeyAction

+
+
+
public enum ForeignKeyAction : String
+ +
+
+

A foreign key action.

+ +

See https://www.sqlite.org/foreignkeys.html

+ +
+
+
+
    +
  • +
    + + + + cascade + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case cascade = "CASCADE"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + restrict + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case restrict = "RESTRICT"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + setNull + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case setNull = "SET NULL"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + setDefault + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case setDefault = "SET DEFAULT"
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/TransactionCompletion.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/TransactionCompletion.html new file mode 100644 index 000000000..9642fb09a --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/TransactionCompletion.html @@ -0,0 +1,871 @@ + + + + TransactionCompletion Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

TransactionCompletion

+
+
+
public enum TransactionCompletion
+ +
+
+

The end of a transaction: Commit, or Rollback

+ +
+
+
+
    +
  • +
    + + + + commit + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case commit
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + rollback + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case rollback
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/TransactionKind.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/TransactionKind.html new file mode 100644 index 000000000..fcbf5a292 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/TransactionKind.html @@ -0,0 +1,901 @@ + + + + TransactionKind Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

TransactionKind

+
+
+
public enum TransactionKind : String
+ +
+
+

An SQLite transaction kind. See https://www.sqlite.org/lang_transaction.html

+ +
+
+
+
    +
  • +
    + + + + deferred + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case deferred = "DEFERRED"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + immediate + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case immediate = "IMMEDIATE"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + exclusive + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case exclusive = "EXCLUSIVE"
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/TransactionObservationExtent.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/TransactionObservationExtent.html new file mode 100644 index 000000000..ab3fff484 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Database/TransactionObservationExtent.html @@ -0,0 +1,903 @@ + + + + TransactionObservationExtent Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

TransactionObservationExtent

+
+
+
public enum TransactionObservationExtent
+ +
+
+

The extent of a transaction observation

+ +

See Database.add(transactionObserver:extent:)

+ +
+
+
+
    +
  • +
    + + + + observerLifetime + +
    +
    +
    +
    +
    +
    +

    Observation lasts until observer is deallocated

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case observerLifetime
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + nextTransaction + +
    +
    +
    +
    +
    +
    +

    Observation lasts until the next transaction

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case nextTransaction
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseLifetime + +
    +
    +
    +
    +
    +
    +

    Observation lasts until the database is closed

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case databaseLifetime
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/DatabaseCollation.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/DatabaseCollation.html new file mode 100644 index 000000000..34581dc52 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/DatabaseCollation.html @@ -0,0 +1,1134 @@ + + + + DatabaseCollation Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseCollation

+
+
+
public final class DatabaseCollation
+ +
+
+

A Collation is a string comparison function used by SQLite.

+ +
+
+
+
    +
  • +
    + + + + name + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let name: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:function:) + +
    +
    +
    +
    +
    +
    +

    Creates a collation.

    +
    let collation = DatabaseCollation("localized_standard") { (string1, string2) in
    +    return (string1 as NSString).localizedStandardCompare(string2)
    +}
    +db.add(collation: collation)
    +try db.execute("CREATE TABLE file (name TEXT COLLATE localized_standard")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ name: String, function: @escaping (String, String) -> ComparisonResult)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + name + + +
    +

    The function name.

    +
    +
    + + function + + +
    +

    A function that compares two strings.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + unicodeCompare + +
    +
    +
    +
    +
    +
    +

    A collation, or SQL string comparison function, that compares strings +according to the the Swift built-in == and <= operators.

    + +

    This collation is automatically added by GRDB to your database +connections.

    + +

    You can use it when creating database tables:

    +
    let collationName = DatabaseCollation.caseInsensitiveCompare.name
    +dbQueue.execute(
    +    "CREATE TABLE players (" +
    +        "name TEXT COLLATE \(collationName)" +
    +    ")"
    +)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let unicodeCompare: DatabaseCollation
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    A collation, or SQL string comparison function, that compares strings +according to the the Swift built-in caseInsensitiveCompare(_:) method.

    + +

    This collation is automatically added by GRDB to your database +connections.

    + +

    You can use it when creating database tables:

    +
    let collationName = DatabaseCollation.caseInsensitiveCompare.name
    +dbQueue.execute(
    +    "CREATE TABLE players (" +
    +        "name TEXT COLLATE \(collationName)" +
    +    ")"
    +)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let caseInsensitiveCompare: DatabaseCollation
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    A collation, or SQL string comparison function, that compares strings +according to the the Swift built-in localizedCaseInsensitiveCompare(_:) method.

    + +

    This collation is automatically added by GRDB to your database +connections.

    + +

    You can use it when creating database tables:

    +
    let collationName = DatabaseCollation.localizedCaseInsensitiveCompare.name
    +dbQueue.execute(
    +    "CREATE TABLE players (" +
    +        "name TEXT COLLATE \(collationName)" +
    +    ")"
    +)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let localizedCaseInsensitiveCompare: DatabaseCollation
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + localizedCompare + +
    +
    +
    +
    +
    +
    +

    A collation, or SQL string comparison function, that compares strings +according to the the Swift built-in localizedCompare(_:) method.

    + +

    This collation is automatically added by GRDB to your database +connections.

    + +

    You can use it when creating database tables:

    +
    let collationName = DatabaseCollation.localizedCompare.name
    +dbQueue.execute(
    +    "CREATE TABLE players (" +
    +        "name TEXT COLLATE \(collationName)" +
    +    ")"
    +)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let localizedCompare: DatabaseCollation
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    A collation, or SQL string comparison function, that compares strings +according to the the Swift built-in localizedStandardCompare(_:) method.

    + +

    This collation is automatically added by GRDB to your database +connections.

    + +

    You can use it when creating database tables:

    +
    let collationName = DatabaseCollation.localizedStandardCompare.name
    +dbQueue.execute(
    +    "CREATE TABLE players (" +
    +        "name TEXT COLLATE \(collationName)" +
    +    ")"
    +)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let localizedStandardCompare: DatabaseCollation
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/DatabaseFunction.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/DatabaseFunction.html new file mode 100644 index 000000000..240a4bf7b --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/DatabaseFunction.html @@ -0,0 +1,1374 @@ + + + + DatabaseFunction Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseFunction

+
+
+
public final class DatabaseFunction : Hashable
+ +
+
+

An SQL function or aggregate.

+ +
+
+
+
    +
  • +
    + + + + name + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var name: String { get }
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns an SQL function.

    +
    let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
    +    guard let int = Int.fromDatabaseValue(dbValues[0]) else {
    +        return nil
    +    }
    +    return int + 1
    +}
    +db.add(function: fn)
    +try Int.fetchOne(db, "SELECT succ(1)")! // 2
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + name + + +
    +

    The function name.

    +
    +
    + + argumentCount + + +
    +

    The number of arguments of the function. If +omitted, or nil, the function accepts any number of arguments.

    +
    +
    + + pure + + +
    +

    Whether the function is pure, which means that its results +only depends on its inputs. When a function is pure, SQLite has +the opportunity to perform additional optimizations. Default value +is false.

    +
    +
    + + function + + +
    +

    A function that takes an array of DatabaseValue +arguments, and returns an optional DatabaseValueConvertible such +as Int, String, NSDate, etc. The array is guaranteed to have +exactly argumentCount elements, provided argumentCount is +not nil.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns an SQL aggregate function.

    +
    struct MySum : DatabaseAggregate {
    +    var sum: Int = 0
    +
    +    mutating func step(_ dbValues: [DatabaseValue]) {
    +        if let int = Int.fromDatabaseValue(dbValues[0]) {
    +            sum += int
    +        }
    +    }
    +
    +    func finalize() -> DatabaseValueConvertible? {
    +        return sum
    +    }
    +}
    +
    +let dbQueue = DatabaseQueue()
    +let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
    +dbQueue.add(function: fn)
    +try dbQueue.write { db in
    +    try db.execute("CREATE TABLE test(i)")
    +    try db.execute("INSERT INTO test(i) VALUES (1)")
    +    try db.execute("INSERT INTO test(i) VALUES (2)")
    +    try Int.fetchOne(db, "SELECT mysum(i) FROM test")! // 3
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init<Aggregate: DatabaseAggregate>(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, aggregate: Aggregate.Type)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + name + + +
    +

    The function name.

    +
    +
    + + argumentCount + + +
    +

    The number of arguments of the aggregate. If +omitted, or nil, the aggregate accepts any number of arguments.

    +
    +
    + + pure + + +
    +

    Whether the aggregate is pure, which means that its +results only depends on its inputs. When an aggregate is pure, +SQLite has the opportunity to perform additional optimizations. +Default value is false.

    +
    +
    + + aggregate + + +
    +

    A type that implements the DatabaseAggregate protocol. +For each step of the aggregation, its step method is called with +an array of DatabaseValue arguments. The array is guaranteed to +have exactly argumentCount elements, provided argumentCount is +not nil.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + capitalize + +
    +
    +
    +
    +
    +
    +

    An SQL function that returns the Swift built-in capitalized +String property.

    + +

    The function returns NULL for non-strings values.

    + +

    This function is automatically added by GRDB to your database +connections. It is the function used by the query interface’s +capitalized:

    +
    let nameColumn = Column("name")
    +let request = Player.select(nameColumn.capitalized)
    +let names = try String.fetchAll(dbQueue, request)   // [String]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let capitalize: DatabaseFunction
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + lowercase + +
    +
    +
    +
    +
    +
    +

    An SQL function that returns the Swift built-in lowercased +String property.

    + +

    The function returns NULL for non-strings values.

    + +

    This function is automatically added by GRDB to your database +connections. It is the function used by the query interface’s +lowercased:

    +
    let nameColumn = Column("name")
    +let request = Player.select(nameColumn.lowercased())
    +let names = try String.fetchAll(dbQueue, request)   // [String]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let lowercase: DatabaseFunction
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + uppercase + +
    +
    +
    +
    +
    +
    +

    An SQL function that returns the Swift built-in uppercased +String property.

    + +

    The function returns NULL for non-strings values.

    + +

    This function is automatically added by GRDB to your database +connections. It is the function used by the query interface’s +uppercased:

    +
    let nameColumn = Column("name")
    +let request = Player.select(nameColumn.uppercased())
    +let names = try String.fetchAll(dbQueue, request)   // [String]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let uppercase: DatabaseFunction
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + localizedCapitalize + +
    +
    +
    +
    +
    +
    +

    An SQL function that returns the Swift built-in +localizedCapitalized String property.

    + +

    The function returns NULL for non-strings values.

    + +

    This function is automatically added by GRDB to your database +connections. It is the function used by the query interface’s +localizedCapitalized:

    +
    let nameColumn = Column("name")
    +let request = Player.select(nameColumn.localizedCapitalized)
    +let names = try String.fetchAll(dbQueue, request)   // [String]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
    +public static let localizedCapitalize: DatabaseFunction
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + localizedLowercase + +
    +
    +
    +
    +
    +
    +

    An SQL function that returns the Swift built-in +localizedLowercased String property.

    + +

    The function returns NULL for non-strings values.

    + +

    This function is automatically added by GRDB to your database +connections. It is the function used by the query interface’s +localizedLowercased:

    +
    let nameColumn = Column("name")
    +let request = Player.select(nameColumn.localizedLowercased)
    +let names = try String.fetchAll(dbQueue, request)   // [String]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
    +public static let localizedLowercase: DatabaseFunction
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + localizedUppercase + +
    +
    +
    +
    +
    +
    +

    An SQL function that returns the Swift built-in +localizedUppercased String property.

    + +

    The function returns NULL for non-strings values.

    + +

    This function is automatically added by GRDB to your database +connections. It is the function used by the query interface’s +localizedUppercased:

    +
    let nameColumn = Column("name")
    +let request = Player.select(nameColumn.localizedUppercased)
    +let names = try String.fetchAll(dbQueue, request)   // [String]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
    +public static let localizedUppercase: DatabaseFunction
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/DatabasePool.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/DatabasePool.html new file mode 100644 index 000000000..d832f3eea --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/DatabasePool.html @@ -0,0 +1,1927 @@ + + + + DatabasePool Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabasePool

+
+
+
public final class DatabasePool : DatabaseWriter
+ +
+
+

A DatabasePool grants concurrent accesses to an SQLite database.

+ +
+
+
+ +
    +
  • +
    + + + + path + +
    +
    +
    +
    +
    +
    +

    The path to the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var path: String { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Opens the SQLite database at path path.

    +
    let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
    +
    + +

    Database connections get closed when the database pool gets deallocated.

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(path: String, configuration: Configuration = Configuration()) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + path + + +
    +

    The path to the database file.

    +
    +
    + + configuration + + +
    +

    A configuration.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+ +
    +
  • +
    + + + + releaseMemory() + +
    +
    +
    +
    +
    +
    +

    Free as much memory as possible.

    + +

    This method blocks the current thread until all database accesses are completed.

    + +

    See also setupMemoryManagement(application:)

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func releaseMemory()
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Listens to UIApplicationDidEnterBackgroundNotification and +UIApplicationDidReceiveMemoryWarningNotification in order to release +as much memory as possible.

    + +
      +
    • param application: The UIApplication that will start a background +task to let the database pool release its memory when the application +enters background.
    • +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func setupMemoryManagement(in application: UIApplication)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + read(_:) + +
    +
    +
    +
    +
    +
    +

    Synchronously executes a read-only block in a protected dispatch queue, +and returns its result. The block is wrapped in a deferred transaction.

    +
    let players = try dbPool.read { db in
    +    try Player.fetchAll(...)
    +}
    +
    + +

    The block is completely isolated. Eventual concurrent database updates +are not visible inside the block:

    +
    try dbPool.read { db in
    +    // Those two values are guaranteed to be equal, even if the
    +    // `wine` table is modified between the two requests:
    +    let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +    let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +}
    +
    +try dbPool.read { db in
    +    // Now this value may be different:
    +    let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +}
    +
    + +

    This method is not reentrant.

    +
    +

    Throws

    + The error thrown by the block, or any DatabaseError that would +happen while establishing the read access to the database. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func read<T>(_ block: (Database) throws -> T) throws -> T
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + block + + +
    +

    A block that accesses the database.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + unsafeRead(_:) + +
    +
    +
    +
    +
    +
    +

    Synchronously executes a read-only block in a protected dispatch queue, +and returns its result.

    + +

    The block argument is not isolated: eventual concurrent database updates +are visible inside the block:

    +
    try dbPool.unsafeRead { db in
    +    // Those two values may be different because some other thread
    +    // may have inserted or deleted a wine between the two requests:
    +    let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +    let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +}
    +
    + +

    Cursor iteration is safe, though:

    +
    try dbPool.unsafeRead { db in
    +    // No concurrent update can mess with this iteration:
    +    let rows = try Row.fetchCursor(db, "SELECT ...")
    +    while let row = try rows.next() { ... }
    +}
    +
    + +

    This method is not reentrant.

    +
    +

    Throws

    + The error thrown by the block, or any DatabaseError that would +happen while establishing the read access to the database. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + block + + +
    +

    A block that accesses the database.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Synchronously executes a read-only block in a protected dispatch queue, +and returns its result.

    + +

    The block argument is not isolated: eventual concurrent database updates +are visible inside the block:

    +
    try dbPool.unsafeReentrantRead { db in
    +    // Those two values may be different because some other thread
    +    // may have inserted or deleted a wine between the two requests:
    +    let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +    let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +}
    +
    + +

    Cursor iteration is safe, though:

    +
    try dbPool.unsafeReentrantRead { db in
    +    // No concurrent update can mess with this iteration:
    +    let rows = try Row.fetchCursor(db, "SELECT ...")
    +    while let row = try rows.next() { ... }
    +}
    +
    + +

    This method is reentrant. It is unsafe because it fosters dangerous +concurrency practices.

    +
    +

    Throws

    + The error thrown by the block, or any DatabaseError that would +happen while establishing the read access to the database. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + block + + +
    +

    A block that accesses the database.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Asynchronously executes a read-only block in a protected dispatch queue, +wrapped in a deferred transaction.

    + +

    This method must be called from the writing dispatch queue, outside of a +transaction. You’ll get a fatal error otherwise.

    + +

    The block argument is guaranteed to see the database in the last +committed state at the moment this method is called. Eventual concurrent +database updates are not visible inside the block.

    +
    try dbPool.write { db in
    +    try db.execute("DELETE FROM player")
    +    try dbPool.readFromCurrentState { db in
    +        // Guaranteed to be zero
    +        try Int.fetchOne(db, "SELECT COUNT(*) FROM player")!
    +    }
    +    try db.execute("INSERT INTO player ...")
    +}
    +
    + +

    This method blocks the current thread until the isolation guarantee has +been established, and before the block argument has run.

    +
    +

    Throws

    + The error thrown by the block, or any DatabaseError that would +happen while establishing the read access to the database. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + block + + +
    +

    A block that accesses the database.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + write(_:) + +
    +
    +
    +
    +
    +
    +

    Synchronously executes an update block in a protected dispatch queue, +wrapped inside a transaction, and returns the result of the block.

    + +

    Eventual concurrent database updates are postponed until the block +has executed.

    +
    try dbPool.write { db in
    +    try db.execute(...)
    +}
    +
    + +

    Eventual concurrent reads are guaranteed not to see any changes +performed in the block until they are all saved in the database.

    + +

    This method is not reentrant.

    +
    +

    Throws

    + The error thrown by the block, or by the wrapping transaction. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func write<T>(_ block: (Database) throws -> T) throws -> T
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Synchronously executes a block that takes a database connection, and +returns its result.

    + +

    Eventual concurrent database updates are postponed until the block +has executed.

    + +

    Eventual concurrent reads may see changes performed in the block before +the block completes.

    + +

    The block is guaranteed to be executed outside of a transaction.

    + +

    This method is not reentrant.

    +
    +

    Throws

    + The error thrown by the block. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func writeWithoutTransaction<T>(_ block: (Database) throws -> T) rethrows -> T
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Synchronously executes a block in a protected dispatch queue, wrapped +inside a transaction.

    + +

    Eventual concurrent database updates are postponed until the block +has executed.

    + +

    If the block throws an error, the transaction is rollbacked and the +error is rethrown. If the block returns .rollback, the transaction is +also rollbacked, but no error is thrown.

    +
    try dbPool.writeInTransaction { db in
    +    db.execute(...)
    +    return .commit
    +}
    +
    + +

    Eventual concurrent reads are guaranteed not to see any changes +performed in the block until they are all saved in the database.

    + +

    This method is not reentrant.

    +
    +

    Throws

    + The error thrown by the block, or any error establishing the +transaction. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + kind + + +
    +

    The transaction type (default nil). If nil, the transaction +type is configuration.defaultTransactionKind, which itself +defaults to .deferred. See https://www.sqlite.org/lang_transaction.html +for more information.

    +
    +
    + + block + + +
    +

    A block that executes SQL statements and return either +.commit or .rollback.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Synchronously executes an update block in a protected dispatch queue, +and returns its result.

    + +

    Eventual concurrent database updates are postponed until the block +has executed.

    +
    try dbPool.unsafeReentrantWrite { db in
    +    try db.execute(...)
    +}
    +
    + +

    Eventual concurrent reads may see changes performed in the block before +the block completes.

    + +

    This method is reentrant. It is unsafe because it fosters dangerous +concurrency practices.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(function:) + +
    +
    +
    +
    +
    +
    +

    Add or redefine an SQL function.

    +
    let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
    +    guard let int = Int.fromDatabaseValue(dbValues[0]) else {
    +        return nil
    +    }
    +    return int + 1
    +}
    +dbPool.add(function: fn)
    +try dbPool.read { db in
    +    try Int.fetchOne(db, "SELECT succ(1)") // 2
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func add(function: DatabaseFunction)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + remove(function:) + +
    +
    +
    +
    +
    +
    +

    Remove an SQL function.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func remove(function: DatabaseFunction)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(collation:) + +
    +
    +
    +
    +
    +
    +

    Add or redefine a collation.

    +
    let collation = DatabaseCollation("localized_standard") { (string1, string2) in
    +    return (string1 as NSString).localizedStandardCompare(string2)
    +}
    +dbPool.add(collation: collation)
    +try dbPool.write { db in
    +    try db.execute("CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD")
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func add(collation: DatabaseCollation)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + remove(collation:) + +
    +
    +
    +
    +
    +
    +

    Remove a collation.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func remove(collation: DatabaseCollation)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + makeSnapshot() + +
    +
    +
    +
    +
    +
    +

    Creates a database snapshot.

    + +

    The snapshot sees an unchanging database content, as it existed at the +moment it was created.

    + +

    When you want to control the latest committed changes seen by a +snapshot, create it from the pool’s writer protected dispatch queue:

    +
    let snapshot1 = try dbPool.write { db -> DatabaseSnapshot in
    +    try Player.deleteAll()
    +    return try dbPool.makeSnapshot()
    +}
    +// <- Other threads may modify the database here
    +let snapshot2 = try dbPool.makeSnapshot()
    +
    +try snapshot1.read { db in
    +    // Guaranteed to be zero
    +    try Player.fetchCount(db)
    +}
    +
    +try snapshot2.read { db in
    +    // Could be anything
    +    try Player.fetchCount(db)
    +}
    +
    + +

    It is forbidden to create a snapshot from the writer protected dispatch +queue when a transaction is opened, though, because it is likely a +programmer error:

    +
    try dbPool.write { db in
    +    try db.inTransaction {
    +        try Player.deleteAll()
    +        // fatal error: makeSnapshot() must not be called from inside a transaction
    +        let snapshot = try dbPool.makeSnapshot()
    +        return .commit
    +    }
    +}
    +
    + +

    To avoid this fatal error, create the snapshot before or after the +transaction:

    +
    try dbPool.writeWithoutTransaction { db in
    +    // OK
    +    let snapshot = try dbPool.makeSnapshot()
    +
    +    try db.inTransaction {
    +        try Player.deleteAll()
    +        return .commit
    +    }
    +
    +    // OK
    +    let snapshot = try dbPool.makeSnapshot()
    +}
    +
    + +

    You can create as many snapshots as you need, regardless of the maximum +number of reader connections in the pool.

    + +

    For more information, read about snapshot isolation at https://sqlite.org/isolation.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func makeSnapshot() throws -> DatabaseSnapshot
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Listens to UIApplicationDidEnterBackgroundNotification and +UIApplicationDidReceiveMemoryWarningNotification in order to release +as much memory as possible.

    + +
      +
    • param application: The UIApplication that will start a background +task to let the database pool release its memory when the application +enters background.
    • +
    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/DatabaseQueue.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/DatabaseQueue.html new file mode 100644 index 000000000..6a7e42d8a --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/DatabaseQueue.html @@ -0,0 +1,1628 @@ + + + + DatabaseQueue Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseQueue

+
+
+
public final class DatabaseQueue : DatabaseWriter
+ +
+
+

A DatabaseQueue serializes access to an SQLite database.

+ +
+
+
+ +
    +
  • +
    + + + + configuration + +
    +
    +
    +
    +
    +
    +

    The database configuration

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var configuration: Configuration { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + path + +
    +
    +
    +
    +
    +
    +

    The path to the database file; it is :memory: for in-memory databases.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var path: String { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Opens the SQLite database at path path.

    +
    let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
    +
    + +

    Database connections get closed when the database queue gets deallocated.

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(path: String, configuration: Configuration = Configuration()) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + path + + +
    +

    The path to the database file.

    +
    +
    + + configuration + + +
    +

    A configuration.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(configuration:) + +
    +
    +
    +
    +
    +
    +

    Opens an in-memory SQLite database.

    +
    let dbQueue = DatabaseQueue()
    +
    + +

    Database memory is released when the database queue gets deallocated.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(configuration: Configuration = Configuration())
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + configuration + + +
    +

    A configuration.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + releaseMemory() + +
    +
    +
    +
    +
    +
    +

    Free as much memory as possible.

    + +

    This method blocks the current thread until all database accesses are completed.

    + +

    See also setupMemoryManagement(application:)

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func releaseMemory()
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Listens to UIApplicationDidEnterBackgroundNotification and +UIApplicationDidReceiveMemoryWarningNotification in order to release +as much memory as possible.

    + +
      +
    • param application: The UIApplication that will start a background +task to let the database queue release its memory when the application +enters background.
    • +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func setupMemoryManagement(in application: UIApplication)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + read(_:) + +
    +
    +
    +
    +
    +
    +

    Synchronously executes a read-only block in a protected dispatch queue, +and returns its result.

    +
    let players = try dbQueue.read { db in
    +    try Player.fetchAll(db)
    +}
    +
    + +

    This method is not reentrant.

    + +

    Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and +SQLCipher), attempts to write in the database from this meethod throw a +DatabaseError of resultCode SQLITE_READONLY.

    +
    +

    Throws

    + The error thrown by the block. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func read<T>(_ block: (Database) throws -> T) rethrows -> T
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + block + + +
    +

    A block that accesses the database.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + write(_:) + +
    +
    +
    +
    +
    +
    +

    Synchronously executes a block in a protected dispatch queue, wrapped +inside a transaction.

    + +

    If the block throws an error, the transaction is rollbacked and the +error is rethrown.

    +
    try dbQueue.write { db in
    +    try Player(...).insert(db)
    +}
    +
    + +

    This method is not reentrant.

    +
    +

    Throws

    + An eventual database error, or the error thrown by the block. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func write<T>(_ block: (Database) throws -> T) throws -> T
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + block + + +
    +

    A block that executes SQL statements.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + inTransaction(_:_:) + +
    +
    +
    +
    +
    +
    +

    Synchronously executes a block in a protected dispatch queue, wrapped +inside a transaction.

    + +

    If the block throws an error, the transaction is rollbacked and the +error is rethrown. If the block returns .rollback, the transaction is +also rollbacked, but no error is thrown.

    +
    try dbQueue.inTransaction { db in
    +    try Player(...).insert(db)
    +    return .commit
    +}
    +
    + +

    This method is not reentrant.

    +
    +

    Throws

    + The error thrown by the block. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func inTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + kind + + +
    +

    The transaction type (default nil). If nil, the transaction +type is configuration.defaultTransactionKind, which itself +defaults to .deferred. See https://www.sqlite.org/lang_transaction.html +for more information.

    +
    +
    + + block + + +
    +

    A block that executes SQL statements and return either +.commit or .rollback.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + inDatabase(_:) + +
    +
    +
    +
    +
    +
    +

    Synchronously executes a block in a protected dispatch queue, and +returns its result.

    +
    // INSERT INTO player ...
    +let players = try dbQueue.inDatabase { db in
    +    try Player(...).insert(db)
    +}
    +
    + +

    This method is not reentrant.

    +
    +

    Throws

    + The error thrown by the block. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func inDatabase<T>(_ block: (Database) throws -> T) rethrows -> T
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + block + + +
    +

    A block that accesses the database.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Synchronously executes a block in a protected dispatch queue, and +returns its result.

    +
    // INSERT INTO player ...
    +try dbQueue.unsafeReentrantWrite { db in
    +    try Player(...).insert(db)
    +}
    +
    + +

    This method is reentrant. It is unsafe because it fosters dangerous +concurrency practices.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(function:) + +
    +
    +
    +
    +
    +
    +

    Add or redefine an SQL function.

    +
    let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
    +    guard let int = Int.fromDatabaseValue(dbValues[0]) else {
    +        return nil
    +    }
    +    return int + 1
    +}
    +dbQueue.add(function: fn)
    +try dbQueue.read { db in
    +    try Int.fetchOne(db, "SELECT succ(1)") // 2
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func add(function: DatabaseFunction)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + remove(function:) + +
    +
    +
    +
    +
    +
    +

    Remove an SQL function.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func remove(function: DatabaseFunction)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(collation:) + +
    +
    +
    +
    +
    +
    +

    Add or redefine a collation.

    +
    let collation = DatabaseCollation("localized_standard") { (string1, string2) in
    +    return (string1 as NSString).localizedStandardCompare(string2)
    +}
    +dbQueue.add(collation: collation)
    +try dbQueue.write { db in
    +    try db.execute("CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD")
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func add(collation: DatabaseCollation)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + remove(collation:) + +
    +
    +
    +
    +
    +
    +

    Remove a collation.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func remove(collation: DatabaseCollation)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Listens to UIApplicationDidEnterBackgroundNotification and +UIApplicationDidReceiveMemoryWarningNotification in order to release +as much memory as possible.

    + +
      +
    • param application: The UIApplication that will start a background +task to let the database queue release its memory when the application +enters background.
    • +
    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/DatabaseSnapshot.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/DatabaseSnapshot.html new file mode 100644 index 000000000..8492fe1ae --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/DatabaseSnapshot.html @@ -0,0 +1,1043 @@ + + + + DatabaseSnapshot Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseSnapshot

+
+
+
public class DatabaseSnapshot : DatabaseReader
+ +
+
+

A DatabaseSnapshot sees an unchanging database content, as it existed at the +moment it was created.

+ +

See DatabasePool.makeSnapshot()

+ +

For more information, read about snapshot isolation at https://sqlite.org/isolation.html

+ +
+
+
+ +
    +
  • +
    + + + + read(_:) + +
    +
    +
    +
    +
    +
    +

    Synchronously executes a read-only block that takes a database +connection, and returns its result.

    +
    let players = try snapshot.read { db in
    +    try Player.fetchAll(...)
    +}
    +
    +
    +

    Throws

    + The error thrown by the block. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func read<T>(_ block: (Database) throws -> T) rethrows -> T
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + block + + +
    +

    A block that accesses the database.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(function:) + +
    +
    +
    +
    +
    +
    +

    Add or redefine an SQL function.

    +
    let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
    +    guard let int = Int.fromDatabaseValue(dbValues[0]) else {
    +        return nil
    +    }
    +    return int + 1
    +}
    +snapshot.add(function: fn)
    +try snapshot.read { db in
    +    try Int.fetchOne(db, "SELECT succ(1)") // 2
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func add(function: DatabaseFunction)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + remove(function:) + +
    +
    +
    +
    +
    +
    +

    Remove an SQL function.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func remove(function: DatabaseFunction)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(collation:) + +
    +
    +
    +
    +
    +
    +

    Add or redefine a collation.

    +
    let collation = DatabaseCollation("localized_standard") { (string1, string2) in
    +    return (string1 as NSString).localizedStandardCompare(string2)
    +}
    +snapshot.add(collation: collation)
    +let files = try snapshot.read { db in
    +    try File.fetchAll(db, "SELECT * FROM file ORDER BY name COLLATE localized_standard")
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func add(collation: DatabaseCollation)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + remove(collation:) + +
    +
    +
    +
    +
    +
    +

    Remove a collation.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func remove(collation: DatabaseCollation)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/FTS3TableDefinition.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/FTS3TableDefinition.html new file mode 100644 index 000000000..041aaef04 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/FTS3TableDefinition.html @@ -0,0 +1,907 @@ + + + + FTS3TableDefinition Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS3TableDefinition

+
+
+
public final class FTS3TableDefinition
+ +
+
+

The FTS3TableDefinition class lets you define columns of a FTS3 virtual table.

+ +

You don’t create instances of this class. Instead, you use the Database +create(virtualTable:using:) method:

+
try db.create(virtualTable: "document", using: FTS3()) { t in // t is FTS3TableDefinition
+    t.column("content")
+}
+
+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/FTS4ColumnDefinition.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/FTS4ColumnDefinition.html new file mode 100644 index 000000000..8c0fa2068 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/FTS4ColumnDefinition.html @@ -0,0 +1,905 @@ + + + + FTS4ColumnDefinition Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS4ColumnDefinition

+
+
+
public final class FTS4ColumnDefinition
+ +
+
+

The FTS4ColumnDefinition class lets you refine a column of an FTS4 +virtual table.

+ +

You get instances of this class when you create an FTS4 table:

+
try db.create(virtualTable: "document", using: FTS4()) { t in
+    t.column("content")      // FTS4ColumnDefinition
+}
+
+ +

See https://www.sqlite.org/fts3.html

+ +
+
+
+
    +
  • +
    + + + + notIndexed() + +
    +
    +
    +
    +
    +
    +

    Excludes the column from the full-text index.

    +
    try db.create(virtualTable: "document", using: FTS4()) { t in
    +    t.column("a")
    +    t.column("b").notIndexed()
    +}
    +
    + +

    See https://www.sqlite.org/fts3.html#the_notindexed_option

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @available(iOS 8.2, OSX 10.10, *)
    +@discardableResult
    +public func notIndexed() -> Self
    + +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
  • +
    + + + + asLanguageId() + +
    +
    +
    +
    +
    +
    +

    Uses the column as the Int32 language id hidden column.

    +
    try db.create(virtualTable: "document", using: FTS4()) { t in
    +    t.column("a")
    +    t.column("lid").asLanguageId()
    +}
    +
    + +

    See https://www.sqlite.org/fts3.html#the_languageid_option

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func asLanguageId() -> Self
    + +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/FTS4TableDefinition.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/FTS4TableDefinition.html new file mode 100644 index 000000000..60e963eb5 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/FTS4TableDefinition.html @@ -0,0 +1,1120 @@ + + + + FTS4TableDefinition Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS4TableDefinition

+
+
+
public final class FTS4TableDefinition
+ +
+
+

The FTS4TableDefinition class lets you define columns of a FTS4 virtual table.

+ +

You don’t create instances of this class. Instead, you use the Database +create(virtualTable:using:) method:

+
try db.create(virtualTable: "document", using: FTS4()) { t in // t is FTS4TableDefinition
+    t.column("content")
+}
+
+ +

See https://www.sqlite.org/fts3.html

+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/FTS5ColumnDefinition.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/FTS5ColumnDefinition.html new file mode 100644 index 000000000..8f0589172 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/FTS5ColumnDefinition.html @@ -0,0 +1,840 @@ + + + + FTS5ColumnDefinition Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS5ColumnDefinition

+

The FTS5ColumnDefinition class lets you refine a column of an FTS5 +virtual table.

+ +

You get instances of this class when you create an FTS5 table:

+
try db.create(virtualTable: "document", using: FTS5()) { t in
+    t.column("content")      // FTS5ColumnDefinition
+}
+
+ +

See https://www.sqlite.org/fts5.html

+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/FTS5TableDefinition.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/FTS5TableDefinition.html new file mode 100644 index 000000000..ccf6c2d71 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/FTS5TableDefinition.html @@ -0,0 +1,1007 @@ + + + + FTS5TableDefinition Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS5TableDefinition

+

The FTS5TableDefinition class lets you define columns of a FTS5 virtual table.

+ +

You don’t create instances of this class. Instead, you use the Database +create(virtualTable:using:) method:

+
try db.create(virtualTable: "document", using: FTS5()) { t in // t is FTS5TableDefinition
+    t.column("content")
+}
+
+ +

See https://www.sqlite.org/fts5.html

+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/FetchedRecordsController.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/FetchedRecordsController.html new file mode 100644 index 000000000..0aaaf3406 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/FetchedRecordsController.html @@ -0,0 +1,1965 @@ + + + + FetchedRecordsController Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FetchedRecordsController

+
+
+
public final class FetchedRecordsController<Record> where Record : FetchableRecord
+ +
+
+

You use FetchedRecordsController to track changes in the results of an +SQLite request.

+ +

See https://github.com/groue/GRDB.swift#fetchedrecordscontroller for +more information.

+ +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Creates a fetched records controller initialized from a SQL query and +its eventual arguments.

    +
    let controller = FetchedRecordsController<Wine>(
    +    dbQueue,
    +    sql: "SELECT * FROM wine WHERE color = ? ORDER BY name",
    +    arguments: [Color.red],
    +    isSameRecord: { (wine1, wine2) in wine1.id == wine2.id })
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public convenience init(
    +    _ databaseWriter: DatabaseWriter,
    +    sql: String,
    +    arguments: StatementArguments? = nil,
    +    adapter: RowAdapter? = nil,
    +    queue: DispatchQueue = .main,
    +    isSameRecord: ((Record, Record) -> Bool)? = nil) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + databaseWriter + + +
    +

    A DatabaseWriter (DatabaseQueue, or DatabasePool)

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    + + queue + + +
    +

    A serial dispatch queue (defaults to the main queue)

    + +

    The fetched records controller tracking callbacks will be +notified of changes in this queue. The controller itself must be +used from this queue.

    +
    +
    + + isSameRecord + + +
    +

    Optional function that compares two records.

    + +

    This function should return true if the two records have the +same identity. For example, they have the same id.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a fetched records controller initialized from a fetch request +from the Query Interface.

    +
    let request = Wine.order(Column("name"))
    +let controller = FetchedRecordsController(
    +    dbQueue,
    +    request: request,
    +    isSameRecord: { (wine1, wine2) in wine1.id == wine2.id })
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public convenience init<Request>(
    +    _ databaseWriter: DatabaseWriter,
    +    request: Request,
    +    queue: DispatchQueue = .main,
    +    isSameRecord: ((Record, Record) -> Bool)? = nil) throws
    +    where Request: FetchRequest, Request.RowDecoder == Record
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + databaseWriter + + +
    +

    A DatabaseWriter (DatabaseQueue, or DatabasePool)

    +
    +
    + + request + + +
    +

    A fetch request.

    +
    +
    + + queue + + +
    +

    A serial dispatch queue (defaults to the main queue)

    + +

    The fetched records controller tracking callbacks will be +notified of changes in this queue. The controller itself must be +used from this queue.

    +
    +
    + + isSameRecord + + +
    +

    Optional function that compares two records.

    + +

    This function should return true if the two records have the +same identity. For example, they have the same id.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + performFetch() + +
    +
    +
    +
    +
    +
    +

    Executes the controller’s fetch request.

    + +

    After executing this method, you can access the the fetched objects with +the fetchedRecords property.

    + +

    This method must be used from the controller’s dispatch queue (the +main queue unless stated otherwise in the controller’s initializer).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func performFetch() throws
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + databaseWriter + +
    +
    +
    +
    +
    +
    +

    The database writer used to fetch records.

    + +

    The controller registers as a transaction observer in order to respond +to changes.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let databaseWriter: DatabaseWriter
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + queue + +
    +
    +
    +
    +
    +
    +

    The dispatch queue on which the controller must be used.

    + +

    Unless specified otherwise at initialization time, it is the main queue.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let queue: DispatchQueue
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + setRequest(_:) + +
    +
    +
    +
    +
    +
    +

    Updates the fetch request, and eventually notifies the tracking +callbacks if performFetch() has been called.

    + +

    This method must be used from the controller’s dispatch queue (the +main queue unless stated otherwise in the controller’s initializer).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func setRequest<Request>(_ request: Request) throws where Record == Request.RowDecoder, Request : FetchRequest
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Updates the fetch request, and eventually notifies the tracking +callbacks if performFetch() has been called.

    + +

    This method must be used from the controller’s dispatch queue (the +main queue unless stated otherwise in the controller’s initializer).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func setRequest(sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Registers changes notification callbacks.

    + +

    This method must be used from the controller’s dispatch queue (the +main queue unless stated otherwise in the controller’s initializer).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func trackChanges(
    +    willChange: ((FetchedRecordsController<Record>) -> ())? = nil,
    +    onChange: ((FetchedRecordsController<Record>, Record, FetchedRecordChange) -> ())? = nil,
    +    didChange: ((FetchedRecordsController<Record>) -> ())? = nil)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + willChange + + +
    +

    Invoked before records are updated.

    +
    +
    + + onChange + + +
    +

    Invoked for each record that has been added, +removed, moved, or updated.

    +
    +
    + + didChange + + +
    +

    Invoked after records have been updated.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Registers changes notification callbacks.

    + +

    This method must be used from the controller’s dispatch queue (the +main queue unless stated otherwise in the controller’s initializer).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func trackChanges<T>(
    +    fetchAlongside: @escaping (Database) throws -> T,
    +    willChange: ((FetchedRecordsController<Record>, _ fetchedAlongside: T) -> ())? = nil,
    +    onChange: ((FetchedRecordsController<Record>, Record, FetchedRecordChange) -> ())? = nil,
    +    didChange: ((FetchedRecordsController<Record>, _ fetchedAlongside: T) -> ())? = nil)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + fetchAlongside + + +
    +

    The value returned from this closure is given to +willChange and didChange callbacks, as their +fetchedAlongside argument. The closure is guaranteed to see the +database in the state it has just after eventual changes to the +fetched records have been performed. Use it in order to fetch +values that must be consistent with the fetched records.

    +
    +
    + + willChange + + +
    +

    Invoked before records are updated.

    +
    +
    + + onChange + + +
    +

    Invoked for each record that has been added, +removed, moved, or updated.

    +
    +
    + + didChange + + +
    +

    Invoked after records have been updated.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + trackErrors(_:) + +
    +
    +
    +
    +
    +
    +

    Registers an error callback.

    + +

    Whenever the controller could not look for changes after a transaction +has potentially modified the tracked request, this error handler is +called.

    + +

    The request observation is not stopped, though: future transactions may +successfully be handled, and the notified changes will then be based on +the last successful fetch.

    + +

    This method must be used from the controller’s dispatch queue (the +main queue unless stated otherwise in the controller’s initializer).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func trackErrors(_ errorHandler: @escaping (FetchedRecordsController<Record>, Error) -> ())
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Call this method when changes performed while the application is +in the background should be processed before the application enters the +suspended state.

    + +

    Whenever the tracked request is changed, the fetched records controller +sets up a background task using +UIApplication.beginBackgroundTask(expirationHandler:) which is ended +after the didChange callback has completed.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func allowBackgroundChangesTracking(in application: UIApplication)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchedRecords + +
    +
    +
    +
    +
    +
    +

    The fetched records.

    + +

    The value of this property is nil until performFetch() has been called.

    + +

    The records reflect the state of the database after the initial +call to performFetch, and after each database transaction that affects +the results of the fetch request.

    + +

    This property must be used from the controller’s dispatch queue (the +main queue unless stated otherwise in the controller’s initializer).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var fetchedRecords: [Record] { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Call this method when changes performed while the application is +in the background should be processed before the application enters the +suspended state.

    + +

    Whenever the tracked request is changed, the fetched records controller +sets up a background task using +UIApplication.beginBackgroundTask(expirationHandler:) which is ended +after the didChange callback has completed.

    + +
    +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Creates a fetched records controller initialized from a SQL query and +its eventual arguments.

    +
    let controller = FetchedRecordsController<Wine>(
    +    dbQueue,
    +    sql: "SELECT * FROM wine WHERE color = ? ORDER BY name",
    +    arguments: [Color.red])
    +
    + +

    The records are compared by primary key (single-column primary key, +compound primary key, or implicit rowid). For a database table which +has an id primary key, this initializer is equivalent to:

    +
    // Assuming the wine table has an `id` primary key:
    +let controller = FetchedRecordsController<Wine>(
    +    dbQueue,
    +    sql: "SELECT * FROM wine WHERE color = ? ORDER BY name",
    +    arguments: [Color.red],
    +    isSameRecord: { (wine1, wine2) in wine1.id == wine2.id })
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public convenience init(
    +    _ databaseWriter: DatabaseWriter,
    +    sql: String,
    +    arguments: StatementArguments? = nil,
    +    adapter: RowAdapter? = nil,
    +    queue: DispatchQueue = .main) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + + + + + +
    + + databaseWriter + + +
    +

    A DatabaseWriter (DatabaseQueue, or DatabasePool)

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    + + queue + + +
    +

    A serial dispatch queue (defaults to the main queue)

    + +

    The fetched records controller tracking callbacks will be +notified of changes in this queue. The controller itself must be +used from this queue.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a fetched records controller initialized from a fetch request +from the Query Interface.

    +
    let request = Wine.order(Column("name"))
    +let controller = FetchedRecordsController(
    +    dbQueue,
    +    request: request)
    +
    + +

    The records are compared by primary key (single-column primary key, +compound primary key, or implicit rowid). For a database table which +has an id primary key, this initializer is equivalent to:

    +
    // Assuming the wine table has an `id` primary key:
    +let controller = FetchedRecordsController<Wine>(
    +    dbQueue,
    +    request: request,
    +    isSameRecord: { (wine1, wine2) in wine1.id == wine2.id })
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public convenience init<Request>(
    +    _ databaseWriter: DatabaseWriter,
    +    request: Request,
    +    queue: DispatchQueue = .main) throws
    +    where Request: FetchRequest, Request.RowDecoder == Record
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + databaseWriter + + +
    +

    A DatabaseWriter (DatabaseQueue, or DatabasePool)

    +
    +
    + + request + + +
    +

    A fetch request.

    +
    +
    + + queue + + +
    +

    A serial dispatch queue (defaults to the main queue)

    + +

    The fetched records controller tracking callbacks will be +notified of changes in this queue. The controller itself must be +used from this queue.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + record(at:) + +
    +
    +
    +
    +
    +
    +

    Returns the object at the given index path.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func record(at indexPath: IndexPath) -> Record
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + indexPath + + +
    +

    An index path in the fetched records.

    + +

    If indexPath does not describe a valid index path in the fetched +records, a fatal error is raised.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + sections + +
    +
    +
    +
    +
    +
    +

    The sections for the fetched records.

    + +

    You typically use the sections array when implementing +UITableViewDataSource methods, such as numberOfSectionsInTableView.

    + +

    The sections array is never empty, even when there are no fetched +records. In this case, there is a single empty section.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var sections: [FetchedRecordsSectionInfo<Record>] { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + indexPath(for:) + +
    +
    +
    +
    +
    +
    +

    Returns the indexPath of a given record.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func indexPath(for record: Record) -> IndexPath?
    + +
    +
    +
    +

    Return Value

    +

    The index path of record in the fetched records, or nil +if record could not be found.

    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Record.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Record.html new file mode 100644 index 000000000..af2182d6f --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Record.html @@ -0,0 +1,1657 @@ + + + + Record Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Record

+
+
+
open class Record : FetchableRecord, TableRecord, PersistableRecord
+ +
+
+

Record is a class that wraps a table row, or the result of any query. It is +designed to be subclassed.

+ +
+
+
+ +
    +
  • +
    + + + + init() + +
    +
    +
    +
    +
    +
    +

    Creates a Record.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init()
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(row:) + +
    +
    +
    +
    +
    +
    +

    Creates a Record from a row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    required public init(row: Row)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + databaseTableName + +
    +
    +
    +
    +
    +
    +

    The name of a database table.

    + +

    This table name is required by the insert, update, save, delete, +and exists methods.

    +
    class Player : Record {
    +    override class var databaseTableName: String {
    +        return "player"
    +    }
    +}
    +
    + +

    The implementation of the base class Record raises a fatal error.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    open class var databaseTableName: String { get }
    + +
    +
    +
    +

    Return Value

    +

    The name of a database table.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    The policy that handles SQLite conflicts when records are inserted +or updated.

    + +

    This property is optional: its default value uses the ABORT policy +for both insertions and updates, and has GRDB generate regular +INSERT and UPDATE queries.

    + +

    If insertions are resolved with .ignore policy, the +didInsert(with:for:) method is not called upon successful insertion, +even if a row was actually inserted without any conflict.

    + +

    See https://www.sqlite.org/lang_conflict.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    open class var persistenceConflictPolicy: PersistenceConflictPolicy { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseSelection + +
    +
    +
    +
    +
    +
    +

    The default request selection.

    + +

    Unless this method is overriden, requests select all columns:

    +
    // SELECT * FROM player
    +try Player.fetchAll(db)
    +
    + +

    You can override this property and provide an explicit list +of columns:

    +
    class RestrictedPlayer : Record {
    +    override static var databaseSelection: [SQLSelectable] {
    +        return [Column("id"), Column("name")]
    +    }
    +}
    +
    +// SELECT id, name FROM player
    +try RestrictedPlayer.fetchAll(db)
    +
    + +

    You can also add extra columns such as the rowid column:

    +
    class ExtendedPlayer : Player {
    +    override static var databaseSelection: [SQLSelectable] {
    +        return [AllColumns(), Column.rowID]
    +    }
    +}
    +
    +// SELECT *, rowid FROM player
    +try ExtendedPlayer.fetchAll(db)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    open class var databaseSelection: [SQLSelectable] { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + encode(to:) + +
    +
    +
    +
    +
    +
    +

    Defines the values persisted in the database.

    + +

    Store in the container argument all values that should be stored in +the columns of the database table (see Record.databaseTableName()).

    + +

    Primary key columns, if any, must be included.

    +
    class Player : Record {
    +    var id: Int64?
    +    var name: String?
    +
    +    override func encode(to container: inout PersistenceContainer) {
    +        container["id"] = id
    +        container["name"] = name
    +    }
    +}
    +
    + +

    The implementation of the base class Record does not store any value in +the container.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    open func encode(to container: inout PersistenceContainer)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + didInsert(with:for:) + +
    +
    +
    +
    +
    +
    +

    Notifies the record that it was succesfully inserted.

    + +

    Do not call this method directly: it is called for you, in a protected +dispatch queue, with the inserted RowID and the eventual +INTEGER PRIMARY KEY column name.

    + +

    The implementation of the base Record class does nothing.

    +
    class Player : Record {
    +    var id: Int64?
    +    var name: String?
    +
    +    func didInsert(with rowID: Int64, for column: String?) {
    +        id = rowID
    +    }
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    open func didInsert(with rowID: Int64, for column: String?)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + rowID + + +
    +

    The inserted rowID.

    +
    +
    + + column + + +
    +

    The name of the eventual INTEGER PRIMARY KEY column.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
+ + + +

Copy

+
+
+
    +
  • +
    + + + + copy() + +
    +
    +
    +
    +
    +
    +

    Returns a copy of self, initialized from all values encoded in the +encode(to:) method.

    + +

    The eventual primary key is copied, as well as the +hasDatabaseChanges flag.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    open func copy() -> Self
    + +
    +
    +
    +

    Return Value

    +

    A copy of self.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + hasDatabaseChanges + +
    +
    +
    +
    +
    +
    +

    A boolean that indicates whether the record has changes that have not +been saved.

    + +

    This flag is purely informative, and does not prevent insert(), +update(), and save() from performing their database queries.

    + +

    A record is edited if has been changed since last database +synchronization (fetch, update, insert). Comparison +is performed between values (values stored in the encode(to:) +method, and values loaded from the database). Property setters do not +trigger this flag.

    + +

    You can rely on the Record base class to compute this flag for you, or +you may set it to true or false when you know better. Setting it to +false does not prevent it from turning true on subsequent modifications +of the record.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var hasDatabaseChanges: Bool { get set }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseChanges + +
    +
    +
    +
    +
    +
    +

    A dictionary of changes that have not been saved.

    + +

    Its keys are column names, and values the old values that have been +changed since last fetching or saving of the record.

    + +

    Unless the record has actually been fetched or saved, the old values +are nil.

    + +

    See hasDatabaseChanges for more information.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseChanges: [String : DatabaseValue?] { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ + + +

CRUD

+
+
+
    +
  • +
    + + + + insert(_:) + +
    +
    +
    +
    +
    +
    +

    Executes an INSERT statement.

    + +

    On success, this method sets the hasDatabaseChanges flag to false.

    + +

    This method is guaranteed to have inserted a row in the database if it +returns without error.

    + +

    Records whose primary key is declared as INTEGER PRIMARY KEY have +their id automatically set after successful insertion, if it was nil +before the insertion.

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    open func insert(_ db: Database) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + update(_:columns:) + +
    +
    +
    +
    +
    +
    +

    Executes an UPDATE statement.

    + +

    On success, this method sets the hasDatabaseChanges flag to false.

    + +

    This method is guaranteed to have updated a row in the database if it +returns without error.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. +PersistenceError.recordNotFound is thrown if the primary key does not +match any row in the database and record could not be updated. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    open func update(_ db: Database, columns: Set<String>) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + columns + + +
    +

    The columns to update.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + updateChanges(_:) + +
    +
    +
    +
    +
    +
    +

    If the record has been changed, executes an UPDATE statement so that +those changes and only those changes are saved in the database.

    + +

    On success, this method sets the hasDatabaseChanges flag to false.

    + +

    This method is guaranteed to have saved the eventual changes in the +database if it returns without error.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. +PersistenceError.recordNotFound is thrown if the primary key does not +match any row in the database and record could not be updated. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +final public func updateChanges(_ db: Database) throws -> Bool
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + columns + + +
    +

    The columns to update.

    +
    +
    +
    +
    +

    Return Value

    +

    Whether the record had changes.

    +
    + +
    +
    +
  • +
  • +
    + + + + save(_:) + +
    +
    +
    +
    +
    +
    +

    Executes an INSERT or an UPDATE statement so that self is saved in +the database.

    + +

    If the record has a non-nil primary key and a matching row in the +database, this method performs an update.

    + +

    Otherwise, performs an insert.

    + +

    On success, this method sets the hasDatabaseChanges flag to false.

    + +

    This method is guaranteed to have inserted or updated a row in the +database if it returns without error.

    + +

    You can’t override this method. Instead, override insert(_:) +or update(_:columns:).

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs, or errors +thrown by update(). + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    final public func save(_ db: Database) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + delete(_:) + +
    +
    +
    +
    +
    +
    +

    Executes a DELETE statement.

    + +

    On success, this method sets the hasDatabaseChanges flag to true.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +open func delete(_ db: Database) throws -> Bool
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    Whether a database row was deleted.

    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Row.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Row.html new file mode 100644 index 000000000..9557b7a5d --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Row.html @@ -0,0 +1,3207 @@ + + + + Row Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Row

+
+
+
public final class Row : Equatable, Hashable, RandomAccessCollection, ExpressibleByDictionaryLiteral, CustomStringConvertible, CustomDebugStringConvertible
+ +
+
+

A database row.

+ +
+
+
+
    +
  • +
    + + + + count + +
    +
    +
    +
    +
    +
    +

    The number of columns in the row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let count: Int
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + init() + +
    +
    +
    +
    +
    +
    +

    Creates an empty row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public convenience init()
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a row from a dictionary of values.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public convenience init(_ dictionary: [String : DatabaseValueConvertible?])
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a row from [AnyHashable: Any].

    + +

    The result is nil unless all dictionary keys are strings, and values +adopt DatabaseValueConvertible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public convenience init?(_ dictionary: [AnyHashable : Any])
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + copy() + +
    +
    +
    +
    +
    +
    +

    Returns an immutable copy of the row.

    + +

    For performance reasons, rows fetched from a cursor are reused during +the iteration of a query: make sure to make a copy of it whenever you +want to keep a specific one: row.copy().

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func copy() -> Row
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + columnNames + +
    +
    +
    +
    +
    +
    +

    The names of columns in the row.

    + +

    Columns appear in the same order as they occur as the .0 member +of column-value pairs in self.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var columnNames: LazyMapCollection<Row, String> { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + hasColumn(_:) + +
    +
    +
    +
    +
    +
    +

    Returns true if and only if the row has that column.

    + +

    This method is case-insensitive.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func hasColumn(_ columnName: String) -> Bool
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + containsNonNullValue + +
    +
    +
    +
    +
    +
    +

    Returns true if and only if one column contains a non-null value, or if +the row was fetched with a row adapter that defines a scoped row that +contains a non-null value.

    + +

    For example:

    +
    let row = try Row.fetchOne(db, "SELECT 'foo', 1")!
    +row.containsNonNullValue // true
    +
    +let row = try Row.fetchOne(db, "SELECT NULL, NULL")!
    +row.containsNonNullValue // false
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var containsNonNullValue: Bool { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + hasNull(atIndex:) + +
    +
    +
    +
    +
    +
    +

    Returns true if the row contains null at given index.

    + +

    Indexes span from 0 for the leftmost column to (row.count - 1) for the +righmost column.

    + +

    This method is equivalent to row[index] == nil, but may be preferred +in performance-critical code because it can avoid decoding database +values.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func hasNull(atIndex index: Int) -> Bool
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns Int64, Double, String, Data or nil, depending on the value +stored at the given index.

    + +

    Indexes span from 0 for the leftmost column to (row.count - 1) for the +righmost column.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript(index: Int) -> DatabaseValueConvertible? { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the value at given index, converted to the requested type.

    + +

    Indexes span from 0 for the leftmost column to (row.count - 1) for the +righmost column.

    + +

    If the SQLite value is NULL, the result is nil. Otherwise the SQLite +value is converted to the requested type Value. Should this conversion +fail, a fatal error is raised.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript<Value>(index: Int) -> Value? where Value : DatabaseValueConvertible { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the value at given index, converted to the requested type.

    + +

    Indexes span from 0 for the leftmost column to (row.count - 1) for the +righmost column.

    + +

    If the SQLite value is NULL, the result is nil. Otherwise the SQLite +value is converted to the requested type Value. Should this conversion +fail, a fatal error is raised.

    + +

    This method exists as an optimization opportunity for types that adopt +StatementColumnConvertible. It may trigger SQLite built-in conversions +(see https://www.sqlite.org/datatype3.html).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript<Value>(index: Int) -> Value? where Value : DatabaseValueConvertible, Value : StatementColumnConvertible { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the value at given index, converted to the requested type.

    + +

    Indexes span from 0 for the leftmost column to (row.count - 1) for the +righmost column.

    + +

    This method crashes if the fetched SQLite value is NULL, or if the +SQLite value can not be converted to Value.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript<Value>(index: Int) -> Value where Value : DatabaseValueConvertible { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the value at given index, converted to the requested type.

    + +

    Indexes span from 0 for the leftmost column to (row.count - 1) for the +righmost column.

    + +

    This method crashes if the fetched SQLite value is NULL, or if the +SQLite value can not be converted to Value.

    + +

    This method exists as an optimization opportunity for types that adopt +StatementColumnConvertible. It may trigger SQLite built-in conversions +(see https://www.sqlite.org/datatype3.html).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript<Value>(index: Int) -> Value where Value : DatabaseValueConvertible, Value : StatementColumnConvertible { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns Int64, Double, String, Data or nil, depending on the value +stored at the given column.

    + +

    Column name lookup is case-insensitive, and when several columns have +the same name, the leftmost column is considered.

    + +

    The result is nil if the row does not contain the column.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript(columnName: String) -> DatabaseValueConvertible? { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the value at given column, converted to the requested type.

    + +

    Column name lookup is case-insensitive, and when several columns have +the same name, the leftmost column is considered.

    + +

    If the column is missing or if the SQLite value is NULL, the result is +nil. Otherwise the SQLite value is converted to the requested type +Value. Should this conversion fail, a fatal error is raised.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript<Value>(columnName: String) -> Value? where Value : DatabaseValueConvertible { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the value at given column, converted to the requested type.

    + +

    Column name lookup is case-insensitive, and when several columns have +the same name, the leftmost column is considered.

    + +

    If the column is missing or if the SQLite value is NULL, the result is +nil. Otherwise the SQLite value is converted to the requested type +Value. Should this conversion fail, a fatal error is raised.

    + +

    This method exists as an optimization opportunity for types that adopt +StatementColumnConvertible. It may trigger SQLite built-in conversions +(see https://www.sqlite.org/datatype3.html).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript<Value>(columnName: String) -> Value? where Value : DatabaseValueConvertible, Value : StatementColumnConvertible { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the value at given column, converted to the requested type.

    + +

    Column name lookup is case-insensitive, and when several columns have +the same name, the leftmost column is considered.

    + +

    If the row does not contain the column, a fatal error is raised.

    + +

    This method crashes if the fetched SQLite value is NULL, or if the +SQLite value can not be converted to Value.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript<Value>(columnName: String) -> Value where Value : DatabaseValueConvertible { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the value at given column, converted to the requested type.

    + +

    Column name lookup is case-insensitive, and when several columns have +the same name, the leftmost column is considered.

    + +

    If the row does not contain the column, a fatal error is raised.

    + +

    This method crashes if the fetched SQLite value is NULL, or if the +SQLite value can not be converted to Value.

    + +

    This method exists as an optimization opportunity for types that adopt +StatementColumnConvertible. It may trigger SQLite built-in conversions +(see https://www.sqlite.org/datatype3.html).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript<Value>(columnName: String) -> Value where Value : DatabaseValueConvertible, Value : StatementColumnConvertible { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns Int64, Double, String, NSData or nil, depending on the value +stored at the given column.

    + +

    Column name lookup is case-insensitive, and when several columns have +the same name, the leftmost column is considered.

    + +

    The result is nil if the row does not contain the column.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript(column: ColumnExpression) -> DatabaseValueConvertible? { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the value at given column, converted to the requested type.

    + +

    Column name lookup is case-insensitive, and when several columns have +the same name, the leftmost column is considered.

    + +

    If the column is missing or if the SQLite value is NULL, the result is +nil. Otherwise the SQLite value is converted to the requested type +Value. Should this conversion fail, a fatal error is raised.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript<Value>(column: ColumnExpression) -> Value? where Value : DatabaseValueConvertible { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the value at given column, converted to the requested type.

    + +

    Column name lookup is case-insensitive, and when several columns have +the same name, the leftmost column is considered.

    + +

    If the column is missing or if the SQLite value is NULL, the result is +nil. Otherwise the SQLite value is converted to the requested type +Value. Should this conversion fail, a fatal error is raised.

    + +

    This method exists as an optimization opportunity for types that adopt +StatementColumnConvertible. It may trigger SQLite built-in conversions +(see https://www.sqlite.org/datatype3.html).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript<Value>(column: ColumnExpression) -> Value? where Value : DatabaseValueConvertible, Value : StatementColumnConvertible { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the value at given column, converted to the requested type.

    + +

    Column name lookup is case-insensitive, and when several columns have +the same name, the leftmost column is considered.

    + +

    If the row does not contain the column, a fatal error is raised.

    + +

    This method crashes if the fetched SQLite value is NULL, or if the +SQLite value can not be converted to Value.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript<Value>(column: ColumnExpression) -> Value where Value : DatabaseValueConvertible { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the value at given column, converted to the requested type.

    + +

    Column name lookup is case-insensitive, and when several columns have +the same name, the leftmost column is considered.

    + +

    If the row does not contain the column, a fatal error is raised.

    + +

    This method crashes if the fetched SQLite value is NULL, or if the +SQLite value can not be converted to Value.

    + +

    This method exists as an optimization opportunity for types that adopt +StatementColumnConvertible. It may trigger SQLite built-in conversions +(see https://www.sqlite.org/datatype3.html).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript<Value>(column: ColumnExpression) -> Value where Value : DatabaseValueConvertible, Value : StatementColumnConvertible { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + dataNoCopy(atIndex:) + +
    +
    +
    +
    +
    +
    +

    Returns the optional Data at given index.

    + +

    Indexes span from 0 for the leftmost column to (row.count - 1) for the +righmost column.

    + +

    If the SQLite value is NULL, the result is nil. If the SQLite value can +not be converted to Data, a fatal error is raised.

    + +

    The returned data does not owns its bytes: it must not be used longer +than the row’s lifetime.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func dataNoCopy(atIndex index: Int) -> Data?
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + dataNoCopy(named:) + +
    +
    +
    +
    +
    +
    +

    Returns the optional Data at given column.

    + +

    Column name lookup is case-insensitive, and when several columns have +the same name, the leftmost column is considered.

    + +

    If the column is missing or if the SQLite value is NULL, the result is +nil. If the SQLite value can not be converted to Data, a fatal error +is raised.

    + +

    The returned data does not owns its bytes: it must not be used longer +than the row’s lifetime.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func dataNoCopy(named columnName: String) -> Data?
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + dataNoCopy(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the optional NSData at given column.

    + +

    Column name lookup is case-insensitive, and when several columns have +the same name, the leftmost column is considered.

    + +

    If the column is missing or if the SQLite value is NULL, the result is +nil. If the SQLite value can not be converted to NSData, a fatal error +is raised.

    + +

    The returned data does not owns its bytes: it must not be used longer +than the row’s lifetime.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func dataNoCopy(_ column: ColumnExpression) -> Data?
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + databaseValues + +
    +
    +
    +
    +
    +
    +

    The database values in the row.

    + +

    Values appear in the same order as they occur as the .1 member +of column-value pairs in self.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValues: LazyMapCollection<Row, DatabaseValue> { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+
+ + + +

Scopes

+
+
+
    +
  • +
    + + + + scopes + +
    +
    +
    +
    +
    +
    +

    Returns a view on the scopes defined by row adapters.

    + +

    For example:

    +
    // Define a tree of nested scopes
    +let adapter = ScopeAdapter([
    +    "foo": RangeRowAdapter(0..<1),
    +    "bar": RangeRowAdapter(1..<2).addingScopes([
    +        "baz" : RangeRowAdapter(2..<3)])])
    +
    +// Fetch
    +let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
    +let row = try Row.fetchOne(db, sql, adapter: adapter)!
    +
    +row.scopes.count  // 2
    +row.scopes.names  // ["foo", "bar"]
    +
    +row.scopes["foo"] // [foo:1]
    +row.scopes["bar"] // [bar:2]
    +row.scopes["baz"] // nil
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var scopes: ScopesView { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + scopesTree + +
    +
    +
    +
    +
    +
    +

    Returns a view on the scopes tree defined by row adapters.

    + +

    For example:

    +
    // Define a tree of nested scopes
    +let adapter = ScopeAdapter([
    +    "foo": RangeRowAdapter(0..<1),
    +    "bar": RangeRowAdapter(1..<2).addingScopes([
    +        "baz" : RangeRowAdapter(2..<3)])])
    +
    +// Fetch
    +let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
    +let row = try Row.fetchOne(db, sql, adapter: adapter)!
    +
    +row.scopesTree.names  // ["foo", "bar", "baz"]
    +
    +row.scopesTree["foo"] // [foo:1]
    +row.scopesTree["bar"] // [bar:2]
    +row.scopesTree["baz"] // [baz:3]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var scopesTree: ScopesTreeView { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + unscoped + +
    +
    +
    +
    +
    +
    +

    Returns a copy of the row, without any scopes.

    + +

    This property can turn out useful when you want to test the content of +adapted rows, such as rows fetched from joined requests.

    +
    let row = ...
    +// Failure because row equality tests for row scopes:
    +XCTAssertEqual(row, ["id": 1, "name": "foo"])
    +// Success:
    +XCTAssertEqual(row.unscoped, ["id": 1, "name": "foo"])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var unscoped: Row { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + unadapted + +
    +
    +
    +
    +
    +
    +

    Return the raw row fetched from the database.

    + +

    This property can turn out useful when you debug the consumption of +adapted rows, such as rows fetched from joined requests.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var unadapted: Row { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Returns a cursor over rows fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT ...")
    +let rows = try Row.fetchCursor(statement) // RowCursor
    +while let row = try rows.next() { // Row
    +    let id: Int64 = row[0]
    +    let name: String = row[1]
    +}
    +
    + +

    Fetched rows are reused during the cursor iteration: don’t turn a row +cursor into an array with Array(rows) or rows.filter { ... } since +you would not get the distinct rows you expect. Use Row.fetchAll(...) +instead.

    + +

    For the same reason, make sure you make a copy whenever you extract a +row for later use: row.copy().

    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched rows.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns an array of rows fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT ...")
    +let rows = try Row.fetchAll(statement)
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An array of rows.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns a single row fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT ...")
    +let row = try Row.fetchOne(statement)
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row?
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An optional row.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Returns a cursor over rows fetched from an SQL query.

    +
    let rows = try Row.fetchCursor(db, "SELECT id, name FROM player") // RowCursor
    +while let row = try rows.next() { // Row
    +    let id: Int64 = row[0]
    +    let name: String = row[1]
    +}
    +
    + +

    Fetched rows are reused during the cursor iteration: don’t turn a row +cursor into an array with Array(rows) or rows.filter { ... } since +you would not get the distinct rows you expect. Use Row.fetchAll(...) +instead.

    + +

    For the same reason, make sure you make a copy whenever you extract a +row for later use: row.copy().

    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched rows.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns an array of rows fetched from an SQL query.

    +
    let rows = try Row.fetchAll(db, "SELECT ...")
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An array of rows.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns a single row fetched from an SQL query.

    +
    let row = try Row.fetchOne(db, "SELECT ...")
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row?
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An optional row.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:_:) + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over rows fetched from a fetch request.

    +
    let request = Player.all()
    +let rows = try Row.fetchCursor(db, request) // RowCursor
    +while let row = try rows.next() { // Row
    +    let id: Int64 = row["id"]
    +    let name: String = row["name"]
    +}
    +
    + +

    Fetched rows are reused during the cursor iteration: don’t turn a row +cursor into an array with Array(rows) or rows.filter { ... } since +you would not get the distinct rows you expect. Use Row.fetchAll(...) +instead.

    + +

    For the same reason, make sure you make a copy whenever you extract a +row for later use: row.copy().

    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor<R>(_ db: Database, _ request: R) throws -> RowCursor where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched rows.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:_:) + +
    +
    +
    +
    +
    +
    +

    Returns an array of rows fetched from a fetch request.

    +
    let request = Player.all()
    +let rows = try Row.fetchAll(db, request)
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll<R>(_ db: Database, _ request: R) throws -> [Row] where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of rows.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:_:) + +
    +
    +
    +
    +
    +
    +

    Returns a single row fetched from a fetch request.

    +
    let request = Player.filter(key: 1)
    +let row = try Row.fetchOne(db, request)
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne<R>(_ db: Database, _ request: R) throws -> Row? where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    An optional row.

    +
    + +
    +
    +
  • +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Creates a row initialized with elements. Column order is preserved, and +duplicated columns names are allowed.

    +
    let row: Row = ["foo": 1, "foo": "bar", "baz": nil]
    +print(row)
    +// Prints [foo:1 foo:"bar" baz:NULL]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public convenience init(dictionaryLiteral elements: (String, DatabaseValueConvertible?)...)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Accesses the (ColumnName, DatabaseValue) pair at given index.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript(position: RowIndex) -> (String, DatabaseValue) { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + ScopesView + +
    +
    +
    +
    +
    +
    +

    A view of the scopes defined by row adapters. It is a collection of +tuples made of a scope name and a scoped row, which behaves like a +dictionary.

    + +

    For example:

    +
    // Define a tree of nested scopes
    +let adapter = ScopeAdapter([
    +    "foo": RangeRowAdapter(0..<1),
    +    "bar": RangeRowAdapter(1..<2).addingScopes([
    +        "baz" : RangeRowAdapter(2..<3)])])
    +
    +// Fetch
    +let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
    +let row = try Row.fetchOne(db, sql, adapter: adapter)!
    +
    +row.scopes.count  // 2
    +row.scopes.names  // ["foo", "bar"]
    +
    +row.scopes["foo"] // [foo:1]
    +row.scopes["bar"] // [bar:2]
    +row.scopes["baz"] // nil
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct ScopesView : Collection
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + ScopesTreeView + +
    +
    +
    +
    +
    +
    +

    A view on the scopes tree defined by row adapters.

    + +

    For example:

    +
    // Define a tree of nested scopes
    +let adapter = ScopeAdapter([
    +    "foo": RangeRowAdapter(0..<1),
    +    "bar": RangeRowAdapter(1..<2).addingScopes([
    +        "baz" : RangeRowAdapter(2..<3)])])
    +
    +// Fetch
    +let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
    +let row = try Row.fetchOne(db, sql, adapter: adapter)!
    +
    +row.scopesTree.names  // ["foo", "bar", "baz"]
    +
    +row.scopesTree["foo"] // [foo:1]
    +row.scopesTree["bar"] // [bar:2]
    +row.scopesTree["baz"] // [baz:3]
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct ScopesTreeView
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Row/ScopesTreeView.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Row/ScopesTreeView.html new file mode 100644 index 000000000..529fd4941 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Row/ScopesTreeView.html @@ -0,0 +1,891 @@ + + + + ScopesTreeView Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ScopesTreeView

+
+
+
public struct ScopesTreeView
+ +
+
+

A view on the scopes tree defined by row adapters.

+ +

For example:

+
// Define a tree of nested scopes
+let adapter = ScopeAdapter([
+    "foo": RangeRowAdapter(0..<1),
+    "bar": RangeRowAdapter(1..<2).addingScopes([
+        "baz" : RangeRowAdapter(2..<3)])])
+
+// Fetch
+let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
+let row = try Row.fetchOne(db, sql, adapter: adapter)!
+
+row.scopesTree.names  // ["foo", "bar", "baz"]
+
+row.scopesTree["foo"] // [foo:1]
+row.scopesTree["bar"] // [bar:2]
+row.scopesTree["baz"] // [baz:3]
+
+ +
+
+
+
    +
  • +
    + + + + names + +
    +
    +
    +
    +
    +
    +

    The scopes defined on this row, recursively.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var names: Set<String> { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the row associated with the given scope, by performing a +breadth-first search in this row’s scopes and the scopes of its +scoped rows, recursively.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript(name: String) -> Row? { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Row/ScopesView.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Row/ScopesView.html new file mode 100644 index 000000000..e1424584c --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Row/ScopesView.html @@ -0,0 +1,922 @@ + + + + ScopesView Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ScopesView

+
+
+
public struct ScopesView : Collection
+ +
+
+

A view of the scopes defined by row adapters. It is a collection of +tuples made of a scope name and a scoped row, which behaves like a +dictionary.

+ +

For example:

+
// Define a tree of nested scopes
+let adapter = ScopeAdapter([
+    "foo": RangeRowAdapter(0..<1),
+    "bar": RangeRowAdapter(1..<2).addingScopes([
+        "baz" : RangeRowAdapter(2..<3)])])
+
+// Fetch
+let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
+let row = try Row.fetchOne(db, sql, adapter: adapter)!
+
+row.scopes.count  // 2
+row.scopes.names  // ["foo", "bar"]
+
+row.scopes["foo"] // [foo:1]
+row.scopes["bar"] // [bar:2]
+row.scopes["baz"] // nil
+
+ +
+
+
+
    +
  • +
    + + + + Index + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public typealias Index = Dictionary<String, LayoutedRowAdapter>.Index
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + names + +
    +
    +
    +
    +
    +
    +

    The scopes defined on this row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var names: Dictionary<String, LayoutedRowAdapter>.Keys { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the row associated with the given scope, or nil if the +scope is not defined.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript(name: String) -> Row? { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/RowCursor.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/RowCursor.html new file mode 100644 index 000000000..a7a340865 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/RowCursor.html @@ -0,0 +1,845 @@ + + + + RowCursor Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

RowCursor

+
+
+
public final class RowCursor : Cursor
+ +
+
+

A cursor of database rows. For example:

+
try dbQueue.read { db in
+    let rows: RowCursor = try Row.fetchCursor(db, "SELECT * FROM player")
+}
+
+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/SelectStatement.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/SelectStatement.html new file mode 100644 index 000000000..3674275d6 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/SelectStatement.html @@ -0,0 +1,940 @@ + + + + SelectStatement Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

SelectStatement

+
+
+
public final class SelectStatement : Statement
+ +
+
+

A subclass of Statement that fetches database rows.

+ +

You create SelectStatement with the Database.makeSelectStatement() method:

+
try dbQueue.read { db in
+    let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
+    let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
+    let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
+}
+
+ +
+
+
+
    +
  • +
    + + + + databaseRegion + +
    +
    +
    +
    +
    +
    +

    The database region that the statement looks into.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public private(set) var databaseRegion: DatabaseRegion
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + columnCount + +
    +
    +
    +
    +
    +
    +

    The number of columns in the resulting rows.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var columnCount: Int { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + columnNames + +
    +
    +
    +
    +
    +
    +

    The column names, ordered from left to right.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public lazy var columnNames: [String] { get set }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + index(ofColumn:) + +
    +
    +
    +
    +
    +
    +

    Returns the index of the leftmost column named name, in a +case-insensitive way.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func index(ofColumn name: String) -> Int?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Statement.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Statement.html new file mode 100644 index 000000000..21e11e91c --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/Statement.html @@ -0,0 +1,976 @@ + + + + Statement Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Statement

+
+
+
public class Statement
+ +
+
+

A statement represents an SQL query.

+ +

It is the base class of UpdateStatement that executes update statements, +and SelectStatement that fetches rows.

+ +
+
+
+
    +
  • +
    + + + + sqliteStatement + +
    +
    +
    +
    +
    +
    +

    The raw SQLite statement, suitable for the SQLite C API.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let sqliteStatement: SQLiteStatement
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + sql + +
    +
    +
    +
    +
    +
    +

    The SQL query

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var sql: String { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/StatementCursor.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/StatementCursor.html new file mode 100644 index 000000000..787889293 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/StatementCursor.html @@ -0,0 +1,847 @@ + + + + StatementCursor Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

StatementCursor

+
+
+
public final class StatementCursor : Cursor
+ +
+
+

A cursor that iterates a database statement without producing any value. +For example:

+
try dbQueue.read { db in
+    let statement = db.makeSelectStatement("SELECT * FROM player")
+    let cursor: StatementCursor = statement.makeCursor()
+}
+
+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/TableAlias.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/TableAlias.html new file mode 100644 index 000000000..03941d4b1 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/TableAlias.html @@ -0,0 +1,905 @@ + + + + TableAlias Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

TableAlias

+
+
+
public class TableAlias : Hashable
+ +
+
+

Experimental

+ +

A TableAlias identifies a table in a request.

+ +
+
+
+
    +
  • +
    + + + + init(name:) + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(name: String? = nil)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a qualified value that is able to resolve ambiguities in +joined queries.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript(selectable: SQLSelectable) -> SQLSelectable { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a qualified expression that is able to resolve ambiguities in +joined queries.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript(expression: SQLExpression) -> SQLExpression { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/TableAlteration.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/TableAlteration.html new file mode 100644 index 000000000..e8cce7c4e --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/TableAlteration.html @@ -0,0 +1,893 @@ + + + + TableAlteration Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

TableAlteration

+
+
+
public final class TableAlteration
+ +
+
+

The TableAlteration class lets you alter database tables.

+ +

You don’t create instances of this class. Instead, you use the Database +alter(table:) method:

+
try db.alter(table: "player") { t in // t is TableAlteration
+    t.add(column: ...)
+}
+
+ +

See https://www.sqlite.org/lang_altertable.html

+ +
+
+
+
    +
  • +
    + + + + add(column:_:) + +
    +
    +
    +
    +
    +
    +

    Appends a column to the table.

    +
    try db.alter(table: "player") { t in
    +    t.add(column: "url", .text)
    +}
    +
    + +

    See https://www.sqlite.org/lang_altertable.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func add(column name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + name + + +
    +

    the column name.

    +
    +
    + + type + + +
    +

    the column type.

    +
    +
    +
    +
    +

    Return Value

    +

    An ColumnDefinition that allows you to refine the +column definition.

    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/TableDefinition.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/TableDefinition.html new file mode 100644 index 000000000..82d249f33 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/TableDefinition.html @@ -0,0 +1,1348 @@ + + + + TableDefinition Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

TableDefinition

+
+
+
public final class TableDefinition
+ +
+
+

The TableDefinition class lets you define table columns and constraints.

+ +

You don’t create instances of this class. Instead, you use the Database +create(table:) method:

+
try db.create(table: "player") { t in // t is TableDefinition
+    t.column(...)
+}
+
+ +

See https://www.sqlite.org/lang_createtable.html

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Defines the auto-incremented primary key.

    +
    try db.create(table: "player") { t in
    +    t.autoIncrementedPrimaryKey("id")
    +}
    +
    + +

    The auto-incremented primary key is an integer primary key that +automatically generates unused values when you do not explicitly +provide one, and prevents the reuse of ids over the lifetime of +the database.

    + +

    It is the preferred way to define a numeric primary key.

    + +

    The fact that an auto-incremented primary key prevents the reuse of +ids is an excellent guard against data races that could happen when your +application processes ids in an asynchronous way. The auto-incremented +primary key provides the guarantee that a given id can’t reference a row +that is different from the one it used to be at the beginning of the +asynchronous process, even if this row gets deleted and a new one is +inserted in between.

    + +

    See https://www.sqlite.org/lang_createtable.html#primkeyconst and +https://www.sqlite.org/lang_createtable.html#rowid

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func autoIncrementedPrimaryKey(_ name: String, onConflict conflictResolution: Database.ConflictResolution? = nil) -> ColumnDefinition
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + conflitResolution + + +
    +

    An optional conflict resolution +(see https://www.sqlite.org/lang_conflict.html).

    +
    +
    +
    +
    +

    Return Value

    +

    Self so that you can further refine the column definition.

    +
    + +
    +
    +
  • +
  • +
    + + + + column(_:_:) + +
    +
    +
    +
    +
    +
    +

    Appends a table column.

    +
    try db.create(table: "player") { t in
    +    t.column("name", .text)
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#tablecoldef

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func column(_ name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + name + + +
    +

    the column name.

    +
    +
    + + type + + +
    +

    the eventual column type.

    +
    +
    +
    +
    +

    Return Value

    +

    An ColumnDefinition that allows you to refine the +column definition.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Defines the table primary key.

    +
    try db.create(table: "citizenship") { t in
    +    t.column("citizenID", .integer)
    +    t.column("countryCode", .text)
    +    t.primaryKey(["citizenID", "countryCode"])
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#primkeyconst and +https://www.sqlite.org/lang_createtable.html#rowid

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func primaryKey(_ columns: [String], onConflict conflictResolution: Database.ConflictResolution? = nil)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + columns + + +
    +

    The primary key columns.

    +
    +
    + + conflitResolution + + +
    +

    An optional conflict resolution +(see https://www.sqlite.org/lang_conflict.html).

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Adds a unique key.

    +
    try db.create(table: "place") { t in
    +    t.column("latitude", .double)
    +    t.column("longitude", .double)
    +    t.uniqueKey(["latitude", "longitude"])
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#uniqueconst

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func uniqueKey(_ columns: [String], onConflict conflictResolution: Database.ConflictResolution? = nil)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + columns + + +
    +

    The unique key columns.

    +
    +
    + + conflitResolution + + +
    +

    An optional conflict resolution +(see https://www.sqlite.org/lang_conflict.html).

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Adds a foreign key.

    +
    try db.create(table: "passport") { t in
    +    t.column("issueDate", .date)
    +    t.column("citizenID", .integer)
    +    t.column("countryCode", .text)
    +    t.foreignKey(["citizenID", "countryCode"], references: "citizenship", onDelete: .cascade)
    +}
    +
    + +

    See https://www.sqlite.org/foreignkeys.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func foreignKey(_ columns: [String], references table: String, columns destinationColumns: [String]? = nil, onDelete deleteAction: Database.ForeignKeyAction? = nil, onUpdate updateAction: Database.ForeignKeyAction? = nil, deferred: Bool = false)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + columns + + +
    +

    The foreign key columns.

    +
    +
    + + table + + +
    +

    The referenced table.

    +
    +
    + + destinationColumns + + +
    +

    The columns in the referenced table. If not +specified, the columns of the primary key of the referenced table +are used.

    +
    +
    + + deleteAction + + +
    +

    Optional action when the referenced row is deleted.

    +
    +
    + + updateAction + + +
    +

    Optional action when the referenced row is updated.

    +
    +
    + + deferred + + +
    +

    If true, defines a deferred foreign key constraint. +See https://www.sqlite.org/foreignkeys.html#fk_deferred.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + check(_:) + +
    +
    +
    +
    +
    +
    +

    Adds a CHECK constraint.

    +
    try db.create(table: "player") { t in
    +    t.column("personalPhone", .text)
    +    t.column("workPhone", .text)
    +    let personalPhone = Column("personalPhone")
    +    let workPhone = Column("workPhone")
    +    t.check(personalPhone != nil || workPhone != nil)
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#ckconst

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func check(_ condition: SQLExpressible)
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + condition + + +
    +

    The checked condition

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + check(sql:) + +
    +
    +
    +
    +
    +
    +

    Adds a CHECK constraint.

    +
    try db.create(table: "player") { t in
    +    t.column("personalPhone", .text)
    +    t.column("workPhone", .text)
    +    t.check(sql: "personalPhone IS NOT NULL OR workPhone IS NOT NULL")
    +}
    +
    + +

    See https://www.sqlite.org/lang_createtable.html#ckconst

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func check(sql: String)
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + sql + + +
    +

    An SQL snippet

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/UpdateStatement.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/UpdateStatement.html new file mode 100644 index 000000000..0cd822412 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Classes/UpdateStatement.html @@ -0,0 +1,874 @@ + + + + UpdateStatement Class Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

UpdateStatement

+
+
+
public final class UpdateStatement : Statement
+ +
+
+

A subclass of Statement that executes SQL queries.

+ +

You create UpdateStatement with the Database.makeUpdateStatement() method:

+
try dbQueue.inTransaction { db in
+    let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)")
+    try statement.execute(arguments: ["Arthur"])
+    try statement.execute(arguments: ["Barbara"])
+    return .commit
+}
+
+ +
+
+
+
    +
  • +
    + + + + execute(arguments:) + +
    +
    +
    +
    +
    +
    +

    Executes the SQL query.

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func execute(arguments: StatementArguments? = nil) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + arguments + + +
    +

    Statement arguments.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Enums.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Enums.html new file mode 100644 index 000000000..5d4c14de7 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Enums.html @@ -0,0 +1,1129 @@ + + + + Enumerations Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Enumerations

+

The following enumerations are available globally.

+ +
+
+
+ +
    +
  • +
    + + + + DatabaseEventKind + +
    +
    +
    +
    +
    +
    +

    A kind of database event. See the TransactionObserver protocol for +more information.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public enum DatabaseEventKind
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    DatabaseDateDecodingStrategy specifies how FetchableRecord types that also +adopt the standard Decodable protocol decode their date properties.

    + +

    For example:

    +
    struct Player: FetchableRecord, Decodable {
    +    static let databaseDateDecodingStrategy: DatabaseDateDecodingStrategy = .timeIntervalSince1970
    +
    +    var name: String
    +    var registrationDate: Date // decoded from epoch timestamp
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public enum DatabaseDateDecodingStrategy
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + FetchedRecordChange + +
    +
    +
    +
    +
    +
    +

    A record change, given by a FetchedRecordsController to its change callback.

    + +

    The move and update events hold a changes dictionary, whose keys are +column names, and values the old values that have been changed.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public enum FetchedRecordChange
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + PersistenceError + +
    +
    +
    +
    +
    +
    +

    An error thrown by a type that adopts PersistableRecord.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public enum PersistenceError : Error, CustomStringConvertible
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    DatabaseDateEncodingStrategy specifies how PersistableRecord types that also +adopt the standard Encodable protocol encode their date properties.

    + +

    For example:

    +
    struct Player: PersistableRecord, Encodable {
    +    static let databaseDateEncodingStrategy: DatabaseDateEncodingStrategy = .timeIntervalSince1970
    +
    +    var name: String
    +    var registrationDate: Date // encoded as an epoch timestamp
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public enum DatabaseDateEncodingStrategy
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    DatabaseUUIDEncodingStrategy specifies how FetchableRecord types that also +adopt the standard Encodable protocol encode their UUID properties.

    + +

    For example:

    +
    struct Player: PersistableProtocol, Encodable {
    +    static let databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy = .string
    +
    +    // encoded in a string like "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
    +    var uuid: UUID
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public enum DatabaseUUIDEncodingStrategy
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Enums/DatabaseDateDecodingStrategy.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Enums/DatabaseDateDecodingStrategy.html new file mode 100644 index 000000000..f0509a7a3 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Enums/DatabaseDateDecodingStrategy.html @@ -0,0 +1,1054 @@ + + + + DatabaseDateDecodingStrategy Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseDateDecodingStrategy

+
+
+
public enum DatabaseDateDecodingStrategy
+ +
+
+

DatabaseDateDecodingStrategy specifies how FetchableRecord types that also +adopt the standard Decodable protocol decode their date properties.

+ +

For example:

+
struct Player: FetchableRecord, Decodable {
+    static let databaseDateDecodingStrategy: DatabaseDateDecodingStrategy = .timeIntervalSince1970
+
+    var name: String
+    var registrationDate: Date // decoded from epoch timestamp
+}
+
+ +
+
+
+
    +
  • +
    + + + + deferredToDate + +
    +
    +
    +
    +
    +
    +

    The strategy that uses formatting from the Date structure.

    + +

    It decodes numeric values as a nunber of seconds since Epoch +(midnight UTC on January 1st, 1970).

    + +

    It decodes strings in the following formats, assuming UTC time zone. +Missing components are assumed to be zero:

    + +
      +
    • YYYY-MM-DD
    • +
    • YYYY-MM-DD HH:MM
    • +
    • YYYY-MM-DD HH:MM:SS
    • +
    • YYYY-MM-DD HH:MM:SS.SSS
    • +
    • YYYY-MM-DDTHH:MM
    • +
    • YYYY-MM-DDTHH:MM:SS
    • +
    • YYYY-MM-DDTHH:MM:SS.SSS
    • +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case deferredToDate
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Decodes numeric values as a number of seconds between the date and +midnight UTC on 1 January 2001

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case timeIntervalSinceReferenceDate
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + timeIntervalSince1970 + +
    +
    +
    +
    +
    +
    +

    Decodes numeric values as a number of seconds between the date and +midnight UTC on 1 January 1970

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case timeIntervalSince1970
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + millisecondsSince1970 + +
    +
    +
    +
    +
    +
    +

    Decodes numeric values as a number of milliseconds between the date and +midnight UTC on 1 January 1970

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case millisecondsSince1970
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + iso8601 + +
    +
    +
    +
    +
    +
    +

    Decodes dates according to the ISO 8601 standards

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case iso8601
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + formatted + +
    +
    +
    +
    +
    +
    +

    Decodes a String, according to the provided formatter

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case formatted(DateFormatter)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + custom + +
    +
    +
    +
    +
    +
    +

    Decodes according to the user-provided function.

    + +

    If the database value does not contain a suitable value, the function +must return nil (GRDB will interpret this nil result as a conversion +error, and react accordingly).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case custom((DatabaseValue) -> Date?)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Enums/DatabaseDateEncodingStrategy.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Enums/DatabaseDateEncodingStrategy.html new file mode 100644 index 000000000..8c686e2b3 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Enums/DatabaseDateEncodingStrategy.html @@ -0,0 +1,1068 @@ + + + + DatabaseDateEncodingStrategy Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseDateEncodingStrategy

+
+
+
public enum DatabaseDateEncodingStrategy
+ +
+
+

DatabaseDateEncodingStrategy specifies how PersistableRecord types that also +adopt the standard Encodable protocol encode their date properties.

+ +

For example:

+
struct Player: PersistableRecord, Encodable {
+    static let databaseDateEncodingStrategy: DatabaseDateEncodingStrategy = .timeIntervalSince1970
+
+    var name: String
+    var registrationDate: Date // encoded as an epoch timestamp
+}
+
+ +
+
+
+
    +
  • +
    + + + + deferredToDate + +
    +
    +
    +
    +
    +
    +

    The strategy that uses formatting from the Date structure.

    + +

    It encodes dates using the format YYYY-MM-DD HH:MM:SS.SSS in the +UTC time zone.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case deferredToDate
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Encodes a Double: the number of seconds between the date and +midnight UTC on 1 January 2001

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case timeIntervalSinceReferenceDate
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + timeIntervalSince1970 + +
    +
    +
    +
    +
    +
    +

    Encodes a Double: the number of seconds between the date and +midnight UTC on 1 January 1970

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case timeIntervalSince1970
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + secondsSince1970 + +
    +
    +
    +
    +
    +
    +

    Encodes an Int64: the number of seconds between the date and +midnight UTC on 1 January 1970

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case secondsSince1970
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + millisecondsSince1970 + +
    +
    +
    +
    +
    +
    +

    Encodes an Int64: the number of milliseconds between the date and +midnight UTC on 1 January 1970

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case millisecondsSince1970
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + iso8601 + +
    +
    +
    +
    +
    +
    +

    Encodes dates according to the ISO 8601 and RFC 3339 standards

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case iso8601
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + formatted + +
    +
    +
    +
    +
    +
    +

    Encodes a String, according to the provided formatter

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case formatted(DateFormatter)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + custom + +
    +
    +
    +
    +
    +
    +

    Encodes the result of the user-provided function

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case custom((Date) -> DatabaseValueConvertible?)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Enums/DatabaseEventKind.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Enums/DatabaseEventKind.html new file mode 100644 index 000000000..6e1fe63b6 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Enums/DatabaseEventKind.html @@ -0,0 +1,943 @@ + + + + DatabaseEventKind Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseEventKind

+
+
+
public enum DatabaseEventKind
+ +
+
+

A kind of database event. See the TransactionObserver protocol for +more information.

+ +
+
+
+
    +
  • +
    + + + + insert + +
    +
    +
    +
    +
    +
    +

    The insertion of a row in a database table

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case insert(tableName: String)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + delete + +
    +
    +
    +
    +
    +
    +

    The deletion of a row in a database table

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case delete(tableName: String)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + update + +
    +
    +
    +
    +
    +
    +

    The update of a set of columns in a database table

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case update(tableName: String, columnNames: Set<String>)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + tableName + +
    +
    +
    +
    +
    +
    +

    The impacted database table

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var tableName: String { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Enums/DatabaseUUIDEncodingStrategy.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Enums/DatabaseUUIDEncodingStrategy.html new file mode 100644 index 000000000..d05b465d5 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Enums/DatabaseUUIDEncodingStrategy.html @@ -0,0 +1,883 @@ + + + + DatabaseUUIDEncodingStrategy Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseUUIDEncodingStrategy

+
+
+
public enum DatabaseUUIDEncodingStrategy
+ +
+
+

DatabaseUUIDEncodingStrategy specifies how FetchableRecord types that also +adopt the standard Encodable protocol encode their UUID properties.

+ +

For example:

+
struct Player: PersistableProtocol, Encodable {
+    static let databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy = .string
+
+    // encoded in a string like "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
+    var uuid: UUID
+}
+
+ +
+
+
+
    +
  • +
    + + + + deferredToUUID + +
    +
    +
    +
    +
    +
    +

    The strategy that uses formatting from the UUID type.

    + +

    It encodes UUIDs as 16-bytes data blobs.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case deferredToUUID
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + string + +
    +
    +
    +
    +
    +
    +

    Encodes UUIDs as strings such as E621E1F8-C36C-495A-93FC-0C247A3E6E5F

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case string
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Enums/FetchedRecordChange.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Enums/FetchedRecordChange.html new file mode 100644 index 000000000..702d23825 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Enums/FetchedRecordChange.html @@ -0,0 +1,978 @@ + + + + FetchedRecordChange Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FetchedRecordChange

+
+
+
public enum FetchedRecordChange
+ +
+
+

A record change, given by a FetchedRecordsController to its change callback.

+ +

The move and update events hold a changes dictionary, whose keys are +column names, and values the old values that have been changed.

+ +
+
+
+
    +
  • +
    + + + + insertion + +
    +
    +
    +
    +
    +
    +

    An insertion event, at given indexPath.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case insertion(indexPath: IndexPath)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + deletion + +
    +
    +
    +
    +
    +
    +

    A deletion event, at given indexPath.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case deletion(indexPath: IndexPath)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + move + +
    +
    +
    +
    +
    +
    +

    A move event, from indexPath to newIndexPath. The changes are a +dictionary whose keys are column names, and values the old values that +have been changed.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case move(indexPath: IndexPath, newIndexPath: IndexPath, changes: [String : DatabaseValue])
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + update + +
    +
    +
    +
    +
    +
    +

    An update event, at given indexPath. The changes are a dictionary +whose keys are column names, and values the old values that have +been changed.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case update(indexPath: IndexPath, changes: [String : DatabaseValue])
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + description + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var description: String { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Enums/PersistenceError.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Enums/PersistenceError.html new file mode 100644 index 000000000..845efc3ee --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Enums/PersistenceError.html @@ -0,0 +1,842 @@ + + + + PersistenceError Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

PersistenceError

+
+
+
public enum PersistenceError : Error, CustomStringConvertible
+ +
+
+

An error thrown by a type that adopts PersistableRecord.

+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Enums/SQLLogicalBinaryOperator.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Enums/SQLLogicalBinaryOperator.html new file mode 100644 index 000000000..fd9fb2aa6 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Enums/SQLLogicalBinaryOperator.html @@ -0,0 +1,871 @@ + + + + SQLLogicalBinaryOperator Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

SQLLogicalBinaryOperator

+
+
+
public enum SQLLogicalBinaryOperator
+ +
+
+

Undocumented

+ +
+
+
+
    +
  • +
    + + + + and + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case and
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + or + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case or
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions.html new file mode 100644 index 000000000..007ce9e7e --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions.html @@ -0,0 +1,1982 @@ + + + + Extensions Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Extensions

+

The following extensions are available globally.

+ +
+
+
+ +
    +
  • +
    + + + + Array + +
    +
    +
    +
    +
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Array<Element> : _DestructorSafeContainer
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + Sequence + +
    +
    +
    +
    +
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    protocol Sequence
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + Set + +
    +
    +
    +
    +
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Set<Element> where Element : Hashable
    + +
    +
    +
    +
    +
  • +
+
+
+ +
+
+ +
+
+ +
    +
  • +
    + + + + Optional + +
    +
    +
    +
    +
    +
    +

    Swift’s Optional comes with built-in methods that allow to fetch cursors +and arrays of optional DatabaseValueConvertible:

    +
    try Optional<String>.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String?
    +try Optional<String>.fetchAll(db, "SELECT name FROM ...", arguments:...)    // [String?]
    +
    +let statement = try db.makeSelectStatement("SELECT name FROM ...")
    +try Optional<String>.fetchCursor(statement, arguments:...) // Cursor of String?
    +try Optional<String>.fetchAll(statement, arguments:...)    // [String?]
    +
    + +

    DatabaseValueConvertible is adopted by Bool, Int, String, etc.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    enum Optional<Wrapped> : ExpressibleByNilLiteral
    + +
    +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + CGFloat + +
    +
    +
    +
    +
    +
    +

    CGFloat adopts DatabaseValueConvertible

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct CGFloat
    + +
    +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + Data + +
    +
    +
    +
    +
    +
    +

    Data is convertible to and from DatabaseValue.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessCollection, MutableCollection, RangeReplaceableCollection
    + +
    +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + NSDate + +
    +
    +
    +
    +
    +
    +

    NSDate is stored in the database using the format +yyyy-MM-dd HH:mm:ss.SSS, in the UTC time zone.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    class NSDate : NSObject, NSCopying, NSSecureCoding
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + Date + +
    +
    +
    +
    +
    +
    +

    Date is stored in the database using the format +yyyy-MM-dd HH:mm:ss.SSS, in the UTC time zone.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Date : ReferenceConvertible, Comparable, Equatable
    + +
    +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + NSData + +
    +
    +
    +
    +
    +
    +

    NSData is convertible to and from DatabaseValue.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding
    + +
    +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + NSNull + +
    +
    +
    +
    +
    +
    +

    NSNull adopts DatabaseValueConvertible

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    class NSNull : NSObject, NSCopying, NSSecureCoding
    + +
    +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + NSNumber + +
    +
    +
    +
    +
    +
    +

    NSNumber adopts DatabaseValueConvertible

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    class NSNumber : NSValue
    + +
    +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + NSString + +
    +
    +
    +
    +
    +
    +

    NSString adopts DatabaseValueConvertible

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    class NSString : NSObject, NSCopying, NSMutableCopying, NSSecureCoding
    + +
    +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + NSURL + +
    +
    +
    +
    +
    +
    +

    NSURL stores its absoluteString in the database.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    class NSURL : NSObject, NSSecureCoding, NSCopying
    + +
    +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + NSUUID + +
    +
    +
    +
    +
    +
    +

    NSUUID adopts DatabaseValueConvertible

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    class NSUUID : NSObject, NSCopying, NSSecureCoding
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + UUID + +
    +
    +
    +
    +
    +
    +

    UUID adopts DatabaseValueConvertible

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @available(OSX 10.8, iOS 6.0, *)
    +struct UUID : ReferenceConvertible, Hashable, Equatable, CustomStringConvertible
    + +
    +
    +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + Bool + +
    +
    +
    +
    +
    +
    +

    Bool adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Bool
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + Int + +
    +
    +
    +
    +
    +
    +

    Int adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Int : FixedWidthInteger, SignedInteger
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + Int8 + +
    +
    +
    +
    +
    +
    +

    Int8 adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Int8 : FixedWidthInteger, SignedInteger
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + Int16 + +
    +
    +
    +
    +
    +
    +

    Int16 adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Int16 : FixedWidthInteger, SignedInteger
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + Int32 + +
    +
    +
    +
    +
    +
    +

    Int32 adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Int32 : FixedWidthInteger, SignedInteger
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + Int64 + +
    +
    +
    +
    +
    +
    +

    Int64 adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Int64 : FixedWidthInteger, SignedInteger
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + UInt + +
    +
    +
    +
    +
    +
    +

    UInt adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct UInt : FixedWidthInteger, UnsignedInteger
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + UInt8 + +
    +
    +
    +
    +
    +
    +

    UInt8 adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct UInt8 : FixedWidthInteger, UnsignedInteger
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + UInt16 + +
    +
    +
    +
    +
    +
    +

    UInt16 adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct UInt16 : FixedWidthInteger, UnsignedInteger
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + UInt32 + +
    +
    +
    +
    +
    +
    +

    UInt32 adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct UInt32 : FixedWidthInteger, UnsignedInteger
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + UInt64 + +
    +
    +
    +
    +
    +
    +

    UInt64 adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct UInt64 : FixedWidthInteger, UnsignedInteger
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + Double + +
    +
    +
    +
    +
    +
    +

    Double adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Double
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + Float + +
    +
    +
    +
    +
    +
    +

    Float adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Float
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + String + +
    +
    +
    +
    +
    +
    +

    String adopts DatabaseValueConvertible and StatementColumnConvertible.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct String
    + +
    +
    +
    +
    +
  • +
+
+
+ +
+
+ +
+
+ +
    +
  • +
    + + + + Range + +
    +
    +
    +
    +
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct Range<Bound> where Bound : Comparable
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + ClosedRange + +
    +
    +
    +
    +
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct ClosedRange<Bound> where Bound : Comparable
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + CountableRange + +
    +
    +
    +
    +
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct CountableRange<Bound> where Bound : Strideable, Bound.Stride : SignedInteger
    + +
    +
    +
    +
    +
  • +
  • +
    + + + + CountableClosedRange + +
    +
    +
    +
    +
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    struct CountableClosedRange<Bound> where Bound : Strideable, Bound.Stride : SignedInteger
    + +
    +
    +
    +
    +
  • +
+
+
+ + +
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Array.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Array.html new file mode 100644 index 000000000..7d1798a8c --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Array.html @@ -0,0 +1,843 @@ + + + + Array Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Array

+
+
+
struct Array<Element> : _DestructorSafeContainer
+ +
+
+ +
+
+
+
    +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    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"]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init<C>(_ cursor: C) throws where Element == C.Element, C : Cursor
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Bool.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Bool.html new file mode 100644 index 000000000..7609b4ff1 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Bool.html @@ -0,0 +1,932 @@ + + + + Bool Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Bool

+
+
+
struct Bool
+ +
+
+

Bool adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a Bool initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Bool?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/CGFloat.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/CGFloat.html new file mode 100644 index 000000000..f25ef9cdd --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/CGFloat.html @@ -0,0 +1,871 @@ + + + + CGFloat Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

CGFloat

+
+
+
struct CGFloat
+ +
+
+

CGFloat adopts DatabaseValueConvertible

+ +
+
+
+
    +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a CGFloat initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> CGFloat?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/ClosedRange.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/ClosedRange.html new file mode 100644 index 000000000..b2626bda7 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/ClosedRange.html @@ -0,0 +1,876 @@ + + + + ClosedRange Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ClosedRange

+
+
+
struct ClosedRange<Bound> where Bound : Comparable
+ +
+
+ +
+
+
+
    +
  • +
    + + + + contains(_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that checks the inclusion of an expression in a range.

    +
    // email BETWEEN 'A' AND 'B'
    +("A"..."B").contains(Column("email"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func contains(_ element: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + contains(_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that checks the inclusion of an expression in a range.

    +
    // email BETWEEN 'A' AND 'B' COLLATE NOCASE
    +("A"..."B").contains(Column("email").collating(.nocase))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func contains(_ element: SQLCollatedExpression) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Column.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Column.html new file mode 100644 index 000000000..875e20977 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Column.html @@ -0,0 +1,823 @@ + + + + Column Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Column

+ +
+
+
+
    +
  • +
    + + + + rank + +
    +
    +
    +
    +
    +
    +

    The FTS5 rank column

    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/CountableClosedRange.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/CountableClosedRange.html new file mode 100644 index 000000000..dce75d259 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/CountableClosedRange.html @@ -0,0 +1,843 @@ + + + + CountableClosedRange Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

CountableClosedRange

+
+
+
struct CountableClosedRange<Bound> where Bound : Strideable, Bound.Stride : SignedInteger
+ +
+
+ +
+
+
+
    +
  • +
    + + + + contains(_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that checks the inclusion of an expression in a range.

    +
    // id BETWEEN 1 AND 10
    +(1...10).contains(Column("id"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func contains(_ element: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/CountableRange.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/CountableRange.html new file mode 100644 index 000000000..9a9831ae8 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/CountableRange.html @@ -0,0 +1,843 @@ + + + + CountableRange Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

CountableRange

+
+
+
struct CountableRange<Bound> where Bound : Strideable, Bound.Stride : SignedInteger
+ +
+
+ +
+
+
+
    +
  • +
    + + + + contains(_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that checks the inclusion of an expression in a range.

    +
    // id BETWEEN 1 AND 9
    +(1..<10).contains(Column("id"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func contains(_ element: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Data.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Data.html new file mode 100644 index 000000000..97645f9cb --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Data.html @@ -0,0 +1,901 @@ + + + + Data Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Data

+
+
+
struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessCollection, MutableCollection, RangeReplaceableCollection
+ +
+
+

Data is convertible to and from DatabaseValue.

+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Database.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Database.html new file mode 100644 index 000000000..91630f2b1 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Database.html @@ -0,0 +1,937 @@ + + + + Database Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Database

+ +
+
+
+ +
+
+
+ + + +

FTS5

+
+
+
    +
  • +
    + + + + add(tokenizer:) + +
    +
    +
    +
    +
    +
    +

    Add a custom FTS5 tokenizer.

    +
    class MyTokenizer : FTS5CustomTokenizer { ... }
    +db.add(tokenizer: MyTokenizer.self)
    +
    + +
    +
    +
    +
  • +
+
+
+
+ + + +

FTS5

+
+
+ +
+
+
+ + + +

FTS5

+
+
+
    +
  • +
    + + + + makeTokenizer(_:) + +
    +
    +
    +
    +
    +
    +

    Creates an FTS5 tokenizer, given its descriptor.

    +
    let unicode61 = try db.makeTokenizer(.unicode61())
    +
    + +

    It is a programmer error to use the tokenizer outside of a protected +database queue, or after the database has been closed.

    + +

    Use this method when you implement a custom wrapper tokenizer:

    +
    final class MyTokenizer : FTS5WrapperTokenizer {
    +    var wrappedTokenizer: FTS5Tokenizer
    +
    +    init(db: Database, arguments: [String]) throws {
    +        wrappedTokenizer = try db.makeTokenizer(.unicode61())
    +    }
    +}
    +
    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/DatabasePool.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/DatabasePool.html new file mode 100644 index 000000000..45034336c --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/DatabasePool.html @@ -0,0 +1,863 @@ + + + + DatabasePool Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabasePool

+ +
+
+
+ +
    +
  • +
    + + + + change(passphrase:) + +
    +
    +
    +
    +
    +
    +

    Changes the passphrase of an encrypted database

    + +
    +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(tokenizer:) + +
    +
    +
    +
    +
    +
    +

    Add a custom FTS5 tokenizer.

    +
    class MyTokenizer : FTS5CustomTokenizer { ... }
    +dbPool.add(tokenizer: MyTokenizer.self)
    +
    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/DatabaseQueue.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/DatabaseQueue.html new file mode 100644 index 000000000..ffc7e7c09 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/DatabaseQueue.html @@ -0,0 +1,863 @@ + + + + DatabaseQueue Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseQueue

+ +
+
+
+ +
    +
  • +
    + + + + change(passphrase:) + +
    +
    +
    +
    +
    +
    +

    Changes the passphrase of an encrypted database

    + +
    +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(tokenizer:) + +
    +
    +
    +
    +
    +
    +

    Add a custom FTS5 tokenizer.

    +
    class MyTokenizer : FTS5CustomTokenizer { ... }
    +dbQueue.add(tokenizer: MyTokenizer.self)
    +
    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Date.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Date.html new file mode 100644 index 000000000..9f25f9b8e --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Date.html @@ -0,0 +1,977 @@ + + + + Date Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Date

+
+
+
struct Date : ReferenceConvertible, Comparable, Equatable
+ +
+
+

Date is stored in the database using the format +yyyy-MM-dd HH:mm:ss.SSS, in the UTC time zone.

+ +
+
+
+
    +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a database value that contains the date encoded as +yyyy-MM-dd HH:mm:ss.SSS, in the UTC time zone.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a date initialized from dbValue, if possible.

    + +

    If database value contains a number, that number is interpreted as a +timeinterval since 00:00:00 UTC on 1 January 1970.

    + +

    If database value contains a string, that string is interpreted as a +SQLite date in the UTC time +zone. Nil is returned if the date string does not contain at least the +year, month and day components. Other components (minutes, etc.) +are set to zero if missing.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Date?
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(julianDay:) + +
    +
    +
    +
    +
    +
    +

    Creates a date from a Julian Day.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init?(julianDay: Double)
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Double.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Double.html new file mode 100644 index 000000000..3017e6613 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Double.html @@ -0,0 +1,932 @@ + + + + Double Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Double

+
+
+
struct Double
+ +
+
+

Double adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a Double initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Double?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Float.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Float.html new file mode 100644 index 000000000..125cd0978 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Float.html @@ -0,0 +1,932 @@ + + + + Float Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Float

+
+
+
struct Float
+ +
+
+

Float adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a Float initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Float?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Int.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Int.html new file mode 100644 index 000000000..f4b069f20 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Int.html @@ -0,0 +1,932 @@ + + + + Int Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Int

+
+
+
struct Int : FixedWidthInteger, SignedInteger
+ +
+
+

Int adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an Int initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Int16.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Int16.html new file mode 100644 index 000000000..a7cc80d58 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Int16.html @@ -0,0 +1,932 @@ + + + + Int16 Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Int16

+
+
+
struct Int16 : FixedWidthInteger, SignedInteger
+ +
+
+

Int16 adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an Int16 initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int16?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Int32.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Int32.html new file mode 100644 index 000000000..832d17ea2 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Int32.html @@ -0,0 +1,932 @@ + + + + Int32 Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Int32

+
+
+
struct Int32 : FixedWidthInteger, SignedInteger
+ +
+
+

Int32 adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an Int32 initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int32?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Int64.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Int64.html new file mode 100644 index 000000000..1a25d8e19 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Int64.html @@ -0,0 +1,932 @@ + + + + Int64 Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Int64

+
+
+
struct Int64 : FixedWidthInteger, SignedInteger
+ +
+
+

Int64 adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an Int64 initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int64?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Int8.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Int8.html new file mode 100644 index 000000000..af282b1ab --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Int8.html @@ -0,0 +1,932 @@ + + + + Int8 Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Int8

+
+
+
struct Int8 : FixedWidthInteger, SignedInteger
+ +
+
+

Int8 adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an Int8 initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int8?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/NSData.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/NSData.html new file mode 100644 index 000000000..8416534a8 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/NSData.html @@ -0,0 +1,872 @@ + + + + NSData Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

NSData

+
+
+
class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding
+ +
+
+

NSData is convertible to and from DatabaseValue.

+ +
+
+
+
    +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an NSData initialized from dbValue, if it contains +a Blob.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> `Self`?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/NSDate.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/NSDate.html new file mode 100644 index 000000000..9388547db --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/NSDate.html @@ -0,0 +1,882 @@ + + + + NSDate Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

NSDate

+
+
+
class NSDate : NSObject, NSCopying, NSSecureCoding
+ +
+
+

NSDate is stored in the database using the format +yyyy-MM-dd HH:mm:ss.SSS, in the UTC time zone.

+ +
+
+
+
    +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a database value that contains the date encoded as +yyyy-MM-dd HH:mm:ss.SSS, in the UTC time zone.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a date initialized from dbValue, if possible.

    + +

    If database value contains a number, that number is interpreted as a +timeinterval since 00:00:00 UTC on 1 January 1970.

    + +

    If database value contains a string, that string is interpreted as a +SQLite date in the UTC time +zone. Nil is returned if the date string does not contain at least the +year, month and day components. Other components (minutes, etc.) +are set to zero if missing.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> `Self`?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/NSNull.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/NSNull.html new file mode 100644 index 000000000..bea335158 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/NSNull.html @@ -0,0 +1,871 @@ + + + + NSNull Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

NSNull

+
+
+
class NSNull : NSObject, NSCopying, NSSecureCoding
+ +
+
+

NSNull adopts DatabaseValueConvertible

+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/NSNumber.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/NSNumber.html new file mode 100644 index 000000000..e53edea85 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/NSNumber.html @@ -0,0 +1,871 @@ + + + + NSNumber Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

NSNumber

+
+
+
class NSNumber : NSValue
+ +
+
+

NSNumber adopts DatabaseValueConvertible

+ +
+
+
+
    +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an NSNumber initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> `Self`?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/NSString.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/NSString.html new file mode 100644 index 000000000..2634a38fb --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/NSString.html @@ -0,0 +1,871 @@ + + + + NSString Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

NSString

+
+
+
class NSString : NSObject, NSCopying, NSMutableCopying, NSSecureCoding
+ +
+
+

NSString adopts DatabaseValueConvertible

+ +
+
+
+
    +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an NSString initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> `Self`?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/NSURL.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/NSURL.html new file mode 100644 index 000000000..61e40c254 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/NSURL.html @@ -0,0 +1,872 @@ + + + + NSURL Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

NSURL

+
+
+
class NSURL : NSObject, NSSecureCoding, NSCopying
+ +
+
+

NSURL stores its absoluteString in the database.

+ +
+
+
+
    +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database. +(the URL’s absoluteString).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an NSURL initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> `Self`?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/NSUUID.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/NSUUID.html new file mode 100644 index 000000000..a87a0dc48 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/NSUUID.html @@ -0,0 +1,869 @@ + + + + NSUUID Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

NSUUID

+
+
+
class NSUUID : NSObject, NSCopying, NSSecureCoding
+ +
+
+

NSUUID adopts DatabaseValueConvertible

+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Optional.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Optional.html new file mode 100644 index 000000000..fa440d0c9 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Optional.html @@ -0,0 +1,1923 @@ + + + + Optional Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Optional

+
+
+
enum Optional<Wrapped> : ExpressibleByNilLiteral
+ +
+
+

Swift’s Optional comes with built-in methods that allow to fetch cursors +and arrays of optional DatabaseValueConvertible:

+
try Optional<String>.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String?
+try Optional<String>.fetchAll(db, "SELECT name FROM ...", arguments:...)    // [String?]
+
+let statement = try db.makeSelectStatement("SELECT name FROM ...")
+try Optional<String>.fetchCursor(statement, arguments:...) // Cursor of String?
+try Optional<String>.fetchAll(statement, arguments:...)    // [String?]
+
+ +

DatabaseValueConvertible is adopted by Bool, Int, String, etc.

+ +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Returns a cursor over optional values fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT name FROM ...")
    +let names = try Optional<String>.fetchCursor(statement) // Cursor of String?
    +while let name = try names.next() { // String?
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped>
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched optional values.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns an array of optional values fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT name FROM ...")
    +let names = try Optional<String>.fetchAll(statement)  // [String?]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An array of optional values.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Returns a cursor over optional values fetched from an SQL query.

    +
    let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // Cursor of String?
    +while let name = try names.next() { // String?
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped>
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched optional values.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns an array of optional values fetched from an SQL query.

    +
    let names = try String.fetchAll(db, "SELECT name FROM ...") // [String?]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An array of optional values.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:_:) + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over optional values fetched from a fetch request.

    +
    let request = Player.select(Column("name"))
    +let names = try Optional<String>.fetchCursor(db, request) // Cursor of String?
    +while let name = try names.next() { // String?
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor<R>(_ db: Database, _ request: R) throws -> NullableDatabaseValueCursor<Wrapped> where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched optional values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:_:) + +
    +
    +
    +
    +
    +
    +

    Returns an array of optional values fetched from a fetch request.

    +
    let request = Player.select(Column("name"))
    +let names = try Optional<String>.fetchAll(db, request) // [String?]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll<R>(_ db: Database, _ request: R) throws -> [Wrapped?] where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of optional values.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Returns a cursor over optional values fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT name FROM ...")
    +let names = try Optional<String>.fetchCursor(statement) // Cursor of String?
    +while let name = try names.next() { // String?
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor<Wrapped>
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched optional values.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns an array of optional values fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT name FROM ...")
    +let names = try Optional<String>.fetchAll(statement)  // [String?]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An array of optional values.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Returns a cursor over optional values fetched from an SQL query.

    +
    let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // Cursor of String?
    +while let name = try names.next() { // String?
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor<Wrapped>
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched optional values.

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns an array of optional values fetched from an SQL query.

    +
    let names = try String.fetchAll(db, "SELECT name FROM ...") // [String?]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An array of optional values.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:_:) + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over optional values fetched from a fetch request.

    +
    let request = Player.select(Column("name"))
    +let names = try Optional<String>.fetchCursor(db, request) // Cursor of String?
    +while let name = try names.next() { // String?
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor<R>(_ db: Database, _ request: R) throws -> FastNullableDatabaseValueCursor<Wrapped> where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched optional values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:_:) + +
    +
    +
    +
    +
    +
    +

    Returns an array of optional values fetched from a fetch request.

    +
    let request = Player.select(Column("name"))
    +let names = try Optional<String>.fetchAll(db, request) // [String?]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll<R>(_ db: Database, _ request: R) throws -> [Wrapped?] where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of optional values.

    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/QueryInterfaceRequest.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/QueryInterfaceRequest.html new file mode 100644 index 000000000..ba84a2139 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/QueryInterfaceRequest.html @@ -0,0 +1,842 @@ + + + + QueryInterfaceRequest Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

QueryInterfaceRequest

+ +
+
+
+ +
    +
  • +
    + + + + matching(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a request with a full-text predicate added to the eventual +set of already applied predicates.

    +
    // SELECT * FROM book WHERE book MATCH '...'
    +var request = Book.all()
    +request = request.matching(pattern)
    +
    + +

    If the search pattern is nil, the request does not match any +database row.

    + +

    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.

    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Range.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Range.html new file mode 100644 index 000000000..b3f8e3456 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Range.html @@ -0,0 +1,876 @@ + + + + Range Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Range

+
+
+
struct Range<Bound> where Bound : Comparable
+ +
+
+ +
+
+
+
    +
  • +
    + + + + contains(_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that checks the inclusion of an expression in a range.

    +
    // email >= 'A' AND email < 'B'
    +("A"..<"B").contains(Column("email"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func contains(_ element: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + contains(_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that checks the inclusion of an expression in a range.

    +
    // email >= 'A' COLLATE NOCASE AND email < 'B' COLLATE NOCASE
    +("A"..<"B").contains(Column("email").collating(.nocase))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func contains(_ element: SQLCollatedExpression) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/SQLSpecificExpressible.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/SQLSpecificExpressible.html new file mode 100644 index 000000000..119050a42 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/SQLSpecificExpressible.html @@ -0,0 +1,843 @@ + + + + SQLSpecificExpressible Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

SQLSpecificExpressible

+
+
+
public protocol SQLSpecificExpressible : SQLExpressible
+ +
+
+ +
+
+
+
    +
  • +
    + + + + like(_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression with the LIKE SQL operator.

    +
    // email LIKE '%@example.com"
    +Column("email").like("%@example.com")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func like(_ pattern: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Sequence.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Sequence.html new file mode 100644 index 000000000..88a7dfdd3 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Sequence.html @@ -0,0 +1,969 @@ + + + + Sequence Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Sequence

+
+
+
protocol Sequence
+ +
+
+ +
+
+
+
    +
  • +
    + + + + flatMap(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over the concatenated results of mapping transform +over self.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<AnyCursor<Iterator.Element>, SegmentOfResult>>
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + contains(_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that checks the inclusion of an expression in +a sequence.

    +
    // id IN (1,2,3)
    +[1, 2, 3].contains(Column("id"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func contains(_ element: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + contains(_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that checks the inclusion of an expression in +a sequence.

    +
    // name IN ('A', 'B') COLLATE NOCASE
    +["A", "B"].contains(Column("name").collating(.nocase))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func contains(_ element: SQLCollatedExpression) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + joined(operator:) + +
    +
    +
    +
    +
    +
    +

    Returns an expression by joining all elements with an SQL +logical operator.

    + +

    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))
    +
    + +

    When the sequence is empty, joined(operator: .and) returns true, +and joined(operator: .or) returns false:

    +
    // SELECT * FROM player WHERE 1
    +Player.filter([].joined(operator: .and))
    +
    +// SELECT * FROM player WHERE 0
    +Player.filter([].joined(operator: .or))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func joined(operator: SQLLogicalBinaryOperator) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Set.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Set.html new file mode 100644 index 000000000..c25e3319c --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/Set.html @@ -0,0 +1,843 @@ + + + + Set Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Set

+
+
+
struct Set<Element> where Element : Hashable
+ +
+
+ +
+
+
+
    +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a set containing the elements of a cursor.

    +
    let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'foo'")
    +let strings = try Set(cursor) // ["foo"]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init<C>(_ cursor: C) throws where Element == C.Element, C : Cursor
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/String.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/String.html new file mode 100644 index 000000000..c033d242b --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/String.html @@ -0,0 +1,969 @@ + + + + String Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

String

+
+
+
struct String
+ +
+
+

String adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a String initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> String?
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns the receiver, quoted for safe insertion as an identifier in an +SQL query.

    +
    db.execute("SELECT * FROM \(tableName.quotedDatabaseIdentifier)")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var quotedDatabaseIdentifier: String { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/TableRecord.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/TableRecord.html new file mode 100644 index 000000000..dbfb4a96c --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/TableRecord.html @@ -0,0 +1,836 @@ + + + + TableRecord Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

TableRecord

+ +
+
+
+ +
    +
  • +
    + + + + matching(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a QueryInterfaceRequest with a matching predicate.

    +
    // SELECT * FROM book WHERE book MATCH '...'
    +var request = Book.matching(pattern)
    +
    + +

    If the search pattern is nil, the request does not match any +database row.

    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/UInt.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/UInt.html new file mode 100644 index 000000000..03c835216 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/UInt.html @@ -0,0 +1,932 @@ + + + + UInt Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

UInt

+
+
+
struct UInt : FixedWidthInteger, UnsignedInteger
+ +
+
+

UInt adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an Int initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/UInt16.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/UInt16.html new file mode 100644 index 000000000..1da653a5b --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/UInt16.html @@ -0,0 +1,932 @@ + + + + UInt16 Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

UInt16

+
+
+
struct UInt16 : FixedWidthInteger, UnsignedInteger
+ +
+
+

UInt16 adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an UInt16 initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt16?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/UInt32.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/UInt32.html new file mode 100644 index 000000000..3a8b6bf33 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/UInt32.html @@ -0,0 +1,932 @@ + + + + UInt32 Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

UInt32

+
+
+
struct UInt32 : FixedWidthInteger, UnsignedInteger
+ +
+
+

UInt32 adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an UInt32 initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt32?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/UInt64.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/UInt64.html new file mode 100644 index 000000000..487c6afb2 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/UInt64.html @@ -0,0 +1,932 @@ + + + + UInt64 Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

UInt64

+
+
+
struct UInt64 : FixedWidthInteger, UnsignedInteger
+ +
+
+

UInt64 adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an UInt64 initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt64?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/UInt8.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/UInt8.html new file mode 100644 index 000000000..811677ddf --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/UInt8.html @@ -0,0 +1,932 @@ + + + + UInt8 Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

UInt8

+
+
+
struct UInt8 : FixedWidthInteger, UnsignedInteger
+ +
+
+

UInt8 adopts DatabaseValueConvertible and StatementColumnConvertible.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an UInt8 initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt8?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/UUID.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/UUID.html new file mode 100644 index 000000000..43325c58b --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Extensions/UUID.html @@ -0,0 +1,903 @@ + + + + UUID Extension Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

UUID

+
+
+
@available(OSX 10.8, iOS 6.0, *)
+struct UUID : ReferenceConvertible, Hashable, Equatable, CustomStringConvertible
+ +
+
+

UUID adopts DatabaseValueConvertible

+ +
+
+
+ +
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Functions.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Functions.html new file mode 100644 index 000000000..c0abdcc19 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Functions.html @@ -0,0 +1,3512 @@ + + + + Functions Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Functions

+

The following functions are available globally.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Returns an array of row adapters that split a row according to the input +number of columns.

    + +

    For example:

    +
    let sql = "SELECT 1, 2,3,4, 5,6, 7,8"
    +//               <.><. . .><. .><. .>
    +let adapters = splittingRowAdapters([1, 3, 2])
    +let adapter = ScopeAdapter([
    +    "a": adapters[0],
    +    "b": adapters[1],
    +    "c": adapters[2],
    +    "d": adapters[3]])
    +let row = try Row.fetchOne(db, sql, adapter: adapter)
    +row.scopes["a"] // [1]
    +row.scopes["b"] // [2, 3, 4]
    +row.scopes["c"] // [5, 6]
    +row.scopes["d"] // [7, 8]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func splittingRowAdapters(columnCounts: [Int]) -> [RowAdapter]
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + abs(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an expression that evaluates the ABS SQL function.

    +
    // ABS(amount)
    +abs(Column("amount"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func abs(_ value: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + average(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an expression that evaluates the AVG SQL function.

    +
    // AVG(length)
    +average(Column("length"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func average(_ value: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + count(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an expression that evaluates the COUNT SQL function.

    +
    // COUNT(email)
    +count(Column("email"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func count(_ counted: SQLSelectable) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + count(distinct:) + +
    +
    +
    +
    +
    +
    +

    Returns an expression that evaluates the COUNT(DISTINCT) SQL function.

    +
    // COUNT(DISTINCT email)
    +count(distinct: Column("email"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func count(distinct value: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + ??(_:_:) + +
    +
    +
    +
    +
    +
    +

    Returns an expression that evaluates the IFNULL SQL function.

    +
    // IFNULL(name, 'Anonymous')
    +Column("name") ?? "Anonymous"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func ?? (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + length(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an expression that evaluates the LENGTH SQL function.

    +
    // LENGTH(name)
    +length(Column("name"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func length(_ value: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + max(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an expression that evaluates the MAX SQL function.

    +
    // MAX(score)
    +max(Column("score"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func max(_ value: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + min(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an expression that evaluates the MIN SQL function.

    +
    // MIN(score)
    +min(Column("score"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func min(_ value: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + sum(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an expression that evaluates the SUM SQL function.

    +
    // SUM(amount)
    +sum(Column("amount"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func sum(_ value: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + ==(_:_:) + +
    +
    +
    +
    +
    +
    +

    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
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func == (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ==(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the = SQL operator.

    +
    // name = 'Arthur' COLLATE NOCASE
    +Column("name").collating(.nocase) == "Arthur"
    +
    + +

    When the right operand is nil, IS NULL is used instead.

    +
    // name IS NULL
    +Column("name").collating(.nocase) == nil
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func == (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> 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
    +Column("validated") == true
    +
    +// NOT validated
    +Column("validated") == false
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func == (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ==(_:_:) + +
    +
    +
    +
    +
    +
    +

    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")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func == (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ==(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the = SQL operator.

    +
    // 'Arthur' = name COLLATE NOCASE
    +"Arthur" == Column("name").collating(.nocase)
    +
    + +

    When the left operand is nil, IS NULL is used instead.

    +
    // name IS NULL
    +nil == Column("name").collating(.nocase)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func == (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> 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")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func == (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ==(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the = SQL operator.

    +
    // email = login
    +Column("email") == Column("login")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func == (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> 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
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func != (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + !=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the <> SQL operator.

    +
    // name <> 'Arthur' COLLATE NOCASE
    +Column("name").collating(.nocase) != "Arthur"
    +
    + +

    When the right operand is nil, IS NOT NULL is used instead.

    +
    // name IS NOT NULL
    +Column("name").collating(.nocase) != nil
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func != (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + !=(_:_:) + +
    +
    +
    +
    +
    +
    +

    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
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func != (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + !=(_:_:) + +
    +
    +
    +
    +
    +
    +

    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")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func != (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + !=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the <> SQL operator.

    +
    // 'Arthur' <> name COLLATE NOCASE
    +"Arthur" != Column("name").collating(.nocase)
    +
    + +

    When the left operand is nil, IS NOT NULL is used instead.

    +
    // name IS NOT NULL
    +nil != Column("name").collating(.nocase)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func != (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + !=(_:_:) + +
    +
    +
    +
    +
    +
    +

    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")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func != (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + !=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the <> SQL operator.

    +
    // email <> login
    +Column("email") != Column("login")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func != (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ===(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the IS SQL operator.

    +
    // name IS 'Arthur'
    +Column("name") === "Arthur"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func === (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ===(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the IS SQL operator.

    +
    // name IS 'Arthur' COLLATE NOCASE
    +Column("name").collating(.nocase) === "Arthur"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func === (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ===(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the IS SQL operator.

    +
    // name IS 'Arthur'
    +"Arthur" === Column("name")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func === (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ===(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the IS SQL operator.

    +
    // name IS 'Arthur' COLLATE NOCASE
    +"Arthur" === Column("name").collating(.nocase)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func === (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ===(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the IS SQL operator.

    +
    // email IS login
    +Column("email") === Column("login")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func === (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + !==(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the IS NOT SQL operator.

    +
    // name IS NOT 'Arthur'
    +Column("name") !== "Arthur"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func !== (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + !==(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the IS NOT SQL operator.

    +
    // name IS NOT 'Arthur' COLLATE NOCASE
    +Column("name").collating(.nocase) !== "Arthur"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func !== (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + !==(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the IS NOT SQL operator.

    +
    // name IS NOT 'Arthur'
    +"Arthur" !== Column("name")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func !== (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + !==(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the IS NOT SQL operator.

    +
    // name IS NOT 'Arthur' COLLATE NOCASE
    +"Arthur" !== Column("name").collating(.nocase)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func !== (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + !==(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the IS NOT SQL operator.

    +
    // email IS NOT login
    +Column("email") !== Column("login")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func !== (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + <(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the < SQL operator.

    +
    // score < 18
    +Column("score") < 18
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func < (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + <(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the < SQL operator.

    +
    // name < 'Arthur' COLLATE NOCASE
    +Column("name").collating(.nocase) < "Arthur"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func < (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + <(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the < SQL operator.

    +
    // 18 < score
    +18 < Column("score")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func < (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + <(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the < SQL operator.

    +
    // 'Arthur' < name COLLATE NOCASE
    +"Arthur" < Column("name").collating(.nocase)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func < (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + <(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the < SQL operator.

    +
    // width < height
    +Column("width") < Column("height")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func < (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + <=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the <= SQL operator.

    +
    // score <= 18
    +Column("score") <= 18
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func <= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + <=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the <= SQL operator.

    +
    // name <= 'Arthur' COLLATE NOCASE
    +Column("name").collating(.nocase) <= "Arthur"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func <= (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + <=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the <= SQL operator.

    +
    // 18 <= score
    +18 <= Column("score")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func <= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + <=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the <= SQL operator.

    +
    // 'Arthur' <= name COLLATE NOCASE
    +"Arthur" <= Column("name").collating(.nocase)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func <= (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + <=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the <= SQL operator.

    +
    // width <= height
    +Column("width") <= Column("height")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func <= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + >(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the > SQL operator.

    +
    // score > 18
    +Column("score") > 18
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func > (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + >(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the > SQL operator.

    +
    // name > 'Arthur' COLLATE NOCASE
    +Column("name").collating(.nocase) > "Arthur"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func > (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + >(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the > SQL operator.

    +
    // 18 > score
    +18 > Column("score")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func > (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + >(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the > SQL operator.

    +
    // 'Arthur' > name COLLATE NOCASE
    +"Arthur" > Column("name").collating(.nocase)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func > (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + >(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the > SQL operator.

    +
    // width > height
    +Column("width") > Column("height")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func > (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + >=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the >= SQL operator.

    +
    // score >= 18
    +Column("score") >= 18
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func >= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + >=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the >= SQL operator.

    +
    // name >= 'Arthur' COLLATE NOCASE
    +Column("name").collating(.nocase) >= "Arthur"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func >= (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + >=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the >= SQL operator.

    +
    // 18 >= score
    +18 >= Column("score")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func >= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + >=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the >= SQL operator.

    +
    // 'Arthur' >= name COLLATE NOCASE
    +"Arthur" >= Column("name").collating(.nocase)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func >= (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + >=(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL expression that compares two expressions with the >= SQL operator.

    +
    // width >= height
    +Column("width") >= Column("height")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func >= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + *(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL arithmetic multiplication.

    +
    // width * 2
    +Column("width") * 2
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func * (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + *(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL arithmetic multiplication.

    +
    // 2 * width
    +2 * Column("width")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func * (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + *(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL arithmetic multiplication.

    +
    // width * height
    +Column("width") * Column("height")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func * (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + /(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL arithmetic division.

    +
    // width / 2
    +Column("width") / 2
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func / (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + /(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL arithmetic division.

    +
    // 2 / width
    +2 / Column("width")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func / (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + /(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL arithmetic division.

    +
    // width / height
    +Column("width") / Column("height")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func / (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + +(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL arithmetic addition.

    +
    // width + 2
    +Column("width") + 2
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func + (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + +(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL arithmetic addition.

    +
    // 2 + width
    +2 + Column("width")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func + (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + +(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL arithmetic addition.

    +
    // width + height
    +Column("width") + Column("height")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func + (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + -(_:) + +
    +
    +
    +
    +
    +
    +

    A negated SQL arithmetic expression.

    +
    // -width
    +-Column("width")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public prefix func - (value: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + -(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL arithmetic substraction.

    +
    // width - 2
    +Column("width") - 2
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func - (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + -(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL arithmetic substraction.

    +
    // 2 - width
    +2 - Column("width")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func - (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + -(_:_:) + +
    +
    +
    +
    +
    +
    +

    An SQL arithmetic substraction.

    +
    // width - height
    +Column("width") - Column("height")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func - (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + &&(_:_:) + +
    +
    +
    +
    +
    +
    +

    A logical SQL expression with the AND SQL operator.

    +
    // favorite AND 0
    +Column("favorite") && false
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + &&(_:_:) + +
    +
    +
    +
    +
    +
    +

    A logical SQL expression with the AND SQL operator.

    +
    // 0 AND favorite
    +false && Column("favorite")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func && (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + &&(_:_:) + +
    +
    +
    +
    +
    +
    +

    A logical SQL expression with the AND SQL operator.

    +
    // email IS NOT NULL AND favorite
    +Column("email") != nil && Column("favorite")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func && (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ||(_:_:) + +
    +
    +
    +
    +
    +
    +

    A logical SQL expression with the OR SQL operator.

    +
    // favorite OR 1
    +Column("favorite") || true
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ||(_:_:) + +
    +
    +
    +
    +
    +
    +

    A logical SQL expression with the OR SQL operator.

    +
    // 0 OR favorite
    +true || Column("favorite")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func || (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ||(_:_:) + +
    +
    +
    +
    +
    +
    +

    A logical SQL expression with the OR SQL operator.

    +
    // email IS NULL OR hidden
    +Column("email") == nil || Column("hidden")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func || (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> 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")))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public prefix func ! (value: SQLSpecificExpressible) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ + + +

Public

+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Return as many question marks separated with commas as the count argument.

    +
    databaseQuestionMarks(count: 3) // "?,?,?"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func databaseQuestionMarks(count: Int) -> String
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols.html new file mode 100644 index 000000000..10bab949c --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols.html @@ -0,0 +1,1702 @@ + + + + Protocols Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Protocols

+

The following protocols are available globally.

+ +
+
+
+
+ + + +

Cursor

+
+
+
    +
  • +
    + + + + Cursor + +
    +
    +
    +
    +
    +
    +

    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 Sequence protocol: contains, dropFirst, +dropLast, drop(while:), enumerated, filter, first, flatMap, +forEach, joined, joined(separator:), max, max(by:), min, +min(by:), map, prefix, prefix(while:), reduce, reduce(into:), +suffix.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol Cursor : AnyObject
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + DatabaseAggregate + +
    +
    +
    +
    +
    +
    +

    The protocol for custom SQLite aggregates.

    + +

    For example:

    +
    struct MySum : DatabaseAggregate {
    +    var sum: Int = 0
    +
    +    mutating func step(_ dbValues: [DatabaseValue]) {
    +        if let int = Int.fromDatabaseValue(dbValues[0]) {
    +            sum += int
    +        }
    +    }
    +
    +    func finalize() -> DatabaseValueConvertible? {
    +        return sum
    +    }
    +}
    +
    +let dbQueue = DatabaseQueue()
    +let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
    +dbQueue.add(function: fn)
    +try dbQueue.write { db in
    +    try db.execute("CREATE TABLE test(i)")
    +    try db.execute("INSERT INTO test(i) VALUES (1)")
    +    try db.execute("INSERT INTO test(i) VALUES (2)")
    +    try Int.fetchOne(db, "SELECT mysum(i) FROM test")! // 3
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol DatabaseAggregate
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + DatabaseReader + +
    +
    +
    +
    +
    +
    +

    The protocol for all types that can fetch values from a database.

    + +

    It is adopted by DatabaseQueue and DatabasePool.

    + +

    The protocol comes with isolation guarantees that describe the behavior of +adopting types in a multithreaded application.

    + +

    Types that adopt the protocol can provide in practice stronger guarantees. +For example, DatabaseQueue provides a stronger isolation level +than DatabasePool.

    + +

    Warning: Isolation guarantees stand as long as there is no external +connection to the database. Should you have to cope with external +connections, protect yourself with transactions, and be ready to setup a +busy handler.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol DatabaseReader : AnyObject
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Types that adopt DatabaseValueConvertible can be initialized from +database values.

    + +

    The protocol comes with built-in methods that allow to fetch cursors, +arrays, or single values:

    +
    try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String
    +try String.fetchAll(db, "SELECT name FROM ...", arguments:...)    // [String]
    +try String.fetchOne(db, "SELECT name FROM ...", arguments:...)    // String?
    +
    +let statement = try db.makeSelectStatement("SELECT name FROM ...")
    +try String.fetchCursor(statement, arguments:...) // Cursor of String
    +try String.fetchAll(statement, arguments:...)    // [String]
    +try String.fetchOne(statement, arguments:...)    // String?
    +
    + +

    DatabaseValueConvertible is adopted by Bool, Int, String, etc.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol DatabaseValueConvertible : SQLExpressible
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + FetchRequest + +
    +
    +
    +
    +
    +
    +

    The protocol for all requests that run from a single select statement, and +tell how fetched rows should be interpreted.

    +
    struct Player: FetchableRecord { ... }
    +let request: ... // Some FetchRequest that fetches Player
    +try request.fetchCursor(db) // Cursor of Player
    +try request.fetchAll(db)    // [Player]
    +try request.fetchOne(db)    // Player?
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol FetchRequest
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + DatabaseWriter + +
    +
    +
    +
    +
    +
    +

    The protocol for all types that can update a database.

    + +

    It is adopted by DatabaseQueue and DatabasePool.

    + +

    The protocol comes with isolation guarantees that describe the behavior of +adopting types in a multithreaded application.

    + +

    Types that adopt the protocol can in practice provide stronger guarantees. +For example, DatabaseQueue provides a stronger isolation level +than DatabasePool.

    + +

    Warning: Isolation guarantees stand as long as there is no external +connection to the database. Should you have to cope with external +connections, protect yourself with transactions, and be ready to setup a +busy handler.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol DatabaseWriter : DatabaseReader
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + RowAdapter + +
    +
    +
    +
    +
    +
    +

    RowAdapter is a protocol that helps two incompatible row interfaces working +together.

    + +

    GRDB ships with four concrete types that adopt the RowAdapter protocol:

    + +
      +
    • ColumnMapping: renames row columns
    • +
    • SuffixRowAdapter: hides the first columns of a row
    • +
    • RangeRowAdapter: only exposes a range of columns
    • +
    • ScopeAdapter: groups several adapters together to define named scopes
    • +
    + +

    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, adapter: adapter)
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol RowAdapter
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    The StatementColumnConvertible protocol grants access to the low-level C +interface that extracts values from query results: +https://www.sqlite.org/c3ref/column_blob.html. It can bring performance +improvements.

    + +

    To use it, have a value type adopt both StatementColumnConvertible and +DatabaseValueConvertible. GRDB will then automatically apply the +optimization whenever direct access to SQLite is possible:

    +
    let rows = Row.fetchCursor(db, "SELECT ...")
    +while let row = try rows.next() {
    +    let int: Int = row[0]                 // there
    +}
    +let ints = Int.fetchAll(db, "SELECT ...") // there
    +struct Player {
    +    init(row: Row) {
    +        name = row["name"]                // there
    +        score = row["score"]              // there
    +    }
    +}
    +
    + +

    StatementColumnConvertible is already adopted by all Swift integer types, +Float, Double, String, and Bool.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol StatementColumnConvertible
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + TransactionObserver + +
    +
    +
    +
    +
    +
    +

    A transaction observer is notified of all changes and transactions committed +or rollbacked on a database.

    + +

    Adopting types must be a class.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol TransactionObserver : AnyObject
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
+
+ +
+
+
    +
  • +
    + + + + FTS5WrapperTokenizer + +
    +
    +
    +
    +
    +
    +

    The protocol for custom FTS5 tokenizers that wrap another tokenizer.

    + +

    Types that adopt FTS5WrapperTokenizer don’t have to implement the +low-level FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:).

    + +

    Instead, they process regular Swift strings.

    + +

    Here is the implementation for a trivial tokenizer that wraps the +built-in ascii tokenizer without any custom processing:

    +
    class TrivialAsciiTokenizer : FTS5WrapperTokenizer {
    +    static let name = "trivial"
    +    let wrappedTokenizer: FTS5Tokenizer
    +
    +    init(db: Database, arguments: [String]) throws {
    +        wrappedTokenizer = try db.makeTokenizer(.ascii())
    +    }
    +
    +    func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws {
    +        try tokenCallback(token, flags)
    +    }
    +}
    +
    + + See more +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + Association + +
    +
    +
    +
    +
    +
    +

    Experimental

    + +

    The base protocol for all associations that define a connection between two +record types.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol Association : DerivableRequest
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + TableRecord + +
    +
    +
    +
    +
    +
    +

    Types that adopt TableRecord declare a particular relationship with +a database table.

    + +

    Types that adopt both TableRecord and FetchableRecord are granted with +built-in methods that allow to fetch instances identified by key:

    +
    try Player.fetchOne(db, key: 123)  // Player?
    +try Citizenship.fetchOne(db, key: ["citizenId": 12, "countryId": 45]) // Citizenship?
    +
    + +

    TableRecord is adopted by Record.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol TableRecord
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + ColumnExpression + +
    +
    +
    +
    +
    +
    +

    Adopt the ColumnExpression protocol when you define a column type.

    + +

    You can, for example, define a String-based column enum:

    +
    enum Columns: String, ColumnExpression {
    +    case id, name, score
    +}
    +let arthur = try Player.filter(Columns.name == "Arthur").fetchOne(db)
    +
    + +

    You can also define a genuine column type:

    +
    struct MyColumn: ColumnExpression {
    +    var name: String
    +    var sqlType: String
    +}
    +let nameColumn = MyColumn(name: "name", sqlType: "VARCHAR")
    +let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db)
    +
    + +

    See https://github.com/groue/GRDB.swift#the-query-interface

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol ColumnExpression : SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+
    +
  • +
    + + + + VirtualTableModule + +
    +
    +
    +
    +
    +
    +

    The protocol for SQLite virtual table modules. It lets you define a DSL for +the Database.create(virtualTable:using:) method:

    +
    let module = ...
    +try db.create(virtualTable: "item", using: module) { t in
    +    ...
    +}
    +
    + +

    GRDB ships with three concrete classes that implement this protocol: FTS3, +FTS4 and FTS5.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol VirtualTableModule
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + FetchableRecord + +
    +
    +
    +
    +
    +
    +

    Types that adopt FetchableRecord can be initialized from a database Row.

    +
    let row = try Row.fetchOne(db, "SELECT ...")!
    +let player = Player(row)
    +
    + +

    The protocol comes with built-in methods that allow to fetch cursors, +arrays, or single records:

    +
    try Player.fetchCursor(db, "SELECT ...", arguments:...) // Cursor of Player
    +try Player.fetchAll(db, "SELECT ...", arguments:...)    // [Player]
    +try Player.fetchOne(db, "SELECT ...", arguments:...)    // Player?
    +
    +let statement = try db.makeSelectStatement("SELECT ...")
    +try Player.fetchCursor(statement, arguments:...) // Cursor of Player
    +try Player.fetchAll(statement, arguments:...)    // [Player]
    +try Player.fetchOne(statement, arguments:...)    // Player?
    +
    + +

    FetchableRecord is adopted by Record.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol FetchableRecord
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + PersistableRecord + +
    +
    +
    +
    +
    +
    +

    Types that adopt PersistableRecord can be inserted, updated, and deleted.

    + +

    This protocol is intented for types that don’t have an INTEGER PRIMARY KEY.

    + +

    Unlike MutablePersistableRecord, the insert() and save() methods are not +mutating methods.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public protocol PersistableRecord : MutablePersistableRecord
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/Association.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/Association.html new file mode 100644 index 000000000..539167c57 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/Association.html @@ -0,0 +1,1412 @@ + + + + Association Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Association

+
+
+
public protocol Association : DerivableRequest
+ +
+
+

Experimental

+ +

The base protocol for all associations that define a connection between two +record types.

+ +
+
+
+
    +
  • +
    + + + + OriginRowDecoder + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    associatedtype OriginRowDecoder
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + RowDecoder + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    associatedtype RowDecoder
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + key + +
    +
    +
    +
    +
    +
    +

    The association key defines how rows fetched from this association +should be consumed.

    + +

    For example:

    +
    struct Player: TableRecord {
    +    // The default key of this association is the name of the
    +    // database table for teams, let's say "team":
    +    static let team = belongsTo(Team.self)
    +}
    +print(Player.team.key) // Prints "team"
    +
    +// Consume rows:
    +let request = Player.including(required: Player.team)
    +for row in Row.fetchAll(db, request) {
    +    let team: Team = row["team"] // the association key
    +}
    +
    + +

    The key can be redefined with the forKey method:

    +
    let request = Player.including(required: Player.team.forKey("custom"))
    +for row in Row.fetchAll(db, request) {
    +    let team: Team = row["custom"]
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    var key: String { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + forKey(_:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Creates an association with the given key.

    + +

    This new key impacts how rows fetched from the resulting association +should be consumed:

    +
    struct Player: TableRecord {
    +    static let team = belongsTo(Team.self)
    +}
    +
    +// Consume rows:
    +let request = Player.including(required: Player.team.forKey("custom"))
    +for row in Row.fetchAll(db, request) {
    +    let team: Team = row["custom"]
    +}
    +
    + +
    +

    Default Implementation

    +
    +

    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)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func forKey(_ key: String) -> Self
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + select(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    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([Column("color")])
    +var request = Player.including(required: association)
    +
    + +

    Any previous selection is replaced:

    +
    // SELECT player.*, team.color
    +// FROM player
    +// JOIN team ON team.id = player.teamId
    +let association = Player.team
    +    .select([Column("id")])
    +    .select([Column("color")])
    +var request = Player.including(required: association)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func select(_ selection: [SQLSelectable]) -> Self
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + filter(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    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)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + order(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    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)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + reversed() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    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)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func reversed() -> Self
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + aliased(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    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"])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func aliased(_ alias: TableAlias) -> Self
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + including(optional:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates an association that includes another one. The columns of the +associated record are selected. The returned association does not +require that the associated database table contains a matching row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func including<A>(optional association: A) -> Self where A : Association, Self.RowDecoder == A.OriginRowDecoder
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + including(required:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates an association that includes another one. The columns of the +associated record are selected. The returned association requires +that the associated database table contains a matching row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func including<A>(required association: A) -> Self where A : Association, Self.RowDecoder == A.OriginRowDecoder
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + joining(optional:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates an association that joins another one. The columns of the +associated record are not selected. The returned association does not +require that the associated database table contains a matching row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func joining<A>(optional association: A) -> Self where A : Association, Self.RowDecoder == A.OriginRowDecoder
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + joining(required:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates an association that joins another one. The columns of the +associated record are not selected. The returned association requires +that the associated database table contains a matching row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func joining<A>(required association: A) -> Self where A : Association, Self.RowDecoder == A.OriginRowDecoder
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/ColumnExpression.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/ColumnExpression.html new file mode 100644 index 000000000..06d1b87a8 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/ColumnExpression.html @@ -0,0 +1,911 @@ + + + + ColumnExpression Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ColumnExpression

+
+
+
public protocol ColumnExpression : SQLExpression
+ +
+
+

Adopt the ColumnExpression protocol when you define a column type.

+ +

You can, for example, define a String-based column enum:

+
enum Columns: String, ColumnExpression {
+    case id, name, score
+}
+let arthur = try Player.filter(Columns.name == "Arthur").fetchOne(db)
+
+ +

You can also define a genuine column type:

+
struct MyColumn: ColumnExpression {
+    var name: String
+    var sqlType: String
+}
+let nameColumn = MyColumn(name: "name", sqlType: "VARCHAR")
+let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db)
+
+ +

See https://github.com/groue/GRDB.swift#the-query-interface

+ +
+
+
+
    +
  • +
    + + + + name + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    The unqualified name of a database column.

    + +

    score is a valid unqualified name. player.score is not.

    + +
    +

    Default Implementation

    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    var name: String { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + match(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    A matching SQL expression with the MATCH SQL operator.

    +
    // content MATCH '...'
    +Column("content").match(pattern)
    +
    + +

    If the search pattern is nil, SQLite will evaluate the expression +to false.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func match(_ pattern: FTS3Pattern?) -> SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/Cursor.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/Cursor.html new file mode 100644 index 000000000..3b626c16a --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/Cursor.html @@ -0,0 +1,2251 @@ + + + + Cursor Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Cursor

+
+
+
public protocol Cursor : AnyObject
+ +
+
+

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 Sequence protocol: contains, dropFirst, +dropLast, drop(while:), enumerated, filter, first, flatMap, +forEach, joined, joined(separator:), max, max(by:), min, +min(by:), map, prefix, prefix(while:), reduce, reduce(into:), +suffix.

+ +
+
+
+
    +
  • +
    + + + + Element + +
    +
    +
    +
    +
    +
    +

    The type of element traversed by the cursor.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    associatedtype Element
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + next() + +
    +
    +
    +
    +
    +
    +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func next() throws -> Element?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ + + +

Cursor

+
+
+
    +
  • +
    + + + + contains(where:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a Boolean value indicating whether the cursor contains an +element that satisfies the given predicate.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func contains(where predicate: (Element) throws -> Bool) throws -> Bool
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + 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.

    +
    +
    +
    +
    +

    Return Value

    +

    true if the cursor contains an element that satisfies +predicate; otherwise, false.

    +
    + +
    +
    +
  • +
  • +
    + + + + enumerated() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    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"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func enumerated() -> EnumeratedCursor<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + filter(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns the elements of the cursor that satisfy the given predicate.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func filter(_ isIncluded: @escaping (Element) throws -> Bool) -> FilterCursor<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + first(where:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns the first element of the cursor that satisfies the given +predicate or nil if no such element is found.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func first(where predicate: (Element) throws -> Bool) throws -> Element?
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + compactMap(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over the concatenated non-nil results of mapping +transform over this cursor.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func compactMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + flatMap(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func flatMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + drop(while:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor that skips any initial elements that satisfy +predicate.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func drop(while predicate: @escaping (Element) throws -> Bool) -> DropWhileCursor<Self>
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + predicate + + +
    +

    A closure that takes an element of the cursir as +its argument and returns true if the element should be skipped or +false otherwise. Once predicate returns false it will not be +called again.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + dropFirst(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor containing all but the given number of initial +elements.

    + +

    If the number of elements to drop exceeds the number of elements in +the cursor, the result is an empty cursor.

    +
    let numbers = AnyCursor([1, 2, 3, 4, 5])
    +try print(numbers.dropFirst(2))
    +// Prints "[3, 4, 5]"
    +try print(numbers.dropFirst(10))
    +// Prints "[]"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func dropFirst(_ n: Int) -> DropFirstCursor<Self>
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + n + + +
    +

    The number of elements to drop from the beginning of +the cursor. n must be greater than or equal to zero.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor starting after the specified number of +elements.

    +
    + +
    +
    +
  • +
  • +
    + + + + dropFirst() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor containing all but the first element of the cursor.

    + +

    The following example drops the first element from a cursor of integers.

    +
    let numbers = AnyCursor([1, 2, 3, 4, 5])
    +try print(numbers.dropFirst())
    +// Prints "[2, 3, 4, 5]"
    +
    + +

    If the cursor has no elements, the result is an empty cursor.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func dropFirst() -> DropFirstCursor<Self>
    + +
    +
    +
    +

    Return Value

    +

    A cursor starting after the first element of the cursor.

    +
    + +
    +
    +
  • +
  • +
    + + + + dropLast(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array containing all but the given number of final +elements.

    + +

    The cursor must be finite. If the number of elements to drop exceeds +the number of elements in the cursor, the result is an empty array.

    +
    let numbers = AnyCursor([1, 2, 3, 4, 5])
    +try print(numbers.dropLast(2))
    +// Prints "[1, 2, 3]"
    +try print(numbers.dropLast(10))
    +// Prints "[]"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func dropLast(_ n: Int) throws -> [Element]
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + n + + +
    +

    The number of elements to drop off the end of the +cursor. n must be greater than or equal to zero.

    +
    +
    +
    +
    +

    Return Value

    +

    An array leaving off the specified number of elements.

    +
    + +
    +
    +
  • +
  • +
    + + + + dropLast() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array containing all but the last element of the cursor.

    + +

    The following example drops the last element from a cursor of integers.

    +
    let numbers = AnyCursor([1, 2, 3, 4, 5])
    +try print(numbers.dropLast())
    +// Prints "[1, 2, 3, 4]"
    +
    + +

    If the cursor has no elements, the result is an empty cursor.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func dropLast() throws -> [Element]
    + +
    +
    +
    +

    Return Value

    +

    An array leaving off the last element of the cursor.

    +
    + +
    +
    +
  • +
  • +
    + + + + flatMap(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over the concatenated results of mapping transform +over self.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func flatMap<SegmentOfResult: Sequence>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, AnyCursor<SegmentOfResult.Element>>>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + flatMap(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over the concatenated results of mapping transform +over self.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, SegmentOfResult>>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + forEach(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Calls the given closure on each element in the cursor.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func forEach(_ body: (Element) throws -> Void) throws
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + map(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over the results of the transform function applied to +this cursor’s elements.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func map<T>(_ transform: @escaping (Element) throws -> T) -> MapCursor<Self, T>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + max(by:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns the maximum element in the cursor, using the given predicate as +the comparison between elements.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func max(by areInIncreasingOrder: (Element, Element) throws -> Bool) throws -> Element?
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + areInIncreasingOrder + + +
    +

    A predicate that returns true +if its first argument should be ordered before its second +argument; otherwise, false.

    +
    +
    +
    +
    +

    Return Value

    +

    The cursor’s maximum element, according to +areInIncreasingOrder. If the cursor has no elements, returns nil.

    +
    + +
    +
    +
  • +
  • +
    + + + + min(by:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns the minimum element in the cursor, using the given predicate as +the comparison between elements.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func min(by areInIncreasingOrder: (Element, Element) throws -> Bool) throws -> Element?
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + areInIncreasingOrder + + +
    +

    A predicate that returns true +if its first argument should be ordered before its second +argument; otherwise, false.

    +
    +
    +
    +
    +

    Return Value

    +

    The cursor’s minimum element, according to +areInIncreasingOrder. If the cursor has no elements, returns nil.

    +
    + +
    +
    +
  • +
  • +
    + + + + prefix(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor, up to the specified maximum length, containing the +initial elements of the cursor.

    + +

    If the maximum length exceeds the number of elements in the cursor, +the result contains all the elements in the cursor.

    +
    let numbers = AnyCursor([1, 2, 3, 4, 5])
    +try print(numbers.prefix(2))
    +// Prints "[1, 2]"
    +try print(numbers.prefix(10))
    +// Prints "[1, 2, 3, 4, 5]"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func prefix(_ maxLength: Int) -> PrefixCursor<Self>
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + maxLength + + +
    +

    The maximum number of elements to return. The +value of maxLength must be greater than or equal to zero.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor starting at the beginning of this cursor +with at most maxLength elements.

    +
    + +
    +
    +
  • +
  • +
    + + + + prefix(while:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor of the initial consecutive elements that satisfy +predicate.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func prefix(while predicate: @escaping (Element) throws -> Bool) -> PrefixWhileCursor<Self>
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + predicate + + +
    +

    A closure that takes an element of the cursor as +its argument and returns true if the element should be included or +false otherwise. Once predicate returns false it will not be +called again.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + reduce(_:_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns the result of calling the given combining closure with each +element of this cursor and an accumulating value.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func reduce<Result>(
    +    _ initialResult: Result,
    +    _ nextPartialResult: (Result, Element) throws -> Result)
    +    throws -> Result
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + reduce(into:_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns the result of calling the given combining closure with each +element of this cursor and an accumulating value.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func reduce<Result>(
    +    into initialResult: Result,
    +    _ updateAccumulatingResult: (inout Result, Element) throws -> Void)
    +    throws -> Result
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + suffix(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array, up to the given maximum length, containing the +final elements of the cursor.

    + +

    The cursor must be finite. If the maximum length exceeds the number of +elements in the cursor, the result contains all the elements in the +cursor.

    +
    let numbers = AnyCursor([1, 2, 3, 4, 5])
    +try print(numbers.suffix(2))
    +// Prints "[4, 5]"
    +try print(numbers.suffix(10))
    +// Prints "[1, 2, 3, 4, 5]"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func suffix(_ maxLength: Int) throws -> [Element]
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + maxLength + + +
    +

    The maximum number of elements to return. The +value of maxLength must be greater than or equal to zero.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + contains(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a Boolean value indicating whether the cursor contains the +given element.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func contains(_ element: Element) throws -> Bool
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + max() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns the maximum element in the cursor.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func max() throws -> Element?
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + areInIncreasingOrder + + +
    +

    A predicate that returns true +if its first argument should be ordered before its second +argument; otherwise, false.

    +
    +
    +
    +
    +

    Return Value

    +

    The cursor’s maximum element, according to +areInIncreasingOrder. If the cursor has no elements, returns +nil.

    +
    + +
    +
    +
  • +
  • +
    + + + + min() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns the minimum element in the cursor.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func min() throws -> Element?
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + areInIncreasingOrder + + +
    +

    A predicate that returns true +if its first argument should be ordered before its second +argument; otherwise, false.

    +
    +
    +
    +
    +

    Return Value

    +

    The cursor’s minimum element, according to +areInIncreasingOrder. If the cursor has no elements, returns +nil.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + joined() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns the elements of this cursor of cursors, concatenated.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func joined() -> FlattenCursor<Self>
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + joined() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns the elements of this cursor of sequences, concatenated.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func joined() -> FlattenCursor<MapCursor<Self, AnyCursor<Element.Element>>>
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + joined(separator:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns the elements of this cursor of sequences, concatenated.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func joined(separator: String = "") throws -> String
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/DatabaseAggregate.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/DatabaseAggregate.html new file mode 100644 index 000000000..0f9a472b1 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/DatabaseAggregate.html @@ -0,0 +1,938 @@ + + + + DatabaseAggregate Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseAggregate

+
+
+
public protocol DatabaseAggregate
+ +
+
+

The protocol for custom SQLite aggregates.

+ +

For example:

+
struct MySum : DatabaseAggregate {
+    var sum: Int = 0
+
+    mutating func step(_ dbValues: [DatabaseValue]) {
+        if let int = Int.fromDatabaseValue(dbValues[0]) {
+            sum += int
+        }
+    }
+
+    func finalize() -> DatabaseValueConvertible? {
+        return sum
+    }
+}
+
+let dbQueue = DatabaseQueue()
+let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
+dbQueue.add(function: fn)
+try dbQueue.write { db in
+    try db.execute("CREATE TABLE test(i)")
+    try db.execute("INSERT INTO test(i) VALUES (1)")
+    try db.execute("INSERT INTO test(i) VALUES (2)")
+    try Int.fetchOne(db, "SELECT mysum(i) FROM test")! // 3
+}
+
+ +
+
+
+
    +
  • +
    + + + + init() + +
    +
    +
    +
    +
    +
    +

    Creates an aggregate.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    init()
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + step(_:) + +
    +
    +
    +
    +
    +
    +

    This method is called at each step of the aggregation.

    + +

    The dbValues argument contains as many values as given to the SQL +aggregate function.

    + +

    – One value + SELECT maxLength(name) FROM player

    + +

    – Two values + SELECT maxFullNameLength(firstName, lastName) FROM player

    + +

    This method is never called after the finalize() method has been called.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    mutating func step(_ dbValues: [DatabaseValue]) throws
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + finalize() + +
    +
    +
    +
    +
    +
    +

    Returns the final result

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func finalize() throws -> DatabaseValueConvertible?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/DatabaseReader.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/DatabaseReader.html new file mode 100644 index 000000000..f6ebbd952 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/DatabaseReader.html @@ -0,0 +1,1278 @@ + + + + DatabaseReader Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseReader

+
+
+
public protocol DatabaseReader : AnyObject
+ +
+
+

The protocol for all types that can fetch values from a database.

+ +

It is adopted by DatabaseQueue and DatabasePool.

+ +

The protocol comes with isolation guarantees that describe the behavior of +adopting types in a multithreaded application.

+ +

Types that adopt the protocol can provide in practice stronger guarantees. +For example, DatabaseQueue provides a stronger isolation level +than DatabasePool.

+ +

Warning: Isolation guarantees stand as long as there is no external +connection to the database. Should you have to cope with external +connections, protect yourself with transactions, and be ready to setup a +busy handler.

+ +
+
+
+ +
    +
  • +
    + + + + read(_:) + +
    +
    +
    +
    +
    +
    +

    Synchronously executes a read-only block that takes a database +connection, and returns its result.

    + +

    Guarantee 1: the block argument is isolated. Eventual concurrent +database updates are not visible inside the block:

    +
    try reader.read { db in
    +    // Those two values are guaranteed to be equal, even if the
    +    // `wine` table is modified between the two requests:
    +    let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +    let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +}
    +
    +try reader.read { db in
    +    // Now this value may be different:
    +    let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +}
    +
    + +

    Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds +and SQLCipher, attempts to write in the database throw a DatabaseError +whose resultCode is SQLITE_READONLY.

    +
    +

    Throws

    + The error thrown by the block, or any DatabaseError that would +happen while establishing the read access to the database. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func read<T>(_ block: (Database) throws -> T) throws -> T
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + block + + +
    +

    A block that accesses the database.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + unsafeRead(_:) + +
    +
    +
    +
    +
    +
    +

    Synchronously executes a read-only block that takes a database +connection, and returns its result.

    + +

    The two guarantees of the safe read method are lifted:

    + +

    The block argument is not isolated: eventual concurrent database updates +are visible inside the block:

    +
    try reader.unsafeRead { db in
    +    // Those two values may be different because some other thread
    +    // may have inserted or deleted a wine between the two requests:
    +    let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +    let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +}
    +
    + +

    Cursor iterations are isolated, though:

    +
    try reader.unsafeRead { db in
    +    // No concurrent update can mess with this iteration:
    +    let rows = try Row.fetchCursor(db, "SELECT ...")
    +    while let row = try rows.next() { ... }
    +}
    +
    + +

    The block argument is not prevented from writing (DatabaseQueue, in +particular, will accept database modifications in unsafeRead).

    +
    +

    Throws

    + The error thrown by the block, or any DatabaseError that would +happen while establishing the read access to the database. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + block + + +
    +

    A block that accesses the database.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Synchronously executes a block that takes a database connection, and +returns its result.

    + +

    The two guarantees of the safe read method are lifted:

    + +

    The block argument is not isolated: eventual concurrent database updates +are visible inside the block:

    +
    try reader.unsafeReentrantRead { db in
    +    // Those two values may be different because some other thread
    +    // may have inserted or deleted a wine between the two requests:
    +    let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +    let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
    +}
    +
    + +

    Cursor iterations are isolated, though:

    +
    try reader.unsafeReentrantRead { db in
    +    // No concurrent update can mess with this iteration:
    +    let rows = try Row.fetchCursor(db, "SELECT ...")
    +    while let row = try rows.next() { ... }
    +}
    +
    + +

    The block argument is not prevented from writing (DatabaseQueue, in +particular, will accept database modifications in unsafeReentrantRead).

    +
    +

    Throws

    + The error thrown by the block, or any DatabaseError that would +happen while establishing the read access to the database. + +
    + +

    This method is reentrant. It should be avoided because it fosters +dangerous concurrency practices.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + block + + +
    +

    A block that accesses the database.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(function:) + +
    +
    +
    +
    +
    +
    +

    Add or redefine an SQL function.

    +
    let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
    +    guard let int = Int.fromDatabaseValue(dbValues[0]) else {
    +        return nil
    +    }
    +    return int + 1
    +}
    +reader.add(function: fn)
    +try reader.read { db in
    +    try Int.fetchOne(db, "SELECT succ(1)")! // 2
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func add(function: DatabaseFunction)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + remove(function:) + +
    +
    +
    +
    +
    +
    +

    Remove an SQL function.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func remove(function: DatabaseFunction)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(collation:) + +
    +
    +
    +
    +
    +
    +

    Add or redefine a collation.

    +
    let collation = DatabaseCollation("localized_standard") { (string1, string2) in
    +    return (string1 as NSString).localizedStandardCompare(string2)
    +}
    +reader.add(collation: collation)
    +try reader.execute("SELECT * FROM file ORDER BY name COLLATE localized_standard")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func add(collation: DatabaseCollation)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + remove(collation:) + +
    +
    +
    +
    +
    +
    +

    Remove a collation.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func remove(collation: DatabaseCollation)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ + + +

Backup

+
+
+
    +
  • +
    + + + + backup(to:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Copies the database contents into another database.

    + +

    The backup method blocks the current thread until the destination +database contains the same contents as the source database.

    + +

    When the source is a DatabasePool, concurrent writes can happen during +the backup. Those writes may, or may not, be reflected in the backup, +but they won’t trigger any error.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func backup(to writer: DatabaseWriter) throws
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/DatabaseValueConvertible.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/DatabaseValueConvertible.html new file mode 100644 index 000000000..186073d65 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/DatabaseValueConvertible.html @@ -0,0 +1,2603 @@ + + + + DatabaseValueConvertible Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseValueConvertible

+
+
+
public protocol DatabaseValueConvertible : SQLExpressible
+ +
+
+

Types that adopt DatabaseValueConvertible can be initialized from +database values.

+ +

The protocol comes with built-in methods that allow to fetch cursors, +arrays, or single values:

+
try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String
+try String.fetchAll(db, "SELECT name FROM ...", arguments:...)    // [String]
+try String.fetchOne(db, "SELECT name FROM ...", arguments:...)    // String?
+
+let statement = try db.makeSelectStatement("SELECT name FROM ...")
+try String.fetchCursor(statement, arguments:...) // Cursor of String
+try String.fetchAll(statement, arguments:...)    // [String]
+try String.fetchOne(statement, arguments:...)    // String?
+
+ +

DatabaseValueConvertible is adopted by Bool, Int, String, etc.

+ +
+
+
+
    +
  • +
    + + + + databaseValue + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +

    Default Implementation

    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Returns a value initialized from dbValue, if possible.

    + +
    +

    Default Implementation

    +
    +

    Returns a value initialized from dbValue, if possible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    static func fromDatabaseValue(_ dbValue: DatabaseValue) -> `Self`?
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over values fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT name FROM ...")
    +let names = try String.fetchCursor(statement) // Cursor of String
    +while let name = try names.next() { // String
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self>
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array of values fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT name FROM ...")
    +let names = try String.fetchAll(statement)  // [String]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An array.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a single value fetched from a prepared statement.

    + +

    The result is nil if the query returns no row, or if no value can be +extracted from the first row.

    +
    let statement = try db.makeSelectStatement("SELECT name FROM ...")
    +let name = try String.fetchOne(statement)   // String?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self?
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An optional value.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over values fetched from an SQL query.

    +
    let names = try String.fetchCursor(db, "SELECT name FROM ...") // Cursor of String
    +while let name = try name.next() { // String
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self>
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array of values fetched from an SQL query.

    +
    let names = try String.fetchAll(db, "SELECT name FROM ...") // [String]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An array.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a single value fetched from an SQL query.

    + +

    The result is nil if the query returns no row, or if no value can be +extracted from the first row.

    +
    let name = try String.fetchOne(db, "SELECT name FROM ...") // String?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self?
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An optional value.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over values fetched from a fetch request.

    +
    let request = Player.select(Column("name"))
    +let names = try String.fetchCursor(db, request) // Cursor of String
    +while let name = try name.next() { // String
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor<R>(_ db: Database, _ request: R) throws -> DatabaseValueCursor<Self> where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array of values fetched from a fetch request.

    +
    let request = Player.select(Column("name"))
    +let names = try String.fetchAll(db, request) // [String]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll<R>(_ db: Database, _ request: R) throws -> [Self] where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    An array.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a single value fetched from a fetch request.

    + +

    The result is nil if the query returns no row, or if no value can be +extracted from the first row.

    +
    let request = Player.filter(key: 1).select(Column("name"))
    +let name = try String.fetchOne(db, request) // String?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne<R>(_ db: Database, _ request: R) throws -> Self? where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    An optional value.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over values fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT name FROM ...")
    +let names = try String.fetchCursor(statement) // Cursor of String
    +while let name = try names.next() { // String
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor<Self>
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array of values fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT name FROM ...")
    +let names = try String.fetchAll(statement)  // [String]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An array of values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a single value fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT name FROM ...")
    +let name = try String.fetchOne(statement)   // String?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self?
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An optional value.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over values fetched from an SQL query.

    +
    let names = try String.fetchCursor(db, "SELECT name FROM ...") // Cursor of String
    +while let name = try names.next() { // String
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor<Self>
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array of values fetched from an SQL query.

    +
    let names = try String.fetchAll(db, "SELECT name FROM ...") // [String]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An array of values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a single value fetched from an SQL query.

    +
    let name = try String.fetchOne(db, "SELECT name FROM ...") // String?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self?
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An optional value.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over values fetched from a fetch request.

    +
    let request = Player.select(Column("name"))
    +let names = try String.fetchCursor(db, request) // Cursor of String
    +while let name = try names.next() { // String
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor<R>(_ db: Database, _ request: R) throws -> FastDatabaseValueCursor<Self> where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array of values fetched from a fetch request.

    +
    let request = Player.select(Column("name"))
    +let names = try String.fetchAll(db, request) // [String]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll<R>(_ db: Database, _ request: R) throws -> [Self] where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a single value fetched from a fetch request.

    +
    let request = Player.filter(key: 1).select(Column("name"))
    +let name = try String.fetchOne(db, request) // String?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne<R>(_ db: Database, _ request: R) throws -> Self? where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    An optional value.

    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/DatabaseWriter.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/DatabaseWriter.html new file mode 100644 index 000000000..9764b7809 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/DatabaseWriter.html @@ -0,0 +1,1222 @@ + + + + DatabaseWriter Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseWriter

+
+
+
public protocol DatabaseWriter : DatabaseReader
+ +
+
+

The protocol for all types that can update a database.

+ +

It is adopted by DatabaseQueue and DatabasePool.

+ +

The protocol comes with isolation guarantees that describe the behavior of +adopting types in a multithreaded application.

+ +

Types that adopt the protocol can in practice provide stronger guarantees. +For example, DatabaseQueue provides a stronger isolation level +than DatabasePool.

+ +

Warning: Isolation guarantees stand as long as there is no external +connection to the database. Should you have to cope with external +connections, protect yourself with transactions, and be ready to setup a +busy handler.

+ +
+
+
+ +
    +
  • +
    + + + + write(_:) + +
    +
    +
    +
    +
    +
    +

    Synchronously executes a block that takes a database connection, and +returns its result.

    + +

    Eventual concurrent database updates are postponed until the block +has executed.

    + +

    Eventual concurrent reads are guaranteed not to see any changes +performed in the block until they are all saved in the database.

    + +

    The block may, or may not, be wrapped inside a transaction.

    + +

    This method is not reentrant.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func write<T>(_ block: (Database) throws -> T) throws -> T
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Synchronously executes a block that takes a database connection, and +returns its result.

    + +

    Eventual concurrent database updates are postponed until the block +has executed.

    + +

    Eventual concurrent reads may see changes performed in the block before +the block completes.

    + +

    The block is guaranteed to be executed outside of a transaction.

    + +

    This method is not reentrant.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func writeWithoutTransaction<T>(_ block: (Database) throws -> T) rethrows -> T
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Synchronously executes a block that takes a database connection, and +returns its result.

    + +

    Eventual concurrent database updates are postponed until the block +has executed.

    + +

    Eventual concurrent reads may see changes performed in the block before +the block completes.

    + +

    This method is reentrant. It should be avoided because it fosters +dangerous concurrency practices.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Synchronously or asynchronously executes a read-only block that takes a +database connection.

    + +

    This method must be called from a writing dispatch queue, outside of any +transaction. You’ll get a fatal error otherwise.

    + +

    The block argument is guaranteed to see the database in the last +committed state at the moment this method is called. Eventual concurrent +database updates are not visible inside the block.

    + +

    For example:

    +
    try writer.writeWithoutTransaction { db in
    +    try db.execute("DELETE FROM player")
    +    try writer.readFromCurrentState { db in
    +        // Guaranteed to be zero
    +        try Int.fetchOne(db, "SELECT COUNT(*) FROM player")!
    +    }
    +    try db.execute("INSERT INTO player ...")
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func readFromCurrentState(_ block: @escaping (Database) -> Void) throws
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + add(transactionObserver:extent:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Add a transaction observer, so that it gets notified of +database changes.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func add(transactionObserver: TransactionObserver, extent: Database.TransactionObservationExtent = .observerLifetime)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + transactionObserver + + +
    +

    A transaction observer.

    +
    +
    + + extent + + +
    +

    The duration of the observation. The default is +the observer lifetime (observation lasts until observer +is deallocated).

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + remove(transactionObserver:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Remove a transaction observer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func remove(transactionObserver: TransactionObserver)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + erase() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Erases the content of the database.

    +
    +

    Precondition

    + database is not accessed concurrently during the +execution of this method. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func erase() throws
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/FTS5CustomTokenizer.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/FTS5CustomTokenizer.html new file mode 100644 index 000000000..c2310d9bf --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/FTS5CustomTokenizer.html @@ -0,0 +1,885 @@ + + + + FTS5CustomTokenizer Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS5CustomTokenizer

+

The protocol for custom FTS5 tokenizers.

+ +
+
+
+
    +
  • +
    + + + + name + +
    +
    +
    +
    +
    +
    +

    The name of the tokenizer; should uniquely identify your custom +tokenizer.

    + +
    +
    +
    +
  • +
  • +
    + + + + init(db:arguments:) + +
    +
    +
    +
    +
    +
    +

    Creates a custom tokenizer.

    + +

    The arguments parameter is an array of String built from the CREATE +VIRTUAL TABLE statement. In the example below, the arguments will +be ["arg1", "arg2"].

    +
    CREATE VIRTUAL TABLE document USING fts5(
    +    tokenize='custom arg1 arg2'
    +)
    +
    + +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + tokenizerDescriptor(arguments:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates an FTS5 tokenizer descriptor.

    +
    class MyTokenizer : FTS5CustomTokenizer { ... }
    +
    +db.create(virtualTable: "book", using: FTS5()) { t in
    +    let tokenizer = MyTokenizer.tokenizerDescriptor(arguments: ["unicode61", "remove_diacritics", "0"])
    +    t.tokenizer = tokenizer
    +}
    +
    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/FTS5Tokenizer.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/FTS5Tokenizer.html new file mode 100644 index 000000000..16639ace1 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/FTS5Tokenizer.html @@ -0,0 +1,827 @@ + + + + FTS5Tokenizer Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS5Tokenizer

+

The protocol for FTS5 tokenizers

+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/FTS5WrapperTokenizer.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/FTS5WrapperTokenizer.html new file mode 100644 index 000000000..2a6d28968 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/FTS5WrapperTokenizer.html @@ -0,0 +1,909 @@ + + + + FTS5WrapperTokenizer Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS5WrapperTokenizer

+

The protocol for custom FTS5 tokenizers that wrap another tokenizer.

+ +

Types that adopt FTS5WrapperTokenizer don’t have to implement the +low-level FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:).

+ +

Instead, they process regular Swift strings.

+ +

Here is the implementation for a trivial tokenizer that wraps the +built-in ascii tokenizer without any custom processing:

+
class TrivialAsciiTokenizer : FTS5WrapperTokenizer {
+    static let name = "trivial"
+    let wrappedTokenizer: FTS5Tokenizer
+
+    init(db: Database, arguments: [String]) throws {
+        wrappedTokenizer = try db.makeTokenizer(.ascii())
+    }
+
+    func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws {
+        try tokenCallback(token, flags)
+    }
+}
+
+ +
+
+
+
    +
  • +
    + + + + wrappedTokenizer + +
    +
    +
    +
    +
    +
    +

    The wrapped tokenizer

    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Given a token produced by the wrapped tokenizer, notifies customized +tokens to the tokenCallback function.

    + +

    For example:

    +
    func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws {
    +    // pass through:
    +    try tokenCallback(token, flags)
    +}
    +
    + +

    When implementing the accept method, there are a two rules +to observe:

    + +
      +
    1. Errors thrown by the tokenCallback function must not be caught.

    2. +
    3. The input flags should be given unmodified to the tokenCallback +function, unless you union it with the .colocated flag when the +tokenizer produces synonyms (see +https://www.sqlite.org/fts5.html#synonym_support).

    4. +
    + +
    +
    +
    +
  • +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/FetchRequest.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/FetchRequest.html new file mode 100644 index 000000000..6ade87066 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/FetchRequest.html @@ -0,0 +1,2226 @@ + + + + FetchRequest Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FetchRequest

+
+
+
public protocol FetchRequest
+ +
+
+

The protocol for all requests that run from a single select statement, and +tell how fetched rows should be interpreted.

+
struct Player: FetchableRecord { ... }
+let request: ... // Some FetchRequest that fetches Player
+try request.fetchCursor(db) // Cursor of Player
+try request.fetchAll(db)    // [Player]
+try request.fetchOne(db)    // Player?
+
+ +
+
+
+
    +
  • +
    + + + + RowDecoder + +
    +
    +
    +
    +
    +
    +

    The type that tells how fetched database rows should be interpreted.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    associatedtype RowDecoder
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + prepare(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a tuple that contains a prepared statement that is ready to be +executed, and an eventual row adapter.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?)
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    A prepared statement and an eventual row adapter.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchCount(_:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Returns the number of rows fetched by the request.

    + +

    The default implementation builds a naive SQL query based on the +statement returned by the prepare method: +SELECT COUNT(*) FROM (...).

    + +

    Adopting types can refine this method in order to use more +efficient SQL.

    + +
    +

    Default Implementation

    +
    +

    Returns the number of rows fetched by the request.

    + +

    This default implementation builds a naive SQL query based on the +statement returned by the prepare method: SELECT COUNT(*) FROM (...).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func fetchCount(_ db: Database) throws -> Int
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseRegion(_:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Returns the database region that the request looks into.

    + +
    +

    Default Implementation

    +
    +

    Returns the database region that the request looks into.

    + +

    This default implementation returns a region built from the statement +returned by the prepare method.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func databaseRegion(_ db: Database) throws -> DatabaseRegion
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    A cursor over fetched values.

    +
    let request: ... // Some TypedRequest that fetches String
    +let strings = try request.fetchCursor(db) // Cursor of String
    +while let string = try strings.next() {   // String
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor<RowDecoder>
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    An array of fetched values.

    +
    let request: ... // Some TypedRequest that fetches String
    +let strings = try request.fetchAll(db) // [String]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchAll(_ db: Database) throws -> [RowDecoder]
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    The first fetched value.

    + +

    The result is nil if the request returns no row, or if no value can be +extracted from the first row.

    +
    let request: ... // Some TypedRequest that fetches String
    +let string = try request.fetchOne(db) // String?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchOne(_ db: Database) throws -> RowDecoder?
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    An optional value.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    A cursor over fetched optional values.

    +
    let request: ... // Some TypedRequest that fetches Optional<String>
    +let strings = try request.fetchCursor(db) // Cursor of String?
    +while let string = try strings.next() {   // String?
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor<RowDecoder._Wrapped>
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    An array of fetched optional values.

    +
    let request: ... // Some TypedRequest that fetches Optional<String>
    +let strings = try request.fetchAll(db) // [String?]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?]
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of values.

    +
    + +
    +
    +
  • +
+
+
+ + +
+
+ +
    +
  • +
    + + + + fetchCursor(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    A cursor over fetched rows.

    +
    let request: ... // Some TypedRequest that fetches Row
    +let rows = try request.fetchCursor(db) // RowCursor
    +while let row = try rows.next() {  // Row
    +    let id: Int64 = row[0]
    +    let name: String = row[1]
    +}
    +
    + +

    Fetched rows are reused during the cursor iteration: don’t turn a row +cursor into an array with Array(rows) or rows.filter { ... } since +you would not get the distinct rows you expect. Use Row.fetchAll(...) +instead.

    + +

    For the same reason, make sure you make a copy whenever you extract a +row for later use: row.copy().

    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchCursor(_ db: Database) throws -> RowCursor
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched rows.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    An array of fetched rows.

    +
    let request: ... // Some TypedRequest that fetches Row
    +let rows = try request.fetchAll(db)
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchAll(_ db: Database) throws -> [Row]
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of fetched rows.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    The first fetched row.

    +
    let request: ... // Some TypedRequest that fetches Row
    +let row = try request.fetchOne(db)
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchOne(_ db: Database) throws -> Row?
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    A,n optional rows.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    A cursor over fetched values.

    +
    let request: ... // Some TypedRequest that fetches String
    +let strings = try request.fetchCursor(db) // Cursor of String
    +while let string = try strings.next() {   // String
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchCursor(_ db: Database) throws -> FastDatabaseValueCursor<RowDecoder>
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    An array of fetched values.

    +
    let request: ... // Some TypedRequest that fetches String
    +let strings = try request.fetchAll(db) // [String]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchAll(_ db: Database) throws -> [RowDecoder]
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    The first fetched value.

    + +

    The result is nil if the request returns no row, or if no value can be +extracted from the first row.

    +
    let request: ... // Some TypedRequest that fetches String
    +let string = try request.fetchOne(db) // String?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchOne(_ db: Database) throws -> RowDecoder?
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    An optional value.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    A cursor over fetched optional values.

    +
    let request: ... // Some TypedRequest that fetches Optional<String>
    +let strings = try request.fetchCursor(db) // Cursor of String?
    +while let string = try strings.next() {   // String?
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchCursor(_ db: Database) throws -> FastNullableDatabaseValueCursor<RowDecoder._Wrapped>
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched values.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    An array of fetched optional values.

    +
    let request: ... // Some TypedRequest that fetches Optional<String>
    +let strings = try request.fetchAll(db) // [String?]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?]
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of values.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    A cursor over fetched records.

    +
    let request: ... // Some TypedRequest that fetches Player
    +let players = try request.fetchCursor(db) // Cursor of Player
    +while let player = try players.next() {   // Player
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchCursor(_ db: Database) throws -> RecordCursor<RowDecoder>
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    An array of fetched records.

    +
    let request: ... // Some TypedRequest that fetches Player
    +let players = try request.fetchAll(db) // [Player]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchAll(_ db: Database) throws -> [RowDecoder]
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    The first fetched record.

    +
    let request: ... // Some TypedRequest that fetches Player
    +let player = try request.fetchOne(db) // Player?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func fetchOne(_ db: Database) throws -> RowDecoder?
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    An optional record.

    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/FetchableRecord.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/FetchableRecord.html new file mode 100644 index 000000000..c9be0af33 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/FetchableRecord.html @@ -0,0 +1,2625 @@ + + + + FetchableRecord Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FetchableRecord

+
+
+
public protocol FetchableRecord
+ +
+
+

Types that adopt FetchableRecord can be initialized from a database Row.

+
let row = try Row.fetchOne(db, "SELECT ...")!
+let player = Player(row)
+
+ +

The protocol comes with built-in methods that allow to fetch cursors, +arrays, or single records:

+
try Player.fetchCursor(db, "SELECT ...", arguments:...) // Cursor of Player
+try Player.fetchAll(db, "SELECT ...", arguments:...)    // [Player]
+try Player.fetchOne(db, "SELECT ...", arguments:...)    // Player?
+
+let statement = try db.makeSelectStatement("SELECT ...")
+try Player.fetchCursor(statement, arguments:...) // Cursor of Player
+try Player.fetchAll(statement, arguments:...)    // [Player]
+try Player.fetchOne(statement, arguments:...)    // Player?
+
+ +

FetchableRecord is adopted by Record.

+ +
+
+
+ +
    +
  • +
    + + + + init(row:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Creates a record from row.

    + +

    For performance reasons, the row argument may be reused during the +iteration of a fetch query. If you want to keep the row for later use, +make sure to store a copy: self.row = row.copy().

    + +
    +

    Default Implementation

    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    init(row: Row)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + databaseDecodingUserInfo + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    When the FetchableRecord type also adopts the standard Decodable +protocol, you can use this dictionary to customize the decoding process +from database rows.

    + +

    For example:

    +
    // A key that holds a decoder's name
    +let decoderName = CodingUserInfoKey(rawValue: "decoderName")!
    +
    +// A FetchableRecord + Decodable record
    +struct Player: FetchableRecord, Decodable {
    +    // Customize the decoder name when decoding a database row
    +    static let databaseDecodingUserInfo: [CodingUserInfoKey: Any] = [decoderName: "Database"]
    +
    +    init(from decoder: Decoder) throws {
    +        // Print the decoder name
    +        print(decoder.userInfo[decoderName])
    +        ...
    +    }
    +}
    +
    +// prints "Database"
    +let player = try Player.fetchOne(db, ...)
    +
    +// prints "JSON"
    +let decoder = JSONDecoder()
    +decoder.userInfo = [decoderName: "JSON"]
    +let player = try decoder.decode(Player.self, from: ...)
    +
    + +
    +

    Default Implementation

    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    static var databaseDecodingUserInfo: [CodingUserInfoKey : Any] { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseJSONDecoder(for:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    When the FetchableRecord type also adopts the standard Decodable +protocol, this method controls the decoding process of nested properties +from JSON database columns.

    + +

    The default implementation returns a JSONDecoder with the +following properties:

    + +
      +
    • dataDecodingStrategy: .base64
    • +
    • dateDecodingStrategy: .millisecondsSince1970
    • +
    • nonConformingFloatDecodingStrategy: .throw
    • +
    + +

    You can override those defaults:

    +
    struct Achievement: Decodable {
    +    var name: String
    +    var date: Date
    +}
    +
    +struct Player: Decodable, FetchableRecord {
    +    // stored in a JSON column
    +    var achievements: [Achievement]
    +
    +    static func databaseJSONDecoder(for column: String) -> JSONDecoder {
    +        let decoder = JSONDecoder()
    +        decoder.dateDecodingStrategy = .iso8601
    +        return decoder
    +    }
    +}
    +
    + +
    +

    Default Implementation

    +
    +

    Returns a JSONDecoder with the following properties:

    + +
      +
    • dataDecodingStrategy: .base64
    • +
    • dateDecodingStrategy: .millisecondsSince1970
    • +
    • nonConformingFloatDecodingStrategy: .throw
    • +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    static func databaseJSONDecoder(for column: String) -> JSONDecoder
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseDateDecodingStrategy + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    When the FetchableRecord type also adopts the standard Decodable +protocol, this property controls the decoding of date properties.

    + +

    Default value is .deferredToDate

    + +

    For example:

    +
    struct Player: FetchableRecord, Decodable {
    +    static let databaseDateDecodingStrategy: DatabaseDateDecodingStrategy = .timeIntervalSince1970
    +
    +    var name: String
    +    var registrationDate: Date // decoded from epoch timestamp
    +}
    +
    + +
    +

    Default Implementation

    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    A cursor over all records fetched from the database.

    +
    // SELECT * FROM player
    +let players = try Player.fetchCursor(db) // Cursor of Player
    +while let player = try players.next() {  // Player
    +    ...
    +}
    +
    + +

    Records are iterated in the natural ordering of the table.

    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    + +

    The selection defaults to all columns. This default can be changed for +all requests by the TableRecord.databaseSelection property, or +for individual requests with the TableRecord.select method.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ db: Database) throws -> RecordCursor<Self>
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    An array of all records fetched from the database.

    +
    // SELECT * FROM player
    +let players = try Player.fetchAll(db) // [Player]
    +
    + +

    The selection defaults to all columns. This default can be changed for +all requests by the TableRecord.databaseSelection property, or +for individual requests with the TableRecord.select method.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ db: Database) throws -> [Self]
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    The first found record.

    +
    // SELECT * FROM player
    +let player = try Player.fetchOne(db) // Player?
    +
    + +

    The selection defaults to all columns. This default can be changed for +all requests by the TableRecord.databaseSelection property, or +for individual requests with the TableRecord.select method.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne(_ db: Database) throws -> Self?
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:keys:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over records, given their primary keys.

    +
    let players = try Player.fetchCursor(db, keys: [1, 2, 3]) // Cursor of Player
    +while let player = try players.next() { // Player
    +    ...
    +}
    +
    + +

    Records are iterated in unspecified order.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor<Sequence>(_ db: Database, keys: Sequence) throws -> RecordCursor<Self> where Sequence : Sequence, Sequence.Element : DatabaseValueConvertible
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + keys + + +
    +

    A sequence of primary keys.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:keys:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array of records, given their primary keys.

    +
    let players = try Player.fetchAll(db, keys: [1, 2, 3]) // [Player]
    +
    + +

    The order of records in the returned array is undefined.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll<Sequence>(_ db: Database, keys: Sequence) throws -> [Self] where Sequence : Sequence, Sequence.Element : DatabaseValueConvertible
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + keys + + +
    +

    A sequence of primary keys.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:key:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a single record given its primary key.

    +
    let player = try Player.fetchOne(db, key: 123) // Player?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne<PrimaryKeyType>(_ db: Database, key: PrimaryKeyType?) throws -> Self? where PrimaryKeyType : DatabaseValueConvertible
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + key + + +
    +

    A primary key value.

    +
    +
    +
    +
    +

    Return Value

    +

    An optional record.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:keys:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over records identified by the provided unique keys +(primary key or any key with a unique index on it).

    +
    let players = try Player.fetchCursor(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // Cursor of Player
    +while let player = try players.next() { // Player
    +    ...
    +}
    +
    + +

    Records are iterated in unspecified order.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ db: Database, keys: [[String : DatabaseValueConvertible?]]) throws -> RecordCursor<Self>
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + keys + + +
    +

    An array of key dictionaries.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:keys:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array of records identified by the provided unique keys +(primary key or any key with a unique index on it).

    +
    let players = try Player.fetchAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // [Player]
    +
    + +

    The order of records in the returned array is undefined.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ db: Database, keys: [[String : DatabaseValueConvertible?]]) throws -> [Self]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + keys + + +
    +

    An array of key dictionaries.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:key:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a single record identified by a unique key (the primary key or +any key with a unique index on it).

    +
    let player = try Player.fetchOne(db, key: ["name": Arthur"]) // Player?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne(_ db: Database, key: [String : DatabaseValueConvertible?]?) throws -> Self?
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + key + + +
    +

    A dictionary of values.

    +
    +
    +
    +
    +

    Return Value

    +

    An optional record.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    A cursor over records fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT * FROM player")
    +let players = try Player.fetchCursor(statement) // Cursor of Player
    +while let player = try players.next() { // Player
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor<Self>
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array of records fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT * FROM player")
    +let players = try Player.fetchAll(statement) // [Player]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An array of records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a single record fetched from a prepared statement.

    +
    let statement = try db.makeSelectStatement("SELECT * FROM player")
    +let player = try Player.fetchOne(statement) // Player?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self?
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + statement + + +
    +

    The statement to run.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An optional record.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over records fetched from an SQL query.

    +
    let players = try Player.fetchCursor(db, "SELECT * FROM player") // Cursor of Player
    +while let player = try players.next() { // Player
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor<Self>
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array of records fetched from an SQL query.

    +
    let players = try Player.fetchAll(db, "SELECT * FROM player") // [Player]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self]
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An array of records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:_:arguments:adapter:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a single record fetched from an SQL query.

    +
    let player = try Player.fetchOne(db, "SELECT * FROM player") // Player?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self?
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter

    +
    +
    +
    +
    +

    Return Value

    +

    An optional record.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCursor(_:_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a cursor over records fetched from a fetch request.

    +
    let request = try Player.all()
    +let players = try Player.fetchCursor(db, request) // Cursor of Player
    +while let player = try players.next() { // Player
    +    ...
    +}
    +
    + +

    If the database is modified during the cursor iteration, the remaining +elements are undefined.

    + +

    The cursor must be iterated in a protected dispath queue.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCursor<R>(_ db: Database, _ request: R) throws -> RecordCursor<Self> where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    a FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    A cursor over fetched records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchAll(_:_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an array of records fetched from a fetch request.

    +
    let request = try Player.all()
    +let players = try Player.fetchAll(db, request) // [Player]
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchAll<R>(_ db: Database, _ request: R) throws -> [Self] where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    a FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    An array of records.

    +
    + +
    +
    +
  • +
  • +
    + + + + fetchOne(_:_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a single record fetched from a fetch request.

    +
    let request = try Player.filter(key: 1)
    +let player = try Player.fetchOne(db, request) // Player?
    +
    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchOne<R>(_ db: Database, _ request: R) throws -> Self? where R : FetchRequest
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + sql + + +
    +

    a FetchRequest.

    +
    +
    +
    +
    +

    Return Value

    +

    An optional record.

    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/MutablePersistableRecord.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/MutablePersistableRecord.html new file mode 100644 index 000000000..bddf524b6 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/MutablePersistableRecord.html @@ -0,0 +1,2648 @@ + + + + MutablePersistableRecord Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

MutablePersistableRecord

+
+
+
public protocol MutablePersistableRecord : TableRecord
+ +
+
+

Types that adopt MutablePersistableRecord can be inserted, updated, and deleted.

+ +
+
+
+
    +
  • +
    + + + + persistenceConflictPolicy + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    The policy that handles SQLite conflicts when records are inserted +or updated.

    + +

    This property is optional: its default value uses the ABORT policy +for both insertions and updates, and has GRDB generate regular +INSERT and UPDATE queries.

    + +

    If insertions are resolved with .ignore policy, the +didInsert(with:for:) method is not called upon successful insertion, +even if a row was actually inserted without any conflict.

    + +

    See https://www.sqlite.org/lang_conflict.html

    + +
    +

    Default Implementation

    +
    +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    static var persistenceConflictPolicy: PersistenceConflictPolicy { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + encode(to:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Defines the values persisted in the database.

    + +

    Store in the container argument all values that should be stored in +the columns of the database table (see databaseTableName()).

    + +

    Primary key columns, if any, must be included.

    +
    struct Player : MutablePersistableRecord {
    +    var id: Int64?
    +    var name: String?
    +
    +    func encode(to container: inout PersistenceContainer) {
    +        container["id"] = id
    +        container["name"] = name
    +    }
    +}
    +
    + +

    It is undefined behavior to set different values for the same column. +Column names are case insensitive, so defining both name and NAME +is considered undefined behavior.

    + +
    +

    Default Implementation

    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func encode(to container: inout PersistenceContainer)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + didInsert(with:for:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Notifies the record that it was succesfully inserted.

    + +

    Do not call this method directly: it is called for you, in a protected +dispatch queue, with the inserted RowID and the eventual +INTEGER PRIMARY KEY column name.

    + +

    This method is optional: the default implementation does nothing.

    +
    struct Player : MutablePersistableRecord {
    +    var id: Int64?
    +    var name: String?
    +
    +    mutating func didInsert(with rowID: Int64, for column: String?) {
    +        self.id = rowID
    +    }
    +}
    +
    + +
    +

    Default Implementation

    +
    +

    Notifies the record that it was succesfully inserted.

    + +

    The default implementation does nothing.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    mutating func didInsert(with rowID: Int64, for column: String?)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + rowID + + +
    +

    The inserted rowID.

    +
    +
    + + column + + +
    +

    The name of the eventual INTEGER PRIMARY KEY column.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
+ + + +

CRUD

+
+
+
    +
  • +
    + + + + insert(_:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Executes an INSERT statement.

    + +

    This method is guaranteed to have inserted a row in the database if it +returns without error.

    + +

    Upon successful insertion, the didInsert(with:for:) method +is called with the inserted RowID and the eventual INTEGER PRIMARY KEY +column name.

    + +

    This method has a default implementation, so your adopting types don’t +have to implement it. Yet your types can provide their own +implementation of insert(). In their implementation, it is recommended +that they invoke the performInsert() method.

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +

    Default Implementation

    +
    +

    Executes an INSERT statement.

    + +

    The default implementation for insert() invokes performInsert().

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    mutating func insert(_ db: Database) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + update(_:columns:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Executes an UPDATE statement.

    + +

    This method is guaranteed to have updated a row in the database if it +returns without error.

    + +

    This method has a default implementation, so your adopting types don’t +have to implement it. Yet your types can provide their own +implementation of update(). In their implementation, it is recommended +that they invoke the performUpdate() method.

    +
    +

    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. + +
    + +
    +

    Default Implementation

    +
    +

    Executes an UPDATE statement.

    +
    +

    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. + +
    +

    Executes an UPDATE statement.

    +
    +

    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. + +
    +

    Executes an UPDATE statement.

    +
    +

    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. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func update(_ db: Database, columns: Set<String>) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + columns + + +
    +

    The columns to update.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + save(_:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Executes an INSERT or an UPDATE statement so that self is saved in +the database.

    + +

    If the receiver has a non-nil primary key and a matching row in the +database, this method performs an update.

    + +

    Otherwise, performs an insert.

    + +

    This method is guaranteed to have inserted or updated a row in the +database if it returns without error.

    + +

    This method has a default implementation, so your adopting types don’t +have to implement it. Yet your types can provide their own +implementation of save(). In their implementation, it is recommended +that they invoke the performSave() method.

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs, or errors +thrown by update(). + +
    + +
    +

    Default Implementation

    +
    +

    Executes an INSERT or an UPDATE statement so that self is saved in +the database.

    + +

    The default implementation for save() invokes performSave().

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    mutating func save(_ db: Database) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + delete(_:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Executes a DELETE statement.

    + +

    This method has a default implementation, so your adopting types don’t +have to implement it. Yet your types can provide their own +implementation of delete(). In their implementation, it is recommended +that they invoke the performDelete() method.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +

    Default Implementation

    +
    +

    Executes a DELETE statement.

    + +

    The default implementation for delete() invokes performDelete().

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +func delete(_ db: Database) throws -> Bool
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    Whether a database row was deleted.

    +
    + +
    +
    +
  • +
  • +
    + + + + exists(_:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Returns true if and only if the primary key matches a row in +the database.

    + +

    This method has a default implementation, so your adopting types don’t +have to implement it. Yet your types can provide their own +implementation of exists(). In their implementation, it is recommended +that they invoke the performExists() method.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +

    Default Implementation

    +
    +

    Returns true if and only if the primary key matches a row in +the database.

    + +

    The default implementation for exists() invokes performExists().

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func exists(_ db: Database) throws -> Bool
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    Whether the primary key matches a row in the database.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + databaseEncodingUserInfo + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    When the PersistableRecord type also adopts the standard Encodable +protocol, you can use this dictionary to customize the encoding process +into database rows.

    + +

    For example:

    +
    // A key that holds a encoder's name
    +let encoderName = CodingUserInfoKey(rawValue: "encoderName")!
    +
    +// A PersistableRecord + Encodable record
    +struct Player: PersistableRecord, Encodable {
    +    // Customize the encoder name when encoding a database row
    +    static let databaseEncodingUserInfo: [CodingUserInfoKey: Any] = [encoderName: "Database"]
    +
    +    func encode(to encoder: Encoder) throws {
    +        // Print the encoder name
    +        print(encoder.userInfo[encoderName])
    +        ...
    +    }
    +}
    +
    +let player = Player(...)
    +
    +// prints "Database"
    +try player.insert(db)
    +
    +// prints "JSON"
    +let encoder = JSONEncoder()
    +encoder.userInfo = [encoderName: "JSON"]
    +let data = try encoder.encode(player)
    +
    + +
    +

    Default Implementation

    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    static var databaseEncodingUserInfo: [CodingUserInfoKey : Any] { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseJSONEncoder(for:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    When the PersistableRecord type also adopts the standard Encodable +protocol, this method controls the encoding process of nested properties +into JSON database columns.

    + +

    The default implementation returns a JSONEncoder with the +following properties:

    + +
      +
    • dataEncodingStrategy: .base64
    • +
    • dateEncodingStrategy: .millisecondsSince1970
    • +
    • nonConformingFloatEncodingStrategy: .throw
    • +
    • outputFormatting: .sortedKeys (iOS 11.0+, macOS 10.13+, watchOS 4.0+)
    • +
    + +

    You can override those defaults:

    +
    struct Achievement: Encodable {
    +    var name: String
    +    var date: Date
    +}
    +
    +struct Player: Encodable, PersistableRecord {
    +    // stored in a JSON column
    +    var achievements: [Achievement]
    +
    +    static func databaseJSONEncoder(for column: String) -> JSONEncoder {
    +        let encoder = JSONEncoder()
    +        encoder.dateEncodingStrategy = .iso8601
    +        return encoder
    +    }
    +}
    +
    + +
    +

    Default Implementation

    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    static func databaseJSONEncoder(for column: String) -> JSONEncoder
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseDateEncodingStrategy + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    When the PersistableRecord type also adopts the standard Encodable +protocol, this property controls the encoding of date properties.

    + +

    Default value is .deferredToDate

    + +

    For example:

    +
    struct Player: PersistableRecord, Encodable {
    +    static let databaseDateEncodingStrategy: DatabaseDateEncodingStrategy = .timeIntervalSince1970
    +
    +    var name: String
    +    var registrationDate: Date // encoded as an epoch timestamp
    +}
    +
    + +
    +

    Default Implementation

    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseUUIDEncodingStrategy + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    When the PersistableRecord type also adopts the standard Encodable +protocol, this property controls the encoding of UUID properties.

    + +

    Default value is .deferredToUUID

    + +

    For example:

    +
    struct Player: PersistableProtocol, Encodable {
    +    static let databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy = .string
    +
    +    // encoded in a string like "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
    +    var uuid: UUID
    +}
    +
    + +
    +

    Default Implementation

    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + request(for:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request that fetches the associated record(s).

    + +

    For example:

    +
    struct Team: {
    +    static let players = hasMany(Player.self)
    +    var players: QueryInterfaceRequest<Player> {
    +        return request(for: Team.players)
    +    }
    +}
    +
    +let team: Team = ...
    +let players = try team.players.fetchAll(db) // [Player]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func request<A>(for association: A) -> QueryInterfaceRequest<A.RowDecoder> where Self == A.OriginRowDecoder, A : Association
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+
+ + + +

CRUD

+
+
+
    +
  • +
    + + + + update(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Executes an UPDATE statement that updates all table columns.

    +
    +

    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. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func update(_ db: Database) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + updateChanges(_:from:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    If the record has differences from the other record, executes an UPDATE +statement so that those changes and only those changes are saved in +the database.

    + +

    This method is guaranteed to have saved the eventual changes in the +database if it returns without error.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. +PersistenceError.recordNotFound is thrown if the primary key does not +match any row in the database and record could not be updated. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func updateChanges(_ db: Database, from record: MutablePersistableRecord) throws -> Bool
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + columns + + +
    +

    The columns to update.

    +
    +
    +
    +
    +

    Return Value

    +

    Whether the record had changes.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + databaseEquals(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a boolean indicating whether this record and the other record +have the same database representation.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func databaseEquals(_ record: Self) -> Bool
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseChanges(from:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    A dictionary of values changed from the other record.

    + +

    Its keys are column names. Its values come from the other record.

    + +

    Note that this method is not symmetrical, not only in terms of values, +but also in terms of columns. When the two records don’t define the +same set of columns in their encode(to:) method, only the columns +defined by the receiver record are considered.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func databaseChanges(from record: MutablePersistableRecord) -> [String : DatabaseValue]
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + performInsert(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Don’t invoke this method directly: it is an internal method for types +that adopt MutablePersistableRecord.

    + +

    performInsert() provides the default implementation for insert(). Types +that adopt MutablePersistableRecord can invoke performInsert() in their +implementation of insert(). They should not provide their own +implementation of performInsert().

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public mutating func performInsert(_ db: Database) throws
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + performUpdate(_:columns:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Don’t invoke this method directly: it is an internal method for types +that adopt MutablePersistableRecord.

    + +

    performUpdate() provides the default implementation for update(). Types +that adopt MutablePersistableRecord can invoke performUpdate() in their +implementation of update(). They should not provide their own +implementation of performUpdate().

    +
    +

    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. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func performUpdate(_ db: Database, columns: Set<String>) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + columns + + +
    +

    The columns to update.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + performSave(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Don’t invoke this method directly: it is an internal method for types +that adopt MutablePersistableRecord.

    + +

    performSave() provides the default implementation for save(). Types +that adopt MutablePersistableRecord can invoke performSave() in their +implementation of save(). They should not provide their own +implementation of performSave().

    + +

    This default implementation forwards the job to update or insert.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public mutating func performSave(_ db: Database) throws
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + performDelete(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Don’t invoke this method directly: it is an internal method for types +that adopt MutablePersistableRecord.

    + +

    performDelete() provides the default implementation for deelte(). Types +that adopt MutablePersistableRecord can invoke performDelete() in +their implementation of delete(). They should not provide their own +implementation of performDelete().

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func performDelete(_ db: Database) throws -> Bool
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + performExists(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Don’t invoke this method directly: it is an internal method for types +that adopt MutablePersistableRecord.

    + +

    performExists() provides the default implementation for exists(). Types +that adopt MutablePersistableRecord can invoke performExists() in +their implementation of exists(). They should not provide their own +implementation of performExists().

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func performExists(_ db: Database) throws -> Bool
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + deleteAll(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Deletes all records; returns the number of deleted rows.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public static func deleteAll(_ db: Database) throws -> Int
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    The number of deleted rows

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + deleteAll(_:keys:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Delete records identified by their primary keys; returns the number of +deleted rows.

    +
    // 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])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public static func deleteAll<Sequence>(_ db: Database, keys: Sequence) throws -> Int where Sequence : Sequence, Sequence.Element : DatabaseValueConvertible
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + keys + + +
    +

    A sequence of primary keys.

    +
    +
    +
    +
    +

    Return Value

    +

    The number of deleted rows

    +
    + +
    +
    +
  • +
  • +
    + + + + deleteOne(_:key:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Delete a record, identified by its primary key; returns whether a +database row was deleted.

    +
    // DELETE FROM player WHERE id = 123
    +try Player.deleteOne(db, key: 123)
    +
    +// 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)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public static func deleteOne<PrimaryKeyType>(_ db: Database, key: PrimaryKeyType?) throws -> Bool where PrimaryKeyType : DatabaseValueConvertible
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + key + + +
    +

    A primary key value.

    +
    +
    +
    +
    +

    Return Value

    +

    Whether a database row was deleted.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + deleteAll(_:keys:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Delete records identified by the provided unique keys (primary key or +any key with a unique index on it); returns the number of deleted rows.

    +
    try Player.deleteAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public static func deleteAll(_ db: Database, keys: [[String : DatabaseValueConvertible?]]) throws -> Int
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + keys + + +
    +

    An array of key dictionaries.

    +
    +
    +
    +
    +

    Return Value

    +

    The number of deleted rows

    +
    + +
    +
    +
  • +
  • +
    + + + + deleteOne(_:key:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Delete a record, identified by a unique key (the primary key or any key +with a unique index on it); returns whether a database row was deleted.

    +
    Player.deleteOne(db, key: ["name": Arthur"])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public static func deleteOne(_ db: Database, key: [String : DatabaseValueConvertible?]) throws -> Bool
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + key + + +
    +

    A dictionary of values.

    +
    +
    +
    +
    +

    Return Value

    +

    Whether a database row was deleted.

    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/PersistableRecord.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/PersistableRecord.html new file mode 100644 index 000000000..0bfae7c36 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/PersistableRecord.html @@ -0,0 +1,1143 @@ + + + + PersistableRecord Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

PersistableRecord

+
+
+
public protocol PersistableRecord : MutablePersistableRecord
+ +
+
+

Types that adopt PersistableRecord can be inserted, updated, and deleted.

+ +

This protocol is intented for types that don’t have an INTEGER PRIMARY KEY.

+ +

Unlike MutablePersistableRecord, the insert() and save() methods are not +mutating methods.

+ +
+
+
+
    +
  • +
    + + + + didInsert(with:for:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Notifies the record that it was succesfully inserted.

    + +

    Do not call this method directly: it is called for you, in a protected +dispatch queue, with the inserted RowID and the eventual +INTEGER PRIMARY KEY column name.

    + +

    This method is optional: the default implementation does nothing.

    + +

    If you need a mutating variant of this method, adopt the +MutablePersistableRecord protocol instead.

    + +
    +

    Default Implementation

    +
    +

    Notifies the record that it was succesfully inserted.

    + +

    The default implementation does nothing.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func didInsert(with rowID: Int64, for column: String?)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + rowID + + +
    +

    The inserted rowID.

    +
    +
    + + column + + +
    +

    The name of the eventual INTEGER PRIMARY KEY column.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + insert(_:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Executes an INSERT statement.

    + +

    This method is guaranteed to have inserted a row in the database if it +returns without error.

    + +

    Upon successful insertion, the didInsert(with:for:) method +is called with the inserted RowID and the eventual INTEGER PRIMARY KEY +column name.

    + +

    This method has a default implementation, so your adopting types don’t +have to implement it. Yet your types can provide their own +implementation of insert(). In their implementation, it is recommended +that they invoke the performInsert() method.

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs. + +
    + +
    +

    Default Implementation

    +
    +

    Executes an INSERT statement.

    + +

    The default implementation for insert() invokes performInsert().

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func insert(_ db: Database) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + save(_:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Executes an INSERT or an UPDATE statement so that self is saved in +the database.

    + +

    If the receiver has a non-nil primary key and a matching row in the +database, this method performs an update.

    + +

    Otherwise, performs an insert.

    + +

    This method is guaranteed to have inserted or updated a row in the +database if it returns without error.

    + +

    This method has a default implementation, so your adopting types don’t +have to implement it. Yet your types can provide their own +implementation of save(). In their implementation, it is recommended +that they invoke the performSave() method.

    +
    +

    Throws

    + A DatabaseError whenever an SQLite error occurs, or errors +thrown by update(). + +
    + +
    +

    Default Implementation

    +
    +

    Executes an INSERT or an UPDATE statement so that self is saved in +the database.

    + +

    The default implementation for save() invokes performSave().

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func save(_ db: Database) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + performInsert(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Don’t invoke this method directly: it is an internal method for types +that adopt PersistableRecord.

    + +

    performInsert() provides the default implementation for insert(). Types +that adopt PersistableRecord can invoke performInsert() in their +implementation of insert(). They should not provide their own +implementation of performInsert().

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func performInsert(_ db: Database) throws
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + performSave(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Don’t invoke this method directly: it is an internal method for types +that adopt PersistableRecord.

    + +

    performSave() provides the default implementation for save(). Types +that adopt PersistableRecord can invoke performSave() in their +implementation of save(). They should not provide their own +implementation of performSave().

    + +

    This default implementation forwards the job to update or insert.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func performSave(_ db: Database) throws
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/RowAdapter.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/RowAdapter.html new file mode 100644 index 000000000..c8c64ec1d --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/RowAdapter.html @@ -0,0 +1,939 @@ + + + + RowAdapter Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

RowAdapter

+
+
+
public protocol RowAdapter
+ +
+
+

RowAdapter is a protocol that helps two incompatible row interfaces working +together.

+ +

GRDB ships with four concrete types that adopt the RowAdapter protocol:

+ +
    +
  • ColumnMapping: renames row columns
  • +
  • SuffixRowAdapter: hides the first columns of a row
  • +
  • RangeRowAdapter: only exposes a range of columns
  • +
  • ScopeAdapter: groups several adapters together to define named scopes
  • +
+ +

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, adapter: adapter)
+
+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Experimental

    + +

    You never call this method directly. It is called for you whenever an +adapter has to be applied.

    + +

    The result is a value that adopts LayoutedRowAdapter, such as +LayoutedColumnMapping.

    + +

    For example:

    +
    // An adapter that turns any row to a row that contains a single
    +// column named "foo" whose value is the leftmost value of the
    +// base row.
    +struct FirstColumnAdapter : RowAdapter {
    +    func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
    +        return LayoutedColumnMapping(layoutColumns: [(0, "foo")])
    +    }
    +}
    +
    +// [foo:1]
    +try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: FirstColumnAdapter())
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + addingScopes(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns an adapter based on self, with added scopes.

    + +

    If self already defines scopes, the added scopes replace +eventual existing scopes with the same name.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func addingScopes(_ scopes: [String : RowAdapter]) -> RowAdapter
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + scopes + + +
    +

    A dictionary that maps scope names to +row adapters.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/StatementColumnConvertible.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/StatementColumnConvertible.html new file mode 100644 index 000000000..ffb955057 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/StatementColumnConvertible.html @@ -0,0 +1,907 @@ + + + + StatementColumnConvertible Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

StatementColumnConvertible

+
+
+
public protocol StatementColumnConvertible
+ +
+
+

The StatementColumnConvertible protocol grants access to the low-level C +interface that extracts values from query results: +https://www.sqlite.org/c3ref/column_blob.html. It can bring performance +improvements.

+ +

To use it, have a value type adopt both StatementColumnConvertible and +DatabaseValueConvertible. GRDB will then automatically apply the +optimization whenever direct access to SQLite is possible:

+
let rows = Row.fetchCursor(db, "SELECT ...")
+while let row = try rows.next() {
+    let int: Int = row[0]                 // there
+}
+let ints = Int.fetchAll(db, "SELECT ...") // there
+struct Player {
+    init(row: Row) {
+        name = row["name"]                // there
+        score = row["score"]              // there
+    }
+}
+
+ +

StatementColumnConvertible is already adopted by all Swift integer types, +Float, Double, String, and Bool.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Initializes a value from a raw SQLite statement pointer.

    + +

    For example, here is the how Int64 adopts StatementColumnConvertible:

    +
    extension Int64: StatementColumnConvertible {
    +    init(sqliteStatement: SQLiteStatement, index: Int32) {
    +        self = sqlite3_column_int64(sqliteStatement, index)
    +    }
    +}
    +
    + +

    This initializer is never called for NULL database values: don’t perform +any extra check.

    + +

    See https://www.sqlite.org/c3ref/column_blob.html for more information.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/TableRecord.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/TableRecord.html new file mode 100644 index 000000000..e8e1c1301 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/TableRecord.html @@ -0,0 +1,2528 @@ + + + + TableRecord Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

TableRecord

+
+
+
public protocol TableRecord
+ +
+
+

Types that adopt TableRecord declare a particular relationship with +a database table.

+ +

Types that adopt both TableRecord and FetchableRecord are granted with +built-in methods that allow to fetch instances identified by key:

+
try Player.fetchOne(db, key: 123)  // Player?
+try Citizenship.fetchOne(db, key: ["citizenId": 12, "countryId": 45]) // Citizenship?
+
+ +

TableRecord is adopted by Record.

+ +
+
+
+
    +
  • +
    + + + + databaseTableName + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    The name of the database table used to build requests.

    +
    struct Player : TableRecord {
    +    static var databaseTableName = "player"
    +}
    +
    +// SELECT * FROM player
    +try Player.fetchAll(db)
    +
    + +
    +

    Default Implementation

    +
    +

    The default name of the database table used to build requests.

    + +
      +
    • Player -> player
    • +
    • Place -> place
    • +
    • PostalAddress -> postalAddress
    • +
    • HTTPRequest -> httpRequest
    • +
    • TOEFL -> toefl
    • +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    static var databaseTableName: String { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseSelection + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    The default request selection.

    + +

    Unless said otherwise, requests select all columns:

    +
    // SELECT * FROM player
    +try Player.fetchAll(db)
    +
    + +

    You can provide a custom implementation and provide an explicit list +of columns:

    +
    struct RestrictedPlayer : TableRecord {
    +    static var databaseTableName = "player"
    +    static var databaseSelection = [Column("id"), Column("name")]
    +}
    +
    +// 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: [SQLSelectable] = [AllColumns(), Column.rowID]
    +}
    +
    +// SELECT *, rowid FROM player
    +try ExtendedPlayer.fetchAll(db)
    +
    + +
    +

    Default Implementation

    +
    +

    Default value: [AllColumns()].

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    static var databaseSelection: [SQLSelectable] { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + belongsTo(_:key:using:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a Belongs To association between Self and the +destination type.

    +
    struct Author: TableRecord { ... }
    +struct Book: TableRecord {
    +    static let author = belongsTo(Author.self)
    +}
    +
    + +

    The association will let you define requests that load both the source +and the destination type:

    +
    // A request for all books with their authors:
    +let request = Book.including(optional: Book.author)
    +
    + +

    To consume those requests, define a type that adopts both the +FetchableRecord and Decodable protocols:

    +
    struct BookInfo: FetchableRecord, Decodable {
    +    var book: Book
    +    var author: Author?
    +}
    +
    +let bookInfos = try dbQueue.read { db in
    +    return try BookInfo.fetchAll(db, request)
    +}
    +for bookInfo in bookInfos {
    +    print("\(bookInfo.book.title) by \(bookInfo.author.name)")
    +}
    +
    + +

    It is recommended that you define, alongside the association, a property +with the same name:

    +
    struct Book: TableRecord {
    +    static let author = belongsTo(Author.self)
    +    var author: QueryInterfaceRequest<Author> {
    +        return request(for: Book.author)
    +    }
    +}
    +
    + +

    This property will let you navigate from the source type to the +destination type:

    +
    try dbQueue.read { db in
    +    let book: Book = ...
    +    let author = try book.author.fetchOne(db) // Author?
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func belongsTo<Destination>(
    +    _ destination: Destination.Type,
    +    key: String? = nil,
    +    using foreignKey: ForeignKey? = nil)
    +    -> BelongsToAssociation<Self, Destination>
    +    where Destination: TableRecord
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + destination + + +
    +

    The record type at the other side of the association.

    +
    +
    + + key + + +
    +

    An eventual decoding key for the association. By default, it +is destination.databaseTableName.

    +
    +
    + + foreignKey + + +
    +

    An eventual foreign key. You need to provide an +explicit foreign key when GRDB can’t infer one from the database +schema. This happens when the schema does not define any foreign +key to the destination table, or when the schema defines several +foreign keys to the destination table.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + hasMany(_:key:using:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a Has many association between Self and the +destination type.

    +
    struct Book: TableRecord { ... }
    +struct Author: TableRecord {
    +    static let books = hasMany(Book.self)
    +}
    +
    + +

    The association will let you define requests that load both the source +and the destination type:

    +
    // A request for all (author, book) pairs:
    +let request = Author.including(required: Author.books)
    +
    + +

    To consume those requests, define a type that adopts both the +FetchableRecord and Decodable protocols:

    +
    struct Authorship: FetchableRecord, Decodable {
    +    var author: Author
    +    var book: Book
    +}
    +
    +let authorships = try dbQueue.read { db in
    +    return try Authorship.fetchAll(db, request)
    +}
    +for authorship in authorships {
    +    print("\(authorship.author.name) wrote \(authorship.book.title)")
    +}
    +
    + +

    It is recommended that you define, alongside the association, a property +with the same name:

    +
    struct Author: TableRecord {
    +    static let books = hasMany(Book.self)
    +    var books: QueryInterfaceRequest<Book> {
    +        return request(for: Author.books)
    +    }
    +}
    +
    + +

    This property will let you navigate from the source type to the +destination type:

    +
    try dbQueue.read { db in
    +    let author: Author = ...
    +    let books = try author.books.fetchAll(db) // [Book]
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func hasMany<Destination>(
    +    _ destination: Destination.Type,
    +    key: String? = nil,
    +    using foreignKey: ForeignKey? = nil)
    +    -> HasManyAssociation<Self, Destination>
    +    where Destination: TableRecord
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + destination + + +
    +

    The record type at the other side of the association.

    +
    +
    + + key + + +
    +

    An eventual decoding key for the association. By default, it +is destination.databaseTableName.

    +
    +
    + + foreignKey + + +
    +

    An eventual foreign key. You need to provide an +explicit foreign key when GRDB can’t infer one from the database +schema. This happens when the schema does not define any foreign +key from the destination table, or when the schema defines several +foreign keys from the destination table.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + hasOne(_:key:using:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a Has one association between Self and the +destination type.

    +
    struct Demographics: TableRecord { ... }
    +struct Country: TableRecord {
    +    static let demographics = hasOne(Demographics.self)
    +}
    +
    + +

    The association will let you define requests that load both the source +and the destination type:

    +
    // A request for all countries with their demographic profile:
    +let request = Country.including(optional: Country.demographics)
    +
    + +

    To consume those requests, define a type that adopts both the +FetchableRecord and Decodable protocols:

    +
    struct CountryInfo: FetchableRecord, Decodable {
    +    var country: Country
    +    var demographics: Demographics?
    +}
    +
    +let countryInfos = try dbQueue.read { db in
    +    return try CountryInfo.fetchAll(db, request)
    +}
    +for countryInfo in countryInfos {
    +    print("\(countryInfo.country.name) has \(countryInfo.demographics.population) citizens")
    +}
    +
    + +

    It is recommended that you define, alongside the association, a property +with the same name:

    +
    struct Country: TableRecord {
    +    static let demographics = hasOne(Demographics.self)
    +    var demographics: QueryInterfaceRequest<Demographics> {
    +        return request(for: Country.demographics)
    +    }
    +}
    +
    + +

    This property will let you navigate from the source type to the +destination type:

    +
    try dbQueue.read { db in
    +    let country: Country = ...
    +    let demographics = try country.demographics.fetchOne(db) // Demographics?
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func hasOne<Destination>(
    +    _ destination: Destination.Type,
    +    key: String? = nil,
    +    using foreignKey: ForeignKey? = nil)
    +    -> HasOneAssociation<Self, Destination>
    +    where Destination: TableRecord
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + destination + + +
    +

    The record type at the other side of the association.

    +
    +
    + + key + + +
    +

    An eventual decoding key for the association. By default, it +is destination.databaseTableName.

    +
    +
    + + foreignKey + + +
    +

    An eventual foreign key. You need to provide an +explicit foreign key when GRDB can’t infer one from the database +schema. This happens when the schema does not define any foreign +key from the destination table, or when the schema defines several +foreign keys from the destination table.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + matching(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns a QueryInterfaceRequest with a matching predicate.

    +
    // SELECT * FROM book WHERE book MATCH '...'
    +var request = Book.matching(pattern)
    +
    + +

    If the search pattern is nil, the request does not match any +database row.

    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + including(optional:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request that includes an association. The columns of the +associated record are selected. The returned association does not +require that the associated database table contains a matching row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func including<A>(optional association: A) -> QueryInterfaceRequest<Self> where Self == A.OriginRowDecoder, A : Association
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + including(required:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request that includes an association. The columns of the +associated record are selected. The returned association requires +that the associated database table contains a matching row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func including<A>(required association: A) -> QueryInterfaceRequest<Self> where Self == A.OriginRowDecoder, A : Association
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + joining(optional:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request that includes an association. The columns of the +associated record are not selected. The returned association does not +require that the associated database table contains a matching row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func joining<A>(optional association: A) -> QueryInterfaceRequest<Self> where Self == A.OriginRowDecoder, A : Association
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + joining(required:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request that includes an association. The columns of the +associated record are not selected. The returned association requires +that the associated database table contains a matching row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func joining<A>(required association: A) -> QueryInterfaceRequest<Self> where Self == A.OriginRowDecoder, A : Association
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + all() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request which fetches all records.

    +
    // SELECT * FROM player
    +let request = Player.all()
    +
    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func all() -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + none() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request which fetches no record.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func none() -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + select(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request which selects selection.

    +
    // SELECT id, email FROM player
    +let request = Player.select(Column("id"), Column("email"))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func select(_ selection: SQLSelectable...) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + select(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request which selects selection.

    +
    // SELECT id, email FROM player
    +let request = Player.select([Column("id"), Column("email")])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + select(sql:arguments:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request which selects sql.

    +
    // SELECT id, email FROM player
    +let request = Player.select(sql: "id, email")
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func select(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + select(_:as:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request which selects selection, and fetches values of +type type.

    +
    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)
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func select<RowDecoder>(_ selection: [SQLSelectable], as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + select(_:as:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request which selects selection, and fetches values of +type type.

    +
    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)
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func select<RowDecoder>(_ selection: SQLSelectable..., as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + select(sql:arguments:as:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request which selects sql, and fetches values of +type type.

    +
    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)
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func select<RowDecoder>(sql: String, arguments: StatementArguments? = nil, as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + filter(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request with the provided predicate.

    +
    // SELECT * FROM player WHERE email = 'arthur@example.com'
    +let request = Player.filter(Column("email") == "arthur@example.com")
    +
    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func filter(_ predicate: SQLExpressible) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + filter(key:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request with the provided primary key predicate.

    +
    // SELECT * FROM player WHERE id = 1
    +let request = Player.filter(key: 1)
    +
    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func filter<PrimaryKeyType>(key: PrimaryKeyType?) -> QueryInterfaceRequest<Self> where PrimaryKeyType : DatabaseValueConvertible
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + filter(keys:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request with the provided primary key predicate.

    +
    // SELECT * FROM player WHERE id IN (1, 2, 3)
    +let request = Player.filter(keys: [1, 2, 3])
    +
    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func filter<Sequence>(keys: Sequence) -> QueryInterfaceRequest<Self> where Sequence : Sequence, Sequence.Element : DatabaseValueConvertible
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + filter(key:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request with the provided primary key predicate.

    +
    // SELECT * FROM passport WHERE personId = 1 AND countryCode = 'FR'
    +let request = Passport.filter(key: ["personId": 1, "countryCode": "FR"])
    +
    + +

    When executed, this request raises a fatal error if there is no unique +index on the key columns.

    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func filter(key: [String : DatabaseValueConvertible?]?) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + filter(keys:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request with the provided primary key predicate.

    +
    // SELECT * FROM passport WHERE (personId = 1 AND countryCode = 'FR') OR ...
    +let request = Passport.filter(keys: [["personId": 1, "countryCode": "FR"], ...])
    +
    + +

    When executed, this request raises a fatal error if there is no unique +index on the key columns.

    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func filter(keys: [[String : DatabaseValueConvertible?]]) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + filter(sql:arguments:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request with the provided predicate.

    +
    // SELECT * FROM player WHERE email = 'arthur@example.com'
    +let request = Player.filter(sql: "email = ?", arguments: ["arthur@example.com"])
    +
    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func filter(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + order(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request sorted according to the +provided orderings.

    +
    // SELECT * FROM player ORDER BY name
    +let request = Player.order(Column("name"))
    +
    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + order(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request sorted according to the +provided orderings.

    +
    // SELECT * FROM player ORDER BY name
    +let request = Player.order([Column("name")])
    +
    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + orderByPrimaryKey() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request sorted by primary key.

    +
    // SELECT * FROM player ORDER BY id
    +let request = Player.orderByPrimaryKey()
    +
    +// SELECT * FROM country ORDER BY code
    +let request = Country.orderByPrimaryKey()
    +
    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func orderByPrimaryKey() -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + order(sql:arguments:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request sorted according to sql.

    +
    // SELECT * FROM player ORDER BY name
    +let request = Player.order(sql: "name")
    +
    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func order(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + limit(_:offset:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request which fetches limit rows, starting at +offset.

    +
    // SELECT * FROM player LIMIT 1
    +let request = Player.limit(1)
    +
    + +

    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.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + aliased(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Creates a request that allows you to define expressions that target +a specific database table.

    + +

    In the example below, the team.avgScore < player.score condition in +the ON clause could be not achieved without table aliases.

    +
    struct Player: TableRecord {
    +    static let team = belongsTo(Team.self)
    +}
    +
    +// SELECT player.*, team.*
    +// JOIN team ON ... AND team.avgScore < player.score
    +let playerAlias = TableAlias()
    +let request = Player
    +    .aliased(playerAlias)
    +    .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func aliased(_ alias: TableAlias) -> QueryInterfaceRequest<Self>
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + fetchCount(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    The number of records.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fetchCount(_ db: Database) throws -> Int
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + selectionSQL(alias:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    The selection as an SQL String.

    + +

    For example:

    +
    struct Player: TableRecord {
    +    static let databaseTableName = "player"
    +}
    +
    +// SELECT "player".* FROM player
    +let sql = "SELECT \(Player.selectionSQL()) FROM player"
    +
    +// SELECT "p".* FROM player AS p
    +let sql = "SELECT \(Player.selectionSQL(alias: "p")) FROM player p"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func selectionSQL(alias: String? = nil) -> String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + numberOfSelectedColumns(_:) + + + Extension method + +
    +
    +
    +
    +
    +
    +

    Returns the number of selected columns.

    + +

    For example:

    +
    struct Player: TableRecord {
    +    static let databaseTableName = "player"
    +}
    +
    +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)
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func numberOfSelectedColumns(_ db: Database) throws -> Int
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/TransactionObserver.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/TransactionObserver.html new file mode 100644 index 000000000..785978d28 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/TransactionObserver.html @@ -0,0 +1,1135 @@ + + + + TransactionObserver Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

TransactionObserver

+
+
+
public protocol TransactionObserver : AnyObject
+ +
+
+

A transaction observer is notified of all changes and transactions committed +or rollbacked on a database.

+ +

Adopting types must be a class.

+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    Filters database changes that should be notified the the +databaseDidChange(with:) method.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Notifies a database change (insert, update, or delete).

    + +

    The change is pending until the current transaction ends. See +databaseWillCommit, databaseDidCommit and databaseDidRollback.

    + +

    This method is called in a protected dispatch queue, serialized will all +database updates.

    + +

    The event is only valid for the duration of this method call. If you +need to keep it longer, store a copy: event.copy()

    + +

    The observer has an opportunity to stop receiving further change events +from the current transaction by calling the +stopObservingDatabaseChangesUntilNextTransaction() method.

    +
    +

    Warning

    + this method must not change the database. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func databaseDidChange(with event: DatabaseEvent)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseWillCommit() + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    When a transaction is about to be committed, the transaction observer +has an opportunity to rollback pending changes by throwing an error.

    + +

    This method is called on the database queue.

    +
    +

    Warning

    +

    this method must not change the database.

    + +
    +
    +

    Throws

    +

    An eventual error that rollbacks pending changes.

    + +
    + +
    +

    Default Implementation

    +
    +

    Default implementation does nothing

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func databaseWillCommit() throws
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseDidCommit(_:) + +
    +
    +
    +
    +
    +
    +

    Database changes have been committed.

    + +

    This method is called on the database queue. It can change the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func databaseDidCommit(_ db: Database)
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Database changes have been rollbacked.

    + +

    This method is called on the database queue. It can change the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func databaseDidRollback(_ db: Database)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseWillChange(with:) + + + Default implementation + +
    +
    +
    +
    +
    +
    +

    Notifies before a database change (insert, update, or delete) +with change information (initial / final values for the row’s +columns). (Called before databaseDidChangeWithEvent.)

    + +

    The change is pending until the end of the current transaction, +and you always get a second chance to get basic event information in +the databaseDidChangeWithEvent callback.

    + +

    This callback is mostly useful for calculating detailed change +information for a row, and provides the initial / final values.

    + +

    This method is called in a protected dispatch queue, serialized will all +database updates.

    + +

    The event is only valid for the duration of this method call. If you +need to keep it longer, store a copy: event.copy()

    +
    +

    Warning

    + this method must not change the database. + +
    + +

    Availability Info

    + +

    Requires SQLite 3.13.0 + +Compiled with option SQLITE_ENABLE_PREUPDATE_HOOK

    + +

    As of OSX 10.11.5, and iOS 9.3.2, the built-in SQLite library +does not have this enabled, so you’ll need to compile your own +copy using GRDBCustomSQLite. See https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md

    + +

    The databaseDidChangeWithEvent callback is always available, +and may provide most/all of what you need. +(For example, FetchedRecordsController is built without databaseWillChange)

    + +
    +

    Default Implementation

    +
    +

    Default implementation does nothing

    + +
    +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + stopObservingDatabaseChangesUntilNextTransaction() + + + Extension method + +
    +
    +
    +
    +
    +
    +

    After this method has been called, the databaseDidChange(with:) +method won’t be called until the next transaction.

    + +

    For example:

    +
    class PlayerObserver: TransactionObserver {
    +    var playerTableWasModified = false
    +
    +    func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
    +        return eventKind.tableName == "player"
    +    }
    +
    +    func databaseDidChange(with event: DatabaseEvent) {
    +        playerTableWasModified = true
    +
    +        // It is pointless to keep on tracking further changes:
    +        stopObservingDatabaseChangesUntilNextTransaction()
    +    }
    +}
    +
    +
    +

    Precondition

    + This method must be called from databaseDidChange(with:). + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func stopObservingDatabaseChangesUntilNextTransaction()
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/VirtualTableModule.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/VirtualTableModule.html new file mode 100644 index 000000000..165b159ff --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Protocols/VirtualTableModule.html @@ -0,0 +1,981 @@ + + + + VirtualTableModule Protocol Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

VirtualTableModule

+
+
+
public protocol VirtualTableModule
+ +
+
+

The protocol for SQLite virtual table modules. It lets you define a DSL for +the Database.create(virtualTable:using:) method:

+
let module = ...
+try db.create(virtualTable: "item", using: module) { t in
+    ...
+}
+
+ +

GRDB ships with three concrete classes that implement this protocol: FTS3, +FTS4 and FTS5.

+ +
+
+
+
    +
  • +
    + + + + TableDefinition + +
    +
    +
    +
    +
    +
    +

    The type of the closure argument in the +Database.create(virtualTable:using:) method:

    +
    try db.create(virtualTable: "item", using: module) { t in
    +    // t is TableDefinition
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    associatedtype TableDefinition
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + moduleName + +
    +
    +
    +
    +
    +
    +

    The name of the module.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    var moduleName: String { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + makeTableDefinition() + +
    +
    +
    +
    +
    +
    +

    Returns a table definition that is passed as the closure argument in the +Database.create(virtualTable:using:) method:

    +
    try db.create(virtualTable: "item", using: module) { t in
    +    // t is the result of makeTableDefinition()
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func makeTableDefinition() -> TableDefinition
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns the module arguments for the CREATE VIRTUAL TABLE query.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func moduleArguments(for definition: TableDefinition, in db: Database) throws -> [String]
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Execute any relevant database statement after the virtual table has +been created.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    func database(_ db: Database, didCreate tableName: String, using definition: TableDefinition) throws
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs.html new file mode 100644 index 000000000..1b2d2b307 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs.html @@ -0,0 +1,2911 @@ + + + + Structures Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Structures

+

The following structures are available globally.

+ +
+
+
+
    +
  • +
    + + + + Configuration + +
    +
    +
    +
    +
    +
    +

    Configuration for a DatabaseQueue or DatabasePool.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct Configuration
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + ColumnInfo + +
    +
    +
    +
    +
    +
    +

    A column of a database table.

    + +

    This type closely matches the information returned by the +table_info pragma.

    +
    > CREATE TABLE player (
    +    id INTEGER PRIMARY KEY,
    +    firstName TEXT,
    +    lastName TEXT)
    +> PRAGMA table_info("player")
    +cid   name   type     notnull   dflt_value  pk
    +----  -----  -------  --------  ----------  ---
    +0     id     INTEGER  0         NULL        1
    +1     name   TEXT     0         NULL        0
    +2     score  INTEGER  0         NULL        0
    +
    + +

    See Database.columns(in:) and https://www.sqlite.org/pragma.html#pragma_table_info

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct ColumnInfo : FetchableRecord
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + IndexInfo + +
    +
    +
    +
    +
    +
    +

    An index on a database table.

    + +

    See Database.indexes(on:)

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct IndexInfo
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + PrimaryKeyInfo + +
    +
    +
    +
    +
    +
    +

    Primary keys are returned from the Database.primaryKey(_:) method.

    + +

    When the table’s primary key is the rowid:

    +
    // CREATE TABLE item (name TEXT)
    +let pk = try db.primaryKey("item")
    +pk.columns     // ["rowid"]
    +pk.rowIDColumn // nil
    +pk.isRowID     // true
    +
    +// CREATE TABLE citizen (
    +//   id INTEGER PRIMARY KEY,
    +//   name TEXT
    +// )
    +let pk = try db.primaryKey("citizen")!
    +pk.columns     // ["id"]
    +pk.rowIDColumn // "id"
    +pk.isRowID     // true
    +
    + +

    When the table’s primary key is not the rowid:

    +
    // CREATE TABLE country (
    +//   isoCode TEXT NOT NULL PRIMARY KEY
    +//   name TEXT
    +// )
    +let pk = db.primaryKey("country")!
    +pk.columns     // ["isoCode"]
    +pk.rowIDColumn // nil
    +pk.isRowID     // false
    +
    +// CREATE TABLE citizenship (
    +//   citizenID INTEGER NOT NULL REFERENCES citizen(id)
    +//   countryIsoCode TEXT NOT NULL REFERENCES country(isoCode)
    +//   PRIMARY KEY (citizenID, countryIsoCode)
    +// )
    +let pk = db.primaryKey("citizenship")!
    +pk.columns     // ["citizenID", "countryIsoCode"]
    +pk.rowIDColumn // nil
    +pk.isRowID     // false
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct PrimaryKeyInfo
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ForeignKeyInfo + +
    +
    +
    +
    +
    +
    +

    You get foreign keys from table names, with the +foreignKeys(on:) method.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct ForeignKeyInfo
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + ResultCode + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + DatabaseError + +
    +
    +
    +
    +
    +
    +

    DatabaseError wraps an SQLite error.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct DatabaseError : Error, CustomStringConvertible, CustomNSError
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + DatabaseRegion + +
    +
    +
    +
    +
    +
    +

    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.

    + +

    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 (identified by +their rowids):

    +
    |Table1 |   |Table2 |   |Table3 |   |Table4 |   |Table5 |
    +|-------|   |-------|   |-------|   |-------|   |-------|
    +|x|x|x|x|   |x| | | |   |x|x|x|x|   |x|x| |x|   | | | | |
    +|x|x|x|x|   |x| | | |   | | | | |   | | | | |   | |x| | |
    +|x|x|x|x|   |x| | | |   | | | | |   |x|x| |x|   | | | | |
    +|x|x|x|x|   |x| | | |   | | | | |   | | | | |   | | | | |
    +
    + +

    You don’t create a database region directly. Instead, you use one of +those methods:

    + +
      +
    • SelectStatement.databaseRegion:

      + +

      let statement = db.makeSelectStatement(SELECT name, score FROM player) +print(statement.databaseRegion) +// prints player(name,score)

    • +
    • FetchRequest.databaseRegion(_:)

      + +

      let request = Player.filter(key: 1) +try print(request.databaseRegion(db)) +// prints player(*)[1]

    • +
    + +

    Database regions returned by requests can be more precise than regions +returned by select statements. Especially, regions returned by statements +don’t know about rowids:

    +
    // A plain statement
    +let statement = db.makeSelectStatement("SELECT * FROM player WHERE id = 1")
    +statement.databaseRegion       // "player(*)"
    +
    +// A query interface request that executes the same statement:
    +let request = Player.filter(key: 1)
    +try request.databaseRegion(db) // "player(*)[1]"
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct DatabaseRegion : CustomStringConvertible, Equatable
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+ + +
+
+ +
    +
  • +
    + + + + AnyFetchRequest + +
    +
    +
    +
    +
    +
    +

    A type-erased FetchRequest.

    + +

    An AnyFetchRequest forwards its operations to an underlying request, +hiding its specifics.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct AnyFetchRequest<T> : FetchRequest
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+ +
    +
  • +
    + + + + RowIndex + +
    +
    +
    +
    +
    +
    +

    Indexes to (ColumnName, DatabaseValue) pairs in a database row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct RowIndex : Comparable, Strideable
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + EmptyRowAdapter + +
    +
    +
    +
    +
    +
    +

    EmptyRowAdapter is a row adapter that hides all columns.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct EmptyRowAdapter : RowAdapter
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ColumnMapping + +
    +
    +
    +
    +
    +
    +

    ColumnMapping is a row adapter that maps column names.

    +
    let adapter = ColumnMapping(["foo": "bar"])
    +let sql = "SELECT 'foo' AS foo, 'bar' AS bar, 'baz' AS baz"
    +
    +// [foo:"bar"]
    +try Row.fetchOne(db, sql, adapter: adapter)
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct ColumnMapping : RowAdapter
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SuffixRowAdapter + +
    +
    +
    +
    +
    +
    +

    SuffixRowAdapter is a row adapter that hides the first columns in a row.

    +
    let adapter = SuffixRowAdapter(fromIndex: 2)
    +let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
    +
    +// [baz:3]
    +try Row.fetchOne(db, sql, adapter: adapter)
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct SuffixRowAdapter : RowAdapter
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + RangeRowAdapter + +
    +
    +
    +
    +
    +
    +

    RangeRowAdapter is a row adapter that only exposes a range of columns.

    +
    let adapter = RangeRowAdapter(1..<3)
    +let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz, 4 as qux"
    +
    +// [bar:2 baz:3]
    +try Row.fetchOne(db, sql, adapter: adapter)
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct RangeRowAdapter : RowAdapter
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ScopeAdapter + +
    +
    +
    +
    +
    +
    +

    ScopeAdapter is a row adapter that lets you define scopes on rows.

    +
    // Two adapters
    +let fooAdapter = ColumnMapping(["value": "foo"])
    +let barAdapter = ColumnMapping(["value": "bar"])
    +
    +// Define scopes
    +let adapter = ScopeAdapter([
    +    "foo": fooAdapter,
    +    "bar": barAdapter])
    +
    +// Fetch
    +let sql = "SELECT 'foo' AS foo, 'bar' AS bar"
    +let row = try Row.fetchOne(db, sql, adapter: adapter)!
    +
    +// Scoped rows:
    +if let fooRow = row.scopes["foo"] {
    +    fooRow["value"]    // "foo"
    +}
    +if let barRow = row.scopes["bar"] {
    +    barRow["value"]    // "bar"
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct ScopeAdapter : RowAdapter
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + StatementArguments + +
    +
    +
    +
    +
    +
    +

    StatementArguments provide values to argument placeholders in raw +SQL queries.

    + +

    Placeholders can take several forms (see https://www.sqlite.org/lang_expr.html#varparam +for more information):

    + +
      +
    • ?NNN (e.g. ?2): the NNN-th argument (starts at 1)
    • +
    • ?: the N-th argument, where N is one greater than the largest argument +number already assigned
    • +
    • :AAAA (e.g. :name): named argument

    • +
    • $AAAA (e.g. $name): named argument

    • +
    +

    Positional Arguments

    + +

    To fill question marks placeholders, feed StatementArguments with an array:

    +
    db.execute(
    +    "INSERT ... (?, ?)",
    +    arguments: StatementArguments(["Arthur", 41]))
    +
    +// Array literals are automatically converted:
    +db.execute(
    +    "INSERT ... (?, ?)",
    +    arguments: ["Arthur", 41])
    +
    +

    Named Arguments

    + +

    To fill named arguments, feed StatementArguments with a dictionary:

    +
    db.execute(
    +    "INSERT ... (:name, :score)",
    +    arguments: StatementArguments(["name": "Arthur", "score": 41]))
    +
    +// Dictionary literals are automatically converted:
    +db.execute(
    +    "INSERT ... (:name, :score)",
    +    arguments: ["name": "Arthur", "score": 41])
    +
    +

    Concatenating Arguments

    + +

    Several arguments can be concatenated and mixed with the +append(contentsOf:) method and the +, &+, += operators:

    +
    var arguments: StatementArguments = ["Arthur"]
    +arguments += [41]
    +db.execute("INSERT ... (?, ?)", arguments: arguments)
    +
    + +

    + and += operators consider that overriding named arguments is a +programmer error:

    +
    var arguments: StatementArguments = ["name": "Arthur"]
    +arguments += ["name": "Barbara"]
    +// fatal error: already defined statement argument: name
    +
    + +

    &+ and append(contentsOf:) allow overriding named arguments:

    +
    var arguments: StatementArguments = ["name": "Arthur"]
    +arguments = arguments &+ ["name": "Barbara"]
    +print(arguments)
    +// Prints ["name": "Barbara"]
    +
    +

    Mixed Arguments

    + +

    It is possible to mix named and positional arguments. Yet this is usually +confusing, and it is best to avoid this practice:

    +
    let sql = "SELECT ?2 AS two, :foo AS foo, ?1 AS one, :foo AS foo2, :bar AS bar"
    +var arguments: StatementArguments = [1, 2, "bar"] + ["foo": "foo"]
    +let row = try Row.fetchOne(db, sql, arguments: arguments)!
    +print(row)
    +// Prints [two:2 foo:"foo" one:1 foo2:"foo" bar:"bar"]
    +
    + +

    Mixed arguments exist as a support for requests like the following:

    +
    let players = try Player
    +    .filter(sql: "team = :team", arguments: ["team": "Blue"])
    +    .filter(sql: "score > ?", arguments: [1000])
    +    .fetchAll(db)
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct StatementArguments : CustomStringConvertible, Equatable, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
+
+ + +
+
+
    +
  • +
    + + + + FTS3 + +
    +
    +
    +
    +
    +
    +

    FTS3 lets you define fts3 virtual tables.

    +
    // CREATE VIRTUAL TABLE document USING fts3(content)
    +try db.create(virtualTable: "document", using: FTS3()) { t in
    +    t.column("content")
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct FTS3 : VirtualTableModule
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + FTS3Pattern + +
    +
    +
    +
    +
    +
    +

    A full text pattern that can query FTS3 and FTS4 virtual tables.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct FTS3Pattern
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
+
+ +
+
+
    +
  • +
    + + + + FTS5 + +
    +
    +
    +
    +
    +
    +

    FTS5 lets you define fts5 virtual tables.

    +
    // CREATE VIRTUAL TABLE document USING fts5(content)
    +try db.create(virtualTable: "document", using: FTS5()) { t in
    +    t.column("content")
    +}
    +
    + +

    See https://www.sqlite.org/fts5.html

    + + See more +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + FTS5Pattern + +
    +
    +
    +
    +
    +
    +

    A full text pattern that can query FTS5 virtual tables.

    + + See more +
    +
    +
    +
  • +
+
+
+ +
+
+ +
+
+ +
+
+
    +
  • +
    + + + + DatabaseMigrator + +
    +
    +
    +
    +
    +
    +

    A DatabaseMigrator registers and applies database migrations.

    + +

    Migrations are named blocks of SQL statements that are guaranteed to be +applied in order, once and only once.

    + +

    When a user upgrades your application, only non-applied migration are run.

    + +

    Usage:

    +
    var migrator = DatabaseMigrator()
    +
    +// 1st migration
    +migrator.registerMigration("createLibrary") { db in
    +    try db.create(table: "author") { t in
    +        t.autoIncrementedPrimaryKey("id")
    +        t.column("creationDate", .datetime)
    +        t.column("name", .text).notNull()
    +    }
    +
    +    try db.create(table: "book") { t in
    +        t.autoIncrementedPrimaryKey("id")
    +        t.column("authorId", .integer)
    +            .notNull()
    +            .references("author", onDelete: .cascade)
    +        t.column("title", .text).notNull()
    +    }
    +}
    +
    +// 2nd migration
    +migrator.registerMigration("AddBirthYearToAuthors") { db in
    +    try db.alter(table: "author") { t
    +        t.add(column: "birthYear", .integer)
    +    }
    +}
    +
    +// Migrations for future versions will be inserted here:
    +//
    +// // 3rd migration
    +// migrator.registerMigration("...") { db in
    +//     ...
    +// }
    +
    +try migrator.migrate(dbQueue)
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct DatabaseMigrator
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + BelongsToAssociation + +
    +
    +
    +
    +
    +
    +

    The BelongsTo association 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)
    +    ...
    +}
    +
    + +

    A BelongsTo associations 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.

    + +

    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)
    +}
    +
    + +
      +
    1. The author table has a primary key.
    2. +
    3. The book.authorId column is used to link a book to the author it +belongs to.
    4. +
    5. Make the book.authorId column not null if you want SQLite to guarantee +that all books have an author.
    6. +
    7. Create an index on the book.authorId column in order to ease the +selection of an author’s books.
    8. +
    9. Create a foreign key from book.authorId column to authors.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. +See https://sqlite.org/foreignkeys.html#fk_actions for more information.
    10. +
    + +

    The example above uses auto-incremented primary keys. But generally +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 +missing foreign key:

    +
    struct Book: FetchableRecord, TableRecord {
    +    static let author = belongsTo(Author.self, using: ForeignKey(...))
    +}
    +
    + +

    See ForeignKey for more information.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct BelongsToAssociation<Origin, Destination> : Association
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + ForeignKey + +
    +
    +
    +
    +
    +
    +

    A ForeignKey helps building associations when GRDB can’t infer a foreign +key from the database schema.

    + +

    Sometimes the database schema does not define any foreign key between two +tables. And sometimes, there are several foreign keys from a table +to another:

    +
    | Table book   |       | Table person |
    +| ------------ |       | ------------ |
    +| id           |   +-->• id           |
    +| authorId     •---+   | name         |
    +| translatorId •---+
    +| title        |
    +
    + +

    When this happens, associations can’t be automatically inferred from the +database schema. GRDB will complain with a fatal error such as Ambiguous +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:

    +
    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)
    +}
    +
    + +

    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]))
    +}
    +
    + +

    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:

    +
    struct Book: TableRecord {
    +    static let authorForeignKey = ForeignKey(["authorId"], to: ["id"]))
    +    static let author = belongsTo(Person.self, using: authorForeignKey)
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct ForeignKey
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + HasManyAssociation + +
    +
    +
    +
    +
    +
    +

    The HasMany association 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)
    +    ...
    +}
    +
    + +

    HasMany associations 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.

    + +

    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)
    +}
    +
    + +
      +
    1. The author table has a primary key.
    2. +
    3. The book.authorId column is used to link a book to the author it +belongs to.
    4. +
    5. Make the book.authorId column not null if you want SQLite to guarantee +that all books have an author.
    6. +
    7. Create an index on the book.authorId column in order to ease the +selection of an author’s books.
    8. +
    9. Create a foreign key from book.authorId column to authors.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. +See https://sqlite.org/foreignkeys.html#fk_actions for more information.
    10. +
    + +

    The example above uses auto-incremented primary keys. But generally +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 +missing foreign key:

    +
    struct Author: TableRecord {
    +    static let books = hasMany(Book.self, using: ForeignKey(...))
    +}
    +
    + +

    See ForeignKey for more information.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct HasManyAssociation<Origin, Destination> : Association
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + HasOneAssociation + +
    +
    +
    +
    +
    +
    +

    The HasOne association 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.

    + +

    For example, if your application has one database table for countries, and +another for their demographic profiles, you’d declare the association +this way:

    +
    struct Demographics: TableRecord { ... }
    +struct Country: TableRecord {
    +    static let demographics = hasOne(Demographics.self)
    +    ...
    +}
    +
    + +

    HasOne associations 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.

    + +

    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)
    +}
    +
    + +
      +
    1. The country table has a primary key.
    2. +
    3. The demographics.countryCode column is used to link a demographic +profile to the country it belongs to.
    4. +
    5. Make the demographics.countryCode column not null if you want SQLite to +guarantee that all profiles are linked to a country.
    6. +
    7. Create a unique index on the demographics.countryCode column in order to +guarantee the unicity of any country’s profile.
    8. +
    9. 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.
    10. +
    + +

    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:

    +
    struct Country: FetchableRecord, TableRecord {
    +    static let demographics = hasOne(Demographics.self, using: ForeignKey(...))
    +}
    +
    + +

    See ForeignKey for more information.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct HasOneAssociation<Origin, Destination> : Association
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
+
+ +
+
+ +
    +
  • +
    + + + + SQLExpressionLiteral + +
    +
    +
    +
    +
    +
    +

    Experimental

    + +

    SQLExpressionLiteral is an expression built from a raw SQL snippet.

    +
    SQLExpressionLiteral("1 + 2")
    +
    + +

    The SQL literal may contain ? and colon-prefixed arguments:

    +
    SQLExpressionLiteral("? + ?", arguments: [1, 2])
    +SQLExpressionLiteral(":one + :two", arguments: ["one": 1, "two": 2])
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct SQLExpressionLiteral : SQLExpression
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+ +
    +
  • +
    + + + + AllColumns + +
    +
    +
    +
    +
    +
    +

    AllColumns is the * in SELECT *.

    + +

    You use AllColumns in your custom implementation of +TableRecord.databaseSelection.

    + +

    For example:

    +
    struct Player : TableRecord {
    +    static var databaseTableName = "player"
    +    static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
    +}
    +
    +// SELECT *, rowid FROM player
    +let request = Player.all()
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct AllColumns
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+ +
    +
  • +
    + + + + PersistenceContainer + +
    +
    +
    +
    +
    +
    +

    Use persistence containers in the encode(to:) method of your +encodable records:

    +
    struct Player : MutablePersistableRecord {
    +    var id: Int64?
    +    var name: String?
    +
    +    func encode(to container: inout PersistenceContainer) {
    +        container["id"] = id
    +        container["name"] = name
    +    }
    +}
    +
    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public struct PersistenceContainer
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/AdaptedFetchRequest.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/AdaptedFetchRequest.html new file mode 100644 index 000000000..575db0880 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/AdaptedFetchRequest.html @@ -0,0 +1,840 @@ + + + + AdaptedFetchRequest Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

AdaptedFetchRequest

+
+
+
public struct AdaptedFetchRequest<Base> : FetchRequest where Base : FetchRequest
+ +
+
+

An adapted request.

+ +
+
+
+
    +
  • +
    + + + + RowDecoder + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public typealias RowDecoder = Base.RowDecoder
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/AllColumns.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/AllColumns.html new file mode 100644 index 000000000..1237fe745 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/AllColumns.html @@ -0,0 +1,854 @@ + + + + AllColumns Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

AllColumns

+
+
+
public struct AllColumns
+ +
+
+

AllColumns is the * in SELECT *.

+ +

You use AllColumns in your custom implementation of +TableRecord.databaseSelection.

+ +

For example:

+
struct Player : TableRecord {
+    static var databaseTableName = "player"
+    static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
+}
+
+// SELECT *, rowid FROM player
+let request = Player.all()
+
+ +
+
+
+
    +
  • +
    + + + + init() + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init()
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/AnyFetchRequest.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/AnyFetchRequest.html new file mode 100644 index 000000000..64c25f0e4 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/AnyFetchRequest.html @@ -0,0 +1,904 @@ + + + + AnyFetchRequest Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

AnyFetchRequest

+
+
+
public struct AnyFetchRequest<T> : FetchRequest
+ +
+
+

A type-erased FetchRequest.

+ +

An AnyFetchRequest forwards its operations to an underlying request, +hiding its specifics.

+ +
+
+
+
    +
  • +
    + + + + RowDecoder + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public typealias RowDecoder = T
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a request that wraps and forwards operations to request.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init<Request>(_ request: Request) where Request : FetchRequest
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a request whose prepare() method wraps and forwards +operations the argument closure.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?))
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/BelongsToAssociation.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/BelongsToAssociation.html new file mode 100644 index 000000000..8d1084e6d --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/BelongsToAssociation.html @@ -0,0 +1,930 @@ + + + + BelongsToAssociation Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

BelongsToAssociation

+
+
+
public struct BelongsToAssociation<Origin, Destination> : Association
+ +
+
+

The BelongsTo association 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)
+    ...
+}
+
+ +

A BelongsTo associations 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.

+ +

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)
+}
+
+ +
    +
  1. The author table has a primary key.
  2. +
  3. The book.authorId column is used to link a book to the author it +belongs to.
  4. +
  5. Make the book.authorId column not null if you want SQLite to guarantee +that all books have an author.
  6. +
  7. Create an index on the book.authorId column in order to ease the +selection of an author’s books.
  8. +
  9. Create a foreign key from book.authorId column to authors.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. +See https://sqlite.org/foreignkeys.html#fk_actions for more information.
  10. +
+ +

The example above uses auto-incremented primary keys. But generally +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 +missing foreign key:

+
struct Book: FetchableRecord, TableRecord {
+    static let author = belongsTo(Author.self, using: ForeignKey(...))
+}
+
+ +

See ForeignKey for more information.

+ +
+
+
+
    +
  • +
    + + + + key + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var key: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + forKey(_:) + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func forKey(_ key: String) -> BelongsToAssociation<Origin, Destination>
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/Column.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/Column.html new file mode 100644 index 000000000..0dc64da98 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/Column.html @@ -0,0 +1,906 @@ + + + + Column Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Column

+
+
+
public struct Column : ColumnExpression
+ +
+
+

A column in a database table.

+ +

When you need to introduce your own column type, don’t wrap a Column. +Instead, adopt the ColumnExpression protocol.

+ +

See https://github.com/groue/GRDB.swift#the-query-interface

+ +
+
+
+
    +
  • +
    + + + + rowID + +
    +
    +
    +
    +
    +
    +

    The hidden rowID column

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let rowID: Column
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + name + +
    +
    +
    +
    +
    +
    +

    The name of the column

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var name: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a column given its name.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ name: String)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/ColumnInfo.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/ColumnInfo.html new file mode 100644 index 000000000..ba96a4caf --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/ColumnInfo.html @@ -0,0 +1,1012 @@ + + + + ColumnInfo Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ColumnInfo

+
+
+
public struct ColumnInfo : FetchableRecord
+ +
+
+

A column of a database table.

+ +

This type closely matches the information returned by the +table_info pragma.

+
> CREATE TABLE player (
+    id INTEGER PRIMARY KEY,
+    firstName TEXT,
+    lastName TEXT)
+> PRAGMA table_info("player")
+cid   name   type     notnull   dflt_value  pk
+----  -----  -------  --------  ----------  ---
+0     id     INTEGER  0         NULL        1
+1     name   TEXT     0         NULL        0
+2     score  INTEGER  0         NULL        0
+
+ +

See Database.columns(in:) and https://www.sqlite.org/pragma.html#pragma_table_info

+ +
+
+
+
    +
  • +
    + + + + name + +
    +
    +
    +
    +
    +
    +

    The column name

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let name: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + type + +
    +
    +
    +
    +
    +
    +

    The column data type

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let type: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + isNotNull + +
    +
    +
    +
    +
    +
    +

    True if and only if the column is constrained to be not null.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let isNotNull: Bool
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + defaultValueSQL + +
    +
    +
    +
    +
    +
    +

    The SQL snippet that defines the default value, if any.

    + +

    When nil, the column has no default value.

    + +

    When not nil, it contains an SQL string that defines an expression. That +expression may be a literal, as 1, or 'foo'. It may also contain a +non-constant expression such as CURRENT_TIMESTAMP.

    + +

    For example:

    +
    try db.execute("""
    +    CREATE TABLE player(
    +        id INTEGER PRIMARY KEY,
    +        name TEXT DEFAULT 'Anonymous',
    +        score INT DEFAULT 0,
    +        creationDate DATE DEFAULT CURRENT_TIMESTAMP
    +    )
    +    """)
    +let columnInfos = try db.columns(in: "player")
    +columnInfos[0].defaultValueSQL // nil
    +columnInfos[1].defaultValueSQL // "'Anoynymous'"
    +columnInfos[2].defaultValueSQL // "0"
    +columnInfos[3].defaultValueSQL // "CURRENT_TIMESTAMP"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let defaultValueSQL: String?
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + primaryKeyIndex + +
    +
    +
    +
    +
    +
    +

    Zero for columns that are not part of the primary key.

    + +

    Before SQLite 3.7.16, it is 1 for columns that are part of the +primary key.

    + +

    Starting from SQLite 3.7.16, it is the one-based index of the column in +the primary key for columns that are part of the primary key.

    + +

    References:

    + + + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let primaryKeyIndex: Int
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/ColumnMapping.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/ColumnMapping.html new file mode 100644 index 000000000..f7cdda5c8 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/ColumnMapping.html @@ -0,0 +1,848 @@ + + + + ColumnMapping Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ColumnMapping

+
+
+
public struct ColumnMapping : RowAdapter
+ +
+
+

ColumnMapping is a row adapter that maps column names.

+
let adapter = ColumnMapping(["foo": "bar"])
+let sql = "SELECT 'foo' AS foo, 'bar' AS bar, 'baz' AS baz"
+
+// [foo:"bar"]
+try Row.fetchOne(db, sql, adapter: adapter)
+
+ +
+
+
+
    +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a ColumnMapping with a dictionary from mapped column names to +column names in a base row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ mapping: [String : String])
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/Configuration.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/Configuration.html new file mode 100644 index 000000000..be5a7243b --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/Configuration.html @@ -0,0 +1,1244 @@ + + + + Configuration Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Configuration

+
+
+
public struct Configuration
+ +
+
+

Configuration for a DatabaseQueue or DatabasePool.

+ +
+
+
+ +
    +
  • +
    + + + + foreignKeysEnabled + +
    +
    +
    +
    +
    +
    +

    If true, foreign key constraints are checked.

    + +

    Default: true

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var foreignKeysEnabled: Bool
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + readonly + +
    +
    +
    +
    +
    +
    +

    If true, database modifications are disallowed.

    + +

    Default: false

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var readonly: Bool
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + label + +
    +
    +
    +
    +
    +
    +

    The database label.

    + +

    You can query this label at runtime:

    +
    var configuration = Configuration()
    +configuration.label = "MyDatabase"
    +let dbQueue = try DatabaseQueue(path: ..., configuration: configuration)
    +
    +try dbQueue.read { db in
    +    print(db.configuration.label) // Prints "MyDatabase"
    +}
    +
    + +

    The database label is also used to name the various dispatch queues +created by GRDB, visible in debugging sessions and crash logs. However +those dispatch queue labels are intended for debugging only. Their +format may change between GRDB releases. Applications should not depend +on the GRDB dispatch queue labels.

    + +

    If the database label is nil, the current GRDB implementation uses the +following dispatch queue labels:

    + +
      +
    • GRDB.DatabaseQueue: the (unique) dispatch queue of a DatabaseQueue
    • +
    • GRDB.DatabasePool.writer: the (unique) writer dispatch queue of +a DatabasePool
    • +
    • GRDB.DatabasePool.reader.N, where N is 1, 2, …: one of the reader +dispatch queue(s) of a DatabasePool. N grows with the number of SQLite +connections: it may get bigger than the maximum number of concurrent +readers, as SQLite connections get closed and new ones are opened.
    • +
    • GRDB.DatabasePool.snapshot.N: the dispatch queue of a +DatabaseSnapshot. N grows with the number of snapshots.
    • +
    + +

    If the database label is not nil, for example MyDatabase, the current +GRDB implementation uses the following dispatch queue labels:

    + +
      +
    • MyDatabase: the (unique) dispatch queue of a DatabaseQueue
    • +
    • MyDatabase.writer: the (unique) writer dispatch queue of +a DatabasePool
    • +
    • MyDatabase.reader.N, where N is 1, 2, …: one of the reader +dispatch queue(s) of a DatabasePool. N grows with the number of SQLite +connections: it may get bigger than the maximum number of concurrent +readers, as SQLite connections get closed and new ones are opened.
    • +
    • MyDatabase.snapshot.N: the dispatch queue of a +DatabaseSnapshot. N grows with the number of snapshots.
    • +
    + +

    The default label is nil.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var label: String?
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + trace + +
    +
    +
    +
    +
    +
    +

    A function that is called on every statement executed by the database.

    + +

    Default: nil

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var trace: TraceFunction?
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + passphrase + +
    +
    +
    +
    +
    +
    +

    The passphrase for encrypted database.

    + +

    Default: nil

    + +
    +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    The default kind of transaction.

    + +

    Default: deferred

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var defaultTransactionKind: Database.TransactionKind
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    If false, it is a programmer error to leave a transaction opened at the +end of a database access block.

    + +

    For example:

    +
    let dbQueue = DatabaseQueue()
    +
    +// fatal error: A transaction has been left opened at the end of a database access
    +try dbQueue.inDatabase { db in
    +    try db.beginTransaction()
    +}
    +
    + +

    If true, one can leave opened transaction at the end of database access +blocks:

    +
    var config = Configuration()
    +config.allowsUnsafeTransactions = true
    +let dbQueue = DatabaseQueue(configuration: config)
    +
    +try dbQueue.inDatabase { db in
    +    try db.beginTransaction()
    +}
    +
    +try dbQueue.inDatabase { db in
    +    try db.commit()
    +}
    +
    + +

    This configuration flag has no effect on DatabasePool readers: those +never allow leaving a transaction opened at the end of a read access.

    + +

    Default: false

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var allowsUnsafeTransactions: Bool
    + +
    +
    + +
    +
    +
  • +
+
+
+ + +
+
+ +
    +
  • +
    + + + + init() + +
    +
    +
    +
    +
    +
    +

    Creates a factory configuration

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init()
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseDateComponents.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseDateComponents.html new file mode 100644 index 000000000..8843387b7 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseDateComponents.html @@ -0,0 +1,1119 @@ + + + + DatabaseDateComponents Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseDateComponents

+
+
+
public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumnConvertible
+ +
+
+

DatabaseDateComponents reads and stores DateComponents in the database.

+ +
+
+
+
    +
  • +
    + + + + Format + +
    +
    +
    +
    +
    +
    +

    The available formats for reading and storing date components.

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public enum Format : String
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + dateComponents + +
    +
    +
    +
    +
    +
    +

    The date components

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let dateComponents: DateComponents
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + format + +
    +
    +
    +
    +
    +
    +

    The database format

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let format: Format
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:format:) + +
    +
    +
    +
    +
    +
    +

    Creates a DatabaseDateComponents from a DateComponents and a format.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ dateComponents: DateComponents, format: Format)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + dateComponents + + +
    +

    An optional DateComponents.

    +
    +
    + + format + + +
    +

    The format used for storing the date components in +the database.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Returns a value initialized from a raw SQLite statement pointer.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(sqliteStatement: SQLiteStatement, index: Int32)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sqliteStatement + + +
    +

    A pointer to an SQLite statement.

    +
    +
    + + index + + +
    +

    The column index.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns a DatabaseDateComponents if dbValue contains a +valid date.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> DatabaseDateComponents?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseDateComponents/Format.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseDateComponents/Format.html new file mode 100644 index 000000000..74c946614 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseDateComponents/Format.html @@ -0,0 +1,1027 @@ + + + + Format Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Format

+
+
+
public enum Format : String
+ +
+
+

The available formats for reading and storing date components.

+ +
+
+
+
    +
  • +
    + + + + YMD + +
    +
    +
    +
    +
    +
    +

    The format yyyy-MM-dd.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case YMD = "yyyy-MM-dd"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + YMD_HM + +
    +
    +
    +
    +
    +
    +

    The format yyyy-MM-dd HH:mm.

    + +

    This format is lexically comparable with SQLite’s CURRENT_TIMESTAMP.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case YMD_HM = "yyyy-MM-dd HH:mm"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + YMD_HMS + +
    +
    +
    +
    +
    +
    +

    The format yyyy-MM-dd HH:mm:ss.

    + +

    This format is lexically comparable with SQLite’s CURRENT_TIMESTAMP.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case YMD_HMS = "yyyy-MM-dd HH:mm:ss"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + YMD_HMSS + +
    +
    +
    +
    +
    +
    +

    The format yyyy-MM-dd HH:mm:ss.SSS.

    + +

    This format is lexically comparable with SQLite’s CURRENT_TIMESTAMP.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case YMD_HMSS = "yyyy-MM-dd HH:mm:ss.SSS"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + HM + +
    +
    +
    +
    +
    +
    +

    The format HH:mm.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case HM = "HH:mm"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + HMS + +
    +
    +
    +
    +
    +
    +

    The format HH:mm:ss.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case HMS = "HH:mm:ss"
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + HMSS + +
    +
    +
    +
    +
    +
    +

    The format HH:mm:ss.SSS.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case HMSS = "HH:mm:ss.SSS"
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseError.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseError.html new file mode 100644 index 000000000..36d1d0abc --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseError.html @@ -0,0 +1,983 @@ + + + + DatabaseError Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseError

+
+
+
public struct DatabaseError : Error, CustomStringConvertible, CustomNSError
+ +
+
+

DatabaseError wraps an SQLite error.

+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseEvent.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseEvent.html new file mode 100644 index 000000000..2e0640f25 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseEvent.html @@ -0,0 +1,999 @@ + + + + DatabaseEvent Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseEvent

+
+
+
public struct DatabaseEvent
+ +
+
+

A database event, notified to TransactionObserver.

+ +
+
+
+
    +
  • +
    + + + + Kind + +
    +
    +
    +
    +
    +
    +

    An event kind

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public enum Kind : Int32
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + kind + +
    +
    +
    +
    +
    +
    +

    The event kind

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let kind: Kind
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + databaseName + +
    +
    +
    +
    +
    +
    +

    The database name

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseName: String { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + tableName + +
    +
    +
    +
    +
    +
    +

    The table name

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var tableName: String { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + rowID + +
    +
    +
    +
    +
    +
    +

    The rowID of the changed row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let rowID: Int64
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + copy() + +
    +
    +
    +
    +
    +
    +

    Returns an event that can be stored:

    +
    class MyObserver: TransactionObserver {
    +    var events: [DatabaseEvent]
    +    func databaseDidChange(with event: DatabaseEvent) {
    +        events.append(event.copy())
    +    }
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func copy() -> DatabaseEvent
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseEvent/Kind.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseEvent/Kind.html new file mode 100644 index 000000000..7de72780a --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseEvent/Kind.html @@ -0,0 +1,901 @@ + + + + Kind Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Kind

+
+
+
public enum Kind : Int32
+ +
+
+

An event kind

+ +
+
+
+
    +
  • +
    + + + + insert + +
    +
    +
    +
    +
    +
    +

    SQLITE_INSERT

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case insert = 18
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + delete + +
    +
    +
    +
    +
    +
    +

    SQLITE_DELETE

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case delete = 9
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + update + +
    +
    +
    +
    +
    +
    +

    SQLITE_UPDATE

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case update = 23
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseMigrator.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseMigrator.html new file mode 100644 index 000000000..58b48ef86 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseMigrator.html @@ -0,0 +1,1186 @@ + + + + DatabaseMigrator Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseMigrator

+
+
+
public struct DatabaseMigrator
+ +
+
+

A DatabaseMigrator registers and applies database migrations.

+ +

Migrations are named blocks of SQL statements that are guaranteed to be +applied in order, once and only once.

+ +

When a user upgrades your application, only non-applied migration are run.

+ +

Usage:

+
var migrator = DatabaseMigrator()
+
+// 1st migration
+migrator.registerMigration("createLibrary") { db in
+    try db.create(table: "author") { t in
+        t.autoIncrementedPrimaryKey("id")
+        t.column("creationDate", .datetime)
+        t.column("name", .text).notNull()
+    }
+
+    try db.create(table: "book") { t in
+        t.autoIncrementedPrimaryKey("id")
+        t.column("authorId", .integer)
+            .notNull()
+            .references("author", onDelete: .cascade)
+        t.column("title", .text).notNull()
+    }
+}
+
+// 2nd migration
+migrator.registerMigration("AddBirthYearToAuthors") { db in
+    try db.alter(table: "author") { t
+        t.add(column: "birthYear", .integer)
+    }
+}
+
+// Migrations for future versions will be inserted here:
+//
+// // 3rd migration
+// migrator.registerMigration("...") { db in
+//     ...
+// }
+
+try migrator.migrate(dbQueue)
+
+ +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    When the eraseDatabaseOnSchemaChange flag is true, the migrator will +automatically wipe out the full database content, and recreate the whole +database from scratch, if it detects that a migration has changed its +definition.

    + +

    This flag can destroy your precious users’ data!

    + +

    But it may be useful in two situations:

    + +
      +
    1. During application development, as you are still designing +migrations, and the schema changes often.

      + +

      In this case, it is recommended that you make sure this flag does +not ship in the distributed application, in order to avoid undesired +data loss:

      +
      var migrator = DatabaseMigrator()
      +#if DEBUG
      +// Speed up development by nuking the database when migrations change
      +migrator.eraseDatabaseOnSchemaChange = true
      +#endif
      +
    2. +
    3. When the database content can easily be recreated, such as a cache +for some downloaded data.

    4. +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var eraseDatabaseOnSchemaChange: Bool
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init() + +
    +
    +
    +
    +
    +
    +

    A new migrator.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init()
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Registers a migration.

    +
    migrator.registerMigration("createAuthors") { db in
    +    try db.create(table: "author") { t in
    +        t.autoIncrementedPrimaryKey("id")
    +        t.column("creationDate", .datetime)
    +        t.column("name", .text).notNull()
    +    }
    +}
    +
    +
    +

    Precondition

    + No migration with the same same as already been registered. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public mutating func registerMigration(_ identifier: String, migrate: @escaping (Database) throws -> Void)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + identifier + + +
    +

    The migration identifier.

    +
    +
    + + block + + +
    +

    The migration block that performs SQL statements.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public mutating func registerMigrationWithDeferredForeignKeyCheck(_ identifier: String, migrate: @escaping (Database) throws -> Void)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + migrate(_:) + +
    +
    +
    +
    +
    +
    +

    Iterate migrations in the same order as they were registered. If a +migration has not yet been applied, its block is executed in +a transaction.

    +
    +

    Throws

    + An eventual error thrown by the registered migration blocks. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func migrate(_ writer: DatabaseWriter) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A DatabaseWriter (DatabaseQueue or DatabasePool) where +migrations should apply.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + migrate(_:upTo:) + +
    +
    +
    +
    +
    +
    +

    Iterate migrations in the same order as they were registered, up to the +provided target. If a migration has not yet been applied, its block is +executed in a transaction.

    +
  • targetIdentifier: The identifier of a registered migration.
  • +
    +

    Throws

    + An eventual error thrown by the registered migration blocks. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) throws
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A DatabaseWriter (DatabaseQueue or DatabasePool) where +migrations should apply.

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns the set of applied migration identifiers.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func appliedMigrations(in reader: DatabaseReader) throws -> Set<String>
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabasePreUpdateEvent.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabasePreUpdateEvent.html new file mode 100644 index 000000000..41ed19b6a --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabasePreUpdateEvent.html @@ -0,0 +1,1081 @@ + + + + DatabasePreUpdateEvent Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabasePreUpdateEvent

+ +
+
+
+
    +
  • +
    + + + + Kind + +
    +
    +
    +
    +
    +
    +

    An event kind

    + + See more +
    +
    +
    +
  • +
  • +
    + + + + kind + +
    +
    +
    +
    +
    +
    +

    The event kind

    + +
    +
    +
    +
  • +
  • +
    + + + + databaseName + +
    +
    +
    +
    +
    +
    +

    The database name

    + +
    +
    +
    +
  • +
  • +
    + + + + tableName + +
    +
    +
    +
    +
    +
    +

    The table name

    + +
    +
    +
    +
  • +
  • +
    + + + + count + +
    +
    +
    +
    +
    +
    +

    The number of columns in the row that is being inserted, updated, or deleted.

    + +
    +
    +
    +
  • +
  • +
    + + + + depth + +
    +
    +
    +
    +
    +
    +

    1 for inserts, updates, or deletes invoked by top-level triggers; +2 for changes resulting from triggers called by top-level triggers; +… and so forth

    + +
    +
    +
    +
  • +
  • +
    + + + + initialRowID + +
    +
    +
    +
    +
    +
    +

    The initial rowID of the row being changed for .Update and .Delete changes, +and nil for .Insert changes.

    + +
    +
    +
    +
  • +
  • +
    + + + + finalRowID + +
    +
    +
    +
    +
    +
    +

    The final rowID of the row being changed for .Update and .Insert changes, +and nil for .Delete changes.

    + +
    +
    +
    +
  • +
  • +
    + + + + initialDatabaseValues + +
    +
    +
    +
    +
    +
    +

    The initial database values in the row.

    + +

    Values appear in the same order as the columns in the table.

    + +

    The result is nil if the event is an .Insert event.

    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns the initial DatabaseValue at given index.

    + +

    Indexes span from 0 for the leftmost column to (row.count - 1) for the +righmost column.

    + +

    The result is nil if the event is an .Insert event.

    + +
    +
    +
    +
  • +
  • +
    + + + + finalDatabaseValues + +
    +
    +
    +
    +
    +
    +

    The final database values in the row.

    + +

    Values appear in the same order as the columns in the table.

    + +

    The result is nil if the event is a .Delete event.

    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Returns the final DatabaseValue at given index.

    + +

    Indexes span from 0 for the leftmost column to (row.count - 1) for the +righmost column.

    + +

    The result is nil if the event is a .Delete event.

    + +
    +
    +
    +
  • +
  • +
    + + + + copy() + +
    +
    +
    +
    +
    +
    +

    Returns an event that can be stored:

    +
    class MyObserver: TransactionObserver {
    +    var events: [DatabasePreUpdateEvent]
    +    func databaseWillChange(with event: DatabasePreUpdateEvent) {
    +        events.append(event.copy())
    +    }
    +}
    +
    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabasePreUpdateEvent/Kind.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabasePreUpdateEvent/Kind.html new file mode 100644 index 000000000..bfd205a68 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabasePreUpdateEvent/Kind.html @@ -0,0 +1,862 @@ + + + + Kind Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Kind

+

An event kind

+ +
+
+
+
    +
  • +
    + + + + insert + +
    +
    +
    +
    +
    +
    +

    SQLITE_INSERT

    + +
    +
    +
    +
  • +
  • +
    + + + + delete + +
    +
    +
    +
    +
    +
    +

    SQLITE_DELETE

    + +
    +
    +
    +
  • +
  • +
    + + + + update + +
    +
    +
    +
    +
    +
    +

    SQLITE_UPDATE

    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseRegion.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseRegion.html new file mode 100644 index 000000000..b876d8c1a --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseRegion.html @@ -0,0 +1,1082 @@ + + + + DatabaseRegion Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseRegion

+
+
+
public struct DatabaseRegion : CustomStringConvertible, Equatable
+ +
+
+

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.

+ +

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 (identified by +their rowids):

+
|Table1 |   |Table2 |   |Table3 |   |Table4 |   |Table5 |
+|-------|   |-------|   |-------|   |-------|   |-------|
+|x|x|x|x|   |x| | | |   |x|x|x|x|   |x|x| |x|   | | | | |
+|x|x|x|x|   |x| | | |   | | | | |   | | | | |   | |x| | |
+|x|x|x|x|   |x| | | |   | | | | |   |x|x| |x|   | | | | |
+|x|x|x|x|   |x| | | |   | | | | |   | | | | |   | | | | |
+
+ +

You don’t create a database region directly. Instead, you use one of +those methods:

+ +
    +
  • SelectStatement.databaseRegion:

    + +

    let statement = db.makeSelectStatement(SELECT name, score FROM player) +print(statement.databaseRegion) +// prints player(name,score)

  • +
  • FetchRequest.databaseRegion(_:)

    + +

    let request = Player.filter(key: 1) +try print(request.databaseRegion(db)) +// prints player(*)[1]

  • +
+ +

Database regions returned by requests can be more precise than regions +returned by select statements. Especially, regions returned by statements +don’t know about rowids:

+
// A plain statement
+let statement = db.makeSelectStatement("SELECT * FROM player WHERE id = 1")
+statement.databaseRegion       // "player(*)"
+
+// A query interface request that executes the same statement:
+let request = Player.filter(key: 1)
+try request.databaseRegion(db) // "player(*)[1]"
+
+ +
+
+
+
    +
  • +
    + + + + isEmpty + +
    +
    +
    +
    +
    +
    +

    Returns whether the region is empty.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var isEmpty: Bool { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fullDatabase + +
    +
    +
    +
    +
    +
    +

    The region that covers the full database: all columns and all rows +from all tables.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let fullDatabase: DatabaseRegion
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init() + +
    +
    +
    +
    +
    +
    +

    The empty database region

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init()
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + union(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the union of this region and the given one.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func union(_ other: DatabaseRegion) -> DatabaseRegion
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + formUnion(_:) + +
    +
    +
    +
    +
    +
    +

    Inserts the given region into this region

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public mutating func formUnion(_ other: DatabaseRegion)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Returns whether the content in the region would be impacted if the +database were modified by an event of this kind.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func isModified(byEventsOfKind eventKind: DatabaseEventKind) -> Bool
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + isModified(by:) + +
    +
    +
    +
    +
    +
    +

    Returns whether the content in the region is impacted by this event.

    +
    +

    Precondition

    + event has been filtered by the same region +in the TransactionObserver.observes(eventsOfKind:) method, by calling +region.isModified(byEventsOfKind:) + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func isModified(by event: DatabaseEvent) -> Bool
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseValue.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseValue.html new file mode 100644 index 000000000..39c1f4e31 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseValue.html @@ -0,0 +1,1263 @@ + + + + DatabaseValue Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

DatabaseValue

+
+
+
public struct DatabaseValue : Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLExpression
+ +
+
+

DatabaseValue is the intermediate type between SQLite and your values.

+ +

See https://www.sqlite.org/datatype3.html

+ +
+
+
+
    +
  • +
    + + + + storage + +
    +
    +
    +
    +
    +
    +

    The SQLite storage

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let storage: Storage
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + null + +
    +
    +
    +
    +
    +
    +

    The NULL DatabaseValue.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let null: DatabaseValue
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + Storage + +
    +
    +
    +
    +
    +
    +

    An SQLite storage (NULL, INTEGER, REAL, TEXT, BLOB).

    + + See more +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public enum Storage : Equatable
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(value:) + +
    +
    +
    +
    +
    +
    +

    Creates a DatabaseValue from Any.

    + +

    The result is nil unless object adopts DatabaseValueConvertible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init?(value: Any)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + isNull + +
    +
    +
    +
    +
    +
    +

    Returns true if databaseValue is NULL.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var isNull: Bool { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + ==(_:_:) + +
    +
    +
    +
    +
    +
    +

    Returns whether two DatabaseValues are equal.

    +
    1.databaseValue == "foo".databaseValue // false
    +1.databaseValue == 1.databaseValue     // true
    +
    + +

    When comparing integers and doubles, the result is true if and only +values are equal, and if converting one type to the other does +not lose information:

    +
    1.databaseValue == 1.0.databaseValue   // true
    +
    + +

    For a comparison that distinguishes integer and doubles, compare +storages instead:

    +
    1.databaseValue.storage == 1.0.databaseValue.storage // false
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func == (lhs: DatabaseValue, rhs: DatabaseValue) -> Bool
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Converts the database value to the type T.

    +
    let dbValue = "foo".databaseValue
    +let string = dbValue.losslessConvert() as String // "foo"
    +
    + +

    Conversion is successful if and only if T.fromDatabaseValue returns a +non-nil value.

    + +

    This method crashes with a fatal error when conversion fails.

    +
    let dbValue = "foo".databaseValue
    +let int = dbValue.losslessConvert() as Int // fatalError
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil) -> T where T : DatabaseValueConvertible
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sql + + +
    +

    Optional SQL statement that enhances the eventual +conversion error

    +
    +
    + + arguments + + +
    +

    Optional statement arguments that enhances the eventual +conversion error

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Converts the database value to the type Optional.

    +
    let dbValue = "foo".databaseValue
    +let string = dbValue.losslessConvert() as String? // "foo"
    +let null = DatabaseValue.null.losslessConvert() as String? // nil
    +
    + +

    Conversion is successful if and only if T.fromDatabaseValue returns a +non-nil value.

    + +

    This method crashes with a fatal error when conversion fails.

    +
    let dbValue = "foo".databaseValue
    +let int = dbValue.losslessConvert() as Int? // fatalError
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil) -> T? where T : DatabaseValueConvertible
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + sql + + +
    +

    Optional SQL statement that enhances the eventual +conversion error

    +
    +
    + + arguments + + +
    +

    Optional statement arguments that enhances the eventual +conversion error

    +
    +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns self

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns the database value

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> DatabaseValue?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseValue/Storage.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseValue/Storage.html new file mode 100644 index 000000000..a52692a08 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/DatabaseValue/Storage.html @@ -0,0 +1,1025 @@ + + + + Storage Enumeration Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Storage

+
+
+
public enum Storage : Equatable
+ +
+
+

An SQLite storage (NULL, INTEGER, REAL, TEXT, BLOB).

+ +
+
+
+
    +
  • +
    + + + + null + +
    +
    +
    +
    +
    +
    +

    The NULL storage class.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case null
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + int64 + +
    +
    +
    +
    +
    +
    +

    The INTEGER storage class, wrapping an Int64.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case int64(Int64)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + double + +
    +
    +
    +
    +
    +
    +

    The REAL storage class, wrapping a Double.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case double(Double)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + string + +
    +
    +
    +
    +
    +
    +

    The TEXT storage class, wrapping a String.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case string(String)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + blob + +
    +
    +
    +
    +
    +
    +

    The BLOB storage class, wrapping Data.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    case blob(Data)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + value + +
    +
    +
    +
    +
    +
    +

    Returns Int64, Double, String, Data or nil.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var value: DatabaseValueConvertible? { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ==(_:_:) + +
    +
    +
    +
    +
    +
    +

    Return true if the storages are identical.

    + +

    Unlike DatabaseValue equality that considers the integer 1 to be +equal to the 1.0 double (as SQLite does), int64 and double storages +are never equal.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func == (lhs: Storage, rhs: Storage) -> Bool
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/EmptyRowAdapter.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/EmptyRowAdapter.html new file mode 100644 index 000000000..2fd4a7070 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/EmptyRowAdapter.html @@ -0,0 +1,841 @@ + + + + EmptyRowAdapter Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

EmptyRowAdapter

+
+
+
public struct EmptyRowAdapter : RowAdapter
+ +
+
+

EmptyRowAdapter is a row adapter that hides all columns.

+ +
+
+
+
    +
  • +
    + + + + init() + +
    +
    +
    +
    +
    +
    +

    Creates an EmptyRowAdapter

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init()
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS3.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS3.html new file mode 100644 index 000000000..25f0f59a2 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS3.html @@ -0,0 +1,989 @@ + + + + FTS3 Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS3

+
+
+
public struct FTS3 : VirtualTableModule
+ +
+
+

FTS3 lets you define fts3 virtual tables.

+
// CREATE VIRTUAL TABLE document USING fts3(content)
+try db.create(virtualTable: "document", using: FTS3()) { t in
+    t.column("content")
+}
+
+ +
+
+
+
    +
  • +
    + + + + init() + +
    +
    +
    +
    +
    +
    +

    Creates a FTS3 module suitable for the Database +create(virtualTable:using:) method.

    +
    // CREATE VIRTUAL TABLE document USING fts3(content)
    +try db.create(virtualTable: "document", using: FTS3()) { t in
    +    t.column("content")
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init()
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + moduleName + +
    +
    +
    +
    +
    +
    +

    The virtual table module name

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let moduleName: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + makeTableDefinition() + +
    +
    +
    +
    +
    +
    +

    Reserved; part of the VirtualTableModule protocol.

    + +

    See Database.create(virtualTable:using:)

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func makeTableDefinition() -> FTS3TableDefinition
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Reserved; part of the VirtualTableModule protocol.

    + +

    See Database.create(virtualTable:using:)

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func moduleArguments(for definition: FTS3TableDefinition, in db: Database) -> [String]
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Reserved; part of the VirtualTableModule protocol.

    + +

    See Database.create(virtualTable:using:)

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func database(_ db: Database, didCreate tableName: String, using definition: FTS3TableDefinition)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS3Pattern.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS3Pattern.html new file mode 100644 index 000000000..3398a0e5b --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS3Pattern.html @@ -0,0 +1,1173 @@ + + + + FTS3Pattern Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS3Pattern

+
+
+
public struct FTS3Pattern
+ +
+
+

A full text pattern that can query FTS3 and FTS4 virtual tables.

+ +
+
+
+
    +
  • +
    + + + + rawPattern + +
    +
    +
    +
    +
    +
    +

    The raw pattern string. Guaranteed to be a valid FTS3/4 pattern.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let rawPattern: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(rawPattern:) + +
    +
    +
    +
    +
    +
    +

    Creates a pattern from a raw pattern string; throws DatabaseError on +invalid syntax.

    + +

    The pattern syntax is documented at https://www.sqlite.org/fts3.html#full_text_index_queries

    +
    try FTS3Pattern(rawPattern: "and") // OK
    +try FTS3Pattern(rawPattern: "AND") // malformed MATCH expression: [AND]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(rawPattern: String) throws
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a pattern that matches any token found in the input string; +returns nil if no pattern could be built.

    +
    FTS3Pattern(matchingAnyTokenIn: "")        // nil
    +FTS3Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar
    +
    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a pattern that matches all tokens found in the input string; +returns nil if no pattern could be built.

    +
    FTS3Pattern(matchingAllTokensIn: "")        // nil
    +FTS3Pattern(matchingAllTokensIn: "foo bar") // foo bar
    +
    + +
    +
    +
    +
  • +
  • +
    + + + + init(matchingPhrase:) + +
    +
    +
    +
    +
    +
    +

    Creates a pattern that matches a contiguous string; returns nil if no +pattern could be built.

    +
    FTS3Pattern(matchingPhrase: "")        // nil
    +FTS3Pattern(matchingPhrase: "foo bar") // "foo bar"
    +
    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a pattern that matches any token found in the input string; +returns nil if no pattern could be built.

    +
    FTS3Pattern(matchingAnyTokenIn: "")        // nil
    +FTS3Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @available(iOS 8.2, OSX 10.10, *)
    +public init?(matchingAnyTokenIn string: String)
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + string + + +
    +

    The string to turn into an FTS3 pattern

    +
    +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a pattern that matches all tokens found in the input string; +returns nil if no pattern could be built.

    +
    FTS3Pattern(matchingAllTokensIn: "")        // nil
    +FTS3Pattern(matchingAllTokensIn: "foo bar") // foo bar
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @available(iOS 8.2, OSX 10.10, *)
    +public init?(matchingAllTokensIn string: String)
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + string + + +
    +

    The string to turn into an FTS3 pattern

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(matchingPhrase:) + +
    +
    +
    +
    +
    +
    +

    Creates a pattern that matches a contiguous string; returns nil if no +pattern could be built.

    +
    FTS3Pattern(matchingPhrase: "")        // nil
    +FTS3Pattern(matchingPhrase: "foo bar") // "foo bar"
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @available(iOS 8.2, OSX 10.10, *)
    +public init?(matchingPhrase string: String)
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + string + + +
    +

    The string to turn into an FTS3 pattern

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var databaseValue: DatabaseValue { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an FTS3Pattern initialized from dbValue, if it contains +a suitable value.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> FTS3Pattern?
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS3TokenizerDescriptor.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS3TokenizerDescriptor.html new file mode 100644 index 000000000..1578b6e20 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS3TokenizerDescriptor.html @@ -0,0 +1,997 @@ + + + + FTS3TokenizerDescriptor Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS3TokenizerDescriptor

+
+
+
public struct FTS3TokenizerDescriptor
+ +
+
+

An FTS3 tokenizer, suitable for FTS3 and FTS4 table definitions:

+
db.create(virtualTable: "book", using: FTS4()) { t in
+    t.tokenizer = .simple // FTS3TokenizerDescriptor
+}
+
+ +

See https://www.sqlite.org/fts3.html#tokenizer

+ +
+
+
+
    +
  • +
    + + + + simple + +
    +
    +
    +
    +
    +
    +

    The simple tokenizer.

    +
    db.create(virtualTable: "book", using: FTS4()) { t in
    +    t.tokenizer = .simple
    +}
    +
    + +

    See https://www.sqlite.org/fts3.html#tokenizer

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let simple: FTS3TokenizerDescriptor
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + porter + +
    +
    +
    +
    +
    +
    +

    The porter tokenizer.

    +
    db.create(virtualTable: "book", using: FTS4()) { t in
    +    t.tokenizer = .porter
    +}
    +
    + +

    See https://www.sqlite.org/fts3.html#tokenizer

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let porter: FTS3TokenizerDescriptor
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    The unicode61 tokenizer.

    +
    db.create(virtualTable: "book", using: FTS4()) { t in
    +    t.tokenizer = .unicode61()
    +}
    +
    + +

    See https://www.sqlite.org/fts3.html#tokenizer

    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    The unicode61 tokenizer.

    +
    db.create(virtualTable: "book", using: FTS4()) { t in
    +    t.tokenizer = .unicode61()
    +}
    +
    + +

    See https://www.sqlite.org/fts3.html#tokenizer

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @available(iOS 8.2, OSX 10.10, *)
    +public static func unicode61(removeDiacritics: Bool = true, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS3TokenizerDescriptor
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + removeDiacritics + + +
    +

    If true (the default), then SQLite will strip +diacritics from latin characters.

    +
    +
    + + separators + + +
    +

    Unless empty (the default), SQLite will consider these +characters as token separators.

    +
    +
    + + tokenCharacters + + +
    +

    Unless empty (the default), SQLite will consider +these characters as token characters.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS4.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS4.html new file mode 100644 index 000000000..400d2822c --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS4.html @@ -0,0 +1,993 @@ + + + + FTS4 Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS4

+
+
+
public struct FTS4 : VirtualTableModule
+ +
+
+

FTS4 lets you define fts4 virtual tables.

+
// CREATE VIRTUAL TABLE document USING fts4(content)
+try db.create(virtualTable: "document", using: FTS4()) { t in
+    t.column("content")
+}
+
+ +

See https://www.sqlite.org/fts3.html

+ +
+
+
+
    +
  • +
    + + + + init() + +
    +
    +
    +
    +
    +
    +

    Creates a FTS4 module suitable for the Database +create(virtualTable:using:) method.

    +
    // CREATE VIRTUAL TABLE document USING fts4(content)
    +try db.create(virtualTable: "document", using: FTS4()) { t in
    +    t.column("content")
    +}
    +
    + +

    See https://www.sqlite.org/fts3.html

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init()
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + moduleName + +
    +
    +
    +
    +
    +
    +

    The virtual table module name

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let moduleName: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + makeTableDefinition() + +
    +
    +
    +
    +
    +
    +

    Reserved; part of the VirtualTableModule protocol.

    + +

    See Database.create(virtualTable:using:)

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func makeTableDefinition() -> FTS4TableDefinition
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Reserved; part of the VirtualTableModule protocol.

    + +

    See Database.create(virtualTable:using:)

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func moduleArguments(for definition: FTS4TableDefinition, in db: Database) -> [String]
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Reserved; part of the VirtualTableModule protocol.

    + +

    See Database.create(virtualTable:using:)

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func database(_ db: Database, didCreate tableName: String, using definition: FTS4TableDefinition) throws
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS5.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS5.html new file mode 100644 index 000000000..a3b077024 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS5.html @@ -0,0 +1,928 @@ + + + + FTS5 Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS5

+

FTS5 lets you define fts5 virtual tables.

+
// CREATE VIRTUAL TABLE document USING fts5(content)
+try db.create(virtualTable: "document", using: FTS5()) { t in
+    t.column("content")
+}
+
+ +

See https://www.sqlite.org/fts5.html

+ +
+
+
+
    +
  • +
    + + + + init() + +
    +
    +
    +
    +
    +
    +

    Creates a FTS5 module suitable for the Database +create(virtualTable:using:) method.

    +
    // CREATE VIRTUAL TABLE document USING fts5(content)
    +try db.create(virtualTable: "document", using: FTS5()) { t in
    +    t.column("content")
    +}
    +
    + +

    See https://www.sqlite.org/fts5.html

    + +
    +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + moduleName + +
    +
    +
    +
    +
    +
    +

    The virtual table module name

    + +
    +
    +
    +
  • +
  • +
    + + + + makeTableDefinition() + +
    +
    +
    +
    +
    +
    +

    Don’t use this method.

    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Don’t use this method.

    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Reserved; part of the VirtualTableModule protocol.

    + +

    See Database.create(virtualTable:using:)

    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS5Pattern.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS5Pattern.html new file mode 100644 index 000000000..59bd4bede --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS5Pattern.html @@ -0,0 +1,959 @@ + + + + FTS5Pattern Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS5Pattern

+

A full text pattern that can query FTS5 virtual tables.

+ +
+
+
+
    +
  • +
    + + + + rawPattern + +
    +
    +
    +
    +
    +
    +

    The raw pattern string. Guaranteed to be a valid FTS5 pattern.

    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a pattern that matches any token found in the input string; +returns nil if no pattern could be built.

    +
    FTS5Pattern(matchingAnyTokenIn: "")        // nil
    +FTS5Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar
    +
    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a pattern that matches all tokens found in the input string; +returns nil if no pattern could be built.

    +
    FTS5Pattern(matchingAllTokensIn: "")        // nil
    +FTS5Pattern(matchingAllTokensIn: "foo bar") // foo bar
    +
    + +
    +
    +
    +
  • +
  • +
    + + + + init(matchingPhrase:) + +
    +
    +
    +
    +
    +
    +

    Creates a pattern that matches a contiguous string; returns nil if no +pattern could be built.

    +
    FTS5Pattern(matchingPhrase: "")        // nil
    +FTS5Pattern(matchingPhrase: "foo bar") // "foo bar"
    +
    + +
    +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a pattern that matches a contiguous string prefix; returns +nil if no pattern could be built.

    +
    FTS5Pattern(matchingPrefixPhrase: "")        // nil
    +FTS5Pattern(matchingPrefixPhrase: "foo bar") // ^"foo bar"
    +
    + +
    +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + databaseValue + +
    +
    +
    +
    +
    +
    +

    Returns a value that can be stored in the database.

    + +
    +
    +
    +
  • +
  • +
    + + + + fromDatabaseValue(_:) + +
    +
    +
    +
    +
    +
    +

    Returns an FTS5Pattern initialized from dbValue, if it +contains a suitable value.

    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS5TokenFlags.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS5TokenFlags.html new file mode 100644 index 000000000..18d902d08 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS5TokenFlags.html @@ -0,0 +1,862 @@ + + + + FTS5TokenFlags Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS5TokenFlags

+

Flags that tell SQLite how to register a token.

+ +

See https://www.sqlite.org/fts5.html#custom_tokenizers

+ +
+
+
+
    +
  • +
    + + + + rawValue + +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
  • +
  • +
    + + + + init(rawValue:) + +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
  • +
  • +
    + + + + colocated + +
    +
    +
    +
    +
    +
    +

    FTS5_TOKEN_COLOCATED

    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS5Tokenization.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS5Tokenization.html new file mode 100644 index 000000000..c1ca843b1 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS5Tokenization.html @@ -0,0 +1,919 @@ + + + + FTS5Tokenization Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS5Tokenization

+

The reason why FTS5 is requesting tokenization.

+ +

See https://www.sqlite.org/fts5.html#custom_tokenizers

+ +
+
+
+
    +
  • +
    + + + + rawValue + +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
  • +
  • +
    + + + + init(rawValue:) + +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
  • +
  • +
    + + + + query + +
    +
    +
    +
    +
    +
    +

    FTS5_TOKENIZE_QUERY

    + +
    +
    +
    +
  • +
  • +
    + + + + prefix + +
    +
    +
    +
    +
    +
    +

    FTS5_TOKENIZE_PREFIX

    + +
    +
    +
    +
  • +
  • +
    + + + + document + +
    +
    +
    +
    +
    +
    +

    FTS5_TOKENIZE_DOCUMENT

    + +
    +
    +
    +
  • +
  • +
    + + + + aux + +
    +
    +
    +
    +
    +
    +

    FTS5_TOKENIZE_AUX

    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS5TokenizerDescriptor.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS5TokenizerDescriptor.html new file mode 100644 index 000000000..b0f3628af --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FTS5TokenizerDescriptor.html @@ -0,0 +1,934 @@ + + + + FTS5TokenizerDescriptor Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FTS5TokenizerDescriptor

+

An FTS5 tokenizer, suitable for FTS5 table definitions:

+
db.create(virtualTable: "book", using: FTS5()) { t in
+    t.tokenizer = .unicode61() // FTS5TokenizerDescriptor
+}
+
+ +

See https://www.sqlite.org/fts5.html#tokenizers

+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FetchedRecordsSectionInfo.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FetchedRecordsSectionInfo.html new file mode 100644 index 000000000..23b3c27b4 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/FetchedRecordsSectionInfo.html @@ -0,0 +1,871 @@ + + + + FetchedRecordsSectionInfo Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

FetchedRecordsSectionInfo

+
+
+
public struct FetchedRecordsSectionInfo<Record> where Record : FetchableRecord
+ +
+
+

A section given by a FetchedRecordsController.

+ +
+
+
+
    +
  • +
    + + + + numberOfRecords + +
    +
    +
    +
    +
    +
    +

    The number of records (rows) in the section.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var numberOfRecords: Int { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + records + +
    +
    +
    +
    +
    +
    +

    The array of records in the section.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var records: [Record] { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/ForeignKey.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/ForeignKey.html new file mode 100644 index 000000000..48439b7f5 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/ForeignKey.html @@ -0,0 +1,1019 @@ + + + + ForeignKey Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ForeignKey

+
+
+
public struct ForeignKey
+ +
+
+

A ForeignKey helps building associations when GRDB can’t infer a foreign +key from the database schema.

+ +

Sometimes the database schema does not define any foreign key between two +tables. And sometimes, there are several foreign keys from a table +to another:

+
| Table book   |       | Table person |
+| ------------ |       | ------------ |
+| id           |   +-->• id           |
+| authorId     •---+   | name         |
+| translatorId •---+
+| title        |
+
+ +

When this happens, associations can’t be automatically inferred from the +database schema. GRDB will complain with a fatal error such as Ambiguous +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:

+
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)
+}
+
+ +

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]))
+}
+
+ +

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:

+
struct Book: TableRecord {
+    static let authorForeignKey = ForeignKey(["authorId"], to: ["id"]))
+    static let author = belongsTo(Person.self, using: authorForeignKey)
+}
+
+ +
+
+
+
    +
  • +
    + + + + init(_:to:) + +
    +
    +
    +
    +
    +
    +

    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)
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ originColumns: [String], to destinationColumns: [String]? = nil)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + originColumns + + +
    +

    The columns at the origin of the foreign key.

    +
    +
    + + destinationColumns + + +
    +

    The columns at the destination of the +foreign key. When nil (the default), GRDB automatically uses the +primary key.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:to:) + +
    +
    +
    +
    +
    +
    +

    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)
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ originColumns: [ColumnExpression], to destinationColumns: [ColumnExpression]? = nil)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + originColumns + + +
    +

    The columns at the origin of the foreign key.

    +
    +
    + + destinationColumns + + +
    +

    The columns at the destination of the +foreign key. When nil (the default), GRDB automatically uses the +primary key.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/ForeignKeyInfo.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/ForeignKeyInfo.html new file mode 100644 index 000000000..b783e99ea --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/ForeignKeyInfo.html @@ -0,0 +1,932 @@ + + + + ForeignKeyInfo Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ForeignKeyInfo

+
+
+
public struct ForeignKeyInfo
+ +
+
+

You get foreign keys from table names, with the +foreignKeys(on:) method.

+ +
+
+
+
    +
  • +
    + + + + destinationTable + +
    +
    +
    +
    +
    +
    +

    The name of the destination table

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let destinationTable: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + mapping + +
    +
    +
    +
    +
    +
    +

    The column to column mapping

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let mapping: [(origin: String, destination: String)]
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + originColumns + +
    +
    +
    +
    +
    +
    +

    The origin columns

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var originColumns: [String] { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + destinationColumns + +
    +
    +
    +
    +
    +
    +

    The destination columns

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var destinationColumns: [String] { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/HasManyAssociation.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/HasManyAssociation.html new file mode 100644 index 000000000..f558e11b9 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/HasManyAssociation.html @@ -0,0 +1,930 @@ + + + + HasManyAssociation Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

HasManyAssociation

+
+
+
public struct HasManyAssociation<Origin, Destination> : Association
+ +
+
+

The HasMany association 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)
+    ...
+}
+
+ +

HasMany associations 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.

+ +

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)
+}
+
+ +
    +
  1. The author table has a primary key.
  2. +
  3. The book.authorId column is used to link a book to the author it +belongs to.
  4. +
  5. Make the book.authorId column not null if you want SQLite to guarantee +that all books have an author.
  6. +
  7. Create an index on the book.authorId column in order to ease the +selection of an author’s books.
  8. +
  9. Create a foreign key from book.authorId column to authors.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. +See https://sqlite.org/foreignkeys.html#fk_actions for more information.
  10. +
+ +

The example above uses auto-incremented primary keys. But generally +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 +missing foreign key:

+
struct Author: TableRecord {
+    static let books = hasMany(Book.self, using: ForeignKey(...))
+}
+
+ +

See ForeignKey for more information.

+ +
+
+
+
    +
  • +
    + + + + key + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var key: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + forKey(_:) + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func forKey(_ key: String) -> HasManyAssociation<Origin, Destination>
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/HasOneAssociation.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/HasOneAssociation.html new file mode 100644 index 000000000..4fd5f1f7e --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/HasOneAssociation.html @@ -0,0 +1,932 @@ + + + + HasOneAssociation Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

HasOneAssociation

+
+
+
public struct HasOneAssociation<Origin, Destination> : Association
+ +
+
+

The HasOne association 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.

+ +

For example, if your application has one database table for countries, and +another for their demographic profiles, you’d declare the association +this way:

+
struct Demographics: TableRecord { ... }
+struct Country: TableRecord {
+    static let demographics = hasOne(Demographics.self)
+    ...
+}
+
+ +

HasOne associations 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.

+ +

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)
+}
+
+ +
    +
  1. The country table has a primary key.
  2. +
  3. The demographics.countryCode column is used to link a demographic +profile to the country it belongs to.
  4. +
  5. Make the demographics.countryCode column not null if you want SQLite to +guarantee that all profiles are linked to a country.
  6. +
  7. Create a unique index on the demographics.countryCode column in order to +guarantee the unicity of any country’s profile.
  8. +
  9. 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.
  10. +
+ +

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:

+
struct Country: FetchableRecord, TableRecord {
+    static let demographics = hasOne(Demographics.self, using: ForeignKey(...))
+}
+
+ +

See ForeignKey for more information.

+ +
+
+
+
    +
  • +
    + + + + key + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var key: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + forKey(_:) + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func forKey(_ key: String) -> HasOneAssociation<Origin, Destination>
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/IndexInfo.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/IndexInfo.html new file mode 100644 index 000000000..d567f4b0a --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/IndexInfo.html @@ -0,0 +1,903 @@ + + + + IndexInfo Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

IndexInfo

+
+
+
public struct IndexInfo
+ +
+
+

An index on a database table.

+ +

See Database.indexes(on:)

+ +
+
+
+
    +
  • +
    + + + + name + +
    +
    +
    +
    +
    +
    +

    The name of the index

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let name: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + columns + +
    +
    +
    +
    +
    +
    +

    The indexed columns

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let columns: [String]
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + isUnique + +
    +
    +
    +
    +
    +
    +

    True if the index is unique

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let isUnique: Bool
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/PersistenceConflictPolicy.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/PersistenceConflictPolicy.html new file mode 100644 index 000000000..110f7c526 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/PersistenceConflictPolicy.html @@ -0,0 +1,906 @@ + + + + PersistenceConflictPolicy Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

PersistenceConflictPolicy

+
+
+
public struct PersistenceConflictPolicy
+ +
+
+

The MutablePersistableRecord protocol uses this type in order to handle SQLite +conflicts when records are inserted or updated.

+ +

See MutablePersistableRecord.persistenceConflictPolicy.

+ +

See https://www.sqlite.org/lang_conflict.html

+ +
+
+
+ +
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/PersistenceContainer.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/PersistenceContainer.html new file mode 100644 index 000000000..77628f1f8 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/PersistenceContainer.html @@ -0,0 +1,890 @@ + + + + PersistenceContainer Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

PersistenceContainer

+
+
+
public struct PersistenceContainer
+ +
+
+

Use persistence containers in the encode(to:) method of your +encodable records:

+
struct Player : MutablePersistableRecord {
+    var id: Int64?
+    var name: String?
+
+    func encode(to container: inout PersistenceContainer) {
+        container["id"] = id
+        container["name"] = name
+    }
+}
+
+ +
+
+
+
    +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Accesses the value associated with the given column.

    + +

    It is undefined behavior to set different values for the same column. +Column names are case insensitive, so defining both name and NAME +is considered undefined behavior.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript(column: String) -> DatabaseValueConvertible? { get set }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + subscript(_:) + +
    +
    +
    +
    +
    +
    +

    Accesses the value associated with the given column.

    + +

    It is undefined behavior to set different values for the same column. +Column names are case insensitive, so defining both name and NAME +is considered undefined behavior.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public subscript(column: ColumnExpression) -> DatabaseValueConvertible? { get set }
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/PrimaryKeyInfo.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/PrimaryKeyInfo.html new file mode 100644 index 000000000..868ba6747 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/PrimaryKeyInfo.html @@ -0,0 +1,939 @@ + + + + PrimaryKeyInfo Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

PrimaryKeyInfo

+
+
+
public struct PrimaryKeyInfo
+ +
+
+

Primary keys are returned from the Database.primaryKey(_:) method.

+ +

When the table’s primary key is the rowid:

+
// CREATE TABLE item (name TEXT)
+let pk = try db.primaryKey("item")
+pk.columns     // ["rowid"]
+pk.rowIDColumn // nil
+pk.isRowID     // true
+
+// CREATE TABLE citizen (
+//   id INTEGER PRIMARY KEY,
+//   name TEXT
+// )
+let pk = try db.primaryKey("citizen")!
+pk.columns     // ["id"]
+pk.rowIDColumn // "id"
+pk.isRowID     // true
+
+ +

When the table’s primary key is not the rowid:

+
// CREATE TABLE country (
+//   isoCode TEXT NOT NULL PRIMARY KEY
+//   name TEXT
+// )
+let pk = db.primaryKey("country")!
+pk.columns     // ["isoCode"]
+pk.rowIDColumn // nil
+pk.isRowID     // false
+
+// CREATE TABLE citizenship (
+//   citizenID INTEGER NOT NULL REFERENCES citizen(id)
+//   countryIsoCode TEXT NOT NULL REFERENCES country(isoCode)
+//   PRIMARY KEY (citizenID, countryIsoCode)
+// )
+let pk = db.primaryKey("citizenship")!
+pk.columns     // ["citizenID", "countryIsoCode"]
+pk.rowIDColumn // nil
+pk.isRowID     // false
+
+ +
+
+
+
    +
  • +
    + + + + columns + +
    +
    +
    +
    +
    +
    +

    The columns in the primary key; this array is never empty.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var columns: [String] { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + rowIDColumn + +
    +
    +
    +
    +
    +
    +

    When not nil, the name of the column that contains the INTEGER PRIMARY KEY.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var rowIDColumn: String? { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + isRowID + +
    +
    +
    +
    +
    +
    +

    When true, the primary key is the rowid:

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var isRowID: Bool { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/QueryInterfaceRequest.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/QueryInterfaceRequest.html new file mode 100644 index 000000000..11297137e --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/QueryInterfaceRequest.html @@ -0,0 +1,1623 @@ + + + + QueryInterfaceRequest Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

QueryInterfaceRequest

+
+
+
public struct QueryInterfaceRequest<T>
+ +
+
+

A QueryInterfaceRequest describes an SQL query.

+ +

See https://github.com/groue/GRDB.swift#the-query-interface

+ +
+
+
+ +
    +
  • +
    + + + + matching(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a request with a full-text predicate added to the eventual +set of already applied predicates.

    +
    // SELECT * FROM book WHERE book MATCH '...'
    +var request = Book.all()
    +request = request.matching(pattern)
    +
    + +

    If the search pattern is nil, the request does not match any +database row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest<T>
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + including(optional:) + +
    +
    +
    +
    +
    +
    +

    Creates a request that includes an association. The columns of the +associated record are selected. The returned association does not +require that the associated database table contains a matching row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func including<A>(optional association: A) -> QueryInterfaceRequest<RowDecoder> where T == A.OriginRowDecoder, A : Association
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + including(required:) + +
    +
    +
    +
    +
    +
    +

    Creates a request that includes an association. The columns of the +associated record are selected. The returned association requires +that the associated database table contains a matching row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func including<A>(required association: A) -> QueryInterfaceRequest<RowDecoder> where T == A.OriginRowDecoder, A : Association
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + joining(optional:) + +
    +
    +
    +
    +
    +
    +

    Creates a request that includes an association. The columns of the +associated record are not selected. The returned association does not +require that the associated database table contains a matching row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func joining<A>(optional association: A) -> QueryInterfaceRequest<RowDecoder> where T == A.OriginRowDecoder, A : Association
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + joining(required:) + +
    +
    +
    +
    +
    +
    +

    Creates a request that includes an association. The columns of the +associated record are not selected. The returned association requires +that the associated database table contains a matching row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func joining<A>(required association: A) -> QueryInterfaceRequest<RowDecoder> where T == A.OriginRowDecoder, A : Association
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + RowDecoder + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public typealias RowDecoder = T
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + select(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a request which selects selection.

    +
    // SELECT id, email FROM player
    +var request = Player.all()
    +request = request.select([Column("id"), Column("email")])
    +
    + +

    Any previous selection is replaced:

    +
    // SELECT email FROM player
    +request
    +    .select([Column("id")])
    +    .select([Column("email")])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest<T>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + select(_:as:) + +
    +
    +
    +
    +
    +
    +

    Creates a request which selects selection, and fetches values of +type type.

    +
    try dbQueue.read { db in
    +    // SELECT max(score) FROM player
    +    let request = Player.all().select([max(Column("score"))], as: Int.self)
    +    let maxScore: Int? = try request.fetchOne(db)
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func select<RowDecoder>(_ selection: [SQLSelectable], as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + select(_:as:) + +
    +
    +
    +
    +
    +
    +

    Creates a request which selects selection, and fetches values of +type type.

    +
    try dbQueue.read { db in
    +    // SELECT max(score) FROM player
    +    let request = Player.all().select(max(Column("score")), as: Int.self)
    +    let maxScore: Int? = try request.fetchOne(db)
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func select<RowDecoder>(_ selection: SQLSelectable..., as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder>
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a request which selects sql, and fetches values of +type type.

    +
    try dbQueue.read { db in
    +    // SELECT max(score) FROM player
    +    let request = Player.all().select(sql: "max(score)", as: Int.self)
    +    let maxScore: Int? = try request.fetchOne(db)
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func select<RowDecoder>(sql: String, arguments: StatementArguments? = nil, as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + distinct() + +
    +
    +
    +
    +
    +
    +

    Creates a request which returns distinct rows.

    +
    // SELECT DISTINCT * FROM player
    +var request = Player.all()
    +request = request.distinct()
    +
    +// SELECT DISTINCT name FROM player
    +var request = Player.select(Column("name"))
    +request = request.distinct()
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func distinct() -> QueryInterfaceRequest<T>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + filter(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a request with the provided predicate promise added to the +eventual set of already applied predicates.

    +
    // SELECT * FROM player WHERE 1
    +var request = Player.all()
    +request = request.filter { db in true }
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest<T>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + group(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a request grouped according to expressions.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func group(_ expressions: [SQLExpressible]) -> QueryInterfaceRequest<T>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + having(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a request with the provided predicate added to the +eventual set of already applied predicates.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func having(_ predicate: SQLExpressible) -> QueryInterfaceRequest<T>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + order(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a request with the provided orderings promise.

    +
    // SELECT * FROM player ORDER BY name
    +var request = Player.all()
    +request = request.order { _ in [Column("name")] }
    +
    + +

    Any previous ordering is replaced:

    +
    // SELECT * FROM player ORDER BY name
    +request
    +    .order{ _ in [Column("email")] }
    +    .reversed()
    +    .order{ _ in [Column("name")] }
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceRequest<T>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + reversed() + +
    +
    +
    +
    +
    +
    +

    Creates a request that reverses applied orderings.

    +
    // SELECT * FROM player ORDER BY name DESC
    +var request = Player.all().order(Column("name"))
    +request = request.reversed()
    +
    + +

    If no ordering was applied, the returned request is identical.

    +
    // SELECT * FROM player
    +var request = Player.all()
    +request = request.reversed()
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func reversed() -> QueryInterfaceRequest<T>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + limit(_:offset:) + +
    +
    +
    +
    +
    +
    +

    Creates a request which fetches limit rows, starting at offset.

    +
    // SELECT * FROM player LIMIT 1
    +var request = Player.all()
    +request = request.limit(1)
    +
    + +

    Any previous limit is replaced.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest<T>
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + aliased(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a request that allows you to define expressions that target +a specific database table.

    + +

    In the example below, the team.avgScore < player.score condition in +the ON clause could be not achieved without table aliases.

    +
    struct Player: TableRecord {
    +    static let team = belongsTo(Team.self)
    +}
    +
    +// SELECT player.*, team.*
    +// JOIN team ON ... AND team.avgScore < player.score
    +let playerAlias = TableAlias()
    +let request = Player
    +    .all()
    +    .aliased(playerAlias)
    +    .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + asRequest(of:) + +
    +
    +
    +
    +
    +
    +

    Creates a request bound to type Target.

    + +

    The returned request can fetch if the type Target is fetchable (Row, +value, record).

    +
    // Int?
    +let maxScore = try Player
    +    .select(max(scoreColumn))
    +    .asRequest(of: Int.self)    // <--
    +    .fetchOne(db)
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public func asRequest<Target>(of type: Target.Type) -> QueryInterfaceRequest<Target>
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + type + + +
    +

    The fetched type Target

    +
    +
    +
    +
    +

    Return Value

    +

    A typed request bound to type Target.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + deleteAll(_:) + +
    +
    +
    +
    +
    +
    +

    Deletes matching rows; returns the number of deleted rows.

    +
    +

    Throws

    + A DatabaseError is thrown whenever an SQLite error occurs. + +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    @discardableResult
    +public func deleteAll(_ db: Database) throws -> Int
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    +
    +
    +

    Return Value

    +

    The number of deleted rows

    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/RangeRowAdapter.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/RangeRowAdapter.html new file mode 100644 index 000000000..7cac78269 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/RangeRowAdapter.html @@ -0,0 +1,877 @@ + + + + RangeRowAdapter Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

RangeRowAdapter

+
+
+
public struct RangeRowAdapter : RowAdapter
+ +
+
+

RangeRowAdapter is a row adapter that only exposes a range of columns.

+
let adapter = RangeRowAdapter(1..<3)
+let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz, 4 as qux"
+
+// [bar:2 baz:3]
+try Row.fetchOne(db, sql, adapter: adapter)
+
+ +
+
+
+
    +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a RangeRowAdapter that only exposes a range of columns.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ range: CountableRange<Int>)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates a RangeRowAdapter that only exposes a range of columns.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ range: CountableClosedRange<Int>)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/ResultCode.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/ResultCode.html new file mode 100644 index 000000000..0ae7cef71 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/ResultCode.html @@ -0,0 +1,3552 @@ + + + + ResultCode Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ResultCode

+
+
+
public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
+ +
+
+

Undocumented

+ +
+
+
+
    +
  • +
    + + + + rawValue + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let rawValue: Int32
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(rawValue:) + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(rawValue: Int32)
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + primaryResultCode + +
    +
    +
    +
    +
    +
    +

    A result code limited to the least significant 8 bits of the receiver. +See https://www.sqlite.org/rescode.html for more information.

    +
    let resultCode = .SQLITE_CONSTRAINT_FOREIGNKEY
    +resultCode.primaryResultCode == .SQLITE_CONSTRAINT // true
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var primaryResultCode: ResultCode { get }
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + ~=(_:_:) + +
    +
    +
    +
    +
    +
    +

    Returns true if the code on the left matches the code on the right.

    + +

    Primary result codes match themselves and their extended result codes, +while extended result codes match only themselves:

    +
    switch error.extendedResultCode {
    +case .SQLITE_CONSTRAINT_FOREIGNKEY: // foreign key constraint error
    +case .SQLITE_CONSTRAINT:            // any other constraint error
    +default:                            // any other database error
    +}
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func ~= (pattern: ResultCode, code: ResultCode) -> Bool
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_OK + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_OK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_ERROR + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_ERROR: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_INTERNAL + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_INTERNAL: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_PERM + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_PERM: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_ABORT + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_ABORT: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_BUSY + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_BUSY: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_LOCKED + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_LOCKED: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_NOMEM + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_NOMEM: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_READONLY + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_READONLY: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_INTERRUPT + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_INTERRUPT: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_CORRUPT + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CORRUPT: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_NOTFOUND + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_NOTFOUND: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_FULL + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_FULL: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_CANTOPEN + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CANTOPEN: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_PROTOCOL + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_PROTOCOL: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_EMPTY + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_EMPTY: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_SCHEMA + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_SCHEMA: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_TOOBIG + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_TOOBIG: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_CONSTRAINT + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CONSTRAINT: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_MISMATCH + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_MISMATCH: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_MISUSE + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_MISUSE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_NOLFS + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_NOLFS: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_AUTH + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_AUTH: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_FORMAT + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_FORMAT: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_RANGE + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_RANGE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_NOTADB + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_NOTADB: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_NOTICE + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_NOTICE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_WARNING + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_WARNING: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_ROW + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_ROW: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_DONE + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_DONE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_READ + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_READ: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_SHORT_READ: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_WRITE + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_WRITE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_FSYNC + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_FSYNC: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_DIR_FSYNC: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_TRUNCATE + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_TRUNCATE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_FSTAT + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_FSTAT: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_UNLOCK + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_UNLOCK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_RDLOCK + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_RDLOCK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_DELETE + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_DELETE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_BLOCKED + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_BLOCKED: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_NOMEM + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_NOMEM: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_ACCESS + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_ACCESS: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_CHECKRESERVEDLOCK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_LOCK + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_LOCK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_CLOSE + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_CLOSE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_DIR_CLOSE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_SHMOPEN + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_SHMOPEN: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_SHMSIZE + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_SHMSIZE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_SHMLOCK + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_SHMLOCK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_SHMMAP + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_SHMMAP: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_SEEK + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_SEEK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_DELETE_NOENT: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_MMAP + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_MMAP: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_GETTEMPPATH: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_CONVPATH + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_CONVPATH: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_VNODE + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_VNODE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_IOERR_AUTH + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_IOERR_AUTH: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_LOCKED_SHAREDCACHE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_BUSY_RECOVERY + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_BUSY_RECOVERY: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_BUSY_SNAPSHOT + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_BUSY_SNAPSHOT: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CANTOPEN_NOTEMPDIR: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_CANTOPEN_ISDIR + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CANTOPEN_ISDIR: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CANTOPEN_FULLPATH: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CANTOPEN_CONVPATH: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_CORRUPT_VTAB + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CORRUPT_VTAB: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_READONLY_RECOVERY: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_READONLY_CANTLOCK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_READONLY_ROLLBACK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_READONLY_DBMOVED: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_ABORT_ROLLBACK + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_ABORT_ROLLBACK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CONSTRAINT_CHECK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CONSTRAINT_COMMITHOOK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CONSTRAINT_FOREIGNKEY: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CONSTRAINT_FUNCTION: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CONSTRAINT_NOTNULL: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CONSTRAINT_PRIMARYKEY: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CONSTRAINT_TRIGGER: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CONSTRAINT_UNIQUE: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CONSTRAINT_VTAB: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_CONSTRAINT_ROWID: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_NOTICE_RECOVER_WAL: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_NOTICE_RECOVER_ROLLBACK: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_WARNING_AUTOINDEX: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + SQLITE_AUTH_USER + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_AUTH_USER: ResultCode
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let SQLITE_OK_LOAD_PERMANENTLY: ResultCode
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/SQLExpressionLiteral.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/SQLExpressionLiteral.html new file mode 100644 index 000000000..a707998db --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/SQLExpressionLiteral.html @@ -0,0 +1,921 @@ + + + + SQLExpressionLiteral Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

SQLExpressionLiteral

+
+
+
public struct SQLExpressionLiteral : SQLExpression
+ +
+
+

Experimental

+ +

SQLExpressionLiteral is an expression built from a raw SQL snippet.

+
SQLExpressionLiteral("1 + 2")
+
+ +

The SQL literal may contain ? and colon-prefixed arguments:

+
SQLExpressionLiteral("? + ?", arguments: [1, 2])
+SQLExpressionLiteral(":one + :two", arguments: ["one": 1, "two": 2])
+
+ +
+
+
+
    +
  • +
    + + + + sql + +
    +
    +
    +
    +
    +
    +

    Experimental

    + +

    The SQL literal

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let sql: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + arguments + +
    +
    +
    +
    +
    +
    +

    Experimental

    + +

    Eventual arguments that feed the ? and colon-prefixed arguments in the +SQL literal

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public let arguments: StatementArguments?
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:arguments:) + +
    +
    +
    +
    +
    +
    +

    Experimental

    + +

    Creates an SQL literal expression.

    +
    SQLExpressionLiteral("1 + 2")
    +SQLExpressionLiteral("? + ?", arguments: [1, 2])
    +SQLExpressionLiteral(":one + :two", arguments: ["one": 1, "two": 2])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ sql: String, arguments: StatementArguments? = nil)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/SQLFunctionName.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/SQLFunctionName.html new file mode 100644 index 000000000..81a14b630 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/SQLFunctionName.html @@ -0,0 +1,1096 @@ + + + + SQLFunctionName Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

SQLFunctionName

+
+
+
public struct SQLFunctionName : Hashable
+ +
+
+

Experimental

+ +

SQLFunctionName is an SQL function name.

+ +
+
+
+ +
    +
  • +
    + + + + abs + +
    +
    +
    +
    +
    +
    +

    The ABS function name

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let abs: SQLFunctionName
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + avg + +
    +
    +
    +
    +
    +
    +

    The AVG function name

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let avg: SQLFunctionName
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + ifNull + +
    +
    +
    +
    +
    +
    +

    The IFNULL function name

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let ifNull: SQLFunctionName
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + length + +
    +
    +
    +
    +
    +
    +

    The LENGTH function name

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let length: SQLFunctionName
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + max + +
    +
    +
    +
    +
    +
    +

    The MAX function name

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let max: SQLFunctionName
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + min + +
    +
    +
    +
    +
    +
    +

    The MIN function name

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let min: SQLFunctionName
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + sum + +
    +
    +
    +
    +
    +
    +

    The SUM function name

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static let sum: SQLFunctionName
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/SQLRequest.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/SQLRequest.html new file mode 100644 index 000000000..597edca19 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/SQLRequest.html @@ -0,0 +1,1102 @@ + + + + SQLRequest Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

SQLRequest

+
+
+
public struct SQLRequest<T> : FetchRequest
+ +
+
+

A FetchRequest built from raw SQL.

+ +
+
+
+
    +
  • +
    + + + + RowDecoder + +
    +
    +
    +
    +
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public typealias RowDecoder = T
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + sql + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var sql: String
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + arguments + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var arguments: StatementArguments?
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + adapter + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var adapter: RowAdapter?
    + +
    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates a request from an SQL string, optional arguments, and +optional row adapter.

    +
    let request = SQLRequest("SELECT * FROM player")
    +let request = SQLRequest("SELECT * FROM player WHERE id = ?", arguments: [1])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false)
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + + + + + +
    + + sql + + +
    +

    An SQL query.

    +
    +
    + + arguments + + +
    +

    Optional statement arguments.

    +
    +
    + + adapter + + +
    +

    Optional RowAdapter.

    +
    +
    + + cached + + +
    +

    Defaults to false. If true, the request reuses a cached +prepared statement.

    +
    +
    +
    +
    +

    Return Value

    +

    A SQLRequest

    +
    + +
    +
    +
  • +
  • + +
    +
    +
    +
    +
    +

    Creates an SQL request from any other fetch request.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init<Request: FetchRequest>(_ db: Database, request: Request, cached: Bool = false) throws where Request.RowDecoder == RowDecoder
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + + + + + +
    + + db + + +
    +

    A database connection.

    +
    +
    + + request + + +
    +

    A request.

    +
    +
    + + cached + + +
    +

    Defaults to false. If true, the request reuses a cached +prepared statement.

    +
    +
    +
    +
    +

    Return Value

    +

    An SQLRequest

    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/ScopeAdapter.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/ScopeAdapter.html new file mode 100644 index 000000000..ff191b3b8 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/ScopeAdapter.html @@ -0,0 +1,965 @@ + + + + ScopeAdapter Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

ScopeAdapter

+
+
+
public struct ScopeAdapter : RowAdapter
+ +
+
+

ScopeAdapter is a row adapter that lets you define scopes on rows.

+
// Two adapters
+let fooAdapter = ColumnMapping(["value": "foo"])
+let barAdapter = ColumnMapping(["value": "bar"])
+
+// Define scopes
+let adapter = ScopeAdapter([
+    "foo": fooAdapter,
+    "bar": barAdapter])
+
+// Fetch
+let sql = "SELECT 'foo' AS foo, 'bar' AS bar"
+let row = try Row.fetchOne(db, sql, adapter: adapter)!
+
+// Scoped rows:
+if let fooRow = row.scopes["foo"] {
+    fooRow["value"]    // "foo"
+}
+if let barRow = row.scopes["bar"] {
+    barRow["value"]    // "bar"
+}
+
+ +
+
+
+
    +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates an adapter that preserves row contents and add scoped rows.

    + +

    For example:

    +
    let adapter = ScopeAdapter(["suffix": SuffixRowAdapter(fromIndex: 1)])
    +let row = try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: adapter)!
    +row                  // [1, 2, 3]
    +row.scopes["suffix"] // [2, 3]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ scopes: [String : RowAdapter])
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + scopes + + +
    +

    A dictionary that maps scope names to +row adapters.

    +
    +
    +
    + +
    +
    +
  • +
  • +
    + + + + init(base:scopes:) + +
    +
    +
    +
    +
    +
    +

    Creates an adapter based on the base adapter, and add scoped rows.

    + +

    For example:

    +
    let baseAdapter = RangeRowAdapter(0..<1)
    +let adapter = ScopeAdapter(base: baseAdapter, scopes: ["suffix": SuffixRowAdapter(fromIndex: 1)])
    +let row = try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: adapter)!
    +row                   // [1]
    +row.scopes["initial"] // [2, 3]
    +
    + +

    If the base adapter already defines scopes, the given scopes replace +eventual existing scopes with the same name.

    + +

    This initializer is equivalent to baseAdapter.addingScopes(scopes).

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(base: RowAdapter, scopes: [String : RowAdapter])
    + +
    +
    +
    +

    Parameters

    + + + + + + + + + + + +
    + + base + + +
    +

    A dictionary that maps scope names to +row adapters.

    +
    +
    + + scopes + + +
    +

    A dictionary that maps scope names to +row adapters.

    +
    +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/StatementArguments.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/StatementArguments.html new file mode 100644 index 000000000..8d1a76700 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/StatementArguments.html @@ -0,0 +1,1610 @@ + + + + StatementArguments Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

StatementArguments

+
+
+
public struct StatementArguments : CustomStringConvertible, Equatable, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral
+ +
+
+

StatementArguments provide values to argument placeholders in raw +SQL queries.

+ +

Placeholders can take several forms (see https://www.sqlite.org/lang_expr.html#varparam +for more information):

+ +
    +
  • ?NNN (e.g. ?2): the NNN-th argument (starts at 1)
  • +
  • ?: the N-th argument, where N is one greater than the largest argument +number already assigned
  • +
  • :AAAA (e.g. :name): named argument

  • +
  • $AAAA (e.g. $name): named argument

  • +
+

Positional Arguments

+ +

To fill question marks placeholders, feed StatementArguments with an array:

+
db.execute(
+    "INSERT ... (?, ?)",
+    arguments: StatementArguments(["Arthur", 41]))
+
+// Array literals are automatically converted:
+db.execute(
+    "INSERT ... (?, ?)",
+    arguments: ["Arthur", 41])
+
+

Named Arguments

+ +

To fill named arguments, feed StatementArguments with a dictionary:

+
db.execute(
+    "INSERT ... (:name, :score)",
+    arguments: StatementArguments(["name": "Arthur", "score": 41]))
+
+// Dictionary literals are automatically converted:
+db.execute(
+    "INSERT ... (:name, :score)",
+    arguments: ["name": "Arthur", "score": 41])
+
+

Concatenating Arguments

+ +

Several arguments can be concatenated and mixed with the +append(contentsOf:) method and the +, &+, += operators:

+
var arguments: StatementArguments = ["Arthur"]
+arguments += [41]
+db.execute("INSERT ... (?, ?)", arguments: arguments)
+
+ +

+ and += operators consider that overriding named arguments is a +programmer error:

+
var arguments: StatementArguments = ["name": "Arthur"]
+arguments += ["name": "Barbara"]
+// fatal error: already defined statement argument: name
+
+ +

&+ and append(contentsOf:) allow overriding named arguments:

+
var arguments: StatementArguments = ["name": "Arthur"]
+arguments = arguments &+ ["name": "Barbara"]
+print(arguments)
+// Prints ["name": "Barbara"]
+
+

Mixed Arguments

+ +

It is possible to mix named and positional arguments. Yet this is usually +confusing, and it is best to avoid this practice:

+
let sql = "SELECT ?2 AS two, :foo AS foo, ?1 AS one, :foo AS foo2, :bar AS bar"
+var arguments: StatementArguments = [1, 2, "bar"] + ["foo": "foo"]
+let row = try Row.fetchOne(db, sql, arguments: arguments)!
+print(row)
+// Prints [two:2 foo:"foo" one:1 foo2:"foo" bar:"bar"]
+
+ +

Mixed arguments exist as a support for requests like the following:

+
let players = try Player
+    .filter(sql: "team = :team", arguments: ["team": "Blue"])
+    .filter(sql: "score > ?", arguments: [1000])
+    .fetchAll(db)
+
+ +
+
+
+
    +
  • +
    + + + + isEmpty + +
    +
    +
    +
    +
    +
    +

    Undocumented

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public var isEmpty: Bool { get }
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates statement arguments from a sequence of optional values.

    +
    let values: [DatabaseValueConvertible?] = ["foo", 1, nil]
    +db.execute("INSERT ... (?,?,?)", arguments: StatementArguments(values))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init<Sequence>(_ sequence: Sequence) where Sequence : Sequence, Sequence.Element == DatabaseValueConvertible?
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + sequence + + +
    +

    A sequence of DatabaseValueConvertible values.

    +
    +
    +
    +
    +

    Return Value

    +

    A StatementArguments.

    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates statement arguments from a sequence of optional values.

    +
    let values: [String] = ["foo", "bar"]
    +db.execute("INSERT ... (?,?)", arguments: StatementArguments(values))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init<Sequence>(_ sequence: Sequence) where Sequence : Sequence, Sequence.Element : DatabaseValueConvertible
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + sequence + + +
    +

    A sequence of DatabaseValueConvertible values.

    +
    +
    +
    +
    +

    Return Value

    +

    A StatementArguments.

    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates statement arguments from any array. The result is nil unless all +array elements adopt DatabaseValueConvertible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init?(_ array: [Any])
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + array + + +
    +

    An array

    +
    +
    +
    +
    +

    Return Value

    +

    A StatementArguments.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates statement arguments from a sequence of (key, value) dictionary, +such as a dictionary.

    +
    let values: [String: DatabaseValueConvertible?] = ["firstName": nil, "lastName": "Miller"]
    +db.execute("INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(_ dictionary: [String : DatabaseValueConvertible?])
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + sequence + + +
    +

    A sequence of (key, value) pairs

    +
    +
    +
    +
    +

    Return Value

    +

    A StatementArguments.

    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates statement arguments from a sequence of (key, value) pairs, such +as a dictionary.

    +
    let values: [String: DatabaseValueConvertible?] = ["firstName": nil, "lastName": "Miller"]
    +db.execute("INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init<Sequence>(_ sequence: Sequence) where Sequence : Sequence, Sequence.Element == (String, DatabaseValueConvertible?)
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + sequence + + +
    +

    A sequence of (key, value) pairs

    +
    +
    +
    +
    +

    Return Value

    +

    A StatementArguments.

    +
    + +
    +
    +
  • +
  • +
    + + + + init(_:) + +
    +
    +
    +
    +
    +
    +

    Creates statement arguments from [AnyHashable: Any].

    + +

    The result is nil unless all dictionary keys are strings, and values +adopt DatabaseValueConvertible.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init?(_ dictionary: [AnyHashable : Any])
    + +
    +
    +
    +

    Parameters

    + + + + + + + +
    + + dictionary + + +
    +

    A dictionary.

    +
    +
    +
    +
    +

    Return Value

    +

    A StatementArguments.

    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + append(contentsOf:) + +
    +
    +
    +
    +
    +
    +

    Extends statement arguments with other arguments.

    + +

    Positional arguments (provided as arrays) are concatenated:

    +
    var arguments: StatementArguments = [1]
    +arguments.append(contentsOf: [2, 3])
    +print(arguments)
    +// Prints [1, 2, 3]
    +
    + +

    Named arguments (provided as dictionaries) are updated:

    +
    var arguments: StatementArguments = ["foo": 1]
    +arguments.append(contentsOf: ["bar": 2])
    +print(arguments)
    +// Prints ["foo": 1, "bar": 2]
    +
    + +

    Arguments that were replaced, if any, are returned:

    +
    var arguments: StatementArguments = ["foo": 1, "bar": 2]
    +let replacedValues = arguments.append(contentsOf: ["foo": 3])
    +print(arguments)
    +// Prints ["foo": 3, "bar": 2]
    +print(replacedValues)
    +// Prints ["foo": 1]
    +
    + +

    You can mix named and positional arguments (see documentation of +the StatementArguments type for more information about mixed arguments):

    +
    var arguments: StatementArguments = ["foo": 1]
    +arguments.append(contentsOf: [2, 3])
    +print(arguments)
    +// Prints ["foo": 1, 2, 3]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public mutating func append(contentsOf arguments: StatementArguments) -> [String : DatabaseValue]
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + +(_:_:) + +
    +
    +
    +
    +
    +
    +

    Creates a new StatementArguments by extending the left-hand size +arguments with the right-hand side arguments.

    + +

    Positional arguments (provided as arrays) are concatenated:

    +
    let arguments: StatementArguments = [1] + [2, 3]
    +print(arguments)
    +// Prints [1, 2, 3]
    +
    + +

    Named arguments (provided as dictionaries) are updated:

    +
    let arguments: StatementArguments = ["foo": 1] + ["bar": 2]
    +print(arguments)
    +// Prints ["foo": 1, "bar": 2]
    +
    + +

    You can mix named and positional arguments (see documentation of +the StatementArguments type for more information about mixed arguments):

    +
    let arguments: StatementArguments = ["foo": 1] + [2, 3]
    +print(arguments)
    +// Prints ["foo": 1, 2, 3]
    +
    + +

    If the arguments on the right-hand side has named parameters that are +already defined on the left, a fatal error is raised:

    +
    let arguments: StatementArguments = ["foo": 1] + ["foo": 2]
    +// fatal error: already defined statement argument: foo
    +
    + +

    This fatal error can be avoided with the &+ operator, or the +append(contentsOf:) method.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func + (lhs: StatementArguments, rhs: StatementArguments) -> StatementArguments
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + &+(_:_:) + +
    +
    +
    +
    +
    +
    +

    Creates a new StatementArguments by extending the left-hand size +arguments with the right-hand side arguments.

    + +

    Positional arguments (provided as arrays) are concatenated:

    +
    let arguments: StatementArguments = [1] &+ [2, 3]
    +print(arguments)
    +// Prints [1, 2, 3]
    +
    + +

    Named arguments (provided as dictionaries) are updated:

    +
    let arguments: StatementArguments = ["foo": 1] &+ ["bar": 2]
    +print(arguments)
    +// Prints ["foo": 1, "bar": 2]
    +
    + +

    You can mix named and positional arguments (see documentation of +the StatementArguments type for more information about mixed arguments):

    +
    let arguments: StatementArguments = ["foo": 1] &+ [2, 3]
    +print(arguments)
    +// Prints ["foo": 1, 2, 3]
    +
    + +

    If a named arguments is defined in both arguments, the right-hand +side wins:

    +
    let arguments: StatementArguments = ["foo": 1] &+ ["foo": 2]
    +print(arguments)
    +// Prints ["foo": 2]
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func &+ (lhs: StatementArguments, rhs: StatementArguments) -> StatementArguments
    + +
    +
    + +
    +
    +
  • +
  • +
    + + + + +=(_:_:) + +
    +
    +
    +
    +
    +
    +

    Extends the left-hand size arguments with the right-hand side arguments.

    + +

    Positional arguments (provided as arrays) are concatenated:

    +
    var arguments: StatementArguments = [1]
    +arguments += [2, 3]
    +print(arguments)
    +// Prints [1, 2, 3]
    +
    + +

    Named arguments (provided as dictionaries) are updated:

    +
    var arguments: StatementArguments = ["foo": 1]
    +arguments += ["bar": 2]
    +print(arguments)
    +// Prints ["foo": 1, "bar": 2]
    +
    + +

    You can mix named and positional arguments (see documentation of +the StatementArguments type for more information about mixed arguments):

    +
    var arguments: StatementArguments = ["foo": 1]
    +arguments.append(contentsOf: [2, 3])
    +print(arguments)
    +// Prints ["foo": 1, 2, 3]
    +
    + +

    If the arguments on the right-hand side has named parameters that are +already defined on the left, a fatal error is raised:

    +
    var arguments: StatementArguments = ["foo": 1]
    +arguments += ["foo": 2]
    +// fatal error: already defined statement argument: foo
    +
    + +

    This fatal error can be avoided with the &+ operator, or the +append(contentsOf:) method.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public static func += (lhs: inout StatementArguments, rhs: StatementArguments)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • +
    + + + + init(arrayLiteral:) + +
    +
    +
    +
    +
    +
    +

    Returns a StatementArguments from an array literal:

    +
    db.selectRows("SELECT ...", arguments: ["Arthur", 41])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(arrayLiteral elements: DatabaseValueConvertible?...)
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
    +
  • + +
    +
    +
    +
    +
    +

    Returns a StatementArguments from a dictionary literal:

    +
    db.selectRows("SELECT ...", arguments: ["name": "Arthur", "score": 41])
    +
    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(dictionaryLiteral elements: (String, DatabaseValueConvertible?)...)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/SuffixRowAdapter.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/SuffixRowAdapter.html new file mode 100644 index 000000000..e8f911ae9 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Structs/SuffixRowAdapter.html @@ -0,0 +1,850 @@ + + + + SuffixRowAdapter Structure Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

SuffixRowAdapter

+
+
+
public struct SuffixRowAdapter : RowAdapter
+ +
+
+

SuffixRowAdapter is a row adapter that hides the first columns in a row.

+
let adapter = SuffixRowAdapter(fromIndex: 2)
+let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
+
+// [baz:3]
+try Row.fetchOne(db, sql, adapter: adapter)
+
+ +
+
+
+
    +
  • +
    + + + + init(fromIndex:) + +
    +
    +
    +
    +
    +
    +

    Creates a SuffixRowAdapter that hides all columns before the +provided index.

    + +

    If index is 0, the layout row is identical to the base row.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public init(fromIndex index: Int)
    + +
    +
    + +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Typealiases.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Typealiases.html new file mode 100644 index 000000000..63f18f1c8 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/Typealiases.html @@ -0,0 +1,1017 @@ + + + + Type Aliases Reference + + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+

Type Aliases

+

The following type aliases are available globally.

+ +
+
+
+
    +
  • +
    + + + + TraceFunction + +
    +
    +
    +
    +
    +
    +

    A tracing function that takes an SQL string.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public typealias TraceFunction = (String) -> Void
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + SQLiteConnection + +
    +
    +
    +
    +
    +
    +

    A raw SQLite connection, suitable for the SQLite C API.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public typealias SQLiteConnection = OpaquePointer
    + +
    +
    + +
    +
    +
  • +
+
+
+
    +
  • +
    + + + + SQLiteStatement + +
    +
    +
    +
    +
    +
    +

    A raw SQLite statement, suitable for the SQLite C API.

    + +
    +
    +

    Declaration

    +
    +

    Swift

    +
    public typealias SQLiteStatement = OpaquePointer
    + +
    +
    + +
    +
    +
  • +
+
+
+ +
+
+
    +
  • +
    + + + + FTS5TokenCallback + +
    +
    +
    +
    +
    +
    +

    A low-level SQLite function that lets FTS5Tokenizer notify tokens.

    + +

    See FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:)

    + +
    +
    +
    +
  • +
+
+
+
    +
  • + +
    +
    +
    +
    +
    +

    A function that lets FTS5WrapperTokenizer notify tokens.

    + +

    See FTS5WrapperTokenizer.accept(token:flags:tokenCallback:)

    + +
    +
    +
    +
  • +
+
+
+
+ +
+
+ + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/css/highlight.css b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/css/highlight.css new file mode 100644 index 000000000..d0db0e13b --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/css/highlight.css @@ -0,0 +1,200 @@ +/* Credit to https://gist.github.com/wataru420/2048287 */ +.highlight { + /* Comment */ + /* Error */ + /* Keyword */ + /* Operator */ + /* Comment.Multiline */ + /* Comment.Preproc */ + /* Comment.Single */ + /* Comment.Special */ + /* Generic.Deleted */ + /* Generic.Deleted.Specific */ + /* Generic.Emph */ + /* Generic.Error */ + /* Generic.Heading */ + /* Generic.Inserted */ + /* Generic.Inserted.Specific */ + /* Generic.Output */ + /* Generic.Prompt */ + /* Generic.Strong */ + /* Generic.Subheading */ + /* Generic.Traceback */ + /* Keyword.Constant */ + /* Keyword.Declaration */ + /* Keyword.Pseudo */ + /* Keyword.Reserved */ + /* Keyword.Type */ + /* Literal.Number */ + /* Literal.String */ + /* Name.Attribute */ + /* Name.Builtin */ + /* Name.Class */ + /* Name.Constant */ + /* Name.Entity */ + /* Name.Exception */ + /* Name.Function */ + /* Name.Namespace */ + /* Name.Tag */ + /* Name.Variable */ + /* Operator.Word */ + /* Text.Whitespace */ + /* Literal.Number.Float */ + /* Literal.Number.Hex */ + /* Literal.Number.Integer */ + /* Literal.Number.Oct */ + /* Literal.String.Backtick */ + /* Literal.String.Char */ + /* Literal.String.Doc */ + /* Literal.String.Double */ + /* Literal.String.Escape */ + /* Literal.String.Heredoc */ + /* Literal.String.Interpol */ + /* Literal.String.Other */ + /* Literal.String.Regex */ + /* Literal.String.Single */ + /* Literal.String.Symbol */ + /* Name.Builtin.Pseudo */ + /* Name.Variable.Class */ + /* Name.Variable.Global */ + /* Name.Variable.Instance */ + /* Literal.Number.Integer.Long */ } + .highlight .c { + color: #999988; + font-style: italic; } + .highlight .err { + color: #a61717; + background-color: #e3d2d2; } + .highlight .k { + color: #000000; + font-weight: bold; } + .highlight .o { + color: #000000; + font-weight: bold; } + .highlight .cm { + color: #999988; + font-style: italic; } + .highlight .cp { + color: #999999; + font-weight: bold; } + .highlight .c1 { + color: #999988; + font-style: italic; } + .highlight .cs { + color: #999999; + font-weight: bold; + font-style: italic; } + .highlight .gd { + color: #000000; + background-color: #ffdddd; } + .highlight .gd .x { + color: #000000; + background-color: #ffaaaa; } + .highlight .ge { + color: #000000; + font-style: italic; } + .highlight .gr { + color: #aa0000; } + .highlight .gh { + color: #999999; } + .highlight .gi { + color: #000000; + background-color: #ddffdd; } + .highlight .gi .x { + color: #000000; + background-color: #aaffaa; } + .highlight .go { + color: #888888; } + .highlight .gp { + color: #555555; } + .highlight .gs { + font-weight: bold; } + .highlight .gu { + color: #aaaaaa; } + .highlight .gt { + color: #aa0000; } + .highlight .kc { + color: #000000; + font-weight: bold; } + .highlight .kd { + color: #000000; + font-weight: bold; } + .highlight .kp { + color: #000000; + font-weight: bold; } + .highlight .kr { + color: #000000; + font-weight: bold; } + .highlight .kt { + color: #445588; } + .highlight .m { + color: #009999; } + .highlight .s { + color: #d14; } + .highlight .na { + color: #008080; } + .highlight .nb { + color: #0086B3; } + .highlight .nc { + color: #445588; + font-weight: bold; } + .highlight .no { + color: #008080; } + .highlight .ni { + color: #800080; } + .highlight .ne { + color: #990000; + font-weight: bold; } + .highlight .nf { + color: #990000; } + .highlight .nn { + color: #555555; } + .highlight .nt { + color: #000080; } + .highlight .nv { + color: #008080; } + .highlight .ow { + color: #000000; + font-weight: bold; } + .highlight .w { + color: #bbbbbb; } + .highlight .mf { + color: #009999; } + .highlight .mh { + color: #009999; } + .highlight .mi { + color: #009999; } + .highlight .mo { + color: #009999; } + .highlight .sb { + color: #d14; } + .highlight .sc { + color: #d14; } + .highlight .sd { + color: #d14; } + .highlight .s2 { + color: #d14; } + .highlight .se { + color: #d14; } + .highlight .sh { + color: #d14; } + .highlight .si { + color: #d14; } + .highlight .sx { + color: #d14; } + .highlight .sr { + color: #009926; } + .highlight .s1 { + color: #d14; } + .highlight .ss { + color: #990073; } + .highlight .bp { + color: #999999; } + .highlight .vc { + color: #008080; } + .highlight .vg { + color: #008080; } + .highlight .vi { + color: #008080; } + .highlight .il { + color: #009999; } diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/css/jazzy.css b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/css/jazzy.css new file mode 100644 index 000000000..d62828260 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/css/jazzy.css @@ -0,0 +1,337 @@ +html, body, div, span, h1, h3, h4, p, a, code, em, img, ul, li, table, tbody, tr, td { + background: transparent; + border: 0; + margin: 0; + outline: 0; + padding: 0; + vertical-align: baseline; } + +body { + background-color: #f2f2f2; + font-family: Helvetica, freesans, Arial, sans-serif; + font-size: 14px; + -webkit-font-smoothing: subpixel-antialiased; + word-wrap: break-word; } + +h1, h2, h3 { + margin-top: 0.8em; + margin-bottom: 0.3em; + font-weight: 100; + color: black; } + +h1 { + font-size: 2.5em; } + +h2 { + font-size: 2em; + border-bottom: 1px solid #e2e2e2; } + +h4 { + font-size: 13px; + line-height: 1.5; + margin-top: 21px; } + +h5 { + font-size: 1.1em; } + +h6 { + font-size: 1.1em; + color: #777; } + +.section-name { + color: gray; + display: block; + font-family: Helvetica; + font-size: 22px; + font-weight: 100; + margin-bottom: 15px; } + +pre, code { + font: 0.95em Menlo, monospace; + color: #777; + word-wrap: normal; } + +p code, li code { + background-color: #eee; + padding: 2px 4px; + border-radius: 4px; } + +a { + color: #0088cc; + text-decoration: none; } + +ul { + padding-left: 15px; } + +li { + line-height: 1.8em; } + +img { + max-width: 100%; } + +blockquote { + margin-left: 0; + padding: 0 10px; + border-left: 4px solid #ccc; } + +.content-wrapper { + margin: 0 auto; + width: 980px; } + +header { + font-size: 0.85em; + line-height: 26px; + background-color: #414141; + position: fixed; + width: 100%; + z-index: 1; } + header img { + padding-right: 6px; + vertical-align: -4px; + height: 16px; } + header a { + color: #fff; } + header p { + float: left; + color: #999; } + header .header-right { + float: right; + margin-left: 16px; } + +#breadcrumbs { + background-color: #f2f2f2; + height: 27px; + padding-top: 17px; + position: fixed; + width: 100%; + z-index: 1; + margin-top: 26px; } + #breadcrumbs #carat { + height: 10px; + margin: 0 5px; } + +.sidebar { + background-color: #f9f9f9; + border: 1px solid #e2e2e2; + overflow-y: auto; + overflow-x: hidden; + position: fixed; + top: 70px; + bottom: 0; + width: 230px; + word-wrap: normal; } + +.nav-groups { + list-style-type: none; + background: #fff; + padding-left: 0; } + +.nav-group-name { + border-bottom: 1px solid #e2e2e2; + font-size: 1.1em; + font-weight: 100; + padding: 15px 0 15px 20px; } + .nav-group-name > a { + color: #333; } + +.nav-group-tasks { + margin-top: 5px; } + +.nav-group-task { + font-size: 0.9em; + list-style-type: none; + white-space: nowrap; } + .nav-group-task a { + color: #888; } + +.main-content { + background-color: #fff; + border: 1px solid #e2e2e2; + margin-left: 246px; + position: absolute; + overflow: hidden; + padding-bottom: 60px; + top: 70px; + width: 734px; } + .main-content p, .main-content a, .main-content code, .main-content em, .main-content ul, .main-content table, .main-content blockquote { + margin-bottom: 1em; } + .main-content p { + line-height: 1.8em; } + .main-content section .section:first-child { + margin-top: 0; + padding-top: 0; } + .main-content section .task-group-section .task-group:first-of-type { + padding-top: 10px; } + .main-content section .task-group-section .task-group:first-of-type .section-name { + padding-top: 15px; } + .main-content section .heading:before { + content: ""; + display: block; + padding-top: 70px; + margin: -70px 0 0; } + +.section { + padding: 0 25px; } + +.highlight { + background-color: #eee; + padding: 10px 12px; + border: 1px solid #e2e2e2; + border-radius: 4px; + overflow-x: auto; } + +.declaration .highlight { + overflow-x: initial; + padding: 0 40px 40px 0; + margin-bottom: -25px; + background-color: transparent; + border: none; } + +.section-name { + margin: 0; + margin-left: 18px; } + +.task-group-section { + padding-left: 6px; + border-top: 1px solid #e2e2e2; } + +.task-group { + padding-top: 0px; } + +.task-name-container a[name]:before { + content: ""; + display: block; + padding-top: 70px; + margin: -70px 0 0; } + +.item { + padding-top: 8px; + width: 100%; + list-style-type: none; } + .item a[name]:before { + content: ""; + display: block; + padding-top: 70px; + margin: -70px 0 0; } + .item code { + background-color: transparent; + padding: 0; } + .item .token { + padding-left: 3px; + margin-left: 15px; + font-size: 11.9px; } + .item .declaration-note { + font-size: .85em; + color: gray; + font-style: italic; } + +.pointer-container { + border-bottom: 1px solid #e2e2e2; + left: -23px; + padding-bottom: 13px; + position: relative; + width: 110%; } + +.pointer { + background: #f9f9f9; + border-left: 1px solid #e2e2e2; + border-top: 1px solid #e2e2e2; + height: 12px; + left: 21px; + top: -7px; + -webkit-transform: rotate(45deg); + -moz-transform: rotate(45deg); + -o-transform: rotate(45deg); + transform: rotate(45deg); + position: absolute; + width: 12px; } + +.height-container { + display: none; + left: -25px; + padding: 0 25px; + position: relative; + width: 100%; + overflow: hidden; } + .height-container .section { + background: #f9f9f9; + border-bottom: 1px solid #e2e2e2; + left: -25px; + position: relative; + width: 100%; + padding-top: 10px; + padding-bottom: 5px; } + +.aside, .language { + padding: 6px 12px; + margin: 12px 0; + border-left: 5px solid #dddddd; + overflow-y: hidden; } + .aside .aside-title, .language .aside-title { + font-size: 9px; + letter-spacing: 2px; + text-transform: uppercase; + padding-bottom: 0; + margin: 0; + color: #aaa; + -webkit-user-select: none; } + .aside p:last-child, .language p:last-child { + margin-bottom: 0; } + +.language { + border-left: 5px solid #cde9f4; } + .language .aside-title { + color: #4b8afb; } + +.aside-warning { + border-left: 5px solid #ff6666; } + .aside-warning .aside-title { + color: #ff0000; } + +.graybox { + border-collapse: collapse; + width: 100%; } + .graybox p { + margin: 0; + word-break: break-word; + min-width: 50px; } + .graybox td { + border: 1px solid #e2e2e2; + padding: 5px 25px 5px 10px; + vertical-align: middle; } + .graybox tr td:first-of-type { + text-align: right; + padding: 7px; + vertical-align: top; + word-break: normal; + width: 40px; } + +.slightly-smaller { + font-size: 0.9em; } + +#footer { + position: absolute; + bottom: 10px; + margin-left: 25px; } + #footer p { + margin: 0; + color: #aaa; + font-size: 0.8em; } + +html.dash header, html.dash #breadcrumbs, html.dash .sidebar { + display: none; } +html.dash .main-content { + width: 980px; + margin-left: 0; + border: none; + width: 100%; + top: 0; + padding-bottom: 0; } +html.dash .height-container { + display: block; } +html.dash .item .token { + margin-left: 0; } +html.dash .content-wrapper { + width: auto; } +html.dash #footer { + position: static; } diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/img/carat.png b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/img/carat.png new file mode 100755 index 000000000..29d2f7fd4 Binary files /dev/null and b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/img/carat.png differ diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/img/dash.png b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/img/dash.png new file mode 100755 index 000000000..6f694c7a0 Binary files /dev/null and b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/img/dash.png differ diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/img/gh.png b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/img/gh.png new file mode 100755 index 000000000..628da97c7 Binary files /dev/null and b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/img/gh.png differ diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/index.html b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/index.html new file mode 100644 index 000000000..c2092b9c4 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/index.html @@ -0,0 +1,8122 @@ + + + + GRDB Reference + + + + + + + + + +
+
+

GRDB Docs (89% documented)

+

View on GitHub

+

Install in Dash

+
+
+
+ +
+
+ +
+
+
+ +

GRDB 3 Swift Platforms License Build Status

+

A toolkit for SQLite databases, with a focus on application development

+ +

Latest release: August 31, 2018 • version 3.3.0-beta1 • CHANGELOG • Migrating From GRDB 2 to GRDB 3

+ +

Requirements: iOS 8.0+ / macOS 10.9+ / watchOS 2.0+ • Swift 4.1+ / Xcode 9.3+

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Swift versionGRDB version
Swift 4.2v3.3.0-beta1
Swift 4.1v3.2.0
Swift 4v2.10.0
Swift 3.2v1.3.0
Swift 3.1v1.3.0
Swift 3v1.0
Swift 2.3v0.81.2
Swift 2.2v0.80.2
+ +

Contact:

+ + +

What is this?

+ +

GRDB provides raw access to SQL and advanced SQLite features, because one sometimes enjoys a sharp tool. It has robust concurrency primitives, so that multi-threaded applications can efficiently use their databases. It grants your application models with persistence and fetching methods, so that you don’t have to deal with SQL and raw database rows when you don’t want to.

+ +

Compared to SQLite.swift or FMDB, GRDB can spare you a lot of glue code. Compared to Core Data or Realm, it can simplify your multi-threaded applications.

+ +

It comes with up-to-date documentation, general guides, and it is fast.

+ +

See Why Adopt GRDB? if you are looking for your favorite database library.

+ +
+ +

+ Features • + Usage • + Installation • + Documentation • + FAQ +

+ +
+

Features

+ +

GRDB ships with:

+ + + +

Companion libraries that enhance and extend GRDB:

+ +
    +
  • RxGRDB: track database changes in a reactive way, with RxSwift.
  • +
  • GRDBObjc: FMDB-compatible bindings to GRDB.
  • +
+

Usage

+ +
+ Connect to an SQLite database + +“`swift +import GRDB + +// Simple database connection +let dbQueue = try DatabaseQueue(path: ”/path/to/database.sqlite") + +// Enhanced multithreading based on SQLite’s WAL mode +let dbPool = try DatabasePool(path: “/path/to/database.sqlite”) +“` + +See [Database Connections](#database-connections) + +
+ +
+ Execute SQL statements + +”`swift +try dbQueue.write { db in + try db.execute(“”“ + CREATE TABLE place ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT NOT NULL, + favorite BOOLEAN NOT NULL DEFAULT 0, + latitude DOUBLE NOT NULL, + longitude DOUBLE NOT NULL) + ”“”) + + try db.execute(“”“ + INSERT INTO place (title, favorite, latitude, longitude) + VALUES (?, ?, ?, ?) + ”“”, arguments: [“Paris”, true, 48.85341, 2.3488]) + + let parisId = db.lastInsertedRowID +} +“` + +See [Executing Updates](#executing-updates) + +
+ +
+ Fetch database rows and values + +”`swift +try dbQueue.read { db in + // Fetch database rows + let rows = try Row.fetchCursor(db, “SELECT * FROM place”) + while let row = try rows.next() { + let title: String = row[“title”] + let isFavorite: Bool = row[“favorite”] + let coordinate = CLLocationCoordinate2D( + latitude: row[“latitude”], + longitude: row[“longitude”]) + } + + // Fetch values + let placeCount = try Int.fetchOne(db, “SELECT COUNT(*) FROM place”)! // Int + let placeTitles = try String.fetchAll(db, “SELECT title FROM place”) // [String] +} + +let placeCount = try dbQueue.read { db in + try Int.fetchOne(db, “SELECT COUNT(*) FROM place”)! +} +“` + +See [Fetch Queries](#fetch-queries) + +
+ +
+ Store custom models aka "records” + +“`swift +struct Place { + var id: Int64? + var title: String + var isFavorite: Bool + var coordinate: CLLocationCoordinate2D +} + +// snip: turn Place into a "record” by adopting the protocols that +// provide fetching and persistence methods. + +try dbQueue.write { db in + // Create database table + try db.create(table: “place”) { t in + t.autoIncrementedPrimaryKey(“id”) + t.column(“title”, .text).notNull() + t.column(“favorite”, .boolean).notNull().defaults(to: false) + t.column(“longitude”, .double).notNull() + t.column(“latitude”, .double).notNull() + } + + var berlin = Place( + id: nil, + title: “Berlin”, + isFavorite: false, + coordinate: CLLocationCoordinate2D(latitude: 52.52437, longitude: 13.41053)) + + try berlin.insert(db) + berlin.id // some value + + berlin.isFavorite = true + try berlin.update(db) +} +“` + +See [Records](#records) + +
+ +
+ Fetch records and values with the Swift query interface + +”`swift +try dbQueue.write { db in + // Place? + let paris = try Place.fetchOne(db, key: 1) + + // Place? + let berlin = try Place.filter(Column(“title”) == “Berlin”).fetchOne(db) + + // [Place] + let favoritePlaces = try Place + .filter(Column(“favorite”) == true) + .order(Column(“title”)) + .fetchAll(db) + + // Int + let favoriteCount = try Place.filter(Column(“favorite”)).fetchCount(db) + + // SQL is always welcome + let places = try Place.fetchAll(db, “SELECT * FROM place”) +} +“` + +See the [Query Interface](#the-query-interface) + +
+ +
+ Be notified of database changes + +”`swift +// Track query interface requests +Place.filter(key: 1) + .rx + .fetchOne(in: dbQueue) + .subscribe(onNext: { place: Place? in + print(“Place 1 has changed”) + }) + +// Track SQL requests +SQLRequest(“SELECT * FROM place WHERE favorite ORDER BY title”) + .rx + .fetchAll(in: dbQueue) + .subscribe(onNext: { places: [Place] in + print(“Favorite places have changed”) + }) +“` + +See [Database Changes Observation](#database-changes-observation), and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) + +
+

Documentation

+ +

GRDB runs on top of SQLite: you should get familiar with the SQLite FAQ. For general and detailed information, jump to the SQLite Documentation.

+

Reference

+ + +

Getting Started

+ + +

SQLite and SQL

+ + +

Records and the Query Interface

+ + +

Application Tools

+ + +

Good to Know

+ + +

General Guides & Good Practices

+ + + +

FAQ

+ +

Sample Code

+

Installation

+ +

The installation procedures below have GRDB use the version of SQLite that ships with the target operating system.

+ +

See Encryption for the installation procedure of GRDB with SQLCipher.

+ +

See Custom SQLite builds for the installation procedure of GRDB with a customized build of SQLite 3.24.0.

+ +

See Enabling FTS5 Support for the installation procedure of GRDB with support for the FTS5 full-text engine.

+

CocoaPods

+ +

CocoaPods is a dependency manager for Xcode projects. To use GRDB with CocoaPods (version 1.2 or higher), specify in your Podfile:

+
use_frameworks!
+pod 'GRDB.swift'
+
+

Swift Package Manager

+ +

The Swift Package Manager automates the distribution of Swift code. To use GRDB with SPM, add a dependency to your Package.swift file:

+
let package = Package(
+    dependencies: [
+        .package(url: "https://github.com/groue/GRDB.swift.git", from: "3.3.0-beta1")
+    ]
+)
+
+ +

Note that Linux is not currently supported.

+

Carthage

+ +

Carthage can build GRDB frameworks, but it can also inexplicably fail. This installation method is thus unsupported.

+ +

If you decide to use Carthage despite this warning, and get any Carthage-related error, please open an issue in the Carthage repo, ask Stack Overflow, summon your local Xcode guru, or submit a pull request that has the make test_CarthageBuild command succeed 100% of the time (one time is not enough). See #262 for more information.

+

Manually

+ +
    +
  1. Download a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the git checkout v3.3.0-beta1 command.

  2. +
  3. Embed the GRDB.xcodeproj project in your own project.

  4. +
  5. Add the GRDBOSX, GRDBiOS, or GRDBWatchOS target in the Target Dependencies section of the Build Phases tab of your application target (extension target for WatchOS).

  6. +
  7. Add the GRDB.framework from the targetted platform to the Embedded Binaries section of the General tab of your application target (extension target for WatchOS).

  8. +
+ +

See GRDBDemoiOS for an example of such integration.

+

Database Connections

+ +

GRDB provides two classes for accessing SQLite databases: DatabaseQueue and DatabasePool:

+
import GRDB
+
+// Pick one:
+let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
+let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
+
+ +

The differences are:

+ +
    +
  • Database pools allow concurrent database accesses (this can improve the performance of multithreaded applications).
  • +
  • Database pools open your SQLite database in the WAL mode (unless read-only).
  • +
  • Database queues support in-memory databases.
  • +
+ +

If you are not sure, choose DatabaseQueue. You will always be able to switch to DatabasePool later.

+ + +

Database Queues

+ +

Open a database queue with the path to a database file:

+
import GRDB
+
+let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
+let inMemoryDBQueue = DatabaseQueue()
+
+ +

SQLite creates the database file if it does not already exist. The connection is closed when the database queue gets deallocated.

+ +

A database queue can be used from any thread. The write and read methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue:

+
// Modify the database:
+try dbQueue.write { db in
+    try db.create(table: "place") { ... }
+    try Place(...).insert(db)
+}
+
+// Read values:
+try dbQueue.read { db in
+    let places = try Place.fetchAll(db)
+    let placeCount = try Place.fetchCount(db)
+}
+
+ +

Database access methods can return values:

+
let placeCount = try dbQueue.read { db in
+    try Place.fetchCount(db)
+}
+
+let newPlaceCount = try dbQueue.write { db -> Int in
+    try Place(...).insert(db)
+    return try Place.fetchCount(db)
+}
+
+ +

A database queue serializes accesses to the database, which means that there is never more than one thread that uses the database.

+ +
    +
  • When you don’t need to modify the database, prefer the read method. It prevents any modification to the database.

  • +
  • The write method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, all changes are reverted, the whole transaction is rollbacked, and the error is rethrown.

    + +

    When precise transaction handling is required, see Transactions and Savepoints.

  • +
+ +

A database queue needs your application to follow rules in order to deliver its safety guarantees. Please refer to the Concurrency chapter.

+ +

See DemoApps/GRDBDemoiOS/AppDatabase.swift for a sample code that sets up a database queue on iOS.

+

DatabaseQueue Configuration

+
var config = Configuration()
+config.readonly = true
+config.foreignKeysEnabled = true // Default is already true
+config.trace = { print($0) }     // Prints all SQL statements
+config.label = "MyDatabase"      // Useful when your app opens multiple databases
+
+let dbQueue = try DatabaseQueue(
+    path: "/path/to/database.sqlite",
+    configuration: config)
+
+ +

See Configuration for more details.

+

Database Pools

+ +

A database pool allows concurrent database accesses.

+
import GRDB
+let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
+
+ +

SQLite creates the database file if it does not already exist. The connection is closed when the database pool gets deallocated.

+ +
+

:point_up: Note: unless read-only, a database pool opens your database in the SQLite WAL mode. The WAL mode does not fit all situations. Please have a look at https://www.sqlite.org/wal.html.

+
+ +

A database pool can be used from any thread. The write and read methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue:

+
// Modify the database:
+try dbPool.write { db in
+    try db.create(table: "place") { ... }
+    try Place(...).insert(db)
+}
+
+// Read values:
+try dbPool.read { db in
+    let places = try Place.fetchAll(db)
+    let placeCount = try Place.fetchCount(db)
+}
+
+ +

Database access methods can return values:

+
let placeCount = try dbPool.read { db in
+    try Place.fetchCount(db)
+}
+
+let newPlaceCount = try dbPool.write { db -> Int in
+    try Place(...).insert(db)
+    return try Place.fetchCount(db)
+}
+
+ +

Database pools allow several threads to access the database at the same time:

+ +
    +
  • When you don’t need to modify the database, prefer the read method, because several threads can perform reads in parallel.

    + +

    Reads are generally non-blocking, unless the maximum number of concurrent reads has been reached. In this case, a read has to wait for another read to complete. That maximum number can be configured.

  • +
  • Reads are guaranteed an immutable view of the last committed state of the database, regardless of concurrent writes. This kind of isolation is called snapshot isolation.

  • +
  • Unlike reads, writes are serialized. There is never more than a single thread that is writing into the database.

  • +
  • The write method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, all changes are reverted, the whole transaction is rollbacked, and the error is rethrown.

    + +

    When precise transaction handling is required, see Transactions and Savepoints.

  • +
  • Database pools can take snapshots of the database.

  • +
+ +

A database pool needs your application to follow rules in order to deliver its safety guarantees. See the Concurrency chapter for more details about database pools, how they differ from database queues, and advanced use cases.

+ +

For a sample code that sets up a database pool on iOS, see DemoApps/GRDBDemoiOS/AppDatabase.swift, and replace DatabaseQueue with DatabasePool.

+

DatabasePool Configuration

+
var config = Configuration()
+config.readonly = true
+config.foreignKeysEnabled = true // Default is already true
+config.trace = { print($0) }     // Prints all SQL statements
+config.label = "MyDatabase"      // Useful when your app opens multiple databases
+config.maximumReaderCount = 10   // The default is 5
+
+let dbPool = try DatabasePool(
+    path: "/path/to/database.sqlite",
+    configuration: config)
+
+ +

See Configuration for more details.

+ +

Database pools are more memory-hungry than database queues. See Memory Management for more information.

+

SQLite API

+ +

In this section of the documentation, we will talk SQL. Jump to the query interface if SQL is not your cup of tea.

+ + + +

Advanced topics:

+ + +

Executing Updates

+ +

Once granted with a database connection, the execute method executes the SQL statements that do not return any database row, such as CREATE TABLE, INSERT, DELETE, ALTER, etc.

+ +

For example:

+
try dbQueue.write { db in
+    try db.execute("""
+        CREATE TABLE player (
+            id INTEGER PRIMARY KEY AUTOINCREMENT,
+            name TEXT NOT NULL,
+            score INT)
+        """)
+
+    try db.execute(
+        "INSERT INTO player (name, score) VALUES (?, ?)",
+        arguments: ["Barbara", 1000])
+
+    try db.execute(
+        "UPDATE player SET score = :score WHERE id = :id",
+        arguments: ["score": 1000, "id": 1])
+    }
+}
+
+ +

The ? and colon-prefixed keys like :score in the SQL query are the statements arguments. You pass arguments with arrays or dictionaries, as in the example above. See Values for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and StatementArguments for a detailed documentation of SQLite arguments.

+ +

Never ever embed values directly in your SQL strings, and always use arguments instead. See Avoiding SQL Injection for more information:

+
// WRONG
+let id = 123
+let name = textField.text
+try db.execute("UPDATE player SET name = '\(name)' WHERE id = \(id)")
+
+// CORRECT
+try db.execute(
+    "UPDATE player SET name = :name WHERE id = :id",
+    arguments: ["name": name, "id": id])
+
+ +

Join multiple statements with a semicolon:

+
try db.execute("""
+    INSERT INTO player (name, score) VALUES (?, ?);
+    INSERT INTO player (name, score) VALUES (?, ?)
+    """, arguments: ["Arthur", 750, "Barbara", 1000])
+
+ +

When you want to make sure that a single statement is executed, use Prepared Statements.

+ +

After an INSERT statement, you can get the row ID of the inserted row:

+
try db.execute(
+    "INSERT INTO player (name, score) VALUES (?, ?)",
+    arguments: ["Arthur", 1000])
+let playerId = db.lastInsertedRowID
+
+ +

Don’t miss Records, that provide classic persistence methods:

+
let player = Player(name: "Arthur", score: 1000)
+try player.insert(db)
+let playerId = player.id
+
+

Fetch Queries

+ +

Database connections let you fetch database rows, plain values, and custom models aka records.

+ +

Rows are the raw results of SQL queries:

+
try dbQueue.read { db in
+    if let row = try Row.fetchOne(db, "SELECT * FROM wine WHERE id = ?", arguments: [1]) {
+        let name: String = row["name"]
+        let color: Color = row["color"]
+        print(name, color)
+    }
+}
+
+ +

Values are the Bool, Int, String, Date, Swift enums, etc. stored in row columns:

+
try dbQueue.read { db in
+    let urls = try URL.fetchCursor(db, "SELECT url FROM wine")
+    while let url = try urls.next() {
+        print(url)
+    }
+}
+
+ +

Records are your application objects that can initialize themselves from rows:

+
let wines = try dbQueue.read { db in
+    try Wine.fetchAll(db, "SELECT * FROM wine")
+}
+
+ + +

Fetching Methods

+ +

Throughout GRDB, you can always fetch cursors, arrays, or single values of any fetchable type (database row, simple value, or custom record):

+
try Row.fetchCursor(...) // A Cursor of Row
+try Row.fetchAll(...)    // [Row]
+try Row.fetchOne(...)    // Row?
+
+ +
    +
  • fetchCursor returns a cursor over fetched values:

    +
    let rows = try Row.fetchCursor(db, "SELECT ...") // A Cursor of Row
    +
  • +
  • fetchAll returns an array:

    +
    let players = try Player.fetchAll(db, "SELECT ...") // [Player]
    +
  • +
  • fetchOne returns a single optional value, and consumes a single database row (if any).

    +
    let count = try Int.fetchOne(db, "SELECT COUNT(*) ...") // Int?
    +
  • +
+

Cursors

+ +

Whenever you consume several rows from the database, you can fetch an Array, or a Cursor.

+ +

The fetchAll() method returns a regular Swift array, that you iterate like all other arrays:

+
try dbQueue.read { db in
+    // [Player]
+    let players = try Player.fetchAll(db, "SELECT ...")
+    for player in players {
+        // use player
+    }
+}
+
+ +

Unlike arrays, cursors returned by fetchCursor() load their results step after step:

+
try dbQueue.read { db in
+    // Cursor of Player
+    let players = try Player.fetchCursor(db, "SELECT ...")
+    while let player = try players.next() {
+        // use player
+    }
+}
+
+ +

Both arrays and cursors can iterate over database results. How do you choose one or the other? Look at the differences:

+ +
    +
  • Cursors can not be used on any thread: you must consume a cursor on the dispatch queue it was created in. Particularly, don’t extract a cursor out of a database access method:

    +
    // Wrong
    +let cursor = try dbQueue.read { db in
    +    try Player.fetchCursor(db, ...)
    +}
    +while let player = try cursor.next() { ... }
    +
    + +

    Conversely, arrays may be consumed on any thread:

    +
    // OK
    +let array = try dbQueue.read { db in
    +    try Player.fetchAll(db, ...)
    +}
    +for player in array { ... }
    +
  • +
  • Cursors can be iterated only one time. Arrays can be iterated many times.

  • +
  • Cursors iterate database results in a lazy fashion, and don’t consume much memory. Arrays contain copies of database values, and may take a lot of memory when there are many fetched results.

  • +
  • Cursors are granted with direct access to SQLite, unlike arrays that have to take the time to copy database values. If you look after extra performance, you may prefer cursors over arrays.

  • +
  • Cursors adopt the Cursor protocol, which looks a lot like standard lazy sequences of Swift. As such, cursors come with many convenience methods: compactMap, contains, dropFirst, dropLast, drop(while:), enumerated, filter, first, flatMap, forEach, joined, joined(separator:), max, max(by:), min, min(by:), map, prefix, prefix(while:), reduce, reduce(into:), suffix:

    +
    // Prints all Github links
    +try URL
    +    .fetchCursor(db, "SELECT url FROM link")
    +    .filter { url in url.host == "github.com" }
    +    .forEach { url in print(url) }
    +
    +// An efficient cursor of coordinates:
    +let locations = try Row.
    +    .fetchCursor(db, "SELECT latitude, longitude FROM place")
    +    .map { row in
    +        CLLocationCoordinate2D(latitude: row[0], longitude: row[1])
    +    }
    +
    +// Turn cursors into arrays or sets:
    +let array = try Array(cursor)
    +let set = try Set(cursor)
    +
  • +
  • Cursors are not Swift sequences. That’s because Swift sequences can’t handle iteration errors, when reading SQLite results may fail at any time. SQL functions may throw errors. On iOS, data protection may block access to the database file in the background. On macOS, your application users may mess with the file system.

  • +
  • Cursors require a little care:

    + +
      +
    • Don’t modify the results during a cursor iteration:

      +
      // Undefined behavior
      +while let player = try players.next() {
      +    try db.execute("DELETE ...")
      +}
      +
    • +
    • Don’t turn a cursor of Row into an array. You would not get the distinct rows you expect. To get a array of rows, use Row.fetchAll(...). Generally speaking, make sure you copy a row whenever you extract it from a cursor for later use: row.copy().

    • +
  • +
+ +

If you don’t see, or don’t care about the difference, use arrays. If you care about memory and performance, use cursors when appropriate.

+

Row Queries

+ + +

Fetching Rows

+ +

Fetch cursors of rows, arrays, or single rows (see fetching methods):

+
try dbQueue.read { db in
+    try Row.fetchCursor(db, "SELECT ...", arguments: ...) // A Cursor of Row
+    try Row.fetchAll(db, "SELECT ...", arguments: ...)    // [Row]
+    try Row.fetchOne(db, "SELECT ...", arguments: ...)    // Row?
+
+    let rows = try Row.fetchCursor(db, "SELECT * FROM wine")
+    while let row = try rows.next() {
+        let name: String = row["name"]
+        let color: Color = row["color"]
+        print(name, color)
+    }
+}
+
+let rows = try dbQueue.read { db in
+    try Row.fetchAll(db, "SELECT * FROM player")
+}
+
+ +

Arguments are optional arrays or dictionaries that fill the positional ? and colon-prefixed keys like :name in the query:

+
let rows = try Row.fetchAll(db,
+    "SELECT * FROM player WHERE name = ?",
+    arguments: ["Arthur"])
+
+let rows = try Row.fetchAll(db,
+    "SELECT * FROM player WHERE name = :name",
+    arguments: ["name": "Arthur"])
+
+ +

See Values for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and StatementArguments for a detailed documentation of SQLite arguments.

+ +

Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care:

+ +
+

:point_up: Don’t turn a cursor of Row into an array. You would not get the distinct rows you expect. To get a array of rows, use Row.fetchAll(...). Generally speaking, make sure you copy a row whenever you extract it from a cursor for later use: row.copy().

+
+

Column Values

+ +

Read column values by index or column name:

+
let name: String = row[0]      // 0 is the leftmost column
+let name: String = row["name"] // Leftmost matching column - lookup is case-insensitive
+let name: String = row[Column("name")] // Using query interface's Column
+
+ +

Make sure to ask for an optional when the value may be NULL:

+
let name: String? = row["name"]
+
+ +

The row[] subscript returns the type you ask for. See Values for more information on supported value types:

+
let bookCount: Int     = row["bookCount"]
+let bookCount64: Int64 = row["bookCount"]
+let hasBooks: Bool     = row["bookCount"] // false when 0
+
+let string: String     = row["date"]      // "2015-09-11 18:14:15.123"
+let date: Date         = row["date"]      // Date
+self.date = row["date"] // Depends on the type of the property.
+
+ +

You can also use the as type casting operator:

+
row[...] as Int
+row[...] as Int?
+
+ +
+

:warning: Warning: avoid the as! and as? operators:

+
if let int = row[...] as? Int { ... } // BAD - doesn't work
+if let int = row[...] as Int? { ... } // GOOD
+
+
+ +

Generally speaking, you can extract the type you need, provided it can be converted from the underlying SQLite value:

+ +
    +
  • Successful conversions include:

    + +
      +
    • All numeric SQLite values to all numeric Swift types, and Bool (zero is the only false boolean).
    • +
    • Text SQLite values to Swift String.
    • +
    • Blob SQLite values to Foundation Data.
    • +
    + +

    See Values for more information on supported types (Bool, Int, String, Date, Swift enums, etc.)

  • +
  • NULL returns nil.

    +
    let row = try Row.fetchOne(db, "SELECT NULL")!
    +row[0] as Int? // nil
    +row[0] as Int  // fatal error: could not convert NULL to Int.
    +
    + +

    There is one exception, though: the DatabaseValue type:

    +
    row[0] as DatabaseValue // DatabaseValue.null
    +
  • +
  • Missing columns return nil.

    +
    let row = try Row.fetchOne(db, "SELECT 'foo' AS foo")!
    +row["missing"] as String? // nil
    +row["missing"] as String  // fatal error: no such column: missing
    +
    + +

    You can explicitly check for a column presence with the hasColumn method.

  • +
  • Invalid conversions throw a fatal error.

    +
    let row = try Row.fetchOne(db, "SELECT 'Mom’s birthday'")!
    +row[0] as String // "Mom’s birthday"
    +row[0] as Date?  // fatal error: could not convert "Mom’s birthday" to Date.
    +row[0] as Date   // fatal error: could not convert "Mom’s birthday" to Date.
    +
    +let row = try Row.fetchOne(db, "SELECT 256")!
    +row[0] as Int    // 256
    +row[0] as UInt8? // fatal error: could not convert 256 to UInt8.
    +row[0] as UInt8  // fatal error: could not convert 256 to UInt8.
    +
    + +

    Those conversion fatal errors can be avoided with the DatabaseValue type:

    +
    let row = try Row.fetchOne(db, "SELECT 'Mom’s birthday'")!
    +let dbValue: DatabaseValue = row[0]
    +if dbValue.isNull {
    +    // Handle NULL
    +} else if let date = Date.fromDatabaseValue(dbValue) {
    +    // Handle valid date
    +} else {
    +    // Handle invalid date
    +}
    +
    + +

    This extra verbosity is the consequence of having to deal with an untrusted database: you may consider fixing the content of your database instead. See Fatal Errors for more information.

  • +
  • SQLite has a weak type system, and provides convenience conversions that can turn String to Int, Double to Blob, etc.

    + +

    GRDB will sometimes let those conversions go through:

    +
    let rows = try Row.fetchCursor(db, "SELECT '20 small cigars'")
    +while let row = try rows.next() {
    +    row[0] as Int   // 20
    +}
    +
    + +

    Don’t freak out: those conversions did not prevent SQLite from becoming the immensely successful database engine you want to use. And GRDB adds safety checks described just above. You can also prevent those convenience conversions altogether by using the DatabaseValue type.

  • +
+

DatabaseValue

+ +

DatabaseValue is an intermediate type between SQLite and your values, which gives information about the raw value stored in the database.

+ +

You get DatabaseValue just like other value types:

+
let dbValue: DatabaseValue = row[0]
+let dbValue: DatabaseValue? = row["name"] // nil if and only if column does not exist
+
+// Check for NULL:
+dbValue.isNull // Bool
+
+// The stored value:
+dbValue.storage.value // Int64, Double, String, Data, or nil
+
+// All the five storage classes supported by SQLite:
+switch dbValue.storage {
+case .null:                 print("NULL")
+case .int64(let int64):     print("Int64: \(int64)")
+case .double(let double):   print("Double: \(double)")
+case .string(let string):   print("String: \(string)")
+case .blob(let data):       print("Data: \(data)")
+}
+
+ +

You can extract regular values (Bool, Int, String, Date, Swift enums, etc.) from DatabaseValue with the DatabaseValueConvertible.fromDatabaseValue() method:

+
let dbValue: DatabaseValue = row["bookCount"]
+let bookCount   = Int.fromDatabaseValue(dbValue)   // Int?
+let bookCount64 = Int64.fromDatabaseValue(dbValue) // Int64?
+let hasBooks    = Bool.fromDatabaseValue(dbValue)  // Bool?, false when 0
+
+let dbValue: DatabaseValue = row["date"]
+let string = String.fromDatabaseValue(dbValue)     // "2015-09-11 18:14:15.123"
+let date   = Date.fromDatabaseValue(dbValue)       // Date?
+
+ +

fromDatabaseValue returns nil for invalid conversions:

+
let row = try Row.fetchOne(db, "SELECT 'Mom’s birthday'")!
+let dbValue: DatabaseValue = row[0]
+let string = String.fromDatabaseValue(dbValue) // "Mom’s birthday"
+let int    = Int.fromDatabaseValue(dbValue)    // nil
+let date   = Date.fromDatabaseValue(dbValue)   // nil
+
+

Rows as Dictionaries

+ +

Row adopts the standard RandomAccessCollection protocol, and can be seen as a dictionary of DatabaseValue:

+
// All the (columnName, dbValue) tuples, from left to right:
+for (columnName, dbValue) in row {
+    ...
+}
+
+ +

You can build rows from dictionaries (standard Swift dictionaries and NSDictionary). See Values for more information on supported types:

+
let row: Row = ["name": "foo", "date": nil]
+let row = Row(["name": "foo", "date": nil])
+let row = Row(/* [AnyHashable: Any] */) // nil if invalid dictionary
+
+ +

Yet rows are not real dictionaries: they may contain duplicate columns:

+
let row = try Row.fetchOne(db, "SELECT 1 AS foo, 2 AS foo")!
+row.columnNames    // ["foo", "foo"]
+row.databaseValues // [1, 2]
+row["foo"]         // 1 (leftmost matching column)
+for (columnName, dbValue) in row { ... } // ("foo", 1), ("foo", 2)
+
+ +

When you build a dictionary from a row, you have to disambiguate identical columns, and choose how to present database values. For example:

+ +
    +
  • A [String: DatabaseValue] dictionary that keeps leftmost value in case of duplicated column name:

    +
    let dict = Dictionary(row, uniquingKeysWith: { (left, _) in left })
    +
  • +
  • A [String: AnyObject] dictionary which keeps rightmost value in case of duplicated column name. This dictionary is identical to FMResultSet’s resultDictionary from FMDB. It contains NSNull values for null columns, and can be shared with Objective-C:

    +
    let dict = Dictionary(
    +    row.map { (column, dbValue) in
    +        (column, dbValue.storage.value as AnyObject)
    +    },
    +    uniquingKeysWith: { (_, right) in right })
    +
  • +
  • A [String: Any] dictionary that can feed, for example, JSONSerialization:

    +
    let dict = Dictionary(
    +    row.map { (column, dbValue) in
    +        (column, dbValue.storage.value)
    +    },
    +    uniquingKeysWith: { (left, _) in left })
    +
  • +
+ +

See the documentation of Dictionary.init(_:uniquingKeysWith:) for more information.

+

Value Queries

+ +

Instead of rows, you can directly fetch values. Like rows, fetch them as cursors, arrays, or single values (see fetching methods). Values are extracted from the leftmost column of the SQL queries:

+
try dbQueue.read { db in
+    try Int.fetchCursor(db, "SELECT ...", arguments: ...) // A Cursor of Int
+    try Int.fetchAll(db, "SELECT ...", arguments: ...)    // [Int]
+    try Int.fetchOne(db, "SELECT ...", arguments: ...)    // Int?
+
+    // When database may contain NULL:
+    try Optional<Int>.fetchCursor(db, "SELECT ...", arguments: ...) // A Cursor of Int?
+    try Optional<Int>.fetchAll(db, "SELECT ...", arguments: ...)    // [Int?]
+}
+
+let playerCount = try dbQueue.read { db in
+    try Int.fetchOne(db, "SELECT COUNT(*) FROM player")!
+}
+
+ +

fetchOne returns an optional value which is nil in two cases: either the SELECT statement yielded no row, or one row with a NULL value.

+ +

There are many supported value types (Bool, Int, String, Date, Swift enums, etc.). See Values for more information:

+
let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM player")! // Int
+let urls = try URL.fetchAll(db, "SELECT url FROM link")          // [URL]
+
+

Values

+ +

GRDB ships with built-in support for the following value types:

+ + + +

Values can be used as statement arguments:

+
let url: URL = ...
+let verified: Bool = ...
+try db.execute(
+    "INSERT INTO link (url, verified) VALUES (?, ?)",
+    arguments: [url, verified])
+
+ +

Values can be extracted from rows:

+
let rows = try Row.fetchCursor(db, "SELECT * FROM link")
+while let row = try rows.next() {
+    let url: URL = row["url"]
+    let verified: Bool = row["verified"]
+}
+
+ +

Values can be directly fetched:

+
let urls = try URL.fetchAll(db, "SELECT url FROM link")  // [URL]
+
+ +

Use values in Records:

+
struct Link: FetchableRecord {
+    var url: URL
+    var isVerified: Bool
+
+    init(row: Row) {
+        url = row["url"]
+        isVerified = row["verified"]
+    }
+}
+
+ +

Use values in the query interface:

+
let url: URL = ...
+let link = try Link.filter(Column("url") == url).fetchOne(db)
+
+

Data (and Memory Savings)

+ +

Data suits the BLOB SQLite columns. It can be stored and fetched from the database just like other values:

+
let rows = try Row.fetchCursor(db, "SELECT data, ...")
+while let row = try rows.next() {
+    let data: Data = row["data"]
+}
+
+ +

At each step of the request iteration, the row[] subscript creates two copies of the database bytes: one fetched by SQLite, and another, stored in the Swift Data value.

+ +

You have the opportunity to save memory by not copying the data fetched by SQLite:

+
while let row = try rows.next() {
+    let data = row.dataNoCopy(named: "data") // Data?
+}
+
+ +

The non-copied data does not live longer than the iteration step: make sure that you do not use it past this point.

+

Date and DateComponents

+ +

Date and DateComponents can be stored and fetched from the database.

+ +

Here is how GRDB supports the various date formats supported by SQLite:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SQLite formatDateDateComponents
YYYY-MM-DDRead ¹Read/Write
YYYY-MM-DD HH:MMRead ¹Read/Write
YYYY-MM-DD HH:MM:SSRead ¹Read/Write
YYYY-MM-DD HH:MM:SS.SSSRead/Write ¹Read/Write
YYYY-MM-DD*T*HH:MMRead ¹Read
YYYY-MM-DD*T*HH:MM:SSRead ¹Read
YYYY-MM-DD*T*HH:MM:SS.SSSRead ¹Read
HH:MMRead/Write
HH:MM:SSRead/Write
HH:MM:SS.SSSRead/Write
Timestamps since unix epochRead ²
now
+ +

¹ Dates are stored and read in the UTC time zone. Missing components are assumed to be zero.

+ +

² GRDB 2+ interprets numerical values as timestamps that fuel Date(timeIntervalSince1970:). Previous GRDB versions used to interpret numbers as julian days. Julian days are still supported, with the Date(julianDay:) initializer.

+

Date

+ +

Date can be stored and fetched from the database just like other values:

+
try db.execute(
+    "INSERT INTO player (creationDate, ...) VALUES (?, ...)",
+    arguments: [Date(), ...])
+
+let row = try Row.fetchOne(db, ...)!
+let creationDate: Date = row["creationDate"]
+
+ +

Dates are stored using the format YYYY-MM-DD HH:MM:SS.SSS in the UTC time zone. It is precise to the millisecond.

+ +
+

:point_up: Note: this format was chosen because it is the only format that is:

+ +
    +
  • Comparable (ORDER BY date works)
  • +
  • Comparable with the SQLite keyword CURRENT_TIMESTAMP (WHERE date > CURRENT_TIMESTAMP works)
  • +
  • Able to feed SQLite date & time functions
  • +
  • Precise enough
  • +
+
+ +

When the default format does not fit your needs, customize date conversions. For example:

+
try db.execute(
+    "INSERT INTO player (creationDate, ...) VALUES (?, ...)",
+    arguments: [Date().timeIntervalSinceReferenceDate, ...])
+
+let row = try Row.fetchOne(db, ...)!
+let creationDate = Date(timeIntervalSinceReferenceDate: row["creationDate"])
+
+ +

See Codable Records for more date customization options.

+

DateComponents

+ +

DateComponents is indirectly supported, through the DatabaseDateComponents helper type.

+ +

DatabaseDateComponents reads date components from all date formats supported by SQLite, and stores them in the format of your choice, from HH:MM to YYYY-MM-DD HH:MM:SS.SSS.

+ +

DatabaseDateComponents can be stored and fetched from the database just like other values:

+
let components = DateComponents()
+components.year = 1973
+components.month = 9
+components.day = 18
+
+// Store "1973-09-18"
+let dbComponents = DatabaseDateComponents(components, format: .YMD)
+try db.execute(
+    "INSERT INTO player (birthDate, ...) VALUES (?, ...)",
+    arguments: [dbComponents, ...])
+
+// Read "1973-09-18"
+let row = try Row.fetchOne(db, "SELECT birthDate ...")!
+let dbComponents: DatabaseDateComponents = row["birthDate"]
+dbComponents.format         // .YMD (the actual format found in the database)
+dbComponents.dateComponents // DateComponents
+
+

NSNumber and NSDecimalNumber

+ +

NSNumber can be stored and fetched from the database just like other values. Floating point NSNumbers are stored as Double. Integer and boolean, as Int64. Integers that don’t fit Int64 won’t be stored: you’ll get a fatal error instead. Be cautious when an NSNumber contains an UInt64, for example.

+ +

NSDecimalNumber deserves a longer discussion:

+ +

SQLite has no support for decimal numbers. Given the table below, SQLite will actually store integers or doubles:

+
CREATE TABLE transfer (
+    amount DECIMAL(10,5) -- will store integer or double, actually
+)
+
+ +

This means that computations will not be exact:

+
try db.execute("INSERT INTO transfer (amount) VALUES (0.1)")
+try db.execute("INSERT INTO transfer (amount) VALUES (0.2)")
+let sum = try NSDecimalNumber.fetchOne(db, "SELECT SUM(amount) FROM transfer")!
+
+// Yikes! 0.3000000000000000512
+print(sum)
+
+ +

Don’t blame SQLite or GRDB, and instead store your decimal numbers differently.

+ +

A classic technique is to store integers instead, since SQLite performs exact computations of integers. For example, don’t store Euros, but store cents instead:

+
// Write
+let amount = NSDecimalNumber(string: "0.10")
+let integerAmount = amount.multiplying(byPowerOf10: 2).int64Value
+try db.execute("INSERT INTO transfer (amount) VALUES (?)", arguments: [integerAmount])
+
+// Read
+let integerAmount = try Int64.fetchOne(db, "SELECT SUM(amount) FROM transfer")!
+let amount = NSDecimalNumber(value: integerAmount).multiplying(byPowerOf10: -2) // 0.10
+
+

UUID

+ +

UUID can be stored and fetched from the database just like other values.

+ +

GRDB stores uuids as 16-bytes data blobs, and decodes them from both 16-bytes data blobs and strings such as E621E1F8-C36C-495A-93FC-0C247A3E6E5F.

+

Swift Enums

+ +

Swift enums and generally all types that adopt the RawRepresentable protocol can be stored and fetched from the database just like their raw values:

+
enum Color : Int {
+    case red, white, rose
+}
+
+enum Grape : String {
+    case chardonnay, merlot, riesling
+}
+
+// Declare empty DatabaseValueConvertible adoption
+extension Color : DatabaseValueConvertible { }
+extension Grape : DatabaseValueConvertible { }
+
+// Store
+try db.execute(
+    "INSERT INTO wine (grape, color) VALUES (?, ?)",
+    arguments: [Grape.merlot, Color.red])
+
+// Read
+let rows = try Row.fetchCursor(db, "SELECT * FROM wine")
+while let row = try rows.next() {
+    let grape: Grape = row["grape"]
+    let color: Color = row["color"]
+}
+
+ +

When a database value does not match any enum case, you get a fatal error. This fatal error can be avoided with the DatabaseValue type:

+
let row = try Row.fetchOne(db, "SELECT 'syrah'")!
+
+row[0] as String  // "syrah"
+row[0] as Grape?  // fatal error: could not convert "syrah" to Grape.
+row[0] as Grape   // fatal error: could not convert "syrah" to Grape.
+
+let dbValue: DatabaseValue = row[0]
+if dbValue.isNull {
+    // Handle NULL
+} else if let grape = Grape.fromDatabaseValue(dbValue) {
+    // Handle valid grape
+} else {
+    // Handle unknown grape
+}
+
+

Custom Value Types

+ +

Conversion to and from the database is based on the DatabaseValueConvertible protocol:

+
protocol DatabaseValueConvertible {
+    /// Returns a value that can be stored in the database.
+    var databaseValue: DatabaseValue { get }
+
+    /// Returns a value initialized from dbValue, if possible.
+    static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self?
+}
+
+ +

All types that adopt this protocol can be used like all other values (Bool, Int, String, Date, Swift enums, etc.)

+ +

The databaseValue property returns DatabaseValue, a type that wraps the five values supported by SQLite: NULL, Int64, Double, String and Data. Since DatabaseValue has no public initializer, use DatabaseValue.null, or another type that already adopts the protocol: 1.databaseValue, "foo".databaseValue, etc. Conversion to DatabaseValue must not fail.

+ +

The fromDatabaseValue() factory method returns an instance of your custom type if the database value contains a suitable value. If the database value does not contain a suitable value, such as foo for Date, fromDatabaseValue must return nil (GRDB will interpret this nil result as a conversion error, and react accordingly).

+

Transactions and Savepoints

+ + +

Transactions and Safety

+ +

A transaction is a fundamental tool of SQLite that guarantees data consistency as well as proper isolation between application threads and database connections.

+ +

GRDB generally opens transactions for you, as a way to enforce its concurrency guarantees, and provide maximal security for both your application data and application logic:

+
// BEGIN TRANSACTION
+// INSERT INTO credit ...
+// INSERT INTO debit ...
+// COMMIT
+try dbQueue.write { db in
+    try Credit(destinationAccout, amount).insert(db)
+    try Debit(sourceAccount, amount).insert(db)
+}
+
+// BEGIN TRANSACTION
+// INSERT INTO credit ...
+// INSERT INTO debit ...
+// COMMIT
+try dbPool.write { db in
+    try Credit(destinationAccout, amount).insert(db)
+    try Debit(sourceAccount, amount).insert(db)
+}
+
+ +

Yet you may need to exactly control when transactions take place:

+

Explicit Transactions

+ +

DatabaseQueue.inDatabase() and DatabasePool.writeWithoutTransaction() execute your database statements outside of any transaction:

+
// INSERT INTO credit ...
+// INSERT INTO debit ...
+try dbQueue.inDatabase { db in
+    try Credit(destinationAccout, amount).insert(db)
+    try Debit(sourceAccount, amount).insert(db)
+}
+
+// INSERT INTO credit ...
+// INSERT INTO debit ...
+try dbPool.writeWithoutTransaction { db in
+    try Credit(destinationAccout, amount).insert(db)
+    try Debit(sourceAccount, amount).insert(db)
+}
+
+ +

Writing outside of any transaction is dangerous, for two reasons:

+ +
    +
  • In our credit/debit example, you may successfully insert a credit, but fail inserting the debit, and end up with unbalanced accounts (oops).

    +
    // UNSAFE DATABASE INTEGRITY
    +try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction
    +    try Credit(destinationAccout, amount).insert(db) // may succeed
    +    try Debit(sourceAccount, amount).insert(db)      // may fail
    +}
    +
    + +

    Transactions avoid this kind of bug.

  • +
  • Database pool concurrent reads can see an inconsistent state of the database:

    +
    // UNSAFE CONCURRENCY
    +try dbPool.writeWithoutTransaction { db in
    +    try Credit(destinationAccout, amount).insert(db)
    +    // <- Concurrent dbPool.read sees a partial db update here
    +    try Debit(sourceAccount, amount).insert(db)
    +}
    +
    + +

    Transactions avoid this kind of bug, too.

  • +
+ +

To open explicit transactions, use one of the Database.inTransaction, DatabaseQueue.inTransaction, or DatabasePool.writeInTransaction methods:

+
// BEGIN TRANSACTION
+// INSERT INTO credit ...
+// INSERT INTO debit ...
+// COMMIT
+try dbQueue.inDatabase { db in  // or dbPool.writeWithoutTransaction
+    try db.inTransaction {
+        try Credit(destinationAccout, amount).insert(db)
+        try Debit(sourceAccount, amount).insert(db)
+        return .commit
+    }
+}
+
+// BEGIN TRANSACTION
+// INSERT INTO credit ...
+// INSERT INTO debit ...
+// COMMIT
+try dbQueue.inTransaction { db in  // or dbPool.writeInTransaction
+    try Credit(destinationAccout, amount).insert(db)
+    try Debit(sourceAccount, amount).insert(db)
+    return .commit
+}
+
+ +

If an error is thrown from the transaction block, the transaction is rollbacked and the error is rethrown by the inTransaction method. If you return .rollback instead of .commit, the transaction is also rollbacked, but no error is thrown.

+ +

You can also perform manual transaction management:

+
try dbQueue.inDatabase { db in  // or dbPool.writeWithoutTransaction
+    try db.beginTransaction()
+    ...
+    try db.commit()
+
+    try db.execute("BEGIN TRANSACTION")
+    ...
+    try db.execute("ROLLBACK")
+}
+
+ +

Transactions can’t be left opened unless you set the allowsUnsafeTransactions configuration flag:

+
// fatal error: A transaction has been left opened at the end of a database access
+try dbQueue.inDatabase { db in
+    try db.execute("BEGIN TRANSACTION")
+    // <- no commit or rollback
+}
+
+ +

You can ask if a transaction is currently opened:

+
func myCriticalMethod(_ db: Database) throws {
+    precondition(db.isInsideTransaction, "This method requires a transaction")
+    try ...
+}
+
+ +

Yet, you have a better option than checking for transactions: critical database sections should use savepoints, described below:

+
func myCriticalMethod(_ db: Database) throws {
+    try db.inSavepoint {
+        // Here the database is guaranteed to be inside a transaction.
+        try ...
+    }
+}
+
+

Savepoints

+ +

Statements grouped in a savepoint can be rollbacked without invalidating a whole transaction:

+
try dbQueue.write { db in
+    // Makes sure both inserts succeed, or none:
+    try db.inSavepoint {
+        try Credit(destinationAccout, amount).insert(db)
+        try Debit(sourceAccount, amount).insert(db)
+        return .commit
+    }
+
+    // Other savepoints, etc...
+}
+
+ +

If an error is thrown from the savepoint block, the savepoint is rollbacked and the error is rethrown by the inSavepoint method. If you return .rollback instead of .commit, the savepoint is also rollbacked, but no error is thrown.

+ +

Unlike transactions, savepoints can be nested. They implicitly open a transaction if no one was opened when the savepoint begins. As such, they behave just like nested transactions. Yet the database changes are only written to disk when the outermost transaction is committed:

+
try dbQueue.inDatabase { db in
+    try db.inSavepoint {
+        ...
+        try db.inSavepoint {
+            ...
+            return .commit
+        }
+        ...
+        return .commit  // writes changes to disk
+    }
+}
+
+ +

SQLite savepoints are more than nested transactions, though. For advanced uses, use SQLite savepoint documentation.

+

Transaction Kinds

+ +

SQLite supports three kinds of transactions: deferred (the default), immediate, and exclusive.

+ +

The transaction kind can be changed in the database configuration, or for each transaction:

+
// 1) Default configuration:
+let dbQueue = try DatabaseQueue(path: "...")
+
+// BEGIN DEFERED TRANSACTION ...
+dbQueue.write { db in ... }
+
+// BEGIN EXCLUSIVE TRANSACTION ...
+dbQueue.inTransaction(.exclusive) { db in ... }
+
+// 2) Customized default transaction kind:
+var config = Configuration()
+config.defaultTransactionKind = .immediate
+let dbQueue = try DatabaseQueue(path: "...", configuration: config)
+
+// BEGIN IMMEDIATE TRANSACTION ...
+dbQueue.write { db in ... }
+
+// BEGIN EXCLUSIVE TRANSACTION ...
+dbQueue.inTransaction(.exclusive) { db in ... }
+
+

Prepared Statements

+ +

Prepared Statements let you prepare an SQL query and execute it later, several times if you need, with different arguments.

+ +

There are two kinds of prepared statements: select statements, and update statements:

+
try dbQueue.write { db in
+    let updateSQL = "INSERT INTO player (name, score) VALUES (:name, :score)"
+    let updateStatement = try db.makeUpdateStatement(updateSQL)
+
+    let selectSQL = "SELECT * FROM player WHERE name = ?"
+    let selectStatement = try db.makeSelectStatement(selectSQL)
+}
+
+ +

The ? and colon-prefixed keys like :name in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type StatementArguments, which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).

+
updateStatement.arguments = ["name": "Arthur", "score": 1000]
+selectStatement.arguments = ["Arthur"]
+
+ +

After arguments are set, you can execute the prepared statement:

+
try updateStatement.execute()
+
+ +

Select statements can be used wherever a raw SQL query string would fit (see fetch queries):

+
let rows = try Row.fetchCursor(selectStatement)    // A Cursor of Row
+let players = try Player.fetchAll(selectStatement) // [Player]
+let player = try Player.fetchOne(selectStatement)  // Player?
+
+ +

You can set the arguments at the moment of the statement execution:

+
try updateStatement.execute(arguments: ["name": "Arthur", "score": 1000])
+let player = try Player.fetchOne(selectStatement, arguments: ["Arthur"])
+
+ +
+

:point_up: Note: it is a programmer error to reuse a prepared statement that has failed: GRDB may crash if you do so.

+
+ +

See row queries, value queries, and Records for more information.

+

Prepared Statements Cache

+ +

When the same query will be used several times in the lifetime of your application, you may feel a natural desire to cache prepared statements.

+ +

Don’t cache statements yourself.

+ +
+

:point_up: Note: This is because you don’t have the necessary tools. Statements are tied to specific SQLite connections and dispatch queues which you don’t manage yourself, especially when you use database pools. A change in the database schema may, or may not invalidate a statement. On systems earlier than iOS 8.2 and OSX 10.10 that don’t have the sqlite3_close_v2 function, SQLite connections won’t close properly if statements have been kept alive.

+
+ +

Instead, use the cachedUpdateStatement and cachedSelectStatement methods. GRDB does all the hard caching and memory management stuff for you:

+
let updateStatement = try db.cachedUpdateStatement(sql)
+let selectStatement = try db.cachedSelectStatement(sql)
+
+ +

Should a cached prepared statement throw an error, don’t reuse it (it is a programmer error). Instead, reload it from the cache.

+

Custom SQL Functions and Aggregates

+ +

SQLite lets you define SQL functions and aggregates.

+ +

A custom SQL function or aggregate extends SQLite:

+
SELECT reverse(name) FROM player;   -- custom function
+SELECT maxLength(name) FROM player; -- custom aggregate
+
+ + +

Custom SQL Functions

+
let reverse = DatabaseFunction("reverse", argumentCount: 1, pure: true) { (values: [DatabaseValue]) in
+    // Extract string value, if any...
+    guard let string = String.fromDatabaseValue(values[0]) else {
+        return nil
+    }
+    // ... and return reversed string:
+    return String(string.reversed())
+}
+dbQueue.add(function: reverse)   // Or dbPool.add(function: ...)
+
+try dbQueue.read { db in
+    // "oof"
+    try String.fetchOne(db, "SELECT reverse('foo')")!
+}
+
+ +

The function argument takes an array of DatabaseValue, and returns any valid value (Bool, Int, String, Date, Swift enums, etc.) The number of database values is guaranteed to be argumentCount.

+ +

SQLite has the opportunity to perform additional optimizations when functions are pure, which means that their result only depends on their arguments. So make sure to set the pure argument to true when possible.

+ +

Functions can take a variable number of arguments:

+ +

When you don’t provide any explicit argumentCount, the function can take any number of arguments:

+
let averageOf = DatabaseFunction("averageOf", pure: true) { (values: [DatabaseValue]) in
+    let doubles = values.compactMap { Double.fromDatabaseValue($0) }
+    return doubles.reduce(0, +) / Double(doubles.count)
+}
+dbQueue.add(function: averageOf)
+
+try dbQueue.read { db in
+    // 2.0
+    try Double.fetchOne(db, "SELECT averageOf(1, 2, 3)")!
+}
+
+ +

Functions can throw:

+
let sqrt = DatabaseFunction("sqrt", argumentCount: 1, pure: true) { (values: [DatabaseValue]) in
+    guard let double = Double.fromDatabaseValue(values[0]) else {
+        return nil
+    }
+    guard double >= 0 else {
+        throw DatabaseError(message: "invalid negative number")
+    }
+    return sqrt(double)
+}
+dbQueue.add(function: sqrt)
+
+// SQLite error 1 with statement `SELECT sqrt(-1)`: invalid negative number
+try dbQueue.read { db in
+    try Double.fetchOne(db, "SELECT sqrt(-1)")!
+}
+
+ +

Use custom functions in the query interface:

+
// SELECT reverseString("name") FROM player
+Player.select(reverseString.apply(nameColumn))
+
+ +

GRDB ships with built-in SQL functions that perform unicode-aware string transformations. See Unicode.

+

Custom Aggregates

+ +

Before registering a custom aggregate, you need to define a type that adopts the DatabaseAggregate protocol:

+
protocol DatabaseAggregate {
+    // Initializes an aggregate
+    init()
+
+    // Called at each step of the aggregation
+    mutating func step(_ dbValues: [DatabaseValue]) throws
+
+    // Returns the final result
+    func finalize() throws -> DatabaseValueConvertible?
+}
+
+ +

For example:

+
struct MaxLength : DatabaseAggregate {
+    var maxLength: Int = 0
+
+    mutating func step(_ dbValues: [DatabaseValue]) {
+        // At each step, extract string value, if any...
+        guard let string = String.fromDatabaseValue(dbValues[0]) else {
+            return
+        }
+        // ... and update the result
+        let length = string.count
+        if length > maxLength {
+            maxLength = length
+        }
+    }
+
+    func finalize() -> DatabaseValueConvertible? {
+        return maxLength
+    }
+}
+
+let maxLength = DatabaseFunction(
+    "maxLength",
+    argumentCount: 1,
+    pure: true,
+    aggregate: MaxLength.self)
+
+dbQueue.add(function: maxLength)   // Or dbPool.add(function: ...)
+
+try dbQueue.read { db in
+    // Some Int
+    try Int.fetchOne(db, "SELECT maxLength(name) FROM player")!
+}
+
+ +

The step method of the aggregate takes an array of DatabaseValue. This array contains as many values as the argumentCount parameter (or any number of values, when argumentCount is omitted).

+ +

The finalize method of the aggregate returns the final aggregated value (Bool, Int, String, Date, Swift enums, etc.).

+ +

SQLite has the opportunity to perform additional optimizations when aggregates are pure, which means that their result only depends on their inputs. So make sure to set the pure argument to true when possible.

+ +

Use custom aggregates in the query interface:

+
// SELECT maxLength("name") FROM player
+let request = Player.select(maxLength.apply(nameColumn))
+try Int.fetchOne(db, request) // Int?
+
+

Database Schema Introspection

+ +

GRDB comes with a set of schema introspection methods:

+
try dbQueue.read { db in
+    // Bool, true if the table exists
+    try db.tableExists("player")
+
+    // [ColumnInfo], the columns in the table
+    try db.columns(in: "player")
+
+    // PrimaryKeyInfo
+    try db.primaryKey("player")
+
+    // [ForeignKeyInfo], the foreign keys defined on the table
+    try db.foreignKeys(on: "player")
+
+    // [IndexInfo], the indexes defined on the table
+    try db.indexes(on: "player")
+
+    // Bool, true if column(s) is a unique key (primary key or unique index)
+    try db.table("player", hasUniqueKey: ["email"])
+}
+
+// Bool, true if argument is the name of an internal SQLite table
+Database.isSQLiteInternalTable(...)
+
+// Bool, true if argument is the name of an internal GRDB table
+Database.isGRDBInternalTable(...)
+
+

Row Adapters

+ +

Row adapters let you present database rows in the way expected by the row consumers.

+ +

They basically help two incompatible row interfaces to work together. For example, a row consumer expects a column named consumed, but the produced row has a column named produced.

+ +

In this case, the ColumnMapping row adapter comes in handy:

+
// Fetch a 'produced' column, and consume a 'consumed' column:
+let adapter = ColumnMapping(["consumed": "produced"])
+let row = try Row.fetchOne(db, "SELECT 'Hello' AS produced", adapter: adapter)!
+row["consumed"] // "Hello"
+row["produced"] // nil
+
+ +

Row adapters are values that adopt the RowAdapter protocol. You can implement your own custom adapters (:fire: EXPERIMENTAL), or use one of the four built-in adapters, described below.

+ +

To see how row adapters can be used, see Joined Queries Support.

+

ColumnMapping

+ +

ColumnMapping renames columns. Build one with a dictionary whose keys are adapted column names, and values the column names in the raw row:

+
// [newName:"Hello"]
+let adapter = ColumnMapping(["newName": "oldName"])
+let row = try Row.fetchOne(db, "SELECT 'Hello' AS oldName", adapter: adapter)!
+
+

SuffixRowAdapter

+ +

SuffixRowAdapter hides the first columns in a row:

+
// [b:1 c:2]
+let adapter = SuffixRowAdapter(fromIndex: 1)
+let row = try Row.fetchOne(db, "SELECT 0 AS a, 1 AS b, 2 AS c", adapter: adapter)!
+
+

RangeRowAdapter

+ +

RangeRowAdapter only exposes a range of columns.

+
// [b:1]
+let adapter = RangeRowAdapter(1..<2)
+let row = try Row.fetchOne(db, "SELECT 0 AS a, 1 AS b, 2 AS c", adapter: adapter)!
+
+

EmptyRowAdapter

+ +

EmptyRowAdapter hides all columns.

+
let adapter = EmptyRowAdapter()
+let row = try Row.fetchOne(db, "SELECT 0 AS a, 1 AS b, 2 AS c", adapter: adapter)!
+row.isEmpty // true
+
+ +

This limit adapter may turn out useful in some narrow use cases. You’ll be happy to find it when you need it.

+

ScopeAdapter

+ +

ScopeAdapter defines row scopes:

+
let adapter = ScopeAdapter([
+    "left": RangeRowAdapter(0..<2),
+    "right": RangeRowAdapter(2..<4)])
+let row = try Row.fetchOne(db, "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d", adapter: adapter)!
+
+ +

ScopeAdapter does not change the columns and values of the fetched row. Instead, it defines scopes, which you access through the Row.scopes property:

+
row                   // [a:0 b:1 c:2 d:3]
+row.scopes["left"]    // [a:0 b:1]
+row.scopes["right"]   // [c:2 d:3]
+row.scopes["missing"] // nil
+
+ +

Scopes can be nested:

+
let adapter = ScopeAdapter([
+    "left": ScopeAdapter([
+        "left": RangeRowAdapter(0..<1),
+        "right": RangeRowAdapter(1..<2)]),
+    "right": ScopeAdapter([
+        "left": RangeRowAdapter(2..<3),
+        "right": RangeRowAdapter(3..<4)])
+    ])
+let row = try Row.fetchOne(db, "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d", adapter: adapter)!
+
+let leftRow = row.scopes["left"]!
+leftRow.scopes["left"]  // [a:0]
+leftRow.scopes["right"] // [b:1]
+
+let rightRow = row.scopes["right"]!
+rightRow.scopes["left"]  // [c:2]
+rightRow.scopes["right"] // [d:3]
+
+ +

Any adapter can be extended with scopes:

+
let baseAdapter = RangeRowAdapter(0..<2)
+let adapter = ScopeAdapter(base: baseAdapter, scopes: [
+    "remainder": SuffixRowAdapter(fromIndex: 2)])
+let row = try Row.fetchOne(db, "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d", adapter: adapter)!
+
+row // [a:0 b:1]
+row.scopes["remainder"] // [c:2 d:3]
+
+

Raw SQLite Pointers

+ +

If not all SQLite APIs are exposed in GRDB, you can still use the SQLite C Interface and call SQLite C functions.

+ +

Those functions are embedded right into the GRDBCustom and GRCBCipher modules. For the regular GRDB framework: you’ll need to import SQLite3, or CSQLite, depending on whether you use the Swift Package Manager or not:

+
#if SWIFT_PACKAGE
+    import CSQLite // For Swift Package Manager
+#else
+    import SQLite3 // Otherwise
+#endif
+
+let sqliteVersion = String(cString: sqlite3_libversion())
+
+ +

Raw pointers to database connections and statements are available through the Database.sqliteConnection and Statement.sqliteStatement properties:

+
try dbQueue.read { db in
+    // The raw pointer to a database connection:
+    let sqliteConnection = db.sqliteConnection
+
+    // The raw pointer to a statement:
+    let statement = try db.makeSelectStatement("SELECT ...")
+    let sqliteStatement = statement.sqliteStatement
+}
+
+ +
+

:point_up: Notes

+ +
    +
  • Those pointers are owned by GRDB: don’t close connections or finalize statements created by GRDB.
  • +
  • GRDB opens SQLite connections in the [multi-thread mode](https://www.sqlite.org/threadsafe.html), which (oddly) means that they are not thread-safe. Make sure you touch raw databases and statements inside their dedicated dispatch queues.
  • +
  • Use the raw SQLite C Interface at your own risk. GRDB won’t prevent you from shooting yourself in the foot.
  • +
+
+ +

Before jumping in the low-level wagon, here is the list of all SQLite APIs used by GRDB:

+ + +

Records

+ +

On top of the SQLite API, GRDB provides protocols and a class that help manipulating database rows as regular objects named records:

+
try dbQueue.write { db in
+    if var place = try Place.fetchOne(db, key: 1) {
+        place.isFavorite = true
+        try place.update(db)
+    }
+}
+
+ +

Of course, you need to open a database connection, and create a database table first.

+ +

Your custom structs and classes can adopt each protocol individually, and opt in to focused sets of features. Or you can subclass the Record class, and get the full toolkit in one go: fetching methods, persistence methods, and record comparison. See the list of record methods for an overview.

+ +
+

:point_up: Note: if you are familiar with Core Data’s NSManagedObject or Realm’s Object, you may experience a cultural shock: GRDB records are not uniqued, do not auto-update, and do not lazy-load. This is both a purpose, and a consequence of protocol-oriented programming. You should read How to build an iOS application with SQLite and GRDB.swift for a general introduction.

+ +

:bulb: Tip: after you have read this chapter, check the Good Practices for Designing Record Types Guide.

+
+ +

Overview

+ + + +

Protocols and the Record Class

+ + + +

Records in a Glance

+ + +

Inserting Records

+ +

To insert a record in the database, call the insert method:

+
let player = Player(name: "Arthur", email: "arthur@example.com")
+try player.insert(db)
+
+ +

:point_right: insert is available for subclasses of the Record class, and types that adopt the PersistableRecord protocol.

+

Fetching Records

+ +

To fetch records from the database, call a fetching method:

+
let arthur = try Player.fetchOne(db,            // Player?
+    "SELECT * FROM players WHERE name = ?",
+    arguments: ["Arthur"])
+
+let bestPlayers = try Player                    // [Player]
+    .order(Column("score").desc)
+    .limit(10)
+    .fetchAll(db)
+
+let spain = try Country.fetchOne(db, key: "ES") // Country?
+
+ +

:point_right: Fetching from raw SQL is available for subclasses of the Record class, and types that adopt the FetchableRecord protocol.

+ +

:point_right: Fetching without SQL, using the query interface, is available for subclasses of the Record class, and types that adopt both FetchableRecord and TableRecord protocol.

+

Updating Records

+ +

To update a record in the database, call the update method:

+
if let player = try Player.fetchOne(db, key: 1) 
+    player.score = 1000
+    try player.update(db)
+}
+
+ +

It is possible to avoid useless updates:

+
if let player = try Player.fetchOne(db, key: 1) {
+    player.score = 1000
+    try player.updateChanges(db) // does nothing if score has not changed
+}
+
+ +

For batch updates, execute an SQL query:

+
try db.execute("UPDATE player SET synchronized = 1")
+
+ +

:point_right: update methods are available for subclasses of the Record class, and types that adopt the PersistableRecord protocol.

+

Deleting Records

+ +

To delete a record in the database, call the delete method:

+
if let player = try Player.fetchOne(db, key: 1) {
+    try player.delete(db)
+}
+
+ +

You can also delete by primary key, or any unique index:

+
try Player.deleteOne(db, key: 1)
+try Player.deleteOne(db, key: ["email": "arthur@example.com"])
+try Country.deleteAll(db, keys: ["FR", "US"])
+
+ +

For batch deletes, execute an SQL query, or see the query interface:

+
try Player
+    .filter(Column("email") == nil)
+    .deleteAll(db)
+
+ +

:point_right: delete methods are available for subclasses of the Record class, and types that adopt the PersistableRecord protocol.

+

Counting Records

+ +

To count records, call the fetchCount method:

+
let playerCount: Int = try Player.fetchCount(db)
+
+let playerWithEmailCount: Int = try Player
+    .filter(Column("email") == nil)
+    .fetchCount(db)
+
+ +

:point_right: fetchCount is available for subclasses of the Record class, and types that adopt the TableRecord protocol.

+ +

Details follow:

+ + +

Record Protocols Overview

+ +

GRDB ships with three record protocols. Your own types will adopt one or several of them, according to the abilities you want to extend your types with.

+ +
    +
  • FetchableRecord is able to decode database rows.

    + +

    It is always possible to decode rows without this protocol:

    +
    struct Place { ... }
    +try dbQueue.read { db in
    +    let rows = try Row.fetchAll(db, "SELECT * FROM place")
    +    let places: [Place] = rows.map { row in
    +        return Place(
    +            id: row["id"],
    +            title: row["title"],
    +            coordinate: CLLocationCoordinate2D(
    +                latitude: row["latitude"],
    +                longitude: row["longitude"]))
    +        )
    +    }
    +}
    +
    + +

    But FetchableRecord lets you write code that is easier to read, and more efficient as well, both in terms of performance and memory usage:

    +
    struct Place: FetchableRecord { ... }
    +try dbQueue.read { db in
    +    let places = try Place.fetchAll(db, "SELECT * FROM place")
    +}
    +
    + +
    +

    :bulb: Tip: FetchableRecord can derive its implementation from the standard Decodable protocol. See Codable Records for more information.

    +
    + +

    FetchableRecord can decode database rows, but it is not able to build SQL requests for you. For that, you also need TableRecord:

  • +
  • TableRecord is able to generate SQL queries:

    +
    struct Place: TableRecord { ... }
    +// SELECT * FROM place ORDER BY title
    +let request = Place.order(Column("title"))
    +
    + +

    When a type adopts both TableRecord and FetchableRecord, it can load from those requests:

    +
    struct Place: TableRecord, FetchableRecord { ... }
    +try dbQueue.read { db in
    +    let places = try Place.order(Column("title")).fetchAll(db)
    +    let paris = try Place.fetchOne(key: 1)
    +}
    +
  • +
  • PersistableRecord is able to write: it can create, update, and delete rows in the database:

    +
    struct Place : PersistableRecord { ... }
    +try dbQueue.write { db in
    +    try Place.delete(db, key: 1)
    +    try Place(...).insert(db)
    +}
    +
    + +

    A persistable record can also compare itself against other records, and avoid useless database updates.

    + +
    +

    :bulb: Tip: PersistableRecord can derive its implementation from the standard Encodable protocol. See Codable Records for more information.

    +
  • +
+

FetchableRecord Protocol

+ +

The FetchableRecord protocol grants fetching methods to any type that can be built from a database row:

+
protocol FetchableRecord {
+    /// Row initializer
+    init(row: Row)
+}
+
+ +

To use FetchableRecord, subclass the Record class, or adopt it explicitly. For example:

+
struct Place {
+    var id: Int64?
+    var title: String
+    var coordinate: CLLocationCoordinate2D
+}
+
+extension Place : FetchableRecord {
+    init(row: Row) {
+        id = row["id"]
+        title = row["title"]
+        coordinate = CLLocationCoordinate2D(
+            latitude: row["latitude"],
+            longitude: row["longitude"])
+    }
+}
+
+ +

Rows also accept column enums:

+
extension Place : FetchableRecord {
+    enum Columns: String, ColumnExpression {
+        case id, title, latitude, longitude
+    }
+
+    init(row: Row) {
+        id = row[Columns.id]
+        title = row[Columns.title]
+        coordinate = CLLocationCoordinate2D(
+            latitude: row[Columns.latitude],
+            longitude: row[Columns.longitude])
+    }
+}
+
+ +

See column values for more information about the row[] subscript.

+ +

When your record type adopts the standard Decodable protocol, you don’t have to provide the implementation for init(row:). See Codable Records for more information:

+
// That's all
+struct Player: Decodable, FetchableRecord {
+    var id: Int64
+    var name: String
+    var score: Int
+}
+
+ +

FetchableRecord allows adopting types to be fetched from SQL queries:

+
try Place.fetchCursor(db, "SELECT ...", arguments:...) // A Cursor of Place
+try Place.fetchAll(db, "SELECT ...", arguments:...)    // [Place]
+try Place.fetchOne(db, "SELECT ...", arguments:...)    // Place?
+
+ +

See fetching methods for information about the fetchCursor, fetchAll and fetchOne methods. See StatementArguments for more information about the query arguments.

+ +
+

:point_up: Note: for performance reasons, the same row argument to init(row:) is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: self.row = row.copy().

+ +

:point_up: Note: The FetchableRecord.init(row:) initializer fits the needs of most applications. But some application are more demanding than others. When FetchableRecord does not exactly provide the support you need, have a look at the Beyond FetchableRecord chapter.

+
+

TableRecord Protocol

+ +

The TableRecord protocol generates SQL for you. To use TableRecord, subclass the Record class, or adopt it explicitly:

+
protocol TableRecord {
+    static var databaseTableName: String { get }
+    static var databaseSelection: [SQLSelectable] { get }
+}
+
+ +

The databaseSelection type property is optional, and documented in the Columns Selected by a Request chapter.

+ +

The databaseTableName type property is the name of a database table. By default, it is derived from the type name:

+
struct Place: TableRecord { }
+print(Place.databaseTableName) // prints "place"
+
+ +

For example:

+ +
    +
  • Place: place
  • +
  • Country: country
  • +
  • PostalAddress: postalAddress
  • +
  • HTTPRequest: httpRequest
  • +
  • TOEFL: toefl
  • +
+ +

You can still provide a custom table name:

+
struct Place: TableRecord {
+    static let databaseTableName = "location"
+}
+print(Place.databaseTableName) // prints "location"
+
+ +

Subclasses of the Record class must always override their superclass’s databaseTableName property:

+
class Place: Record {
+    override class var databaseTableName: String {
+        return "place"
+    }
+}
+print(Place.databaseTableName) // prints "place"
+
+ +

When a type adopts both TableRecord and FetchableRecord, it can be fetched using the query interface:

+
// SELECT * FROM place WHERE name = 'Paris'
+let paris = try Place.filter(nameColumn == "Paris").fetchOne(db)
+
+ +

TableRecord can also fetch records by primary key:

+
try Player.fetchOne(db, key: 1)              // Player?
+try Player.fetchAll(db, keys: [1, 2, 3])     // [Player]
+
+try Country.fetchOne(db, key: "FR")          // Country?
+try Country.fetchAll(db, keys: ["FR", "US"]) // [Country]
+
+ +

When the table has no explicit primary key, GRDB uses the hidden rowid column:

+
// SELECT * FROM document WHERE rowid = 1
+try Document.fetchOne(db, key: 1)            // Document?
+
+ +

For multiple-column primary keys and unique keys defined by unique indexes, provide a dictionary:

+
// SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR'
+try Citizenship.fetchOne(db, key: ["citizenId": 1, "countryCode": "FR"]) // Citizenship?
+
+

PersistableRecord Protocol

+ +

GRDB provides two protocols that let adopting types create, update, and delete rows in the database:

+
protocol MutablePersistableRecord : TableRecord {
+    /// Defines the values persisted in the database
+    func encode(to container: inout PersistenceContainer)
+
+    /// Optional method that lets your adopting type store its rowID upon
+    /// successful insertion. Don't call it directly: it is called for you.
+    mutating func didInsert(with rowID: Int64, for column: String?)
+}
+
+
protocol PersistableRecord : MutablePersistableRecord {
+    /// Non-mutating version of the optional didInsert(with:for:)
+    func didInsert(with rowID: Int64, for column: String?)
+}
+
+ +

Yes, two protocols instead of one. Both grant exactly the same advantages. Here is how you pick one or the other:

+ +
    +
  • If your type is a class, choose PersistableRecord. On top of that, implement didInsert(with:for:) if the database table has an auto-incremented primary key.

  • +
  • If your type is a struct, and the database table has an auto-incremented primary key, choose MutablePersistableRecord, and implement didInsert(with:for:).

  • +
  • Otherwise, choose PersistableRecord, and ignore didInsert(with:for:).

  • +
+ +

The encode(to:) method defines which values (Bool, Int, String, Date, Swift enums, etc.) are assigned to database columns.

+ +

The optional didInsert method lets the adopting type store its rowID after successful insertion, and is only useful for tables that have an auto-incremented primary key. It is called from a protected dispatch queue, and serialized with all database updates.

+ +

To use the persistable protocols, subclass the Record class, or adopt one of them explicitly. For example:

+
extension Place : MutablePersistableRecord {
+    /// The values persisted in the database
+    func encode(to container: inout PersistenceContainer) {
+        container["id"] = id
+        container["title"] = title
+        container["latitude"] = coordinate.latitude
+        container["longitude"] = coordinate.longitude
+    }
+
+    // Update id upon successful insertion:
+    mutating func didInsert(with rowID: Int64, for column: String?) {
+        id = rowID
+    }
+}
+
+var paris = Place(
+    id: nil,
+    title: "Paris",
+    coordinate: CLLocationCoordinate2D(latitude: 48.8534100, longitude: 2.3488000))
+
+try paris.insert(db)
+paris.id   // some value
+
+ +

Persistence containers also accept column enums:

+
extension Place : MutablePersistableRecord {
+    enum Columns: String, ColumnExpression {
+        case id, title, latitude, longitude
+    }
+
+    func encode(to container: inout PersistenceContainer) {
+        container[Columns.id] = id
+        container[Columns.title] = title
+        container[Columns.latitude] = coordinate.latitude
+        container[Columns.longitude] = coordinate.longitude
+    }
+}
+
+ +

When your record type adopts the standard Encodable protocol, you don’t have to provide the implementation for encode(to:). See Codable Records for more information:

+
// That's all
+struct Player: Encodable, MutablePersistableRecord {
+    var id: Int64?
+    var name: String
+    var score: Int
+
+    mutating func didInsert(with rowID: Int64, for column: String?) {
+        id = rowID
+    }
+}
+
+

Persistence Methods

+ +

Record subclasses and types that adopt PersistableRecord are given default implementations for methods that insert, update, and delete:

+
// Instance methods
+try place.save(db)                     // INSERT or UPDATE
+try place.insert(db)                   // INSERT
+try place.update(db)                   // UPDATE
+try place.update(db, columns: ...)     // UPDATE
+try place.updateChanges(db, from: ...) // Maybe UPDATE
+try place.updateChanges(db)            // Maybe UPDATE (Record class only)
+try place.delete(db)                   // DELETE
+try place.exists(db)
+
+// Type methods
+try Place.deleteAll(db)                    // DELETE
+try Place.deleteAll(db, keys:...)          // DELETE
+try Place.deleteOne(db, key:...)           // DELETE
+
+ +
    +
  • insert, update, save and delete can throw a DatabaseError.

  • +
  • update and updateChanges can also throw a PersistenceError, should the update fail because there is no matching row in the database.

    + +

    When saving an object that may or may not already exist in the database, prefer the save method:

  • +
  • save makes sure your values are stored in the database.

    + +

    It performs an UPDATE if the record has a non-null primary key, and then, if no row was modified, an INSERT. It directly perfoms an INSERT if the record has no primary key, or a null primary key.

    + +

    Despite the fact that it may execute two SQL statements, save behaves as an atomic operation: GRDB won’t allow any concurrent thread to sneak in (see concurrency).

  • +
  • delete returns whether a database row was deleted or not.

  • +
+ +

All primary keys are supported, including composite primary keys that span several columns, and the implicit rowid primary key.

+

Customizing the Persistence Methods

+ +

Your custom type may want to perform extra work when the persistence methods are invoked.

+ +

For example, it may want to have its UUID automatically set before inserting. Or it may want to validate its values before saving.

+ +

When you subclass Record, you simply have to override the customized method, and call super:

+
class Player : Record {
+    var uuid: UUID?
+
+    override func insert(_ db: Database) throws {
+        if uuid == nil {
+            uuid = UUID()
+        }
+        try super.insert(db)
+    }
+}
+
+ +

If you use the raw PersistableRecord protocol, use one of the special methods performInsert, performUpdate, performSave, performDelete, or performExists:

+
struct Link : PersistableRecord {
+    var url: URL
+
+    func insert(_ db: Database) throws {
+        try validate()
+        try performInsert(db)
+    }
+
+    func update(_ db: Database, columns: Set<String>) throws {
+        try validate()
+        try performUpdate(db, columns: columns)
+    }
+
+    func validate() throws {
+        if url.host == nil {
+            throw ValidationError("url must be absolute.")
+        }
+    }
+}
+
+ +
+

:point_up: Note: the special methods performInsert, performUpdate, etc. are reserved for your custom implementations. Do not use them elsewhere. Do not provide another implementation for those methods.

+ +

:point_up: Note: it is recommended that you do not implement your own version of the save method. Its default implementation forwards the job to update or insert: these are the methods that may need customization, not save.

+
+

Codable Records

+ +

Record types that adopt an archival protocol (Codable, Encodable or Decodable) get free database support just by declaring conformance to the desired record protocols:

+
// Declare a record...
+struct Player: Codable, FetchableRecord, PersistableRecord {
+    var name: String
+    var score: Int
+}
+
+// ...and there you go:
+try dbQueue.write { db in
+    try Player(name: "Arthur", score: 100).insert(db)
+    let players = try Player.fetchAll(db)
+}
+
+ +

Codable records encode and decode their properties according to their own implementation of the Encodable and Decodable protocols. Yet databases have specific requirements:

+ +
    +
  • Properties are always coded according to their preferred database representation, when they have one (all values that adopt the DatabaseValueConvertible protocol).
  • +
  • You can customize the encoding and decoding of dates and uuids.
  • +
  • Complex properties (arrays, dictionaries, nested structs, etc.) are stored as JSON.
  • +
+ +

For more information about Codable records, see:

+ + +

JSON Columns

+ +

When a Codable record contains a property that is not a simple value (Bool, Int, String, Date, Swift enums, etc.), that value is encoded and decoded as a JSON string. For example:

+
enum AchievementColor: String, Codable {
+    case bronze, silver, gold
+}
+
+struct Achievement: Codable {
+    var name: String
+    var color: AchievementColor
+}
+
+struct Player: Codable, FetchableRecord, PersistableRecord {
+    var name: String
+    var score: Int
+    var achievements: [Achievement] // stored in a JSON column
+}
+
+try! dbQueue.write { db in
+    // INSERT INTO player (name, score, achievements)
+    // VALUES (
+    //   'Arthur',
+    //   100,
+    //   '[{"color":"gold","name":"Use Codable Records"}]')
+    let achievement = Achievement(name: "Use Codable Records", color: .gold)
+    let player = Player(name: "Arthur", score: 100, achievements: [achievement])
+    try player.insert(db)
+}
+
+ +

GRDB uses the standard JSONDecoder and JSONEncoder from Foundation. By default, Data values are handled with the .base64 strategy, Date with the .millisecondsSince1970 strategy, and non conforming floats with the .throw strategy.

+ +

You can customize the JSON format by implementing those methods:

+
protocol FetchableRecord {
+    static func databaseJSONDecoder(for column: String) -> JSONDecoder
+}
+
+protocol MutablePersistableRecord {
+    static func databaseJSONEncoder(for column: String) -> JSONEncoder
+}
+
+ +
+

:bulb: Tip: Make sure you set the JSONEncoder sortedKeys option, available from iOS 11.0+, macOS 10.13+, and watchOS 4.0+. This option makes sure that the JSON output is stable. This stability is required for Record Comparison to work as expected, and database observation tools such as FetchedRecordsController or RxGRDB to accurately recognize changed records.

+
+

Date and UUID Coding Strategies

+ +

By default, Codable Records encode and decode their Date and UUID properties as described in the general Date and DateComponents and UUID chapters.

+ +

To sum up: dates encode themselves in the YYYY-MM-DD HH:MM:SS.SSS format, in the UTC time zone, and decode a variety of date formats and timestamps. UUIDs encode themselves as 16-bytes data blobs, and decode both 16-bytes data blobs and strings such as E621E1F8-C36C-495A-93FC-0C247A3E6E5F.

+ +

Those behaviors can be overridden:

+
protocol FetchableRecord {
+    static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { get }
+}
+
+protocol MutablePersistableRecord {
+    static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { get }
+    static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { get }
+}
+
+ +

See DatabaseDateDecodingStrategy, DatabaseDateEncodingStrategy, and DatabaseUUIDEncodingStrategy to learn about all available strategies.

+ +
+

:point_up: Note: there is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs, and uuid strings).

+
+

The userInfo Dictionary

+ +

Your Codable Records can be stored in the database, but they may also have other purposes. In this case, you may need to customize their implementations of Decodable.init(from:) and Encodable.encode(to:), depending on the context.

+ +

The standard way to provide such context is the userInfo dictionary. Implement those properties:

+
protocol FetchableRecord {
+    static var databaseDecodingUserInfo: [CodingUserInfoKey: Any] { get }
+}
+
+protocol MutablePersistableRecord {
+    static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] { get }
+}
+
+ +

For example, here is a Player type that customizes its decoding:

+
// A key that holds a decoder's name
+let decoderName = CodingUserInfoKey(rawValue: "decoderName")!
+
+struct Player: FetchableRecord, Decodable {
+    init(from decoder: Decoder) throws {
+        // Print the decoder name
+        let decoderName = decoder.userInfo[decoderName] as? String
+        print("Decoded from \(decoderName ?? "unknown decoder")")
+        ...
+    }
+}
+
+ +

You can have a specific decoding from JSON…

+
// prints "Decoded from JSON"
+let decoder = JSONDecoder()
+decoder.userInfo = [decoderName: "JSON"]
+let player = try decoder.decode(Player.self, from: jsonData)
+
+ +

… and another one from database rows:

+
extension Player: FetchableRecord {
+    static let databaseDecodingUserInfo: [CodingUserInfoKey: Any] = [decoderName: "database row"]
+}
+
+// prints "Decoded from database row"
+let player = try Player.fetchOne(db, ...)
+
+ +
+

:point_up: Note: make sure the databaseDecodingUserInfo and databaseEncodingUserInfo properties are explicitly declared as [CodingUserInfoKey: Any]. If they are not, the Swift compiler may silently miss the protocol requirement, resulting in sticky empty userInfo.

+
+

Tip: Use Coding Keys as Columns

+ +

If you declare an explicit CodingKeys enum (what is this?), you can instruct GRDB to use those coding keys as database columns:

+
struct Player: Codable, FetchableRecord, PersistableRecord {
+    var name: String
+    var score: Int
+
+    // Add ColumnExpression conformance
+    private enum CodingKeys: String, CodingKey, ColumnExpression {
+        case name, score
+    }
+}
+
+ +

This allows your record to build requests with the query interface:

+
extension Player {
+    static func filter(name: String) -> QueryInterfaceRequest<Player> {
+        return filter(CodingKeys.name == name)
+    }
+
+    static var maximumScore: QueryInterfaceRequest<Int> {
+        return select(max(CodingKeys.score), as: Int.self)
+    }
+}
+
+ +

Those requests can both fetch…

+
// Fetch values
+try dbQueue.read { db in
+    // SELECT * FROM player WHERE name = 'Arthur'
+    let arthur = try Player.filter(name: "Arthur").fetchOne(db) // Player?
+
+    // SELECT MAX(score) FROM player
+    let maxScore = try Player.maximumScore.fetchOne(db)         // Int?
+}
+
+ +

… and feed database observation tools such as RxGRDB:

+
// Observe changes
+Player.maximumScore.rx
+    .fetchOne(in: dbQueue)
+    .subscribe(onNext: { maxScore: Int? in
+        print("The maximum score has changed")
+    })
+
+

Record Class

+ +

Record is a class that is designed to be subclassed. It inherits its features from the FetchableRecord, TableRecord, and PersistableRecord protocols. On top of that, Record instances can compare against previous versions of themselves in order to avoid useless updates.

+ +

Record subclasses define their custom database relationship by overriding database methods. For example:

+
class Place: Record {
+    var id: Int64?
+    var title: String
+    var isFavorite: Bool
+    var coordinate: CLLocationCoordinate2D
+
+    init(id: Int64?, title: String, isFavorite: Bool, coordinate: CLLocationCoordinate2D) {
+        self.id = id
+        self.title = title
+        self.isFavorite = isFavorite
+        self.coordinate = coordinate
+        super.init()
+    }
+
+    /// The table name
+    override class var databaseTableName: String {
+        return "place"
+    }
+
+    /// The table columns
+    enum Columns: String, ColumnExpression {
+        case id, title, favorite, latitude, longitude
+    }
+
+    /// Creates a record from a database row
+    required init(row: Row) {
+        id = row[Columns.id]
+        title = row[Columns.title]
+        isFavorite = row[Columns.favorite]
+        coordinate = CLLocationCoordinate2D(
+            latitude: row[Columns.latitude],
+            longitude: row[Columns.longitude])
+        super.init(row: row)
+    }
+
+    /// The values persisted in the database
+    override func encode(to container: inout PersistenceContainer) {
+        container[Columns.id] = id
+        container[Columns.title] = title
+        container[Columns.favorite] = isFavorite
+        container[Columns.latitude] = coordinate.latitude
+        container[Columns.longitude] = coordinate.longitude
+    }
+
+    /// Update record ID after a successful insertion
+    override func didInsert(with rowID: Int64, for column: String?) {
+        id = rowID
+    }
+}
+
+

Record Comparison

+ +

Records can compare against other records, or against previous versions of themselves.

+ +

This helps avoiding costly UPDATE statements when a record has not been edited.

+ +

You can use the updateChanges method, available on the PersistableRecord protocol, which performs an update of the changed columns only (and does nothing if record has no change):

+
let oldPlayer = try Player.fetchOne(db, ...)
+var newPlayer = oldPlayer
+newPlayer.score = 100
+if try newPlayer.updateChanges(db, from: oldPlayer) {
+    print("player was modified, and updated in the database")
+} else {
+    print("player was not modified")
+}
+
+ +
+

:point_up: Note: The comparison is performed on the database representation of records. As long as your record type adopts a PersistableRecord protocol, you don’t need to care about Equatable.

+
+ +

The Record class is able to compare against itself, and knows if it has changes that have not been saved since it was last fetched or persisted:

+
// Record class only
+let player = try Player.fetchOne(db, ...)
+player.score = 100
+if try player.updateChanges(db) {
+    print("player was modified, and updated in the database")
+} else {
+    print("player was not modified")
+}
+
+ +

You can also use the databaseEquals method, which returns whether two records have the same database representation:

+
let oldPlayer: Player = ...
+var newPlayer: Player = ...
+if newPlayer.databaseEquals(oldPlayer) == false {
+    try newPlayer.save(db)
+}
+
+ +

Again, Record instances can compare against themselves, with the hasDatabaseChanges property:

+
// Record class only
+player.score = 100
+if player.hasDatabaseChanges {
+    try player.save(db)
+}
+
+ +

Record.hasDatabaseChanges is false after a Record instance has been fetched or saved into the database. Subsequent modifications may set it, or not: hasDatabaseChanges is based on value comparison. Setting a property to the same value does not set the changed flag:

+
let player = Player(name: "Barbara", score: 750)
+player.hasDatabaseChanges // true
+
+try player.insert(db)
+player.hasDatabaseChanges // false
+
+player.name = "Barbara"
+player.hasDatabaseChanges // false
+
+player.score = 1000
+player.hasDatabaseChanges // true
+player.databaseChanges    // ["score": 750]
+
+ +

For an efficient algorithm which synchronizes the content of a database table with a JSON payload, check JSONSynchronization.playground.

+

Record Customization Options

+ +

GRDB records come with many default behaviors, that are designed to fit most situations. Many of those defaults can be customized for your specific needs:

+ + + +

Codable Records have a few extra options:

+ + +

Conflict Resolution

+ +

Insertions and updates can create conflicts: for example, a query may attempt to insert a duplicate row that violates a unique index.

+ +

Those conflicts normally end with an error. Yet SQLite let you alter the default behavior, and handle conflicts with specific policies. For example, the INSERT OR REPLACE statement handles conflicts with the replace policy which replaces the conflicting row instead of throwing an error.

+ +

The five different policies are: abort (the default), replace, rollback, fail, and ignore.

+ +

SQLite let you specify conflict policies at two different places:

+ +
    +
  • In the definition of the database table:

    +
    // CREATE TABLE player (
    +//     id INTEGER PRIMARY KEY AUTOINCREMENT,
    +//     email TEXT UNIQUE ON CONFLICT REPLACE
    +// )
    +try db.create(table: "player") { t in
    +    t.autoIncrementedPrimaryKey("id")
    +    t.column("email", .text).unique(onConflict: .replace) // <--
    +}
    +
    +// Despite the unique index on email, both inserts succeed.
    +// The second insert replaces the first row:
    +try db.execute("INSERT INTO player (email) VALUES (?)", arguments: ["arthur@example.com"])
    +try db.execute("INSERT INTO player (email) VALUES (?)", arguments: ["arthur@example.com"])
    +
  • +
  • In each modification query:

    +
    // CREATE TABLE player (
    +//     id INTEGER PRIMARY KEY AUTOINCREMENT,
    +//     email TEXT UNIQUE
    +// )
    +try db.create(table: "player") { t in
    +    t.autoIncrementedPrimaryKey("id")
    +    t.column("email", .text).unique()
    +}
    +
    +// Again, despite the unique index on email, both inserts succeed.
    +try db.execute("INSERT OR REPLACE INTO player (email) VALUES (?)", arguments: ["arthur@example.com"])
    +try db.execute("INSERT OR REPLACE INTO player (email) VALUES (?)", arguments: ["arthur@example.com"])
    +
  • +
+ +

When you want to handle conflicts at the query level, specify a custom persistenceConflictPolicy in your type that adopts the PersistableRecord protocol. It will alter the INSERT and UPDATE queries run by the insert, update and save persistence methods:

+
protocol MutablePersistableRecord {
+    /// The policy that handles SQLite conflicts when records are
+    /// inserted or updated.
+    ///
+    /// This property is optional: its default value uses the ABORT
+    /// policy for both insertions and updates, so that GRDB generate
+    /// regular INSERT and UPDATE queries.
+    static var persistenceConflictPolicy: PersistenceConflictPolicy { get }
+}
+
+struct Player : MutablePersistableRecord {
+    static let persistenceConflictPolicy = PersistenceConflictPolicy(
+        insert: .replace,
+        update: .replace)
+}
+
+// INSERT OR REPLACE INTO player (...) VALUES (...)
+try player.insert(db)
+
+ +
+

:point_up: Note: the ignore policy does not play well at all with the didInsert method which notifies the rowID of inserted records. Choose your poison:

+ +
    +
  • if you specify the ignore policy in the database table definition, don’t implement the didInsert method: it will be called with some random id in case of failed insert.
  • +
  • if you specify the ignore policy at the query level, the didInsert method is never called.
  • +
+ +

:point_up: Note: The replace policy may have to delete rows so that inserts and updates can succeed. Those deletions are not reported to transaction observers (this might change in a future release of SQLite).

+
+

The Implicit RowID Primary Key

+ +

All SQLite tables have a primary key. Even when the primary key is not explicit:

+
// No explicit primary key
+try db.create(table: "event") { t in
+    t.column("message", .text)
+    t.column("date", .datetime)
+}
+
+// No way to define an explicit primary key
+try db.create(virtualTable: "book", using: FTS4()) { t in
+    t.column("title")
+    t.column("author")
+    t.column("body")
+}
+
+ +

The implicit primary key is stored in the hidden column rowid. Hidden means that SELECT * does not select it, and yet it can be selected and queried: SELECT *, rowid ... WHERE rowid = 1.

+ +

Some GRDB methods will automatically use this hidden column when a table has no explicit primary key:

+
// SELECT * FROM event WHERE rowid = 1
+let event = try Event.fetchOne(db, key: 1)
+
+// DELETE FROM book WHERE rowid = 1
+try Book.deleteOne(db, key: 1)
+
+

Exposing the RowID Column

+ +

By default, a record type that wraps a table without any explicit primary key doesn’t know about the hidden rowid column.

+ +

Without primary key, records don’t have any identity, and the persistence method can behave in undesired fashion: update() throws errors, save() always performs insertions and may break constraints, exists() is always false.

+ +

When SQLite won’t let you provide an explicit primary key (as in full-text tables, for example), you may want to make your record type fully aware of the hidden rowid column:

+ +
    +
  1. Have the databaseSelection static property (from the TableRecord protocol) return the hidden rowid column:

    +
    struct Event : TableRecord {
    +    static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
    +}
    +
    +// When you subclass Record, you need an override:
    +class Book : Record {
    +    override class var databaseSelection: [SQLSelectable] {
    +        return [AllColums(), Column.rowID]
    +    }
    +}
    +
    + +

    GRDB will then select the rowid column by default:

    +
    // SELECT *, rowid FROM event
    +let events = try Event.fetchAll(db)
    +
  2. +
  3. Have init(row:) from the FetchableRecord protocol consume the rowid column:

    +
    struct Event : FetchableRecord {
    +    var id: Int64?
    +
    +    init(row: Row) {
    +        id = row[Column.rowID]
    +    }
    +}
    +
    + +

    Your fetched records will then know their ids:

    +
    let event = try Event.fetchOne(db)!
    +event.id // some value
    +
  4. +
  5. Encode the rowid in encode(to:), and keep it in the didInsert(with:for:) method (both from the PersistableRecord and MutablePersistableRecord protocols):

    +
    struct Event : MutablePersistableRecord {
    +    var id: Int64?
    +
    +    func encode(to container: inout PersistenceContainer) {
    +        container[Column.rowID] = id
    +        container["message"] = message
    +        container["date"] = date
    +    }
    +
    +    mutating func didInsert(with rowID: Int64, for column: String?) {
    +        id = rowID
    +    }
    +}
    +
    + +

    You will then be able to track your record ids, update them, or check for their existence:

    +
    let event = Event(message: "foo", date: Date())
    +
    +// Insertion sets the record id:
    +try event.insert(db)
    +event.id // some value
    +
    +// Record can be updated:
    +event.message = "bar"
    +try event.update(db)
    +
    +// Record knows if it exists:
    +event.exists(db) // true
    +
  6. +
+

Beyond FetchableRecord

+ +

Some GRDB users eventually discover that the FetchableRecord protocol does not fit all situations. Use cases that are not well handled by FetchableRecord include:

+ +
    +
  • Your application needs polymorphic row decoding: it decodes some type or another, depending on the values contained in a database row.

  • +
  • Your application needs to decode rows with a context: each decoded value should be initialized with some extra value that does not come from the database.

  • +
  • Your application needs a record type that supports untrusted databases, and may fail at decoding database rows (throw an error when a row contains invalid values).

  • +
+ +

Since those use cases are not well handled by FetchableRecord, don’t try to implement them on top of this protocol: you’ll just fight the framework.

+ +

Instead, please have a look at the CustomizedDecodingOfDatabaseRows playground. You’ll run some sample code, and learn how to escape FetchableRecord when you need. And remember that leaving FetchableRecord will not deprive you of query interface requests and generally all SQL generation features of the TableRecord and PersistableRecord protocols.

+

Examples of Record Definitions

+ +

We will show below how to declare a record type for the following database table:

+
try dbQueue.write { db in
+    try db.create(table: "place") { t in
+        t.autoIncrementedPrimaryKey("id")
+        t.column("title", .text).notNull()
+        t.column("favorite", .boolean).notNull().defaults(to: false)
+        t.column("longitude", .double).notNull()
+        t.column("latitude", .double).notNull()
+    }
+}
+
+ +

Each one of the three examples below is correct. You will pick one or the other depending on your personal preferences and the requirements of your application:

+ +
+ Define a Codable struct, and adopt the record protocols you need + +This is the shortest way to define a record type. + +See the [Record Protocols Overview](#record-protocols-overview), and [Codable Records] for more information. + +”`swift +struct Place: Codable { + var id: Int64? + var title: String + var favorite: Bool + var latitude: CLLocationDegrees + var longitude: CLLocationDegrees + + var coordinate: CLLocationCoordinate2D { + get { + return CLLocationCoordinate2D( + latitude: latitude, + longitude: longitude) + } + set { + latitude = newValue.latitude + longitude = newValue.longitude + } + } +} + +// SQL generation +extension Place: TableRecord { } + +// Fetching methods +extension Place: FetchableRecord { } + +// Persistence methods +extension Place: MutablePersistableRecord { + /// Update record ID after a successful insertion + mutating func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } +} +“` + +
+ +
+ Define a plain struct, and adopt the record protocols you need + +See the [Record Protocols Overview](#record-protocols-overview) for more information. + +”`swift +struct Place { + var id: Int64? + var title: String + var isFavorite: Bool + var coordinate: CLLocationCoordinate2D +} + +// SQL generation +extension Place: TableRecord { + /// The table columns + enum Columns: String, ColumnExpression { + case id, title, favorite, latitude, longitude + } +} + +// Fetching methods +extension Place: FetchableRecord { + /// Creates a record from a database row + init(row: Row) { + id = row[Columns.id] + title = row[Columns.title] + isFavorite = row[Columns.favorite] + coordinate = CLLocationCoordinate2D( + latitude: row[Columns.latitude], + longitude: row[Columns.longitude]) + } +} + +// Persistence methods +extension Place: MutablePersistableRecord { + /// The values persisted in the database + func encode(to container: inout PersistenceContainer) { + container[Columns.id] = id + container[Columns.title] = title + container[Columns.favorite] = isFavorite + container[Columns.latitude] = coordinate.latitude + container[Columns.longitude] = coordinate.longitude + } + + /// Update record ID after a successful insertion + mutating func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } +} +“` + +
+ +
+ Subclass the Record class + +See the [Record class](#record-class) for more information. + +”`swift +class Place: Record { + var id: Int64? + var title: String + var isFavorite: Bool + var coordinate: CLLocationCoordinate2D + + init(id: Int64?, title: String, isFavorite: Bool, coordinate: CLLocationCoordinate2D) { + self.id = id + self.title = title + self.isFavorite = isFavorite + self.coordinate = coordinate + super.init() + } + + /// The table name + override class var databaseTableName: String { + return “place” + } + + /// The table columns + enum Columns: String, ColumnExpression { + case id, title, favorite, latitude, longitude + } + + /// Creates a record from a database row + required init(row: Row) { + id = row[Columns.id] + title = row[Columns.title] + isFavorite = row[Columns.favorite] + coordinate = CLLocationCoordinate2D( + latitude: row[Columns.latitude], + longitude: row[Columns.longitude]) + super.init(row: row) + } + + /// The values persisted in the database + override func encode(to container: inout PersistenceContainer) { + container[Columns.id] = id + container[Columns.title] = title + container[Columns.favorite] = isFavorite + container[Columns.latitude] = coordinate.latitude + container[Columns.longitude] = coordinate.longitude + } + + /// Update record ID after a successful insertion + override func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } +} +“` + +
+

List of Record Methods

+ +

This is the list of record methods, along with their required protocols. The Record class adopts all these protocols, and adds a few extra methods.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodProtocolsNotes
Core Methods
init(row:)FetchableRecord
Type.databaseTableNameTableRecord
Type.databaseSelectionTableRecord*
Type.persistenceConflictPolicyPersistableRecord*
record.encode(to:)PersistableRecord
record.didInsert(with:for:)PersistableRecord
Insert and Update Records
record.insert(db)PersistableRecord
record.save(db)PersistableRecord
record.update(db)PersistableRecord
record.update(db, columns:...)PersistableRecord
record.updateChanges(db, from:...)PersistableRecord*
record.updateChanges(db)Record*
Delete Records
record.delete(db)PersistableRecord
Type.deleteOne(db, key:...)PersistableRecord¹
Type.deleteAll(db)PersistableRecord
Type.deleteAll(db, keys:...)PersistableRecord¹
Type.filter(...).deleteAll(db)PersistableRecord²
Check Record Existence
record.exists(db)PersistableRecord
Convert Record to Dictionary
record.databaseDictionaryPersistableRecord
Count Records
Type.fetchCount(db)TableRecord
Type.filter(...).fetchCount(db)TableRecord²
Fetch Record Cursors
Type.fetchCursor(db)FetchableRecord & TableRecord
Type.fetchCursor(db, keys:...)FetchableRecord & TableRecord¹
Type.fetchCursor(db, sql)FetchableRecord³
Type.fetchCursor(statement)FetchableRecord⁴
Type.filter(...).fetchCursor(db)FetchableRecord & TableRecord²
Fetch Record Arrays
Type.fetchAll(db)FetchableRecord & TableRecord
Type.fetchAll(db, keys:...)FetchableRecord & TableRecord¹
Type.fetchAll(db, sql)FetchableRecord³
Type.fetchAll(statement)FetchableRecord⁴
Type.filter(...).fetchAll(db)FetchableRecord & TableRecord²
Fetch Individual Records
Type.fetchOne(db)FetchableRecord & TableRecord
Type.fetchOne(db, key:...)FetchableRecord & TableRecord¹
Type.fetchOne(db, sql)FetchableRecord³
Type.fetchOne(statement)FetchableRecord⁴
Type.filter(...).fetchOne(db)FetchableRecord & TableRecord²
Record Comparison
record.databaseEquals(...)PersistableRecord
record.databaseChanges(from:...)PersistableRecord
record.updateChanges(db, from:...)PersistableRecord
record.hasDatabaseChangesRecord
record.databaseChangesRecord
record.updateChanges(db)Record
+ +

¹ All unique keys are supported: primary keys (single-column, composite, implicit RowID) and unique indexes:

+
try Player.fetchOne(db, key: 1)                               // Player?
+try Player.fetchOne(db, key: ["email": "arthur@example.com"]) // Player?
+try Country.fetchAll(db, keys: ["FR", "US"])                  // [Country]
+
+ +

² See Fetch Requests:

+
let request = Player.filter(emailColumn != nil).order(nameColumn)
+let players = try request.fetchAll(db)  // [Player]
+let count = try request.fetchCount(db)  // Int
+
+ +

³ See SQL queries:

+
let player = try Player.fetchOne("SELECT * FROM player WHERE id = ?", arguments: [1]) // Player?
+
+ +

⁴ See Prepared Statements:

+
let statement = try db.makeSelectStatement("SELECT * FROM player WHERE id = ?")
+let player = try Player.fetchOne(statement, arguments: [1])  // Player?
+
+

The Query Interface

+ +

The query interface lets you write pure Swift instead of SQL:

+
try dbQueue.write { db in
+    // Update database schema
+    try db.create(table: "wine") { t in ... }
+
+    // Fetch records
+    let wines = try Wine.filter(origin == "Burgundy").order(price).fetchAll(db)
+
+    // Count
+    let count = try Wine.filter(color == Color.red).fetchCount(db)
+
+    // Delete
+    try Wine.filter(corked == true).deleteAll(db)
+}
+
+ +

You need to open a database connection before you can query the database.

+ +

Please bear in mind that the query interface can not generate all possible SQL queries. You may also prefer writing SQL, and this is just OK. From little snippets to full queries, your SQL skills are welcome:

+
try dbQueue.write { db in
+    // Update database schema (with SQL)
+    try db.execute("CREATE TABLE wine (...)")
+
+    // Fetch records (with SQL)
+    let wines = try Wine.fetchAll(db,
+        "SELECT * FROM wine WHERE origin = ? ORDER BY price",
+        arguments: ["Burgundy"])
+
+    // Count (with an SQL snippet)
+    let count = try Wine
+        .filter(sql: "color = ?", arguments: [Color.red])
+        .fetchCount(db)
+
+    // Delete (with SQL)
+    try db.execute("DELETE FROM wine WHERE corked")
+}
+
+ +

So don’t miss the SQL API.

+ + +

Database Schema

+ +

Once granted with a database connection, you can setup your database schema without writing SQL:

+ + +

Create Tables

+
// CREATE TABLE place (
+//   id INTEGER PRIMARY KEY AUTOINCREMENT,
+//   title TEXT,
+//   favorite BOOLEAN NOT NULL DEFAULT 0,
+//   latitude DOUBLE NOT NULL,
+//   longitude DOUBLE NOT NULL
+// )
+try db.create(table: "place") { t in
+    t.autoIncrementedPrimaryKey("id")
+    t.column("title", .text)
+    t.column("favorite", .boolean).notNull().defaults(to: false)
+    t.column("longitude", .double).notNull()
+    t.column("latitude", .double).notNull()
+}
+
+ +

The create(table:) method covers nearly all SQLite table creation features. For virtual tables, see Full-Text Search, or use raw SQL.

+ +

SQLite itself has many reference documents about table creation: CREATE TABLE, Datatypes In SQLite Version 3, SQLite Foreign Key Support, ON CONFLICT, The WITHOUT ROWID Optimization.

+ +

Configure table creation:

+
// CREATE TABLE example ( ... )
+try db.create(table: "example") { t in ... }
+
+// CREATE TEMPORARY TABLE example IF NOT EXISTS (
+try db.create(table: "example", temporary: true, ifNotExists: true) { t in
+
+ +
+

:bulb: Tip: database table names should be singular, and camel-cased. Make them look like Swift identifiers: place, country, postalAddress, ‘httpRequest’.

+ +

This will help you using Associations when you need them. Database table names that follow another naming convention are totally OK, but you will need to perform extra configuration.

+
+ +

Add regular columns with their name and eventual type (text, integer, double, numeric, boolean, blob, date and datetime) - see SQLite data types:

+
// CREATE TABLE example (
+//   a,
+//   name TEXT,
+//   creationDate DATETIME,
+try db.create(table: "example") { t in
+    t.column("a")
+    t.column("name", .text)
+    t.column("creationDate", .datetime)
+
+ +

Define not null columns, and set default values:

+
    // email TEXT NOT NULL,
+    t.column("email", .text).notNull()
+
+    // name TEXT NOT NULL DEFAULT 'Anonymous',
+    t.column("name", .text).notNull().defaults(to: "Anonymous")
+
+ +

Use an individual column as primary, unique, or foreign key. When defining a foreign key, the referenced column is the primary key of the referenced table (unless you specify otherwise):

+
    // id INTEGER PRIMARY KEY AUTOINCREMENT,
+    t.autoIncrementedPrimaryKey("id")
+
+    // uuid TEXT PRIMARY KEY,
+    t.column("uuid", .text).primaryKey()
+
+    // email TEXT UNIQUE,
+    t.column("email", .text).unique()
+
+    // countryCode TEXT REFERENCES country(code) ON DELETE CASCADE,
+    t.column("countryCode", .text).references("country", onDelete: .cascade)
+
+ +
+

:bulb: Tip: when you need an integer primary key that automatically generates unique values, it is highly recommended that you use the autoIncrementedPrimaryKey method:

+
try db.create(table: "example") { t in
+    t.autoIncrementedPrimaryKey("id")
+    ...
+}
+
+ +

The reason for this recommendation is that auto-incremented primary keys prevent the reuse of ids. This prevents your app or database observation tools to think that a row was updated, when it was actually deleted, then replaced. Depending on your application needs, this may be OK. Or not.

+
+ +

Create an index on the column:

+
    t.column("score", .integer).indexed()
+
+ +

For extra index options, see Create Indexes below.

+ +

Perform integrity checks on individual columns, and SQLite will only let conforming rows in. In the example below, the $0 closure variable is a column which lets you build any SQL expression.

+
    // name TEXT CHECK (LENGTH(name) > 0)
+    // score INTEGER CHECK (score > 0)
+    t.column("name", .text).check { length($0) > 0 }
+    t.column("score", .integer).check(sql: "score > 0")
+
+ +

Other table constraints can involve several columns:

+
    // PRIMARY KEY (a, b),
+    t.primaryKey(["a", "b"])
+
+    // UNIQUE (a, b) ON CONFLICT REPLACE,
+    t.uniqueKey(["a", "b"], onConfict: .replace)
+
+    // FOREIGN KEY (a, b) REFERENCES parents(c, d),
+    t.foreignKey(["a", "b"], references: "parents")
+
+    // CHECK (a + b < 10),
+    t.check(Column("a") + Column("b") < 10)
+
+    // CHECK (a + b < 10)
+    t.check(sql: "a + b < 10")
+}
+
+

Modify Tables

+ +

SQLite lets you rename tables, and add columns to existing tables:

+
// ALTER TABLE referer RENAME TO referrer
+try db.rename(table: "referer", to: "referrer")
+
+// ALTER TABLE player ADD COLUMN url TEXT
+try db.alter(table: "player") { t in
+    t.add(column: "url", .text)
+}
+
+ +
+

:point_up: Note: SQLite restricts the possible table alterations, and may require you to recreate dependent triggers or views. See the documentation of the ALTER TABLE for details. See Advanced Database Schema Changes for a way to lift restrictions.

+
+

Drop Tables

+ +

Drop tables with the drop(table:) method:

+
try db.drop(table: "obsolete")
+
+

Create Indexes

+ +

Create indexes with the create(index:) method:

+
// CREATE UNIQUE INDEX byEmail ON users(email)
+try db.create(index: "byEmail", on: "users", columns: ["email"], unique: true)
+
+ +

Relevant SQLite documentation:

+ + +

Requests

+ +

The query interface requests let you fetch values from the database:

+
let request = Player.filter(emailColumn != nil).order(nameColumn)
+let players = try request.fetchAll(db)  // [Player]
+let count = try request.fetchCount(db)  // Int
+
+ +

All requests start from a type that adopts the TableRecord protocol, such as a Record subclass (see Records):

+
class Player : Record { ... }
+
+ +

Declare the table columns that you want to use for filtering, or sorting:

+
let idColumn = Column("id")
+let nameColumn = Column("name")
+
+ +

You can also declare column enums, if you prefer:

+
// Columns.id and Columns.name can be used just as
+// idColumn and nameColumn declared above.
+enum Columns: String, ColumnExpression {
+    case id
+    case name
+}
+
+ +

You can now build requests with the following methods: all, none, select, distinct, filter, matching, group, having, order, reversed, limit. All those methods return another request, which you can further refine by applying another method: Player.select(...).filter(...).order(...).

+ +
    +
  • all(), none(): the requests for all rows, or no row.

    +
    // SELECT * FROM player
    +Player.all()
    +
    + +

    The hidden rowid column can be selected as well when you need it.

  • +
  • select(...) and select(..., as:) define the selected columns. See Columns Selected by a Request.

    +
    // SELECT name FROM player
    +Player.select(nameColumn, as: String.self)
    +
  • +
  • distinct() performs uniquing.

    +
    // SELECT DISTINCT name FROM player
    +Player.select(nameColumn, as: String.self).distinct()
    +
  • +
  • filter(expression) applies conditions.

    +
    // SELECT * FROM player WHERE id IN (1, 2, 3)
    +Player.filter([1,2,3].contains(idColumn))
    +
    +// SELECT * FROM player WHERE (name IS NOT NULL) AND (height > 1.75)
    +Player.filter(nameColumn != nil && heightColumn > 1.75)
    +
  • +
  • filter(key:) and filter(keys:) apply conditions on primary keys and unique keys:

    +
    // SELECT * FROM player WHERE id = 1
    +Player.filter(key: 1)
    +
    +// SELECT * FROM country WHERE isoCode IN ('FR', 'US')
    +Country.filter(keys: ["FR", "US"])
    +
    +// SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR'
    +Citizenship.filter(key: ["citizenId": 1, "countryCode": "FR"])
    +
    +// SELECT * FROM player WHERE email = 'arthur@example.com'
    +Player.filter(key: ["email": "arthur@example.com"])
    +
  • +
  • matching(pattern) performs full-text search.

    +
    // SELECT * FROM document WHERE document MATCH 'sqlite database'
    +let pattern = FTS3Pattern(matchingAllTokensIn: "SQLite database")
    +Document.matching(pattern)
    +
    + +

    When the pattern is nil, no row will match.

  • +
  • group(expression, ...) groups rows.

    +
    // SELECT name, MAX(score) FROM player GROUP BY name
    +Player
    +    .select(nameColumn, max(scoreColumn))
    +    .group(nameColumn)
    +
  • +
  • having(expression) applies conditions on grouped rows.

    +
    // SELECT team, MAX(score) FROM player GROUP BY team HAVING MIN(score) >= 1000
    +Player
    +    .select(teamColumn, max(scoreColumn))
    +    .group(teamColumn)
    +    .having(min(scoreColumn) >= 1000)
    +
  • +
  • order(ordering, ...) sorts.

    +
    // SELECT * FROM player ORDER BY name
    +Player.order(nameColumn)
    +
    +// SELECT * FROM player ORDER BY score DESC, name
    +Player.order(scoreColumn.desc, nameColumn)
    +
    + +

    Each order call clears any previous ordering:

    +
    // SELECT * FROM player ORDER BY name
    +Player.order(scoreColumn).order(nameColumn)
    +
    + +

    orderByPrimaryKey() sorts by primary key:

    +
    // SELECT * FROM player ORDER BY id
    +Player.orderByPrimaryKey()
    +
    +// SELECT * FROM country ORDER BY code
    +Country.orderByPrimaryKey()
    +
    +// SELECT * FROM citizenship ORDER BY citizenId, countryCode
    +Citizenship.orderByPrimaryKey()
    +
  • +
  • reversed() reverses the eventual orderings.

    +
    // SELECT * FROM player ORDER BY score ASC, name DESC
    +Player.order(scoreColumn.desc, nameColumn).reversed()
    +
    + +

    If no ordering was already specified, this method has no effect:

    +
    // SELECT * FROM player
    +Player.all().reversed()
    +
  • +
  • limit(limit, offset: offset) limits and pages results.

    +
    // SELECT * FROM player LIMIT 5
    +Player.limit(5)
    +
    +// SELECT * FROM player LIMIT 5 OFFSET 10
    +Player.limit(5, offset: 10)
    +
  • +
+ +

You can refine requests by chaining those methods:

+
// SELECT * FROM player WHERE (email IS NOT NULL) ORDER BY name
+Player.order(nameColumn).filter(emailColumn != nil)
+
+ +

The select, order, group, and limit methods ignore and replace previously applied selection, orderings, grouping, and limits. On the opposite, filter, matching, and having methods extend the query:

+
Player                          // SELECT * FROM player
+    .filter(nameColumn != nil)  // WHERE (name IS NOT NULL)
+    .filter(emailColumn != nil) //        AND (email IS NOT NULL)
+    .order(nameColumn)          // - ignored -
+    .reversed()                 // - ignored -
+    .order(scoreColumn)         // ORDER BY score
+    .limit(20, offset: 40)      // - ignored -
+    .limit(10)                  // LIMIT 10
+
+ +

Raw SQL snippets are also accepted, with eventual arguments:

+
// SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate)
+Player
+    .select(sql: "DATE(creationDate), COUNT(*)")
+    .filter(sql: "name = ?", arguments: ["Arthur"])
+    .group(sql: "DATE(creationDate)")
+
+

Columns Selected by a Request

+ +

By default, query interface requests select all columns:

+
// SELECT * FROM player
+let request = Player.all()
+
+ +

The selection can be changed for each individual requests, or for all requests built from a given type.

+ +

The select(...) and select(..., as:) methods change the selection of a single request (see Fetching from Requests for detailed information):

+
let request = Player.select(max(Column("score")))
+let maxScore: Int? = try Int.fetchOne(db, request)
+
+ +

The default selection for a record type is controlled by the databaseSelection property:

+
struct RestrictedPlayer : TableRecord {
+    static let databaseTableName = "player"
+    static let databaseSelection: [SQLSelectable] = [Column("id"), Column("name")]
+}
+
+struct ExtendedPlayer : TableRecord {
+    static let databaseTableName = "player"
+    static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
+}
+
+// SELECT id, name FROM player
+let request = RestrictedPlayer.all()
+
+// SELECT *, rowid FROM player
+let request = ExtendedPlayer.all()
+
+ +
+

:point_up: Note: make sure the databaseSelection property is explicitly declared as [SQLSelectable]. If it is not, the Swift compiler may silently miss the protocol requirement, resulting in sticky SELECT * requests. To verify your setup, see the How do I print a request as SQL? FAQ.

+
+

Expressions

+ +

Feed requests with SQL expressions built from your Swift code:

+

SQL Operators

+ +
    +
  • =, <>, <, <=, >, >=, IS, IS NOT

    + +

    Comparison operators are based on the Swift operators ==, !=, ===, !==, <, <=, >, >=:

    +
    // SELECT * FROM player WHERE (name = 'Arthur')
    +Player.filter(nameColumn == "Arthur")
    +
    +// SELECT * FROM player WHERE (name IS NULL)
    +Player.filter(nameColumn == nil)
    +
    +// SELECT * FROM player WHERE (score IS 1000)
    +Player.filter(scoreColumn === 1000)
    +
    +// SELECT * FROM rectangle WHERE width < height
    +Rectangle.filter(widthColumn < heightColumn)
    +
    + +
    +

    :point_up: Note: SQLite string comparison, by default, is case-sensitive and not Unicode-aware. See string comparison if you need more control.

    +
  • +
  • *, /, +, -

    + +

    SQLite arithmetic operators are derived from their Swift equivalent:

    +
    // SELECT ((temperature * 1.8) + 32) AS farenheit FROM planet
    +Planet.select((temperatureColumn * 1.8 + 32).aliased("farenheit"))
    +
    + +
    +

    :point_up: Note: an expression like nameColumn + "rrr" will be interpreted by SQLite as a numerical addition (with funny results), not as a string concatenation.

    +
  • +
  • AND, OR, NOT

    + +

    The SQL logical operators are derived from the Swift &&, || and !:

    +
    // SELECT * FROM player WHERE ((NOT verified) OR (score < 1000))
    +Player.filter(!verifiedColumn || scoreColumn < 1000)
    +
    + +

    When you want to join a sequence of expressions with AND or OR operators, use joined(operator:):

    +
    // SELECT * FROM player WHERE (verified AND (score >= 1000) AND (name IS NOT NULL))
    +let conditions = [
    +    verifiedColumn,
    +    scoreColumn >= 1000,
    +    nameColumn != nil]
    +Player.filter(conditions.joined(operator: .and))
    +
    + +

    When the sequence is empty, joined(operator: .and) returns true, and joined(operator: .or) returns false:

    +
    // SELECT * FROM player WHERE 1
    +Player.filter([].joined(operator: .and))
    +
    +// SELECT * FROM player WHERE 0
    +Player.filter([].joined(operator: .or))
    +
  • +
  • BETWEEN, IN, NOT IN

    + +

    To check inclusion in a Swift sequence (array, set, range…), call the contains method:

    +
    // SELECT * FROM player WHERE id IN (1, 2, 3)
    +Player.filter([1, 2, 3].contains(idColumn))
    +
    +// SELECT * FROM player WHERE id NOT IN (1, 2, 3)
    +Player.filter(![1, 2, 3].contains(idColumn))
    +
    +// SELECT * FROM player WHERE score BETWEEN 0 AND 1000
    +Player.filter((0...1000).contains(scoreColumn))
    +
    +// SELECT * FROM player WHERE (score >= 0) AND (score < 1000)
    +Player.filter((0..<1000).contains(scoreColumn))
    +
    +// SELECT * FROM player WHERE initial BETWEEN 'A' AND 'N'
    +Player.filter(("A"..."N").contains(initialColumn))
    +
    +// SELECT * FROM player WHERE (initial >= 'A') AND (initial < 'N')
    +Player.filter(("A"..<"N").contains(initialColumn))
    +
    + +
    +

    :point_up: Note: SQLite string comparison, by default, is case-sensitive and not Unicode-aware. See string comparison if you need more control.

    +
  • +
  • LIKE

    + +

    The SQLite LIKE operator is available as the like method:

    +
    // SELECT * FROM player WHERE (email LIKE '%@example.com')
    +Player.filter(emailColumn.like("%@example.com"))
    +
    + +
    +

    :point_up: Note: the SQLite LIKE operator is case-insensitive but not Unicode-aware. For example, the expression 'a' LIKE 'A' is true but 'æ' LIKE 'Æ' is false.

    +
  • +
  • MATCH

    + +

    The full-text MATCH operator is available through FTS3Pattern (for FTS3 and FTS4 tables) and FTS5Pattern (for FTS5):

    + +

    FTS3 and FTS4:

    +
    let pattern = FTS3Pattern(matchingAllTokensIn: "SQLite database")
    +
    +// SELECT * FROM document WHERE document MATCH 'sqlite database'
    +Document.matching(pattern)
    +
    +// SELECT * FROM document WHERE content MATCH 'sqlite database'
    +Document.filter(contentColumn.match(pattern))
    +
    + +

    FTS5:

    +
    let pattern = FTS5Pattern(matchingAllTokensIn: "SQLite database")
    +
    +// SELECT * FROM document WHERE document MATCH 'sqlite database'
    +Document.matching(pattern)
    +
  • +
+

SQL Functions

+ +
    +
  • ABS, AVG, COUNT, LENGTH, MAX, MIN, SUM:

    + +

    Those are based on the abs, average, count, length, max, min and sum Swift functions:

    +
    // SELECT MIN(score), MAX(score) FROM player
    +Player.select(min(scoreColumn), max(scoreColumn))
    +
    +// SELECT COUNT(name) FROM player
    +Player.select(count(nameColumn))
    +
    +// SELECT COUNT(DISTINCT name) FROM player
    +Player.select(count(distinct: nameColumn))
    +
  • +
  • IFNULL

    + +

    Use the Swift ?? operator:

    +
    // SELECT IFNULL(name, 'Anonymous') FROM player
    +Player.select(nameColumn ?? "Anonymous")
    +
    +// SELECT IFNULL(name, email) FROM player
    +Player.select(nameColumn ?? emailColumn)
    +
  • +
  • LOWER, UPPER

    + +

    The query interface does not give access to those SQLite functions. Nothing against them, but they are not unicode aware.

    + +

    Instead, GRDB extends SQLite with SQL functions that call the Swift built-in string functions capitalized, lowercased, uppercased, localizedCapitalized, localizedLowercased and localizedUppercased:

    +
    Player.select(nameColumn.uppercased())
    +
    + +
    +

    :point_up: Note: When comparing strings, you’d rather use a collation:

    +
    let name: String = ...
    +
    +// Not recommended
    +nameColumn.uppercased() == name.uppercased()
    +
    +// Better
    +nameColumn.collating(.caseInsensitiveCompare) == name
    +
    +
  • +
  • Custom SQL functions and aggregates

    + +

    You can apply your own custom SQL functions and aggregates:

    +
    let f = DatabaseFunction("f", ...)
    +
    +// SELECT f(name) FROM player
    +Player.select(f.apply(nameColumn))
    +
  • +
+

Fetching from Requests

+ +

Once you have a request, you can fetch the records at the origin of the request:

+
// Some request based on `Player`
+let request = Player.filter(...)... // QueryInterfaceRequest<Player>
+
+// Fetch players:
+try request.fetchCursor(db) // A Cursor of Player
+try request.fetchAll(db)    // [Player]
+try request.fetchOne(db)    // Player?
+
+ +

For example:

+
let allPlayers = try Player.fetchAll(db)                            // [Player]
+let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db) // Player?
+
+ +

See fetching methods for information about the fetchCursor, fetchAll and fetchOne methods.

+ +

You sometimes want to fetch other values.

+ +

The simplest way is to use the request as an argument to a fetching method of the desired type:

+
// Fetch an Int
+let request = Player.select(max(scoreColumn))
+let maxScore = try Int.fetchOne(db, request) // Int?
+
+// Fetch a Row
+let request = Player.select(min(scoreColumn), max(scoreColumn))
+let row = try Row.fetchOne(db, request)!     // Row
+let minScore = row[0] as Int?
+let maxScore = row[1] as Int?
+
+ +

When you also want to use database observation tools such as FetchedRecordsController or RxGRDB, you have to go one step further, and change the type of the request:

+ +
    +
  • When you change the selection, prefer the select(..., as:) method:

    +
    // A request of Int
    +let request = Player.select(max(scoreColumn), as: Int.self)
    +
    +// Simple fetch
    +let maxScore = try dbQueue.read { db in
    +    try request.fetchOne(db) // Int?
    +}
    +
    +// Observe with RxGRDB
    +request.rx
    +    .fetchOne(in: dbQueue)
    +    .subscribe(onNext: { maxScore: Int? in
    +        print("The maximum score has changed")
    +    })
    +
  • +
  • Otherwise, use asRequest(of:). Here is an example that uses Associations:

    +
    struct BookInfo: FetchableRecord, Decodable {
    +    var book: Book
    +    var author: Author
    +}
    +
    +// A request of BookInfo
    +let request = Book
    +    .including(required: Book.author)
    +    .asRequest(of: BookInfo.self)
    +
    +// Simple fetch
    +let bookInfos = try dbQueue.read { db in
    +    try request.fetchAll(db) // [BookInfo]
    +}
    +
    +// Observe with FetchedRecordsController
    +let controller = FetchedRecordsController(
    +    dbQueue,
    +    request: request,
    +    isSameRecord: { (bookInfo1, bookInfo2) in
    +        bookInfo1.book.id == bookInfo2.book.id
    +    })
    +
  • +
+

Fetching By Key

+ +

Fetching records according to their primary key is a very common task. It has a shortcut which accepts any single-column primary key:

+
// SELECT * FROM player WHERE id = 1
+try Player.fetchOne(db, key: 1)              // Player?
+
+// SELECT * FROM player WHERE id IN (1, 2, 3)
+try Player.fetchAll(db, keys: [1, 2, 3])     // [Player]
+
+// SELECT * FROM country WHERE isoCode = 'FR'
+try Country.fetchOne(db, key: "FR")          // Country?
+
+// SELECT * FROM country WHERE isoCode IN ('FR', 'US')
+try Country.fetchAll(db, keys: ["FR", "US"]) // [Country]
+
+ +

When the table has no explicit primary key, GRDB uses the hidden rowid column:

+
// SELECT * FROM document WHERE rowid = 1
+try Document.fetchOne(db, key: 1)            // Document?
+
+ +

For multiple-column primary keys and unique keys defined by unique indexes, provide a dictionary:

+
// SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR'
+try Citizenship.fetchOne(db, key: ["citizenId": 1, "countryCode": "FR"]) // Citizenship?
+
+// SELECT * FROM player WHERE email = 'arthur@example.com'
+try Player.fetchOne(db, key: ["email": "arthur@example.com"])              // Player?
+
+ +

When you want to build a request and plan to fetch from it later, use the filter(key:) and filter(keys:) methods:

+
// SELECT * FROM player WHERE id = 1
+let request = Player.filter(key: 1)
+let player = try request.fetchOne(db)    // Player?
+
+// SELECT * FROM player WHERE id IN (1, 2, 3)
+let request = Player.filter(keys: [1, 2, 3])
+let players = try request.fetchAll(db)   // [Player]
+
+// SELECT * FROM country WHERE isoCode = 'FR'
+let request = Country.filter(key: "FR")
+let country = try request.fetchOne(db)   // Country?
+
+// SELECT * FROM country WHERE isoCode IN ('FR', 'US')
+let request = Country.filter(keys: ["FR", "US"])
+let countries = try request.fetchAll(db) // [Country]
+
+// SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR'
+let request = Citizenship.filter(key: ["citizenId": 1, "countryCode": "FR"])
+let citizenship = request.fetchOne(db)   // Citizenship?
+
+// SELECT * FROM player WHERE email = 'arthur@example.com'
+let request = Player.filter(key: ["email": "arthur@example.com"])
+let player = try request.fetchOne(db)    // Player?
+
+ +

Those requests help observing the database with FetchedRecordsController or RxGRDB:

+
Player.filter(key: 1).rx
+    .fetchOne(in: dbQueue)
+    .subscribe(onNext: { player: Player? in
+        print("Player 1 has changed")
+    })
+
+

Fetching Aggregated Values

+ +

Requests can count. The fetchCount() method returns the number of rows that would be returned by a fetch request:

+
// SELECT COUNT(*) FROM player
+let count = try Player.fetchCount(db) // Int
+
+// SELECT COUNT(*) FROM player WHERE email IS NOT NULL
+let count = try Player.filter(emailColumn != nil).fetchCount(db)
+
+// SELECT COUNT(DISTINCT name) FROM player
+let count = try Player.select(nameColumn).distinct().fetchCount(db)
+
+// SELECT COUNT(*) FROM (SELECT DISTINCT name, score FROM player)
+let count = try Player.select(nameColumn, scoreColumn).distinct().fetchCount(db)
+
+ +

Other aggregated values can also be selected and fetched (see SQL Functions):

+
let request = Player.select(max(scoreColumn))
+let maxScore = try Int.fetchOne(db, request) // Int?
+
+let request = Player.select(min(scoreColumn), max(scoreColumn))
+let row = try Row.fetchOne(db, request)!     // Row
+let minScore = row[0] as Int?
+let maxScore = row[1] as Int?
+
+

Delete Requests

+ +

Requests can delete records, with the deleteAll() method:

+
// DELETE FROM player WHERE email IS NULL
+let request = Player.filter(emailColumn == nil)
+try request.deleteAll(db)
+
+ +
+

:point_up: Note Deletion methods are only available for records that adopts the PersistableRecord protocol.

+
+ +

Deleting records according to their primary key is also quite common. It has a shortcut which accepts any single-column primary key:

+
// DELETE FROM player WHERE id = 1
+try Player.deleteOne(db, key: 1)
+
+// DELETE FROM player WHERE id IN (1, 2, 3)
+try Player.deleteAll(db, keys: [1, 2, 3])
+
+// DELETE FROM country WHERE isoCode = 'FR'
+try Country.deleteOne(db, key: "FR")
+
+// DELETE FROM country WHERE isoCode IN ('FR', 'US')
+try Country.deleteAll(db, keys: ["FR", "US"])
+
+ +

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)
+
+ +

For multiple-column primary keys and unique keys defined by unique indexes, provide a dictionary:

+
// DELETE FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR'
+try Citizenship.deleteOne(db, key: ["citizenId": 1, "countryCode": "FR"])
+
+// DELETE FROM player WHERE email = 'arthur@example.com'
+Player.deleteOne(db, key: ["email": "arthur@example.com"])
+
+

Custom Requests

+ +

Until now, we have seen requests created from any type that adopts the TableRecord protocol:

+
let request = Player.all()  // QueryInterfaceRequest<Player>
+
+ +

Those requests of type QueryInterfaceRequest can fetch and count:

+
try request.fetchCursor(db) // A Cursor of Player
+try request.fetchAll(db)    // [Player]
+try request.fetchOne(db)    // Player?
+try request.fetchCount(db)  // Int
+
+ +

When the query interface can not generate the SQL you need, you can still fallback to raw SQL:

+
// Custom SQL is always welcome
+try Player.fetchAll(db, "SELECT ...")   // [Player]
+
+ +

But you may prefer to bring some elegance back in, and build custom requests:

+
// No custom SQL in sight
+try Player.customRequest().fetchAll(db) // [Player]
+
+ +

Custom requests also grant FetchedRecordsController and RxGRDB the ability to observe the database:

+
Player.customRequest(...).rx
+    .fetchAll(in: dbQueue)
+    .subscribe(onNext: { players: [Player] in
+        print("Players have changed")
+    })
+
+ + +

FetchRequest Protocol

+ +

FetchRequest is the protocol for all requests that run from a single select statement, and know how fetched rows should be interpreted:

+
protocol FetchRequest {
+    /// The type that tells how fetched rows should be decoded
+    associatedtype RowDecoder
+
+    /// A tuple that contains a prepared statement, and an eventual row adapter.
+    func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?)
+
+    /// The number of rows fetched by the request.
+    func fetchCount(_ db: Database) throws -> Int
+
+    /// The database region that the request looks into.
+    func databaseRegion(_ db: Database) throws -> DatabaseRegion
+}
+
+ +

When the RowDecoder associated type is Row, or a value, or a type that conforms to FetchableRecord, the request can fetch: see Fetching From Custom Requests below.

+ +

The prepare method returns a prepared statement and an optional row adapter. The prepared statement tells which SQL query should be executed. The row adapter helps presenting the fetched rows in the way expected by the row decoders (see row adapter).

+ +

The fetchCount method has a default implementation that builds a correct but naive SQL query from the statement returned by prepare: SELECT COUNT(*) FROM (...). Adopting types can refine the counting SQL by customizing their fetchCount implementation.

+ +

The databaseRegion method is involved in database observation. It is given a default implementation, based on the statement returned by prepare. For more information, see DatabaseRegion, and RxGRDB.

+ +

The FetchRequest protocol is adopted, for example, by query interface requests:

+
// A FetchRequest whose RowDecoder associated type is Player:
+let request = Player.all()
+
+

Building Custom Requests

+ +

To build custom requests, you can use one of the built-in requests, derive requests from other requests, or create your own request type that adopts the FetchRequest protocol.

+ +
    +
  • SQLRequest is a fetch request built from raw SQL. For example:

    +
    extension Player {
    +    static func filter(color: Color) -> SQLRequest<Player> {
    +        return SQLRequest<Player>(
    +            "SELECT * FROM player WHERE color = ?"
    +            arguments: [color])
    +    }
    +}
    +
    +// [Player]
    +try Player.filter(color: .red).fetchAll(db)
    +
  • +
  • The asRequest(of:) method changes the type fetched by the request. It is useful, for example, when you use Associations:

    +
    struct BookInfo: FetchableRecord, Decodable {
    +    var book: Book
    +    var author: Author
    +}
    +
    +let request = Book
    +    .including(required: Book.author)
    +    .asRequest(of: BookInfo.self)
    +
    +// [BookInfo]
    +try request.fetchAll(db)
    +
  • +
  • The adapted(_:) method eases the consumption of complex rows with row adapters. See Joined Queries Support for some sample code that uses this method.

  • +
  • AnyFetchRequest: a type-erased request.

  • +
+

Fetching From Custom Requests

+ +

A type adopting FetchRequest knows exactly what it has to do when its RowDecoder associated type can decode database rows (Row itself, values, or FetchableRecord):

+
let rowRequest = ...        // Some FetchRequest that fetches Row
+try request.fetchCursor(db) // A cursor of rows
+
+let playerRequest = ...     // Some FetchRequest that fetches Player
+try request.fetchAll(db)    // [Player]
+
+let intRequest = ...        // Some FetchRequest that fetches Int
+try request.fetchOne(db)    // Int?
+
+ +

For example:

+
let playerRequest = SQLRequest<Player>(
+    "SELECT * FROM player WHERE color = ?"
+    arguments: [color])
+try request.fetchAll(db)    // [Player]
+
+ +

See fetching methods for information about the fetchCursor, fetchAll and fetchOne methods.

+ +

The RowDecoder type associated with the FetchRequest does not have to be Row, DatabaseValueConvertible, or FetchableRecord. See the Beyond FetchableRecord chapter for more information.

+

Migrations

+ +

Migrations are a convenient way to alter your database schema over time in a consistent and easy way.

+ +

Migrations run in order, once and only once. When a user upgrades your application, only non-applied migrations are run.

+ +

Inside each migration, you typically define and update your database tables according to your evolving application needs:

+
var migrator = DatabaseMigrator()
+
+// 1st migration
+migrator.registerMigration("v1") { db in
+    try db.create(table: "author") { t in ... }
+    try db.create(table: "book") { t in ... }
+    try db.create(index: ...)
+}
+
+// 2nd migration
+migrator.registerMigration("v2") { db in
+    try db.alter(table: "author") { t in ... }
+}
+
+// Migrations for future versions will be inserted here:
+//
+// // 3rd migration
+// migrator.registerMigration("...") { db in
+//     ...
+// }
+
+ +

Each migration runs in a separate transaction. Should one throw an error, its transaction is rollbacked, subsequent migrations do not run, and the error is eventually thrown by migrator.migrate(dbQueue).

+ +

The memory of applied migrations is stored in the database itself (in a reserved table).

+ +

You migrate the database up to the latest version with the migrate(_:) method:

+
try migrator.migrate(dbQueue) // or migrator.migrate(dbPool)
+
+ +

To migrate a database up to a specific version, use migrate(_:upTo:):

+
try migrator.migrate(dbQueue, upTo: "v2")
+
+ +

Migrations can only run forward:

+
try migrator.migrate(dbQueue, upTo: "v2")
+try migrator.migrate(dbQueue, upTo: "v1")
+// fatal error: database is already migrated beyond migration "v1"
+
+ +

Check if a migration has been applied:

+
let appliedMigrations = try migrator.appliedMigrations(in: dbQueue)
+if appliedMigrations.contains("v2") {
+    // "v2" migration has been applied
+}
+
+

The eraseDatabaseOnSchemaChange Option

+ +

A DatabaseMigrator can automatically wipe out the full database content, and recreate the whole database from scratch, if it detects that a migration has changed its definition:

+
var migrator = DatabaseMigrator()
+migrator.eraseDatabaseOnSchemaChange = true
+
+ +

Beware! This flag can destroy your precious users’ data!

+ +

Yet it may be useful in those two situations:

+ +
    +
  1. During application development, as you are still designing migrations, and the schema changes often.

    + +

    In this case, it is recommended that this flag does not ship in the distributed application:

    +
    var migrator = DatabaseMigrator()
    +#if DEBUG
    +// Speed up development by nuking the database when migrations change
    +migrator.eraseDatabaseOnSchemaChange = true
    +#endif
    +
  2. +
  3. When the database content can easily be recreated, such as a cache for some downloaded data.

  4. +
+ +

The eraseDatabaseOnSchemaChange option triggers a recreation of the database if the migrator detects a schema change. A schema change is any difference in the sqlite_master table, which contains the SQL used to create database tables, indexes, triggers, and views.

+

Advanced Database Schema Changes

+ +

SQLite does not support many schema changes, and won’t let you drop a table column with ALTER TABLE … DROP COLUMN …, for example.

+ +

Yet any kind of schema change is still possible. The SQLite documentation explains in detail how to do so: https://www.sqlite.org/lang_altertable.html#otheralter. This technique requires the temporary disabling of foreign key checks, and is supported by the registerMigrationWithDeferredForeignKeyCheck function:

+
// Add a NOT NULL constraint on player.name:
+migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in
+    try db.create(table: "new_player") { t in
+        t.autoIncrementedPrimaryKey("id")
+        t.column("name", .text).notNull()
+    }
+    try db.execute("INSERT INTO new_player SELECT * FROM player")
+    try db.drop(table: "player")
+    try db.rename(table: "new_player", to: "player")
+}
+
+ +

While your migration code runs with disabled foreign key checks, those are re-enabled and checked at the end of the migration, regardless of eventual errors.

+ + +

Full-Text Search is an efficient way to search a corpus of textual documents.

+
// Create full-text tables
+try db.create(virtualTable: "book", using: FTS4()) { t in // or FTS3(), or FTS5()
+    t.column("author")
+    t.column("title")
+    t.column("body")
+}
+
+// Populate full-text table with records or SQL
+try Book(...).insert(db)
+try db.execute(
+    "INSERT INTO book (author, title, body) VALUES (?, ?, ?)",
+    arguments: [...])
+
+// Build search patterns
+let pattern = FTS3Pattern(matchingPhrase: "Moby-Dick")
+
+// Search with the query interface or SQL
+let books = try Book.matching(pattern).fetchAll(db)
+let books = try Book.fetchAll(db,
+    "SELECT * FROM book WHERE book MATCH ?",
+    arguments: [pattern])
+
+ + +

Choosing the Full-Text Engine

+ +

SQLite supports three full-text engines: FTS3, FTS4 and FTS5.

+ +

Generally speaking, FTS5 is better than FTS4 which improves on FTS3. But this does not really tell which engine to choose for your application. Instead, make your choice depend on:

+
  • The full-text features needed by the application:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Full-Text NeedsFTS3FTS4FTS5
    :question: Queries
    Words searches (documents that contain database)XXX
    Prefix searches (documents that contain a word starting with data)XXX
    Phrases searches (documents that contain the phrase SQLite database)XXX
    Boolean searches (documents that contain SQLite or database)XXX
    Proximity search (documents that contain SQLite near database)XXX
    :scissors: Tokenization
    Ascii case insensitivity (have DATABASE match database)XXX
    Unicode case insensitivity (have ÉLÉGANCE match élégance)XXX
    Latin diacritics insensitivity (have elegance match élégance)XXX
    English Stemming (have frustration match frustrated)XXX
    English Stemming and Ascii case insensitivityXXX
    English Stemming and Unicode case insensitivityX
    English Stemming and Latin diacritics insensitivityX
    Synonyms (have 1st match first)¹¹X ²
    Pinyin and Romaji (have romaji match ローマ字)¹¹X ²
    Stop words (don’t index, and don’t match words like and and the)¹¹X ²
    Spell checking (have alamaba match alabama)¹¹¹
    :bowtie: Other Features
    Ranking (sort results by relevance)¹¹X
    Snippets (display a few words around a match)XXX
    + +

    ¹ Requires extra setup, possibly hard to implement.

    + +

    ² Requires a custom tokenizer.

    + +

    For a full feature list, read the SQLite documentation. Some missing features can be achieved with extra application code.

  • +
  • The speed versus disk space constraints. Roughly speaking, FTS4 and FTS5 are faster than FTS3, but use more space. FTS4 only supports content compression.

  • +
  • The location of the indexed text in your database schema. Only FTS4 and FTS5 support contentless and external content tables.

  • +
  • The SQLite library integrated in your application. The version of SQLite that ships with iOS, macOS and watchOS supports FTS3 and FTS4 out of the box, but not always FTS5. To use FTS5, see Enabling FTS5 Support.

  • +
    +

    See

    +

    See FST3 vs. FTS4 and FTS5 vs. FTS3/4 for more differences.

    + +
    + +
    +

    :point_up: Note: In case you were still wondering, it is recommended to read the SQLite documentation: FTS3 & FTS4 and FTS5.

    +
    +

    Create FTS3 and FTS4 Virtual Tables

    + +

    FTS3 and FTS4 full-text tables store and index textual content.

    + +

    Create tables with the create(virtualTable:using:) method:

    +
    // CREATE VIRTUAL TABLE document USING fts3(content)
    +try db.create(virtualTable: "document", using: FTS3()) { t in
    +    t.column("content")
    +}
    +
    +// CREATE VIRTUAL TABLE document USING fts4(content)
    +try db.create(virtualTable: "document", using: FTS4()) { t in
    +    t.column("content")
    +}
    +
    + +

    All columns in a full-text table contain text. If you need to index a table that contains other kinds of values, you need an external content full-text table.

    + +

    You can specify a tokenizer:

    +
    // CREATE VIRTUAL TABLE book USING fts4(
    +//   tokenize=porter,
    +//   author,
    +//   title,
    +//   body
    +// )
    +try db.create(virtualTable: "book", using: FTS4()) { t in
    +    t.tokenizer = .porter
    +    t.column("author")
    +    t.column("title")
    +    t.column("body")
    +}
    +
    + +

    FTS4 supports options:

    +
    // CREATE VIRTUAL TABLE book USING fts4(
    +//   content,
    +//   uuid,
    +//   content="",
    +//   compress=zip,
    +//   uncompress=unzip,
    +//   prefix="2,4",
    +//   notindexed=uuid,
    +//   languageid=lid
    +// )
    +try db.create(virtualTable: "document", using: FTS4()) { t in
    +    t.content = ""
    +    t.compress = "zip"
    +    t.uncompress = "unzip"
    +    t.prefixes = [2, 4]
    +    t.column("content")
    +    t.column("uuid").notIndexed()
    +    t.column("lid").asLanguageId()
    +}
    +
    + +

    The content option is involved in contentless and external content full-text tables. GRDB can help you defining full-text tables that automatically synchronize with their content table. See External Content Full-Text Tables.

    + +

    See SQLite documentation for more information.

    +

    FTS3 and FTS4 Tokenizers

    + +

    A tokenizer defines what matching means. Depending on the tokenizer you choose, full-text searches won’t return the same results.

    + +

    SQLite ships with three built-in FTS3/4 tokenizers: simple, porter and unicode61 that use different algorithms to match queries with indexed content:

    +
    try db.create(virtualTable: "book", using: FTS4()) { t in
    +    // Pick one:
    +    t.tokenizer = .simple // default
    +    t.tokenizer = .porter
    +    t.tokenizer = .unicode61(...)
    +}
    +
    + +

    See below some examples of matches:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    contentquerysimpleporterunicode61
    FooFooXXX
    FooFOOXXX
    JérômeJérômeX ¹X ¹X ¹
    JérômeJÉRÔMEX ¹
    JérômeJeromeX ¹
    DatabaseDatabasesX
    FrustrationFrustratedX
    + +

    ¹ Don’t miss Unicode Full-Text Gotchas

    + +
      +
    • simple

      +
      try db.create(virtualTable: "book", using: FTS4()) { t in
      +    t.tokenizer = .simple   // default
      +}
      +
      + +

      The default simple tokenizer is case-insensitive for ASCII characters. It matches foo with FOO, but not Jérôme with JÉRÔME.

      + +

      It does not provide stemming, and won’t match databases with database.

      + +

      It does not strip diacritics from latin script characters, and won’t match jérôme with jerome.

    • +
    • porter

      +
      try db.create(virtualTable: "book", using: FTS4()) { t in
      +    t.tokenizer = .porter
      +}
      +
      + +

      The porter tokenizer compares English words according to their roots: it matches database with databases, and frustration with frustrated.

      + +

      It does not strip diacritics from latin script characters, and won’t match jérôme with jerome.

    • +
    • unicode61

      +
      try db.create(virtualTable: "book", using: FTS4()) { t in
      +    t.tokenizer = .unicode61()
      +    t.tokenizer = .unicode61(removeDiacritics: false)
      +}
      +
      + +

      The unicode61 tokenizer is case-insensitive for unicode characters. It matches Jérôme with JÉRÔME.

      + +

      It strips diacritics from latin script characters by default, and matches jérôme with jerome. This behavior can be disabled, as in the example above.

      + +

      It does not provide stemming, and won’t match databases with database.

    • +
    + +

    See SQLite tokenizers for more information.

    +

    FTS3Pattern

    + +

    Full-text search in FTS3 and FTS4 tables is performed with search patterns:

    + +
      +
    • database matches all documents that contain database
    • +
    • data* matches all documents that contain a word starting with data
    • +
    • SQLite database matches all documents that contain both SQLite and database
    • +
    • SQLite OR database matches all documents that contain SQLite or database
    • +
    • "SQLite database" matches all documents that contain the SQLite database phrase
    • +
    + +

    Not all search patterns are valid: they must follow the Full-Text Index Queries Grammar.

    + +

    The FTS3Pattern type helps you validating patterns, and building valid patterns from untrusted strings (such as strings typed by users):

    +
    struct FTS3Pattern {
    +    init(rawPattern: String) throws
    +    init?(matchingAnyTokenIn string: String)
    +    init?(matchingAllTokensIn string: String)
    +    init?(matchingPhrase string: String)
    +}
    +
    + +

    The first initializer validates your raw patterns against the query grammar, and may throw a DatabaseError:

    +
    // OK: FTS3Pattern
    +let pattern = try FTS3Pattern(rawPattern: "sqlite AND database")
    +// DatabaseError: malformed MATCH expression: [AND]
    +let pattern = try FTS3Pattern(rawPattern: "AND")
    +
    + +

    The three other initializers don’t throw. They build a valid pattern from any string, including strings provided by users of your application. They let you find documents that match all given words, any given word, or a full phrase, depending on the needs of your application:

    +
    let query = "SQLite database"
    +// Matches documents that contain "SQLite" or "database"
    +let pattern = FTS3Pattern(matchingAnyTokenIn: query)
    +// Matches documents that contain both "SQLite" and "database"
    +let pattern = FTS3Pattern(matchingAllTokensIn: query)
    +// Matches documents that contain "SQLite database"
    +let pattern = FTS3Pattern(matchingPhrase: query)
    +
    + +

    They return nil when no pattern could be built from the input string:

    +
    let pattern = FTS3Pattern(matchingAnyTokenIn: "")  // nil
    +let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
    +
    + +

    FTS3Pattern are regular values. You can use them as query arguments:

    +
    let documents = try Document.fetchAll(db,
    +    "SELECT * FROM document WHERE content MATCH ?",
    +    arguments: [pattern])
    +
    + +

    Use them in the query interface:

    +
    // Search in all columns
    +let documents = try Document.matching(pattern).fetchAll(db)
    +
    +// Search in a specific column:
    +let documents = try Document.filter(Column("content").match(pattern)).fetchAll(db)
    +
    +

    Enabling FTS5 Support

    + +

    When the FTS3 and FTS4 full-text engines don’t suit your needs, you may want to use FTS5. See Choosing the Full-Text Engine to help you make a decision.

    + +

    The version of SQLite that ships with iOS, macOS and watchOS does not always support the FTS5 engine. To enable FTS5 support, you’ll need to install GRDB with one of those installation techniques:

    + +
      +
    1. Use the GRDBPlus CocoaPod. It uses the system SQLite, and requires iOS 11.4+ / macOS 10.13+ / watchOS 4.3+:

      +
      pod 'GRDBPlus'
      +
    2. +
    3. Use the GRDBCipher CocoaPod. It uses SQLCipher (see encryption), and requires iOS 8.0+ / macOS 10.9+ / watchOS 2.0+:

      +
      pod 'GRDBCipher'
      +
    4. +
    5. Use a custom SQLite build and activate the SQLITE_ENABLE_FTS5 compilation option.

    6. +
    +

    Create FTS5 Virtual Tables

    + +

    FTS5 full-text tables store and index textual content.

    + +

    To use FTS5, you’ll need a custom SQLite build that activates the SQLITE_ENABLE_FTS5 compilation option.

    + +

    Create FTS5 tables with the create(virtualTable:using:) method:

    +
    // CREATE VIRTUAL TABLE document USING fts5(content)
    +try db.create(virtualTable: "document", using: FTS5()) { t in
    +    t.column("content")
    +}
    +
    + +

    All columns in a full-text table contain text. If you need to index a table that contains other kinds of values, you need an external content full-text table.

    + +

    You can specify a tokenizer:

    +
    // CREATE VIRTUAL TABLE book USING fts5(
    +//   tokenize='porter',
    +//   author,
    +//   title,
    +//   body
    +// )
    +try db.create(virtualTable: "book", using: FTS5()) { t in
    +    t.tokenizer = .porter()
    +    t.column("author")
    +    t.column("title")
    +    t.column("body")
    +}
    +
    + +

    FTS5 supports options:

    +
    // CREATE VIRTUAL TABLE book USING fts5(
    +//   content,
    +//   uuid UNINDEXED,
    +//   content='table',
    +//   content_rowid='id',
    +//   prefix='2 4',
    +//   columnsize=0,
    +//   detail=column
    +// )
    +try db.create(virtualTable: "document", using: FTS5()) { t in
    +    t.column("content")
    +    t.column("uuid").notIndexed()
    +    t.content = "table"
    +    t.contentRowID = "id"
    +    t.prefixes = [2, 4]
    +    t.columnSize = 0
    +    t.detail = "column"
    +}
    +
    + +

    The content and contentRowID options are involved in contentless and external content full-text tables. GRDB can help you defining full-text tables that automatically synchronize with their content table. See External Content Full-Text Tables.

    + +

    See SQLite documentation for more information.

    +

    FTS5 Tokenizers

    + +

    A tokenizer defines what matching means. Depending on the tokenizer you choose, full-text searches won’t return the same results.

    + +

    SQLite ships with three built-in FTS5 tokenizers: ascii, porter and unicode61 that use different algorithms to match queries with indexed content.

    +
    try db.create(virtualTable: "book", using: FTS5()) { t in
    +    // Pick one:
    +    t.tokenizer = .unicode61() // default
    +    t.tokenizer = .unicode61(...)
    +    t.tokenizer = .ascii
    +    t.tokenizer = .porter(...)
    +}
    +
    + +

    See below some examples of matches:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    contentqueryasciiunicode61porter on asciiporter on unicode61
    FooFooXXXX
    FooFOOXXXX
    JérômeJérômeX ¹X ¹X ¹X ¹
    JérômeJÉRÔMEX ¹X ¹
    JérômeJeromeX ¹X ¹
    DatabaseDatabasesXX
    FrustrationFrustratedXX
    + +

    ¹ Don’t miss Unicode Full-Text Gotchas

    + +
      +
    • unicode61

      +
      try db.create(virtualTable: "book", using: FTS5()) { t in
      +    t.tokenizer = .unicode61()
      +    t.tokenizer = .unicode61(removeDiacritics: false)
      +}
      +
      + +

      The default unicode61 tokenizer is case-insensitive for unicode characters. It matches Jérôme with JÉRÔME.

      + +

      It strips diacritics from latin script characters by default, and matches jérôme with jerome. This behavior can be disabled, as in the example above.

      + +

      It does not provide stemming, and won’t match databases with database.

    • +
    • ascii

      +
      try db.create(virtualTable: "book", using: FTS5()) { t in
      +    t.tokenizer = .ascii
      +}
      +
      + +

      The ascii tokenizer is case-insensitive for ASCII characters. It matches foo with FOO, but not Jérôme with JÉRÔME.

      + +

      It does not provide stemming, and won’t match databases with database.

      + +

      It does not strip diacritics from latin script characters, and won’t match jérôme with jerome.

    • +
    • porter

      +
      try db.create(virtualTable: "book", using: FTS5()) { t in
      +    t.tokenizer = .porter()       // porter wrapping unicode61 (the default)
      +    t.tokenizer = .porter(.ascii) // porter wrapping ascii
      +    t.tokenizer = .porter(.unicode61(removeDiacritics: false)) // porter wrapping unicode61 without diacritics stripping
      +}
      +
      + +

      The porter tokenizer is a wrapper tokenizer which compares English words according to their roots: it matches database with databases, and frustration with frustrated.

      + +

      It strips diacritics from latin script characters if it wraps unicode61, and does not if it wraps ascii (see the example above).

    • +
    + +

    See SQLite tokenizers for more information, and custom FTS5 tokenizers in order to add your own tokenizers.

    +

    FTS5Pattern

    + +

    Full-text search in FTS5 tables is performed with search patterns:

    + +
      +
    • database matches all documents that contain database
    • +
    • data* matches all documents that contain a word starting with data
    • +
    • SQLite database matches all documents that contain both SQLite and database
    • +
    • SQLite OR database matches all documents that contain SQLite or database
    • +
    • "SQLite database" matches all documents that contain the SQLite database phrase
    • +
    + +

    Not all search patterns are valid: they must follow the Full-Text Query Syntax.

    + +

    The FTS5Pattern type helps you validating patterns, and building valid patterns from untrusted strings (such as strings typed by users):

    +
    extension Database {
    +    func makeFTS5Pattern(rawPattern: String, forTable table: String) throws -> FTS5Pattern
    +}
    +
    +struct FTS5Pattern {
    +    init?(matchingAnyTokenIn string: String)
    +    init?(matchingAllTokensIn string: String)
    +    init?(matchingPhrase string: String)
    +}
    +
    + +

    The Database.makeFTS5Pattern(rawPattern:forTable:) method validates your raw patterns against the query grammar and the columns of the targeted table, and may throw a DatabaseError:

    +
    // OK: FTS5Pattern
    +try db.makeFTS5Pattern(rawPattern: "sqlite", forTable: "book")
    +// DatabaseError: syntax error near \"AND\"
    +try db.makeFTS5Pattern(rawPattern: "AND", forTable: "book")
    +// DatabaseError: no such column: missing
    +try db.makeFTS5Pattern(rawPattern: "missing: sqlite", forTable: "book")
    +
    + +

    The FTS5Pattern initializers don’t throw. They build a valid pattern from any string, including strings provided by users of your application. They let you find documents that match all given words, any given word, or a full phrase, depending on the needs of your application:

    +
    let query = "SQLite database"
    +// Matches documents that contain "SQLite" or "database"
    +let pattern = FTS5Pattern(matchingAnyTokenIn: query)
    +// Matches documents that contain both "SQLite" and "database"
    +let pattern = FTS5Pattern(matchingAllTokensIn: query)
    +// Matches documents that contain "SQLite database"
    +let pattern = FTS5Pattern(matchingPhrase: query)
    +// Matches documents that start with "SQLite database"
    +let pattern = FTS5Pattern(matchingPrefixPhrase: query)
    +
    + +

    They return nil when no pattern could be built from the input string:

    +
    let pattern = FTS5Pattern(matchingAnyTokenIn: "")  // nil
    +let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
    +
    + +

    FTS5Pattern are regular values. You can use them as query arguments:

    +
    let documents = try Document.fetchAll(db,
    +    "SELECT * FROM document WHERE document MATCH ?",
    +    arguments: [pattern])
    +
    + +

    Use them in the query interface:

    +
    let documents = try Document.matching(pattern).fetchAll(db)
    +
    +

    FTS5: Sorting by Relevance

    + +

    FTS5 can sort results by relevance (most to least relevant):

    +
    // SQL
    +let documents = try Document.fetchAll(db,
    +    "SELECT * FROM document WHERE document MATCH ? ORDER BY rank",
    +    arguments: [pattern])
    +
    +// Query Interface
    +let documents = try Document.matching(pattern).order(Column.rank).fetchAll(db)
    +
    + +

    For more information about the ranking algorithm, as well as extra options, read Sorting by Auxiliary Function Results

    + +

    GRDB does not provide any ranking for FTS3 and FTS4. See SQLite’s Search Application Tips if you really need it.

    +

    External Content Full-Text Tables

    + +

    An external content table does not store the indexed text. Instead, it indexes the text stored in another table.

    + +

    This is very handy when you want to index a table that can not be declared as a full-text table (because it contains non-textual values, for example). You just have to define an external content full-text table that refers to the regular table.

    + +

    The two tables must be kept up-to-date, so that the full-text index matches the content of the regular table. This synchronization happens automatically if you use the synchronize(withTable:) method in your full-text table definition:

    +
    // A regular table
    +try db.create(table: "book") { t in
    +    t.column("author", .text)
    +    t.column("title", .text)
    +    t.column("content", .text)
    +    ...
    +}
    +
    +// A full-text table synchronized with the regular table
    +try db.create(virtualTable: "book_ft", using: FTS4()) { t in // or FTS5()
    +    t.synchronize(withTable: "book")
    +    t.column("author")
    +    t.column("title")
    +    t.column("content")
    +}
    +
    + +

    The eventual content already present in the regular table is indexed, and every insert, update or delete that happens in the regular table is automatically applied to the full-text index.

    + +

    For more information, see the SQLite documentation about external content tables: FTS4, FTS5.

    + +

    See also WWDC Companion, a sample app that uses external content tables to store, display, and let the user search the WWDC sessions.

    +

    Deleting Synchronized Full-Text Tables

    + +

    Synchronization of full-text tables with their content table happens by the mean of SQL triggers.

    + +

    SQLite automatically deletes those triggers when the content (not full-text) table is dropped.

    + +

    However, those triggers remain after the full-text table has been dropped. Unless they are dropped too, they will prevent future insertion, updates, and deletions in the content table, and the creation of a new full-text table.

    + +

    To drop those triggers, use the dropFTS4SynchronizationTriggers or dropFTS5SynchronizationTriggers methods:

    +
    // Create tables
    +try db.create(table: "book") { t in
    +    ...
    +}
    +try db.create(virtualTable: "book_ft", using: FTS4()) { t in
    +    t.synchronize(withTable: "book")
    +    ...
    +}
    +
    +// Drop full-text table
    +try db.drop(table: "book_ft")
    +try db.dropFTS4SynchronizationTriggers(forTable: "book_ft")
    +
    + +
    +

    :warning: Warning: there was a bug in GRDB up to version 2.3.1 included, which created triggers with a wrong name. If it is possible that the full-text table was created by an old version of GRDB, then delete the synchronization triggers twice: once with the name of the deleted full-text table, and once with the name of the content table:

    +
    // Drop full-text table
    +try db.drop(table: "book_ft")
    +try db.dropFTS4SynchronizationTriggers(forTable: "book_ft")
    +try db.dropFTS4SynchronizationTriggers(forTable: "book") // Support for GRDB <= 2.3.1
    +
    +
    +

    Querying External Content Full-Text Tables

    + +

    When you need to perform a full-text search, and the external content table contains all the data you need, you can simply query the full-text table.

    + +

    But if you need to load columns from the regular table, and in the same time perform a full-text search, then you will need to query both tables at the same time.

    + +

    That is because SQLite will throw an error when you try to perform a full-text search on a regular table:

    +
    // SQLite error 1: unable to use function MATCH in the requested context
    +// SELECT * FROM book WHERE book MATCH '...'
    +let books = Book.matching(pattern).fetchAll(db)
    +
    + +

    The solution is to perform a joined request, using raw SQL:

    +
    let sql = """
    +    SELECT book.*
    +    FROM book
    +    JOIN book_ft
    +        ON book_ft.rowid = book.rowid
    +        AND book_ft MATCH ?
    +    """
    +let books = Book.fetchAll(db, sql, arguments: [pattern])
    +
    +

    Full-Text Records

    + +

    You can define record types around the full-text virtual tables.

    + +

    However these tables don’t have any explicit primary key. Instead, they use the implicit rowid primary key: a special hidden column named rowid.

    + +

    You will have to expose this hidden column in order to fetch, delete, and update full-text records by primary key.

    +

    Unicode Full-Text Gotchas

    + +

    The SQLite built-in tokenizers for FTS3, FTS4 and FTS5 are generally unicode-aware, with a few caveats, and limitations.

    + +

    Generally speaking, matches may fail when content and query don’t use the same unicode normalization. SQLite actually exhibits inconsistent behavior in this regard.

    + +

    For example, for aimé to match aimé, they better have the same normalization: the NFC aim\u{00E9} form may not match its NFD aime\u{0301} equivalent. Most strings that you get from Swift, UIKit and Cocoa use NFC, so be careful with NFD inputs (such as strings from the HFS+ file system, or strings that you can’t trust like network inputs). Use String.precomposedStringWithCanonicalMapping to turn a string into NFC.

    + +

    Besides, if you want fi to match the ligature fi (U+FB01), then you need to normalize your indexed contents and inputs to NFKC or NFKD. Use String.precomposedStringWithCompatibilityMapping to turn a string into NFKC.

    + +

    Unicode normalization is not the end of the story, because it won’t help Encyclopaedia match Encyclopædia, Mueller, Müller, Grossmann, Großmann, or Diyarbakır, DIYARBAKIR. The String.applyingTransform method can help.

    + +

    GRDB lets you write custom FTS5 tokenizers that can transparently deal with all these issues. For FTS3 and FTS4, you’ll need to pre-process your strings before injecting them in the full-text engine.

    + +

    Happy indexing!

    +

    Joined Queries Support

    + +

    GRDB helps consuming joined queries with complex selection.

    + +

    In this chapter, we will focus on the extraction of information from complex rows, such as the ones fetched by the query below:

    +
    -- How to consume the left, middle, and right parts of those rows?
    +SELECT player.*, team.*, MAX(round.score) AS maxScore
    +FROM player
    +LEFT JOIN team ON ...
    +LEFT JOIN round ON ...
    +GROUP BY ...
    +
    + +

    We will not talk about the generation of joined queries, which is covered in Associations.

    + +

    So what are we talking about?

    + +

    It is difficult to consume rows fetched from complex joined queries, because they often contain several columns with the same name: id from table player, id from table team, etc.

    + +

    When such ambiguity happens, GRDB row accessors always favor the leftmost matching column. This means that row["id"] would give a player id, whithout any obvious way to access the team id.

    + +

    A classical technique to avoid this ambiguity is to give each column a unique name. For example:

    +
    -- A classical technique
    +SELECT player.id AS player_id, player.name AS player_name, team.id AS team_id, team.name AS team_name, team.color AS team_color, MAX(round.score) AS maxScore
    +FROM player
    +LEFT JOIN team ON ...
    +LEFT JOIN round ON ...
    +GROUP BY ...
    +
    + +

    This technique works pretty well, but it has three drawbacks:

    + +
      +
    1. The selection becomes hard to read and understand.
    2. +
    3. Such queries are difficult to write by hand.
    4. +
    5. The mangled names are a very bad fit for FetchableRecord types that expect specific column names. After all, if the Team record type can read SELECT * FROM team ..., it should be able to read SELECT ..., team.*, ... as well.
    6. +
    + +

    We thus need another technique. Below we’ll see how to split rows into slices, and preserve column names.

    + +

    SELECT player.*, team.*, MAX(round.score) AS maxScore FROM ... will be splitted into three slices: one that contains player’s columns, one that contains team’s columns, and a remaining slice that contains remaining column(s). The Player record type will be able to read the first slice, which contains the colums expected by the Player.init(row:) initializer. In the same way, the Team record type could read the second slice.

    + +

    Unlike the name-mangling technique, splitting rows keeps SQL legible, accepts your hand-crafted SQL queries, and plays as nicely as possible with your existing record types.

    + + +

    Splitting Rows, an Introduction

    + +

    Let’s first write some introductory code, hoping that this chapter will make you understand how pieces fall together. We’ll see later how records will help us streamline the initial approach, how to track changes in joined requests, and how we can use the standard Decodable protocol.

    + +

    To split rows, we will use row adapters. Row adapters adapt rows so that row consumers see exactly the columns they want. Among other things, row adapters can define several row scopes that give access to as many row slices. Sounds like a perfect match.

    + +

    At the very beginning, there is an SQL query:

    +
    try dbQueue.read { db in
    +    let sql = """
    +        SELECT player.*, team.*, MAX(round.score) AS maxScore
    +        FROM player
    +        LEFT JOIN team ON ...
    +        LEFT JOIN round ON ...
    +        GROUP BY ...
    +        """
    +
    + +

    We need an adapter that extracts player columns, in a slice that has as many columns as there are columns in the player table. That’s RangeRowAdapter:

    +
        // SELECT player.*, team.*, ...
    +    //        <------>
    +    let playerWidth = try db.columns(in: "player").count
    +    let playerAdapter = RangeRowAdapter(0 ..< playerWidth)
    +
    + +

    We also need an adapter that extracts team columns:

    +
        // SELECT player.*, team.*, ...
    +    //                  <---->
    +    let teamWidth = try db.columns(in: "team").count
    +    let teamAdapter = RangeRowAdapter(playerWidth ..< (playerWidth + teamWidth))
    +
    + +

    We merge those two adapters in a single ScopeAdapter that will allow us to access both sliced rows:

    +
        let playerScope = "player"
    +    let teamScope = "team"
    +    let adapter = ScopeAdapter([
    +        playerScope: playerAdapter,
    +        teamScope: teamAdapter])
    +
    + +

    And now we can fetch, and start consuming our rows. You already know row cursors:

    +
        let rows = try Row.fetchCursor(db, sql, adapter: adapter)
    +    while let row = try rows.next() {
    +
    + +

    From a fetched row, we can build a player:

    +
            let player: Player = row[playerScope]
    +
    + +

    In the SQL query, the team is joined with the LEFT JOIN operator. This means that the team may be missing: its slice may contain team values, or it may only contain NULLs. When this happens, we don’t want to build a Team record, and we thus load an optional Team:

    +
            let team: Team? = row[teamScope]
    +
    + +

    And finally, we can load the maximum score, assuming that the maxScore column is not ambiguous:

    +
            let maxScore: Int = row["maxScore"]
    +
    +        print("player: \(player)")
    +        print("team: \(team)")
    +        print("maxScore: \(maxScore)")
    +    }
    +}
    +
    + +
    +

    :bulb: In this chapter, we have learned:

    + +
      +
    • how to use RangeRowAdapter to extract a specific table’s columns into a row slice.
    • +
    • how to use ScopeAdapter to gives access to several row slices through named scopes.
    • +
    • how to use Row subscripting to extract records from rows, or optional records in order to deal with left joins.
    • +
    +
    +

    Splitting Rows, the Record Way

    + +

    Our introduction above has introduced important techniques. It uses row adapters in order to split rows. It uses Row subscripting in order to extract records from row slices.

    + +

    But we may want to make it more usable and robust:

    + +
      +
    1. It’s generally easier to consume records than raw rows.
    2. +
    3. Joined records not always need all columns from a table (see TableRecord.databaseSelection in Columns Selected by a Request).
    4. +
    5. Building row adapters is long and error prone.
    6. +
    + +

    To address the first bullet, let’s define a record that holds our player, optional team, and maximum score. Since it can decode database rows, it adopts the FetchableRecord protocol:

    +
    struct PlayerInfo {
    +    var player: Player
    +    var team: Team?
    +    var maxScore: Int
    +}
    +
    +/// PlayerInfo can decode rows:
    +extension PlayerInfo: FetchableRecord {
    +    private enum Scopes {
    +        static let player = "player"
    +        static let team = "team"
    +    }
    +
    +    init(row: Row) {
    +        player = row[Scopes.player]
    +        team = row[Scopes.team]
    +        maxScore = row["maxScore"]
    +    }
    +}
    +
    + +

    Let’s now write the method that fetches PlayerInfo records:

    +
    extension PlayerInfo {
    +    static func fetchAll(_ db: Database) throws -> [PlayerInfo] {
    +
    + +

    To acknowledge that both Player and Team records may customize their selection of the player and team columns, we’ll write our SQL in a slightly different way:

    +
            // Let Player and Team customize their selection:
    +        let sql = """
    +            SELECT
    +                \(Player.selectionSQL()), -- instead of player.*
    +                \(Team.selectionSQL()),   -- instead of team.*
    +                MAX(round.score) AS maxScore
    +            FROM player
    +            LEFT JOIN team ON ...
    +            LEFT JOIN round ON ...
    +            GROUP BY ...
    +            """
    +
    + +

    Player.selectionSQL() will output player.*, unless Player defines a customized selection.

    + +
    +

    :point_up: Note: you may also use SQL table aliases:

    +
    let sql = """
    +    SELECT
    +        \(Player.selectionSQL(alias: "p")),
    +        \(Team.selectionSQL(alias: "t")),
    +        MAX(r.score) AS maxScore
    +    FROM player p
    +    LEFT JOIN team t ON ...
    +    LEFT JOIN round r ON ...
    +    GROUP BY ...
    +    """
    +
    +
    + +

    Now is the time to build adapters (taking in account the customized selection of both player and team). We use the splittingRowAdapters global function, which builds row adapters of desired widths:

    +
            let adapters = try splittingRowAdapters(columnCounts: [
    +            Player.numberOfSelectedColumns(db),
    +            Team.numberOfSelectedColumns(db)])
    +
    +        let adapter = ScopeAdapter([
    +            Scopes.player: adapters[0],
    +            Scopes.team: adapters[1]])
    +
    + +
    +

    :point_up: Note: splittingRowAdapters returns as many adapters as necessary to fully split a row. In the example above, it returns three adapters: one for player, one for team, and one for the remaining columns.

    +
    + +

    And finally, we can fetch player infos:

    +
            return try PlayerInfo.fetchAll(db, sql, adapter: adapter)
    +    }
    +}
    +
    + +

    And when your app needs to fetch player infos, it now reads:

    +
    // Fetch player infos
    +let playerInfos = try dbQueue.read { db in
    +    try PlayerInfo.fetchAll(db)
    +}
    +
    + +
    +

    :bulb: In this chapter, we have learned:

    + +
      +
    • how to define a FetchableRecord record that consumes rows fetched from a joined query.
    • +
    • how to use selectionSQL and numberOfSelectedColumns in order to deal with nested record types that define custom selection.
    • +
    • how to use splittingRowAdapters in order to streamline the definition of row slices.
    • +
    • how to gather all relevant methods and constants in a record type, fully responsible of its relationship with the database.
    • +
    +
    +

    Splitting Rows, the Request Way

    + +

    The PlayerInfo.fetchAll method above directly fetches records. It’s all good, but in order to profit from database observation with FetchedRecordsController or RxGRDB, you’ll need a custom request that defines a database query.

    + +

    It is recommended that you read the previous paragraphs before you dive in this sample code. We start with the same PlayerInfo record as above:

    +
    struct PlayerInfo {
    +    var player: Player
    +    var team: Team?
    +    var maxScore: Int
    +}
    +
    +/// PlayerInfo can decode rows:
    +extension PlayerInfo: FetchableRecord {
    +    private enum Scopes {
    +        static let player = "player"
    +        static let team = "team"
    +    }
    +
    +    init(row: Row) {
    +        player = row[Scopes.player]
    +        team = row[Scopes.team]
    +        maxScore = row["maxScore"]
    +    }
    +}
    +
    + +

    Now we write a method that returns a request, and build the fetching method on top of that request:

    +
    extension PlayerInfo {
    +    /// The request for all player infos
    +    static func all() -> AdaptedFetchRequest<SQLRequest<PlayerInfo>> {
    +        let sql = """
    +            SELECT
    +                \(Player.selectionSQL()),
    +                \(Team.selectionSQL()),
    +                MAX(round.score) AS maxScore
    +            FROM player
    +            LEFT JOIN team ON ...
    +            LEFT JOIN round ON ...
    +            GROUP BY ...
    +            """
    +        return SQLRequest<PlayerInfo>(sql).adapted { db in
    +            let adapters = try splittingRowAdapters(columnCounts: [
    +                Player.numberOfSelectedColumns(db),
    +                Team.numberOfSelectedColumns(db)])
    +            return ScopeAdapter([
    +                Scopes.player: adapters[0],
    +                Scopes.team: adapters[1]])
    +        }
    +    }
    +
    +    /// Fetches all player infos
    +    static func fetchAll(_ db: Database) throws -> [PlayerInfo] {
    +        return try all().fetchAll(db)
    +    }
    +}
    +
    + +

    It is now time to use our request:

    +
    // Fetch player infos
    +let playerInfos = try dbQueue.read { db in
    +    try PlayerInfo.fetchAll(db)
    +}
    +
    +// Track player infos with RxRGDB:
    +PlayerInfo.all()
    +    .rx.fetchAll(in: dbQueue)
    +    .subscribe(onNext: { playerInfos: [PlayerInfo] in
    +        print("Player infos have changed")
    +    })
    +
    + +
    +

    :bulb: In this chapter, we have learned how to define a custom request that can both fetch records from joined queries, and feed database observation tools.

    +
    +

    Splitting Rows, the Codable Way

    + +

    Codable Records build on top of the standard Decodable protocol in order to decode database rows.

    + +

    You can consume complex joined queries with Codable records as well. As a demonstration, we’ll rewrite the above sample code:

    +
    struct Player: Decodable, FetchableRecord, TableRecord {
    +    var id: Int64
    +    var name: String
    +}
    +struct Team: Decodable, FetchableRecord, TableRecord {
    +    var id: Int64
    +    var name: String
    +    var color: Color
    +}
    +struct PlayerInfo: Decodable, FetchableRecord {
    +    var player: Player
    +    var team: Team?
    +    var maxScore: Int
    +}
    +
    +extension PlayerInfo {
    +    /// The request for all player infos
    +    static func all() -> AdaptedFetchRequest<SQLRequest<PlayerInfo>> {
    +        let sql = """
    +            SELECT
    +                \(Player.selectionSQL()),
    +                \(Team.selectionSQL()),
    +                MAX(round.score) AS maxScore
    +            FROM player
    +            LEFT JOIN team ON ...
    +            LEFT JOIN round ON ...
    +            GROUP BY ...
    +            """
    +        return SQLRequest<PlayerInfo>(sql).adapted { db in
    +            let adapters = try splittingRowAdapters(columnCounts: [
    +                Player.numberOfSelectedColumns(db),
    +                Team.numberOfSelectedColumns(db)])
    +            return ScopeAdapter([
    +                CodingKeys.player.stringValue: adapters[0],
    +                CodingKeys.team.stringValue: adapters[1]])
    +        }
    +    }
    +
    +    /// Fetches all player infos
    +    static func fetchAll(_ db: Database) throws -> [PlayerInfo] {
    +        return try all().fetchAll(db)
    +    }
    +}
    +
    +// Fetch player infos
    +let playerInfos = try dbQueue.read { db in
    +    try PlayerInfo.fetchAll(db)
    +}
    +
    +// Track player infos with RxRGDB:
    +PlayerInfo.all()
    +    .rx.fetchAll(in: dbQueue)
    +    .subscribe(onNext: { playerInfos: [PlayerInfo] in
    +        print("Player infos have changed")
    +    })
    +
    + +
    +

    :bulb: In this chapter, we have learned how to use the Decodable protocol and its associated CodingKeys enum in order to dry up our code.

    +
    +

    Database Changes Observation

    + +

    SQLite notifies its host application of changes performed to the database, as well of transaction commits and rollbacks.

    + +

    GRDB puts this SQLite feature to some good use, and lets you observe the database in various ways:

    + + + +

    Database observation requires that a single database queue or pool is kept open for all the duration of the database usage.

    +

    After Commit Hook

    + +

    When your application needs to make sure a specific database transaction has been successfully committed before it executes some work, use the Database.afterNextTransactionCommit(_:) method.

    + +

    Its closure argument is called right after database changes have been successfully written to disk:

    +
    try dbQueue.write { db in
    +    db.afterNextTransactionCommit { db in
    +        print("success")
    +    }
    +    ...
    +} // prints "success"
    +
    + +

    The closure runs in a protected dispatch queue, serialized with all database updates.

    + +

    This after commit hook helps synchronizing the database with other resources, such as files, or system sensors.

    + +

    In the example below, a location manager starts monitoring a CLRegion if and only if it has successfully been stored in the database:

    +
    /// Inserts a region in the database, and start monitoring upon
    +/// successful insertion.
    +func startMonitoring(_ db: Database, region: CLRegion) throws {
    +    // Make sure database is inside a transaction
    +    try db.inSavepoint {
    +
    +        // Save the region in the database
    +        try insert(...)
    +
    +        // Start monitoring if and only if the insertion is
    +        // eventually committed
    +        db.afterNextTransactionCommit { _ in
    +            // locationManager prefers the main queue:
    +            DispatchQueue.main.async {
    +                locationManager.startMonitoring(for: region)
    +            }
    +        }
    +
    +        return .commit
    +    }
    +}
    +
    + +

    The method above won’t trigger the location manager if the transaction is eventually rollbacked (explicitly, or because of an error), as in the sample code below:

    +
    try dbQueue.write { db in
    +    // success
    +    try startMonitoring(db, region)
    +
    +    // On error, the transaction is rollbacked, the region is not inserted, and
    +    // the location manager is not invoked.
    +    try failableMethod(db)
    +}
    +
    +

    TransactionObserver Protocol

    + +

    The TransactionObserver protocol lets you observe database changes and transactions:

    +
    protocol TransactionObserver : class {
    +    /// Notifies a database change:
    +    /// - event.kind (insert, update, or delete)
    +    /// - event.tableName
    +    /// - event.rowID
    +    ///
    +    /// For performance reasons, the event is only valid for the duration of
    +    /// this method call. If you need to keep it longer, store a copy:
    +    /// event.copy().
    +    func databaseDidChange(with event: DatabaseEvent)
    +
    +    /// Filters the database changes that should be notified to the
    +    /// `databaseDidChange(with:)` method.
    +    func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool
    +
    +    /// An opportunity to rollback pending changes by throwing an error.
    +    func databaseWillCommit() throws
    +
    +    /// Database changes have been committed.
    +    func databaseDidCommit(_ db: Database)
    +
    +    /// Database changes have been rollbacked.
    +    func databaseDidRollback(_ db: Database)
    +}
    +
    + + +

    Activate a Transaction Observer

    + +

    To activate a transaction observer, add it to the database queue or pool:

    +
    let observer = MyObserver()
    +dbQueue.add(transactionObserver: observer)
    +
    + +

    By default, database holds weak references to its transaction observers: they are not retained, and stop getting notifications after they are deallocated. See Observation Extent for more options.

    +

    Database Changes And Transactions

    + +

    A transaction observer is notified of all database changes: inserts, updates and deletes. This includes indirect changes triggered by ON DELETE and ON UPDATE actions associated to foreign keys, and SQL triggers.

    + +
    +

    :point_up: Note: the changes that are not notified are changes to internal system tables (such as sqlite_master), changes to WITHOUT ROWID tables, and the deletion of duplicate rows triggered by ON CONFLICT REPLACE clauses (this last exception might change in a future release of SQLite).

    +
    + +

    Notified changes are not actually written to disk until the transaction commits, and the databaseDidCommit callback is called. On the other side, databaseDidRollback confirms their invalidation:

    +
    try dbQueue.write { db in
    +    try db.execute("INSERT ...") // 1. didChange
    +    try db.execute("UPDATE ...") // 2. didChange
    +}                                // 3. willCommit, 4. didCommit
    +
    +try dbQueue.inTransaction { db in
    +    try db.execute("INSERT ...") // 1. didChange
    +    try db.execute("UPDATE ...") // 2. didChange
    +    return .rollback             // 3. didRollback
    +}
    +
    +try dbQueue.write { db in
    +    try db.execute("INSERT ...") // 1. didChange
    +    throw SomeError()
    +}                                // 2. didRollback
    +
    + +

    Database statements that are executed outside of any transaction do not drop off the radar:

    +
    try dbQueue.inDatabase { db in
    +    try db.execute("INSERT ...") // 1. didChange, 2. willCommit, 3. didCommit
    +    try db.execute("UPDATE ...") // 4. didChange, 5. willCommit, 6. didCommit
    +}
    +
    + +

    Changes that are on hold because of a savepoint are only notified after the savepoint has been released. This makes sure that notified events are only events that have an opportunity to be committed:

    +
    try dbQueue.inTransaction { db in
    +    try db.execute("INSERT ...")            // 1. didChange
    +
    +    try db.execute("SAVEPOINT foo")
    +    try db.execute("UPDATE ...")            // delayed
    +    try db.execute("UPDATE ...")            // delayed
    +    try db.execute("RELEASE SAVEPOINT foo") // 2. didChange, 3. didChange
    +
    +    try db.execute("SAVEPOINT foo")
    +    try db.execute("UPDATE ...")            // not notified
    +    try db.execute("ROLLBACK TO SAVEPOINT foo")
    +
    +    return .commit                          // 4. willCommit, 5. didCommit
    +}
    +
    + +

    Eventual errors thrown from databaseWillCommit are exposed to the application code:

    +
    do {
    +    try dbQueue.inTransaction { db in
    +        ...
    +        return .commit           // 1. willCommit (throws), 2. didRollback
    +    }
    +} catch {
    +    // 3. The error thrown by the transaction observer.
    +}
    +
    + +
    +

    :point_up: Note: all callbacks are called in a protected dispatch queue, and serialized with all database updates.

    + +

    :point_up: Note: the databaseDidChange(with:) and databaseWillCommit() callbacks must not touch the SQLite database. This limitation does not apply to databaseDidCommit and databaseDidRollback which can use their database argument.

    +
    + +

    FetchedRecordsController and RxGRDB are based on the TransactionObserver protocol.

    + +

    See also TableChangeObserver.swift, which shows a transaction observer that notifies of modified database tables with NSNotificationCenter.

    +

    Filtering Database Events

    + +

    Transaction observers can avoid being notified of database changes they are not interested in.

    + +

    The filtering happens in the observes(eventsOfKind:) method, which tells whether the observer wants notification of specific kinds of changes, or not. For example, here is how an observer can focus on the changes that happen on the player database table:

    +
    class PlayerObserver: TransactionObserver {
    +    func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
    +        // Only observe changes to the "player" table.
    +        return eventKind.tableName == "player"
    +    }
    +
    +    func databaseDidChange(with event: DatabaseEvent) {
    +        // This method is only called for changes that happen to
    +        // the "player" table.
    +    }
    +}
    +
    + +

    Generally speaking, the observes(eventsOfKind:) method can distinguish insertions from deletions and updates, and is also able to inspect the columns that are about to be changed:

    +
    class PlayerScoreObserver: TransactionObserver {
    +    func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
    +        // Only observe changes to the "score" column of the "player" table.
    +        switch eventKind {
    +        case .insert(let tableName):
    +            return tableName == "player"
    +        case .delete(let tableName):
    +            return tableName == "player"
    +        case .update(let tableName, let columnNames):
    +            return tableName == "player" && columnNames.contains("score")
    +        }
    +    }
    +}
    +
    + +

    When the observes(eventsOfKind:) method returns false for all event kinds, the observer is still notified of commits and rollbacks:

    +
    class PureTransactionObserver: TransactionObserver {
    +    func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
    +        // Ignore all individual changes
    +        return false
    +    }
    +
    +    func databaseDidChange(with event: DatabaseEvent) { /* Never called */ }
    +    func databaseWillCommit() throws { /* Called before commit */ }
    +    func databaseDidRollback(_ db: Database) { /* Called on rollback */ }
    +    func databaseDidCommit(_ db: Database) { /* Called on commit */ }
    +}
    +
    + +

    For more information about event filtering, see DatabaseRegion.

    +

    Observation Extent

    + +

    You can specify how long an observer is notified of database changes and transactions.

    + +

    The remove(transactionObserver:) method explicitly stops notifications, at any time:

    +
    // From a database queue or pool:
    +dbQueue.remove(transactionObserver: observer)
    +
    +// From a database connection:
    +dbQueue.inDatabase { db in
    +    db.remove(transactionObserver: observer)
    +}
    +
    + +

    Alternatively, use the extent parameter of the add(transactionObserver:extent:) method:

    +
    let observer = MyObserver()
    +
    +// On a database queue or pool:
    +dbQueue.add(transactionObserver: observer) // default extent
    +dbQueue.add(transactionObserver: observer, extent: .observerLifetime)
    +dbQueue.add(transactionObserver: observer, extent: .nextTransaction)
    +dbQueue.add(transactionObserver: observer, extent: .databaseLifetime)
    +
    +// On a database connection:
    +dbQueue.inDatabase { db in
    +    db.add(transactionObserver: ...)
    +}
    +
    + +
      +
    • The default extent is .observerLifetime: the database holds a weak reference to the observer, and the observation automatically ends when the observer is deallocated. Meanwhile, observer is notified of all changes and transactions.

    • +
    • .nextTransaction activates the observer until the current or next transaction completes. The database keeps a strong reference to the observer until its databaseDidCommit or databaseDidRollback method is eventually called. Hereafter the observer won’t get any further notification.

    • +
    • .databaseLifetime has the database retain and notify the observer until the database connection is closed.

    • +
    + +

    Finally, an observer may ignore all database changes until the end of the current transaction:

    +
    class PlayerObserver: TransactionObserver {
    +    var playerTableWasModified = false
    +
    +    func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
    +        return eventKind.tableName == "player"
    +    }
    +
    +    func databaseDidChange(with event: DatabaseEvent) {
    +        playerTableWasModified = true
    +
    +        // It is pointless to keep on tracking further changes:
    +        stopObservingDatabaseChangesUntilNextTransaction()
    +    }
    +}
    +
    + +

    After stopObservingDatabaseChangesUntilNextTransaction(), the databaseDidChange(with:) method will not be notified of any change for the remaining duration of the current transaction. This helps GRDB optimize database observation.

    +

    DatabaseRegion

    + +

    DatabaseRegion is a type that helps observing changes in the results of a database request.

    + +

    A request knows which database modifications can impact its results. It can communicate this information to a transaction observer by the way of a database region.

    + +

    You start by building regions:

    +
    try dbQueue.write { db in
    +    let teamRegion = try Team.filter(key: 1).databaseRegion(db)
    +    let playersRegion = try SQLRequest<Player>("SELECT * FROM player").databaseRegion(db)
    +    let maxScoreRegion = try Player.select(max(Column("score"))).databaseRegion(db)
    +
    + +

    You can group regions:

    +
        let region = teamRegion.union(playersRegion).union(maxScoreRegion)
    +}
    +
    + +

    Those regions provide support for the observes(eventsOfKind:) and databaseDidChange(with:) methods of transaction observers. For example:

    +
    // A region observer
    +class DatabaseRegionObserver: TransactionObserver {
    +    let region: DatabaseRegion
    +    var regionModified = false
    +
    +    init(region: DatabaseRegion) {
    +        self.region = region
    +    }
    +
    +    func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
    +        return region.isModified(byEventsOfKind: eventKind)
    +    }
    +
    +    func databaseDidChange(with event: DatabaseEvent) {
    +        if region.isModified(by: event) {
    +            regionModified = true
    +            stopObservingDatabaseChangesUntilNextTransaction()
    +        }
    +    }
    +
    +    func databaseDidRollback(_ db: Database) {
    +        regionModified = false
    +    }
    +
    +    func databaseDidCommit(_ db: Database) {
    +        if regionModified {
    +            regionModified = false
    +
    +            // You'll customize your handling of changes here:
    +            print("Region changes have been committed.")
    +        }
    +    }
    +}
    +
    +// Observe a region
    +try dbQueue.write { db in
    +    observer = DatabaseRegionObserver(region: region)
    +    db.add(transactionObserver: observer)
    +}
    +
    + +

    Beware that a region notifies potential changes, not actual changes in the results of a request. A change is notified if and only if a statement has actually modified the tracked tables and columns by inserting, updating, or deleting a row.

    + +

    For example, if you observe the region of Player.select(max(Column("score"))), then you’ll get be notified of all changes performed on the score column of the player table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table.

    + +

    Similarly, observing the region of Country.filter(key: "FR") will notify all changes that happen to the whole country table. That is because SQLite only notifies the numerical rowid of changed rows, and we can’t check if it is the row FR that has been changed, or another. This limitation does not apply to tables whose primary key is the rowid: Player.filter(key: 42) will only notify of changes performed on the row with id 42.

    +

    Support for SQLite Pre-Update Hooks

    + +

    A custom SQLite build can activate SQLite preupdate hooks. In this case, TransactionObserverType gets an extra callback which lets you observe individual column values in the rows modified by a transaction:

    +
    protocol TransactionObserverType : class {
    +    #if SQLITE_ENABLE_PREUPDATE_HOOK
    +    /// Notifies before a database change (insert, update, or delete)
    +    /// with change information (initial / final values for the row's
    +    /// columns).
    +    ///
    +    /// The event is only valid for the duration of this method call. If you
    +    /// need to keep it longer, store a copy: event.copy().
    +    func databaseWillChange(with event: DatabasePreUpdateEvent)
    +    #endif
    +}
    +
    +

    FetchedRecordsController

    + +

    You use FetchedRecordsController to track changes in the results of an SQLite request.

    + +

    FetchedRecordsController can also feed table views, collection views, and animate cells when the results of the request change.

    + +

    It looks and behaves very much like Core Data’s NSFetchedResultsController.

    + +

    Given a fetch request, and a type that adopts the FetchableRecord protocol, such as a subclass of the Record class, a FetchedRecordsController is able to track changes in the results of the fetch request, notify of those changes, and return the results of the request in a form that is suitable for a table view or a collection view, with one cell per fetched record.

    + +

    See GRDBDemoiOS for an sample app that uses FetchedRecordsController.

    + +

    See also RxGRDB, an RxSwift extension, for a reactive way to track request changes.

    + + +

    Creating the Fetched Records Controller

    + +

    When you initialize a fetched records controller, you provide the following mandatory information:

    + + +
    class Player : Record { ... }
    +let dbQueue = DatabaseQueue(...)    // or DatabasePool
    +
    +// Using a Request from the Query Interface:
    +let controller = FetchedRecordsController(
    +    dbQueue,
    +    request: Player.order(Column("name")))
    +
    +// Using SQL, and eventual arguments:
    +let controller = FetchedRecordsController<Player>(
    +    dbQueue,
    +    sql: "SELECT * FROM player ORDER BY name WHERE countryCode = ?",
    +    arguments: ["FR"])
    +
    + +

    The fetch request can involve several database tables. The fetched records controller will only track changes in the columns and tables used by the fetch request.

    +
    let controller = FetchedRecordsController<Author>(
    +    dbQueue,
    +    sql: """
    +        SELECT author.name, COUNT(book.id) AS bookCount
    +        FROM author
    +        LEFT JOIN book ON book.authorId = author.id
    +        GROUP BY author.id
    +        ORDER BY author.name
    +        """)
    +
    + +

    After creating an instance, you invoke performFetch() to actually execute +the fetch.

    +
    try controller.performFetch()
    +
    +

    Responding to Changes

    + +

    In general, FetchedRecordsController is designed to respond to changes at the database layer, by notifying when database rows change location or values.

    + +

    Changes are not reflected until they are applied in the database by a successful transaction:

    +
    // One transaction
    +try dbQueue.write { db in         // or dbPool.write
    +    try player1.insert(db)
    +    try player2.insert(db)
    +}
    +
    +// One transaction
    +try dbQueue.inTransaction { db in // or dbPool.writeInTransaction
    +    try player1.insert(db)
    +    try player2.insert(db)
    +    return .commit
    +}
    +
    +// Two transactions
    +try dbQueue.inDatabase { db in    // or dbPool.writeWithoutTransaction
    +    try player1.insert(db)
    +    try player2.insert(db)
    +}
    +
    + +

    When you apply several changes to the database, you should group them in a single explicit transaction. The controller will then notify of all changes together.

    +

    The Changes Notifications

    + +

    An instance of FetchedRecordsController notifies that the controller’s fetched records have been changed by the mean of callbacks:

    +
    let controller = try FetchedRecordsController(...)
    +
    +controller.trackChanges(
    +    // controller's records are about to change:
    +    willChange: { controller in ... },
    +
    +    // notification of individual record changes:
    +    onChange: { (controller, record, change) in ... },
    +
    +    // controller's records have changed:
    +    didChange: { controller in ... })
    +
    +try controller.performFetch()
    +
    + +

    See Implementing Table View Updates for more detail on table view updates.

    + +

    All callbacks are optional. When you only need to grab the latest results, you can omit the didChange argument name:

    +
    controller.trackChanges { controller in
    +    let newPlayers = controller.fetchedRecords // [Player]
    +}
    +
    + +
    +

    :warning: Warning: notification of individual record changes (the onChange callback) has FetchedRecordsController use a diffing algorithm that has a high complexity, a high memory consumption, and is thus not suited for large result sets. One hundred rows is probably OK, but one thousand is probably not. If your application experiences problems with large lists, see Issue 263 for more information.

    +
    + +

    Callbacks have the fetched record controller itself as an argument: use it in order to avoid memory leaks:

    +
    // BAD: memory leak
    +controller.trackChanges { _ in
    +    let newPlayers = controller.fetchedRecords
    +}
    +
    +// GOOD
    +controller.trackChanges { controller in
    +    let newPlayers = controller.fetchedRecords
    +}
    +
    + +

    Callbacks are invoked asynchronously. See FetchedRecordsController Concurrency for more information.

    + +

    Values fetched from inside callbacks may be inconsistent with the controller’s records. This is because after database has changed, and before the controller had the opportunity to invoke callbacks in the main thread, other database changes can happen.

    + +

    To avoid inconsistencies, provide a fetchAlongside argument to the trackChanges method, as below:

    +
    controller.trackChanges(
    +    fetchAlongside: { db in
    +        // Fetch any extra value, for example the number of fetched records:
    +        return try Player.fetchCount(db)
    +    },
    +    didChange: { (controller, count) in
    +        // The extra value is the second argument.
    +        let recordsCount = controller.fetchedRecords.count
    +        assert(count == recordsCount) // guaranteed
    +    })
    +
    + +

    Whenever the fetched records controller can not look for changes after a transaction has potentially modified the tracked request, an error handler is called. The request observation is not stopped, though: future transactions may successfully be handled, and the notified changes will then be based on the last successful fetch.

    +
    controller.trackErrors { (controller, error) in
    +    print("Missed a transaction because \(error)")
    +}
    +
    +

    Modifying the Fetch Request

    + +

    You can change a fetched records controller’s fetch request or SQL query.

    +
    controller.setRequest(Player.order(Column("name")))
    +controller.setRequest(sql: "SELECT ...", arguments: ...)
    +
    + +

    The notification callbacks are notified of eventual changes if the new request fetches a different set of records.

    + +
    +

    :point_up: Note: This behavior differs from Core Data’s NSFetchedResultsController, which does not notify of record changes when the fetch request is replaced.

    +
    + +

    Change callbacks are invoked asynchronously. This means that modifying the request from the main thread does not immediately triggers callbacks. When you need to take immediate action, force the controller to refresh immediately with its performFetch method. In this case, changes callbacks are not called:

    +
    // Change request on the main thread:
    +controller.setRequest(Player.order(Column("name")))
    +// Here callbacks have not been called yet.
    +// You can cancel them, and refresh records immediately:
    +try controller.performFetch()
    +
    +

    Table and Collection Views

    + +

    FetchedRecordsController let you feed table and collection views, and keep them up-to-date with the database content.

    + +

    For nice animated updates, a fetched records controller needs to recognize identical records between two different result sets. When records adopt the TableRecord protocol, they are automatically compared according to their primary key:

    +
    class Player : TableRecord { ... }
    +let controller = FetchedRecordsController(
    +    dbQueue,
    +    request: Player.all())
    +
    + +

    For other types, the fetched records controller needs you to be more explicit:

    +
    let controller = FetchedRecordsController(
    +    dbQueue,
    +    request: ...,
    +    isSameRecord: { (player1, player2) in player1.id == player2.id })
    +
    +

    Implementing the Table View Datasource Methods

    + +

    The table view data source asks the fetched records controller to provide relevant information:

    +
    func numberOfSections(in tableView: UITableView) -> Int {
    +    return fetchedRecordsController.sections.count
    +}
    +
    +func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    +    return fetchedRecordsController.sections[section].numberOfRecords
    +}
    +
    +func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    +    let cell = ...
    +    let record = fetchedRecordsController.record(at: indexPath)
    +    // Configure the cell
    +    return cell
    +}
    +
    + +
    +

    :point_up: Note: In its current state, FetchedRecordsController does not support grouping table view rows into custom sections: it generates a unique section.

    +
    +

    Implementing Table View Updates

    + +

    When changes in the fetched records should reload the whole table view, you can simply tell so:

    +
    controller.trackChanges { [unowned self] _ in
    +    self.tableView.reloadData()
    +}
    +
    + +

    Yet, FetchedRecordsController can notify that the controller’s fetched records have been changed due to some add, remove, move, or update operations, and help applying animated changes to a UITableView.

    +
    Typical Table View Updates
    + +

    For animated table view updates, use the willChange and didChange callbacks to bracket events provided by the fetched records controller, as illustrated in the following example:

    +
    // Assume self has a tableView property, and a cell configuration
    +// method named configure(_:at:).
    +
    +controller.trackChanges(
    +    // controller's records are about to change:
    +    willChange: { [unowned self] _ in
    +        self.tableView.beginUpdates()
    +    },
    +
    +    // notification of individual record changes:
    +    onChange: { [unowned self] (controller, record, change) in
    +        switch change {
    +        case .insertion(let indexPath):
    +            self.tableView.insertRows(at: [indexPath], with: .fade)
    +
    +        case .deletion(let indexPath):
    +            self.tableView.deleteRows(at: [indexPath], with: .fade)
    +
    +        case .update(let indexPath, _):
    +            if let cell = self.tableView.cellForRow(at: indexPath) {
    +                self.configure(cell, at: indexPath)
    +            }
    +
    +        case .move(let indexPath, let newIndexPath, _):
    +            self.tableView.deleteRows(at: [indexPath], with: .fade)
    +            self.tableView.insertRows(at: [newIndexPath], with: .fade)
    +
    +            // // Alternate technique which actually moves cells around:
    +            // let cell = self.tableView.cellForRow(at: indexPath)
    +            // self.tableView.moveRow(at: indexPath, to: newIndexPath)
    +            // if let cell = cell {
    +            //     self.configure(cell, at: newIndexPath)
    +            // }
    +        }
    +    },
    +
    +    // controller's records have changed:
    +    didChange: { [unowned self] _ in
    +        self.tableView.endUpdates()
    +    })
    +
    + +
    +

    :warning: Warning: notification of individual record changes (the onChange callback) has FetchedRecordsController use a diffing algorithm that has a high complexity, a high memory consumption, and is thus not suited for large result sets. One hundred rows is probably OK, but one thousand is probably not. If your application experiences problems with large lists, see Issue 263 for more information.

    +
    + +

    See GRDBDemoiOS for an sample app that uses FetchedRecordsController to animate a table view.

    + +
    +

    :point_up: Note: our sample code above uses unowned references to the table view controller. This is a safe pattern as long as the table view controller owns the fetched records controller, and is deallocated from the main thread (this is usually the case). In other situations, prefer weak references.

    +
    +

    FetchedRecordsController Concurrency

    + +

    A fetched records controller can not be used from any thread.

    + +

    When the database itself can be read and modified from any thread, fetched records controllers must be used from the main thread. Record changes are also notified on the main thread.

    + +

    Change callbacks are invoked asynchronously. This means that changes made from the main thread are not immediately notified. When you need to take immediate action, force the controller to refresh immediately with its performFetch method. In this case, changes callbacks are not called:

    +
    // Change database on the main thread:
    +try dbQueue.write { db in
    +    try Player(...).insert(db)
    +}
    +// Here callbacks have not been called yet.
    +// You can cancel them, and refresh records immediately:
    +try controller.performFetch()
    +
    + +
    +

    :point_up: Note: when the main thread does not fit your needs, give a serial dispatch queue to the controller initializer: the controller must then be used from this queue, and record changes are notified on this queue as well.

    +
    let queue = DispatchQueue()
    +queue.async {
    +    let controller = try FetchedRecordsController(..., queue: queue)
    +    controller.trackChanges { /* in queue */ }
    +    try controller.performFetch()
    +}
    +
    +
    +

    Encryption

    + +

    GRDB can encrypt your database with SQLCipher v3.4.2.

    + +

    You can use CocoaPods (version 1.2 or higher), and specify in your Podfile:

    +
    use_frameworks!
    +pod 'GRDBCipher'
    +
    + +

    Alternatively, perform a manual installation of GRDB and SQLCipher:

    + +
      +
    1. Clone the GRDB git repository, checkout the latest tagged version, and download SQLCipher sources:

      +
      cd [GRDB directory]
      +git checkout v3.3.0-beta1
      +git submodule update --init SQLCipher/src
      +
    2. +
    3. Embed the GRDBCipher.xcodeproj project in your own project.

    4. +
    5. Add the GRDBCipherOSX or GRDBCipheriOS target in the Target Dependencies section of the Build Phases tab of your application target.

    6. +
    7. Add the GRDBCipher.framework from the targetted platform to the Embedded Binaries section of the General tab of your target.

    8. +
    + +

    You create and open an encrypted database by providing a passphrase to your database connection:

    +
    import GRDBCipher
    +
    +var configuration = Configuration()
    +configuration.passphrase = "secret"
    +let dbQueue = try DatabaseQueue(path: "...", configuration: configuration)
    +
    + +

    You can change the passphrase of an already encrypted database:

    +
    try dbQueue.change(passphrase: "newSecret")
    +
    + +

    Providing a passphrase won’t encrypt a clear-text database that already exists, though. SQLCipher can’t do that, and you will get an error instead: SQLite error 26: file is encrypted or is not a database.

    + +

    To encrypt an existing clear-text database, create a new and empty encrypted database, and copy the content of the clear-text database in it. The technique to do that is documented by SQLCipher. With GRDB, it gives:

    +
    // The clear-text database
    +let clearDBQueue = try DatabaseQueue(path: "/path/to/clear.db")
    +
    +// The encrypted database, at some distinct location:
    +var configuration = Configuration()
    +configuration.passphrase = "secret"
    +let encryptedDBQueue = try DatabaseQueue(path: "/path/to/encrypted.db", configuration: config)
    +
    +try clearDBQueue.inDatabase { db in
    +    try db.execute("ATTACH DATABASE ? AS encrypted KEY ?", arguments: [encryptedDBQueue.path, "secret"])
    +    try db.execute("SELECT sqlcipher_export('encrypted')")
    +    try db.execute("DETACH DATABASE encrypted")
    +}
    +
    +// Now the copy is done, and the clear-text database can be deleted.
    +
    +

    Backup

    + +

    You can backup (copy) a database into another.

    + +

    Backups can for example help you copying an in-memory database to and from a database file when you implement NSDocument subclasses.

    +
    let source: DatabaseQueue = ...      // or DatabasePool
    +let destination: DatabaseQueue = ... // or DatabasePool
    +try source.backup(to: destination)
    +
    + +

    The backup method blocks the current thread until the destination database contains the same contents as the source database.

    + +

    When the source is a database pool, concurrent writes can happen during the backup. Those writes may, or may not, be reflected in the backup, but they won’t trigger any error.

    +

    Avoiding SQL Injection

    + +

    SQL injection is a technique that lets an attacker nuke your database.

    + +
    +

    XKCD: Exploits of a Mom

    + +

    https://xkcd.com/327/

    +
    + +

    Here is an example of code that is vulnerable to SQL injection:

    +
    // BAD BAD BAD
    +let id = 1
    +let name = textField.text
    +try dbQueue.write { db in
    +    try db.execute("UPDATE students SET name = '\(name)' WHERE id = \(id)")
    +}
    +
    + +

    If the user enters a funny string like Robert'; DROP TABLE students; --, SQLite will see the following SQL, and drop your database table instead of updating a name as intended:

    +
    UPDATE students SET name = 'Robert';
    +DROP TABLE students;
    +--' WHERE id = 1
    +
    + +

    To avoid those problems, never embed raw values in your SQL queries. The only correct technique is to provide arguments to your raw SQL queries:

    +
    let name = textField.text
    +try dbQueue.write { db in
    +    // Good
    +    try db.execute(
    +        "UPDATE students SET name = ? WHERE id = ?",
    +        arguments: [name, id])
    +
    +    // Just as good
    +    try db.execute(
    +        "UPDATE students SET name = :name WHERE id = :id",
    +        arguments: ["name": name, "id": id])
    +}
    +
    + +

    When you use records and the query interface, GRDB always prevents SQL injection for you:

    +
    let id = 1
    +let name = textField.text
    +try dbQueue.write { db in
    +    if var student = try Student.fetchOne(db, key: id) {
    +        student.name = name
    +        try student.update(db)
    +    }
    +}
    +
    +

    Error Handling

    + +

    GRDB can throw DatabaseError, PersistenceError, or crash your program with a fatal error.

    + +

    Considering that a local database is not some JSON loaded from a remote server, GRDB focuses on trusted databases. Dealing with untrusted databases requires extra care.

    + + +

    DatabaseError

    + +

    DatabaseError are thrown on SQLite errors:

    +
    do {
    +    try db.execute(
    +        "INSERT INTO pet (masterId, name) VALUES (?, ?)",
    +        arguments: [1, "Bobby"])
    +} catch let error as DatabaseError {
    +    // The SQLite error code: 19 (SQLITE_CONSTRAINT)
    +    error.resultCode
    +
    +    // The extended error code: 787 (SQLITE_CONSTRAINT_FOREIGNKEY)
    +    error.extendedResultCode
    +
    +    // The eventual SQLite message: FOREIGN KEY constraint failed
    +    error.message
    +
    +    // The eventual erroneous SQL query
    +    // "INSERT INTO pet (masterId, name) VALUES (?, ?)"
    +    error.sql
    +
    +    // Full error description:
    +    // "SQLite error 19 with statement `INSERT INTO pet (masterId, name)
    +    //  VALUES (?, ?)` arguments [1, "Bobby"]: FOREIGN KEY constraint failed""
    +    error.description
    +}
    +
    + +

    SQLite uses codes to distinguish between various errors:

    +
    do {
    +    try ...
    +} catch let error as DatabaseError where error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY {
    +    // foreign key constraint error
    +} catch let error as DatabaseError where error.resultCode == .SQLITE_CONSTRAINT {
    +    // any other constraint error
    +} catch let error as DatabaseError {
    +    // any other database error
    +}
    +
    + +

    In the example above, error.extendedResultCode is a precise extended result code, and error.resultCode is a less precise primary result code. Extended result codes are refinements of primary result codes, as SQLITE_CONSTRAINT_FOREIGNKEY is to SQLITE_CONSTRAINT, for example. See SQLite result codes for more information.

    + +

    As a convenience, extended result codes match their primary result code in a switch statement:

    +
    do {
    +    try ...
    +} catch let error as DatabaseError {
    +    switch error.extendedResultCode {
    +    case ResultCode.SQLITE_CONSTRAINT_FOREIGNKEY:
    +        // foreign key constraint error
    +    case ResultCode.SQLITE_CONSTRAINT:
    +        // any other constraint error
    +    default:
    +        // any other database error
    +    }
    +}
    +
    + +
    +

    :warning: Warning: SQLite has progressively introduced extended result codes accross its versions. For example, SQLITE_CONSTRAINT_FOREIGNKEY wasn’t introduced yet on iOS 8.1. The SQLite release notes are unfortunately not quite clear about that: write your handling of extended result codes with care.

    +
    +

    PersistenceError

    + +

    PersistenceError is thrown by the PersistableRecord protocol, in a single case: when the update method could not find any row to update:

    +
    do {
    +    try player.update(db)
    +} catch PersistenceError.recordNotFound {
    +    // There was nothing to update
    +}
    +
    +

    Fatal Errors

    + +

    Fatal errors notify that the program, or the database, has to be changed.

    + +

    They uncover programmer errors, false assumptions, and prevent misuses. Here are a few examples:

    + +
      +
    • The code asks for a non-optional value, when the database contains NULL:

      +
      // fatal error: could not convert NULL to String.
      +let name: String = row["name"]
      +
      + +

      Solution: fix the contents of the database, use NOT NULL constraints, or load an optional:

      +
      let name: String? = row["name"]
      +
    • +
    • Conversion from database value to Swift type fails:

      +
      // fatal error: could not convert "Mom’s birthday" to Date.
      +let date: Date = row["date"]
      +
      +// fatal error: could not convert "" to URL.
      +let url: URL = row["url"]
      +
      + +

      Solution: fix the contents of the database, or use DatabaseValue to handle all possible cases:

      +
      let dbValue: DatabaseValue = row["date"]
      +if dbValue.isNull {
      +    // Handle NULL
      +} else if let date = Date.fromDatabaseValue(dbValue) {
      +    // Handle valid date
      +} else {
      +    // Handle invalid date
      +}
      +
    • +
    • The database can’t guarantee that the code does what it says:

      +
      // fatal error: table player has no unique index on column email
      +try Player.deleteOne(db, key: ["email": "arthur@example.com"])
      +
      + +

      Solution: add a unique index to the player.email column, or use the deleteAll method to make it clear that you may delete more than one row:

      +
      try Player.filter(Column("email") == "arthur@example.com").deleteAll(db)
      +
    • +
    • Database connections are not reentrant:

      +
      // fatal error: Database methods are not reentrant.
      +dbQueue.write { db in
      +    dbQueue.write { db in
      +        ...
      +    }
      +}
      +
      + +

      Solution: avoid reentrancy, and instead pass a database connection along.

    • +
    +

    How to Deal with Untrusted Inputs

    + +

    Let’s consider the code below:

    +
    let sql = "SELECT ..."
    +
    +// Some untrusted arguments for the query
    +let arguments: [String: Any] = ...
    +let rows = try Row.fetchCursor(db, sql, arguments: StatementArguments(arguments))
    +
    +while let row = try rows.next() {
    +    // Some untrusted database value:
    +    let date: Date? = row[0]
    +}
    +
    + +

    It has two opportunities to throw fatal errors:

    + +
      +
    • Untrusted arguments: The dictionary may contain values that do not conform to the DatabaseValueConvertible protocol, or may miss keys required by the statement.
    • +
    • Untrusted database content: The row may contain a non-null value that can’t be turned into a date.
    • +
    + +

    In such a situation, you can still avoid fatal errors by exposing and handling each failure point, one level down in the GRDB API:

    +
    // Untrusted arguments
    +if let arguments = StatementArguments(arguments) {
    +    let statement = try db.makeSelectStatement(sql)
    +    try statement.validate(arguments: arguments)
    +    statement.unsafeSetArguments(arguments)
    +
    +    var cursor = try Row.fetchCursor(statement)
    +    while let row = try iterator.next() {
    +        // Untrusted database content
    +        let dbValue: DatabaseValue = row[0]
    +        if dbValue.isNull {
    +            // Handle NULL
    +        if let date = Date.fromDatabaseValue(dbValue) {
    +            // Handle valid date
    +        } else {
    +            // Handle invalid date
    +        }
    +    }
    +}
    +
    + +

    See prepared statements and DatabaseValue for more information.

    +

    Error Log

    + +

    SQLite can be configured to invoke a callback function containing an error code and a terse error message whenever anomalies occur.

    + +

    This global error callback must be configured early in the lifetime of your application:

    +
    Database.logError = { (resultCode, message) in
    +    NSLog("%@", "SQLite error \(resultCode): \(message)")
    +}
    +
    + +
    +

    :warning: Warning: Database.logError must be set before any database connection is opened. This includes the connections that your application opens with GRDB, but also connections opened by other tools, such as third-party libraries. Setting it after a connection has been opened is an SQLite misuse, and has no effect.

    +
    + +

    See The Error And Warning Log for more information.

    +

    Unicode

    + +

    SQLite lets you store unicode strings in the database.

    + +

    However, SQLite does not provide any unicode-aware string transformations or comparisons.

    +

    Unicode functions

    + +

    The UPPER and LOWER built-in SQLite functions are not unicode-aware:

    +
    // "JéRôME"
    +try String.fetchOne(db, "SELECT UPPER('Jérôme')")
    +
    + +

    GRDB extends SQLite with SQL functions that call the Swift built-in string functions capitalized, lowercased, uppercased, localizedCapitalized, localizedLowercased and localizedUppercased:

    +
    // "JÉRÔME"
    +let uppercased = DatabaseFunction.uppercase
    +try String.fetchOne(db, "SELECT \(uppercased.name)('Jérôme')")
    +
    + +

    Those unicode-aware string functions are also readily available in the query interface:

    +
    Player.select(nameColumn.uppercased)
    +
    +

    String Comparison

    + +

    SQLite compares strings in many occasions: when you sort rows according to a string column, or when you use a comparison operator such as = and <=.

    + +

    The comparison result comes from a collating function, or collation. SQLite comes with three built-in collations that do not support Unicode: binary, nocase, and rtrim.

    + +

    GRDB comes with five extra collations that leverage unicode-aware comparisons based on the standard Swift String comparison functions and operators:

    + +
      +
    • unicodeCompare (uses the built-in <= and == Swift operators)
    • +
    • caseInsensitiveCompare
    • +
    • localizedCaseInsensitiveCompare
    • +
    • localizedCompare
    • +
    • localizedStandardCompare
    • +
    + +

    A collation can be applied to a table column. All comparisons involving this column will then automatically trigger the comparison function:

    +
    try db.create(table: "player") { t in
    +    // Guarantees case-insensitive email unicity
    +    t.column("email", .text).unique().collate(.nocase)
    +
    +    // Sort names in a localized case insensitive way
    +    t.column("name", .text).collate(.localizedCaseInsensitiveCompare)
    +}
    +
    +// Players are sorted in a localized case insensitive way:
    +let players = try Player.order(nameColumn).fetchAll(db)
    +
    + +
    +

    :warning: Warning: SQLite requires host applications to provide the definition of any collation other than binary, nocase and rtrim. When a database file has to be shared or migrated to another SQLite library of platform (such as the Android version of your application), make sure you provide a compatible collation.

    +
    + +

    If you can’t or don’t want to define the comparison behavior of a column (see warning above), you can still use an explicit collation in SQL requests and in the query interface:

    +
    let collation = DatabaseCollation.localizedCaseInsensitiveCompare
    +let players = try Player.fetchAll(db,
    +    "SELECT * FROM player ORDER BY name COLLATE \(collation.name))")
    +let players = try Player.order(nameColumn.collating(collation)).fetchAll(db)
    +
    + +

    You can also define your own collations:

    +
    let collation = DatabaseCollation("customCollation") { (lhs, rhs) -> NSComparisonResult in
    +    // return the comparison of lhs and rhs strings.
    +}
    +dbQueue.add(collation: collation) // Or dbPool.add(collation: ...)
    +
    +

    Memory Management

    + +

    Both SQLite and GRDB use non-essential memory that help them perform better.

    + +

    You can reclaim this memory with the releaseMemory method:

    +
    // Release as much memory as possible.
    +dbQueue.releaseMemory()
    +dbPool.releaseMemory()
    +
    + +

    This method blocks the current thread until all current database accesses are completed, and the memory collected.

    +

    Memory Management on iOS

    + +

    The iOS operating system likes applications that do not consume much memory.

    + +

    Database queues and pools can call the releaseMemory method for you, when application receives memory warnings, and when application enters background: call the setupMemoryManagement method after creating the queue or pool instance:

    +
    let dbQueue = try DatabaseQueue(...)
    +dbQueue.setupMemoryManagement(in: UIApplication.shared)
    +
    +

    Data Protection

    + +

    Data Protection lets you protect files so that they are encrypted and unavailable until the device is unlocked.

    + +

    Data protection can be enabled globally for all files created by an application.

    + +

    You can also explicitly protect a database, by configuring its enclosing directory. This will not only protect the database file, but also all temporary files created by SQLite (including the persistent .shm and .wal files created by database pools).

    + +

    For example, to explicitly use complete protection:

    +
    // Paths
    +let fileManager = FileManager.default
    +let directoryURL = try fileManager
    +    .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    +    .appendingPathComponent("database", isDirectory: true)
    +let databaseURL = directoryURL.appendingPathComponent("db.sqlite")
    +
    +// Create directory if needed
    +var isDirectory: ObjCBool = false
    +if !fileManager.fileExists(atPath: directoryURL.path, isDirectory: &isDirectory) {
    +    try fileManager.createDirectory(atPath: directoryURL.path, withIntermediateDirectories: false)
    +} else if !isDirectory.boolValue {
    +    throw NSError(domain: NSCocoaErrorDomain, code: NSFileWriteFileExistsError, userInfo: nil)
    +}
    +
    +// Enable data protection
    +try fileManager.setAttributes([.protectionKey : FileProtectionType.complete], ofItemAtPath: directoryURL.path)
    +
    +// Open database
    +let dbQueue = try DatabaseQueue(path: databaseURL.path)
    +
    + +

    When a database is protected, an application that runs in the background on a locked device won’t be able to read or write from it. Instead, it will get DatabaseError with code SQLITE_IOERR (10) disk I/O error, or SQLITE_AUTH (23) not authorized.

    + +

    You can catch those errors and wait for UIApplicationDelegate.applicationProtectedDataDidBecomeAvailable(_:) or UIApplicationProtectedDataDidBecomeAvailable notification in order to retry the failed database operation.

    +

    Concurrency

    + + +

    Guarantees and Rules

    + +

    GRDB ships with three concurrency modes:

    + +
      +
    • DatabaseQueue opens a single database connection, and serializes all database accesses.
    • +
    • DatabasePool manages a pool of several database connections, and allows concurrent reads and writes.
    • +
    • DatabaseSnapshot opens a single read-only database connection on an unchanging database content, and (currently) serializes all database accesses
    • +
    + +

    All foster application safety: regardless of the concurrency mode you choose, GRDB provides you with the same guarantees, as long as you follow three rules.

    + +
      +
    • :bowtie: Guarantee 1: writes are always serialized. At every moment, there is no more than a single thread that is writing into the database.

      + +
      +

      Database writes always happen in a unique serial dispatch queue, named the writer protected dispatch queue.

      +
    • +
    • :bowtie: Guarantee 2: reads are always isolated. This means that they are guaranteed an immutable view of the last committed state of the database, and that you can perform subsequent fetches without fearing eventual concurrent writes to mess with your application logic:

      +
      try dbPool.read { db in // or dbQueue.read
      +    // Guaranteed to be equal
      +    let count1 = try Player.fetchCount(db)
      +    let count2 = try Player.fetchCount(db)
      +}
      +
      + +
      +

      In database queues, reads happen in the same protected dispatch queue as writes: isolation is just a consequence of the serialization of database accesses

      + +

      Database pools and snapshots both use the snapshot isolation made possible by SQLite’s WAL mode (see Isolation In SQLite).

      +
    • +
    • :bowtie: Guarantee 3: requests don’t fail, unless a database constraint violation, a programmer mistake, or a very low-level issue such as a disk error or an unreadable database file. GRDB grants correct use of SQLite, and particularly avoids locking errors and other SQLite misuses.

    • +
    + +

    Those guarantees hold as long as you follow three rules:

    + +
      +
    • :point_up: Rule 1: Have a unique instance of DatabaseQueue or DatabasePool connected to any database file.

      + +

      This means that opening a new connection each time you access the database is probably a very bad idea. Do share a single connection instead.

      + +

      See, for example, DemoApps/GRDBDemoiOS/AppDatabase.swift for a sample code that properly sets up a single database queue that is available throughout the application.

      + +

      If there are several instances of database queues or pools that write in the same database, a multi-threaded application will eventually face database is locked errors. See Dealing with External Connections.

      +
      // SAFE CONCURRENCY
      +func fetchCurrentUser(_ db: Database) throws -> User? {
      +    return try User.fetchOne(db)
      +}
      +// dbQueue is a singleton defined somewhere in your app
      +let user = try dbQueue.read { db in // or dbPool.read
      +    try fetchCurrentUser(db)
      +}
      +
      +// UNSAFE CONCURRENCY
      +// This method fails when some other thread is currently writing into
      +// the database.
      +func currentUser() throws -> User? {
      +    let dbQueue = try DatabaseQueue(...)
      +    return try dbQueue.read { db in
      +        try User.fetchOne(db)
      +    }
      +}
      +let user = try currentUser()
      +
    • +
    • :point_up: Rule 2: Group related statements within a single call to a DatabaseQueue or DatabasePool database access method (or use snapshots).

      + +

      Database access methods isolate your groups of related statements against eventual database updates performed by other threads, and guarantee a consistent view of the database. This isolation is only guaranteed inside the closure argument of those methods. Two consecutive calls do not guarantee isolation:

      +
      // SAFE CONCURRENCY
      +try dbPool.read { db in  // or dbQueue.read
      +    // Guaranteed to be equal:
      +    let count1 = try Place.fetchCount(db)
      +    let count2 = try Place.fetchCount(db)
      +}
      +
      +// UNSAFE CONCURRENCY
      +// Those two values may be different because some other thread may have
      +// modified the database between the two blocks:
      +let count1 = try dbPool.read { db in try Place.fetchCount(db) }
      +let count2 = try dbPool.read { db in try Place.fetchCount(db) }
      +
      + +

      In the same vein, when you fetch values that depends on some database updates, group them:

      +
      // SAFE CONCURRENCY
      +try dbPool.write { db in
      +    // The count is guaranteed to be non-zero
      +    try Place(...).insert(db)
      +    let count = try Place.fetchCount(db)
      +}
      +
      +// UNSAFE CONCURRENCY
      +// The count may be zero because some other thread may have performed
      +// a deletion between the two blocks:
      +try dbPool.write { db in try Place(...).insert(db) }
      +let count = try dbPool.read { db in try Place.fetchCount(db) }
      +
      + +

      On that last example, see Advanced DatabasePool if you look after extra performance.

    • +
    • :point_up: Rule 3: When you perform several modifications of the database that temporarily put the database in an inconsistent state, make sure those modifications are grouped within a transaction.

      +
      // SAFE CONCURRENCY
      +try dbPool.write { db in               // or dbQueue.write
      +    try Credit(destinationAccout, amount).insert(db)
      +    try Debit(sourceAccount, amount).insert(db)
      +}
      +
      +// SAFE CONCURRENCY
      +try dbPool.writeInTransaction { db in  // or dbQueue.inTransaction
      +    try Credit(destinationAccout, amount).insert(db)
      +    try Debit(sourceAccount, amount).insert(db)
      +    return .commit
      +}
      +
      +// UNSAFE CONCURRENCY
      +try dbPool.writeWithoutTransaction { db in
      +    try Credit(destinationAccout, amount).insert(db)
      +    // <- Concurrent dbPool.read sees a partial db update here
      +    try Debit(sourceAccount, amount).insert(db)
      +}
      +
      + +

      Without transaction, DatabasePool.read { ... } may see the first statement, but not the second, and access a database where the balance of accounts is not zero. A highly bug-prone situation.

      + +

      So do use transactions in order to guarantee database consistency accross your application threads: that’s what they are made for.

    • +
    +

    Differences between Database Queues and Pools

    + +

    Despite the common guarantees and rules shared by database queues and pools, those two database accessors don’t have the same behavior.

    + +

    Database queues serialize all database accesses, reads, and writes. There is never more than one thread that uses the database. In the image below, we see how three threads can see the database as time passes:

    + +

    DatabaseQueueScheduling

    + +

    Database pools also serialize all writes. But they allow concurrent reads and writes, and isolate reads so that they don’t see changes performed by other threads. This gives a very different picture:

    + +

    DatabasePoolScheduling

    + +

    See how, with database pools, two reads can see different database states at the same time.

    + +

    For more information about database pools, grab information about SQLite WAL mode and snapshot isolation. See Database Observation when you look after automatic notifications of database changes.

    +

    Advanced DatabasePool

    + +

    Database pools are very concurrent, since all reads can run in parallel, and can even run during write operations. But writes are still serialized: at any given point in time, there is no more than a single thread that is writing into the database.

    + +

    When your application modifies the database, and then reads some value that depends on those modifications, you may want to avoid locking the writer queue longer than necessary:

    +
    try dbPool.write { db in
    +    // Increment the number of players
    +    try Player(...).insert(db)
    +
    +    // Read the number of players. The writer queue is still locked :-(
    +    let count = try Player.fetchCount(db)
    +}
    +
    + +

    A wrong solution is to chain a write then a read, as below. Don’t do that, because another thread may modify the database in between, and make the read unreliable:

    +
    // WRONG
    +try dbPool.write { db in
    +    // Increment the number of players
    +    try Player(...).insert(db)
    +}
    +try dbPool.read { db in
    +    // Read some random value :-(
    +    let count = try Player.fetchCount(db)
    +}
    +
    + +

    The correct solution is the readFromCurrentState method, which must be called from within a write block, outside of any transaction:

    +
    // CORRECT
    +try dbPool.writeWithoutTransaction { db in
    +    try db.inTransaction {
    +        // increment the number of players
    +        try Player(...).insert(db)
    +        return .commit
    +    }
    +
    +    // <- not in a transaction here
    +    try dbPool.readFromCurrentState { db
    +        // Read the number of players. The writer queue has been unlocked :-)
    +        let count = try Player.fetchCount(db)
    +    }
    +}
    +
    + +

    readFromCurrentState blocks until it can guarantee its closure argument an isolated access to the last committed state of the database. It then asynchronously executes the closure. If the isolated access can’t be established, readFromCurrentState throws an error, and the closure is not executed.

    + +

    The closure can run concurrently with eventual updates performed after readFromCurrentState: those updates won’t be visible from within the closure. In the example below, the number of players is guaranteed to be non-zero, even though it is fetched concurrently with the player deletion:

    +
    try dbPool.writeWithoutTransaction { db in
    +    // Increment the number of players
    +    try Player(...).insert(db)
    +
    +    try dbPool.readFromCurrentState { db
    +        // Guaranteed to be non-zero
    +        let count = try Player.fetchCount(db)
    +    }
    +
    +    try Player.deleteAll(db)
    +}
    +
    + +

    Transaction Observers can also use readFromCurrentState in their databaseDidCommit method in order to process database changes without blocking other threads that want to write into the database.

    +

    Database Snapshots

    + +

    A database snapshot sees an unchanging database content, as it existed at the moment it was created.

    + +

    Unchanging means that a snapshot never sees any database modifications during all its lifetime. And yet it doesn’t prevent database updates. This magic is made possible by SQLite’s WAL mode (see Isolation In SQLite).

    + +

    You create snapshots from a database pool:

    +
    let snapshot = try dbPool.makeSnapshot()
    +
    + +

    You can create as many snapshots as you need, regardless of the maximum number of readers in the pool. A snapshot database connection is closed when the snapshot gets deallocated.

    + +

    A snapshot can be used from any thread. Its read methods is synchronous, and blocks the current thread until your database statements are executed:

    +
    // Read values:
    +try snapshot.read { db in
    +    let players = try Player.fetchAll(db)
    +    let playerCount = try Player.fetchCount(db)
    +}
    +
    +// Extract a value from the database:
    +let playerCount = try snapshot.read { db in
    +    try Player.fetchCount(db)
    +}
    +
    + +

    When you want to control the latest committed changes seen by a snapshot, create it from the pool’s writer protected dispatch queue, outside of any transaction:

    +
    let snapshot1 = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshot in
    +    try db.inTransaction {
    +        // delete all players
    +        try Player.deleteAll()
    +        return .commit
    +    }
    +
    +    // <- not in a transaction here
    +    return dbPool.makeSnapshot()
    +}
    +// <- Other threads may modify the database here
    +let snapshot2 = try dbPool.makeSnapshot()
    +
    +try snapshot1.read { db in
    +    // Guaranteed to be zero
    +    try Player.fetchCount(db)
    +}
    +
    +try snapshot2.read { db in
    +    // Could be anything
    +    try Player.fetchCount(db)
    +}
    +
    + +
    +

    :point_up: Note: snapshots currently serialize all database accesses. In the future, snapshots may allow concurrent reads.

    +
    +

    DatabaseWriter and DatabaseReader Protocols

    + +

    Both DatabaseQueue and DatabasePool adopt the DatabaseReader and DatabaseWriter protocols. DatabaseSnapshot adopts DatabaseReader only.

    + +

    These protocols provide a unified API that lets you write safe concurrent code that targets all three concurrency modes.

    + +

    However, queues are not pools which are different from snapshots, and DatabaseReader and DatabaseWriter provide the smallest common guarantees. They require more discipline:

    + +
      +
    • Pools are less forgiving than queues when one overlooks a transaction (see concurrency rule 3).
    • +
    • DatabaseWriter.readFromCurrentState is synchronous, or asynchronous, depending on whether it is run by a queue or a pool (see advanced DatabasePool). It thus requires higher libDispatch skills, and more complex synchronization code.
    • +
    + +

    DatabaseReader and DatabaseWriter are not a tool for applications that hesitate between DatabaseQueue and DatabasePool, and look for a common API. As seen above, the protocols actually make applications harder to write correctly. Instead, they target generic code that has both queues and pools in mind. The built-in AnyDatabaseReader and AnyDatabaseWriter type erasers serve the same purpose.

    + +

    DatabaseWriter and DatabaseReader fuel, for example:

    + + +

    Unsafe Concurrency APIs

    + +

    Database queues, pools, snapshots, as well as their common protocols DatabaseReader and DatabaseWriter provide unsafe APIs. Unsafe APIs lift concurrency guarantees, and allow advanced yet unsafe patterns.

    + +
      +
    • unsafeRead

      + +

      The unsafeRead method is synchronous, and blocks the current thread until your database statements are executed in a protected dispatch queue. GRDB does just the bare minimum to provide a database connection that can read.

      + +

      When used on a database pool, reads are no longer isolated:

      +
      dbPool.unsafeRead { db in
      +    // Those two values may be different because some other thread
      +    // may have inserted or deleted a player between the two requests:
      +    let count1 = try Player.fetchCount(db)
      +    let count2 = try Player.fetchCount(db)
      +}
      +
      + +

      When used on a database queue, the closure argument is allowed to write in the database.

    • +
    • unsafeReentrantRead

      + +

      The unsafeReentrantRead behaves just as unsafeRead (see above), and allows reentrant calls:

      +
      dbPool.read { db1 in
      +    // No "Database methods are not reentrant" fatal error:
      +    dbPool.unsafeReentrantRead { db2 in
      +        dbPool.unsafeReentrantRead { db3 in
      +            ...
      +        }
      +    }
      +}
      +
      + +

      Reentrant database accesses make it very easy to break the second safety rule, which says: group related statements within a single call to a DatabaseQueue or DatabasePool database access method.. Using a reentrant method is pretty much likely the sign of a wrong application architecture that needs refactoring.

      + +

      There is a single valid use case for reentrant methods, which is when you are unable to control database access scheduling.

    • +
    • unsafeReentrantWrite

      + +

      The unsafeReentrantWrite method is synchronous, and blocks the current thread until your database statements are executed in a protected dispatch queue. Writes are serialized: eventual concurrent database updates are postponed until the block has executed.

      + +

      Reentrant calls are allowed:

      +
      dbQueue.write { db1 in
      +    // No "Database methods are not reentrant" fatal error:
      +    dbQueue.unsafeReentrantWrite { db2 in
      +        dbQueue.unsafeReentrantWrite { db3 in
      +            ...
      +        }
      +    }
      +}
      +
      + +

      Reentrant database accesses make it very easy to break the second safety rule, which says: group related statements within a single call to a DatabaseQueue or DatabasePool database access method.. Using a reentrant method is pretty much likely the sign of a wrong application architecture that needs refactoring.

      + +

      There is a single valid use case for reentrant methods, which is when you are unable to control database access scheduling.

    • +
    +

    Dealing with External Connections

    + +

    The first rule of GRDB is:

    + +
      +
    • Rule 1: Have a unique instance of DatabaseQueue or DatabasePool connected to any database file.
    • +
    + +

    This means that dealing with external connections is not a focus of GRDB. Guarantees of GRDB may or may not hold as soon as some external connection modifies a database.

    + +

    If you absolutely need multiple connections, then:

    + + +

    Performance

    + +

    GRDB is a reasonably fast library, and can deliver quite efficient SQLite access. See Comparing the Performances of Swift SQLite libraries for an overview.

    + +

    You’ll find below general advice when you do look after performance:

    + +
      +
    • Focus
    • +
    • Know your platform
    • +
    • Use transactions
    • +
    • Don’t do useless work
    • +
    • Learn about SQL strengths and weaknesses
    • +
    • Avoid strings & dictionaries
    • +
    +

    Performance tip: focus

    + +

    You don’t know which part of your program needs improvement until you have run a benchmarking tool.

    + +

    Don’t make any assumption, avoid optimizing code too early, and use Instruments.

    +

    Performance tip: know your platform

    + +

    If your application processes a huge JSON file and inserts thousands of rows in the database right from the main thread, it will quite likely become unresponsive, and provide a sub-quality user experience.

    + +

    If not done yet, read the Concurrency Programming Guide and learn how to perform heavy computations without blocking your application.

    + +

    Most GRBD APIs are synchronous. Spawning them into parallel queues is as easy as:

    +
    DispatchQueue.global().async { 
    +    dbQueue.write { db in
    +        // Perform database work
    +    }
    +    DispatchQueue.main.async { 
    +        // update your user interface
    +    }
    +}
    +
    +

    Performance tip: use transactions

    + +

    Performing multiple updates to the database is much faster when executed inside a transaction. This is because a transaction allows SQLite to postpone writing changes to disk until the final commit:

    +
    // Inefficient
    +try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction
    +    for player in players {
    +        try player.insert(db)
    +    }
    +}
    +
    +// Efficient
    +try dbQueue.write { db in      // or dbPool.write
    +    for player in players {
    +        try player.insert(db)
    +    }
    +}
    +
    +// Efficient
    +try dbQueue.inTransaction { db in // or dbPool.writeInTransaction
    +    for player in players {
    +        try player.insert(db)
    +    }
    +    return .commit
    +}
    +
    +

    Performance tip: don’t do useless work

    + +

    Obviously, no code is faster than any code.

    + +

    Don’t fetch columns you don’t use

    +
    // SELECT * FROM player
    +try Player.fetchAll(db)
    +
    +// SELECT id, name FROM player
    +try Player.select(idColumn, nameColumn).fetchAll(db)
    +
    + +

    If your Player type can’t be built without other columns (it has non-optional properties for other columns), do define and use a different type.

    + +

    See Columns Selected by a Request for more information.

    + +

    Don’t fetch rows you don’t use

    + +

    Use fetchOne when you need a single value, and otherwise limit your queries at the database level:

    +
    // Wrong way: this code may discard hundreds of useless database rows
    +let players = try Player.order(scoreColumn.desc).fetchAll(db)
    +let hallOfFame = players.prefix(5)
    +
    +// Better way
    +let hallOfFame = try Player.order(scoreColumn.desc).limit(5).fetchAll(db)
    +
    + +

    Don’t copy values unless necessary

    + +

    Particularly: the Array returned by the fetchAll method, and the cursor returned by fetchCursor aren’t the same:

    + +

    fetchAll copies all values from the database into memory, when fetchCursor iterates database results as they are generated by SQLite, taking profit from SQLite efficiency.

    + +

    You should only load arrays if you need to keep them for later use (such as iterating their contents in the main thread). Otherwise, use fetchCursor.

    + +

    See fetching methods for more information about fetchAll and fetchCursor. See also the Row.dataNoCopy method.

    + +

    Don’t update rows unless necessary

    + +

    An UPDATE statement is costly: SQLite has to look for the updated row, update values, and write changes to disk.

    + +

    When the overwritten values are the same as the existing ones, it’s thus better to avoid performing the UPDATE statement:.

    +
    if player.hasDatabaseChanges {
    +    try player.update(db)
    +}
    +
    + +

    See Record Comparison for more information.

    +

    Performance tip: learn about SQL strengths and weaknesses

    + +

    Consider a simple use case: your store application has to display a list of authors with the number of available books:

    + +
      +
    • J. M. Coetzee (6)
    • +
    • Herman Melville (1)
    • +
    • Alice Munro (3)
    • +
    • Kim Stanley Robinson (7)
    • +
    • Oliver Sacks (4)
    • +
    + +

    The following code is inefficient. It is an example of the N+1 problem, because it performs one query to load the authors, and then N queries, as many as there are authors. This turns very inefficient as the number of authors grows:

    +
    // SELECT * FROM author
    +let authors = try Author.fetchAll(db)
    +for author in authors {
    +    // SELECT COUNT(*) FROM book WHERE authorId = ...
    +    author.bookCount = try Book.filter(authorIdColumn == author.id).fetchCount(db)
    +}
    +
    + +

    Instead, perform a single query:

    +
    let sql = """
    +    SELECT author.*, COUNT(book.id) AS bookCount
    +    FROM author
    +    LEFT JOIN book ON book.authorId = author.id
    +    GROUP BY author.id
    +    """
    +let authors = try Author.fetchAll(db, sql)
    +
    + +

    In the example above, consider extending your Author with an extra bookCount property, or define and use a different type.

    + +

    Generally, define indexes on your database tables, and use SQLite’s efficient query planning:

    + + +

    Performance tip: avoid strings & dictionaries

    + +

    The String and Dictionary Swift types are better avoided when you look for the best performance.

    + +

    Now GRDB records, for your convenience, do use strings and dictionaries:

    +
    class Player : Record {
    +    var id: Int64?
    +    var name: String
    +    var email: String
    +
    +    required init(_ row: Row) {
    +        id = row["id"]       // String
    +        name = row["name"]   // String
    +        email = row["email"] // String
    +        super.init()
    +    }
    +
    +    override func encode(to container: inout PersistenceContainer) {
    +        container["id"] = id              // String
    +        container["name"] = name          // String
    +        container["email"] = email        // String
    +    }
    +}
    +
    + +

    When convenience hurts performance, you can still use records, but you have better avoiding their string and dictionary-based methods.

    + +

    For example, when fetching values, prefer loading columns by index:

    +
    // Strings & dictionaries
    +let players = try Player.fetchAll(db)
    +
    +// Column indexes
    +// SELECT id, name, email FROM player
    +let request = Player.select(idColumn, nameColumn, emailColumn)
    +let rows = try Row.fetchCursor(db, request)
    +while let row = try rows.next() {
    +    let id: Int64 = row[0]
    +    let name: String = row[1]
    +    let email: String = row[2]
    +    let player = Player(id: id, name: name, email: email)
    +    ...
    +}
    +
    + +

    When inserting values, use reusable prepared statements, and set statements values with an array:

    +
    // Strings & dictionaries
    +for player in players {
    +    try player.insert(db)
    +}
    +
    +// Prepared statement
    +let insertStatement = db.prepareStatement("INSERT INTO player (name, email) VALUES (?, ?)")
    +for player in players {
    +    // Only use the unsafe arguments setter if you are sure that you provide
    +    // all statement arguments. A mistake can store unexpected values in
    +    // the database.
    +    insertStatement.unsafeSetArguments([player.name, player.email])
    +    try insertStatement.execute()
    +}
    +
    +

    FAQ

    + + +

    How do I create a database in my application?

    + +

    This question assumes that your application has to create a new database from scratch. If your app has to open an existing database that is embedded inside your application as a resource, see How do I open a database stored as a resource of my application? instead.

    + +

    The database has to be stored in a valid place where it can be created and modified. For example, in the Application Support directory:

    +
    let databaseURL = try FileManager.default
    +    .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    +    .appendingPathComponent("db.sqlite")
    +let dbQueue = try DatabaseQueue(path: databaseURL.path)
    +
    +

    How do I open a database stored as a resource of my application?

    + +

    If your application does not need to modify the database, open a read-only connection to your resource:

    +
    var configuration = Configuration()
    +configuration.readonly = true
    +let dbPath = Bundle.main.path(forResource: "db", ofType: "sqlite")!
    +let dbQueue = try DatabaseQueue(path: dbPath, configuration: configuration)
    +
    + +

    If the application should modify the database, you need to copy it to a place where it can be modified. For example, in the Application Support directory. Only then, open a connection:

    +
    let fileManager = FileManager.default
    +let dbPath = try fileManager
    +    .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    +    .appendingPathComponent("db.sqlite")
    +    .path
    +if !fileManager.fileExists(atPath: dbPath) {
    +    let dbResourcePath = Bundle.main.path(forResource: "db", ofType: "sqlite")!
    +    try fileManager.copyItem(atPath: dbResourcePath, toPath: dbPath)
    +}
    +let dbQueue = try DatabaseQueue(path: dbPath)
    +
    +

    How do I close a database connection?

    + +

    Database connections are managed by database queues and pools. A connection is closed when its database queue or pool is deallocated, and all usages of this connection are completed.

    + +

    Database accesses that run in background threads postpone the closing of connections.

    +

    How do I print a request as SQL?

    + +

    When you want to debug a request that does not deliver the expected results, you may want to print the SQL that is actually executed.

    + +

    You can turn your request into a SQLRequest instance:

    +
    try dbQueue.read { db in
    +    let request = Wine
    +        .filter(Column("origin") == "Burgundy")
    +        .order(Column("price")
    +
    +    let sqlRequest = try SQLRequest(db, request: request)
    +    print(sqlRequest.sql)
    +    // Prints SELECT * FROM wine WHERE origin = ? ORDER BY price
    +    print(sqlRequest.arguments)
    +    // Prints ["Burgundy"]
    +}
    +
    + +

    Another option is to setup a tracing function that will print out all SQL requests executed by your application. You provide the trace function when you connect to the database:

    +
    var config = Configuration()
    +config.trace = { print($0) } // Prints all SQL statements
    +let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
    +
    +try dbQueue.read { db in
    +    let wines = Wine
    +        .filter(Column("origin") == "Burgundy")
    +        .order(Column("price")
    +        .fetchAll(db)
    +    // Prints SELECT * FROM wine WHERE origin = 'Burgundy' ORDER BY price
    +}
    +
    +

    Generic parameter ‘T’ could not be inferred

    + +

    You may get this error when using the read and write methods of database queues and pools:

    +
    // Generic parameter 'T' could not be inferred
    +let x = try dbQueue.read { db in
    +    let result = try String.fetchOne(db, ...)
    +    return result
    +}
    +
    + +

    This is a Swift compiler issue (see SR-1570).

    + +

    The general workaround is to explicitly declare the type of the closure result:

    +
    // General Workaround
    +let string = try dbQueue.read { db -> String? in
    +    let result = try String.fetchOne(db, ...)
    +    return result
    +}
    +
    + +

    You can also, when possible, write a single-line closure:

    +
    // Single-line closure workaround:
    +let string = try dbQueue.read { db in
    +    try String.fetchOne(db, ...)
    +}
    +
    +

    SQLite error 10 disk I/O error, SQLite error 23 not authorized

    + +

    Those errors may be the sign that SQLite can’t access the database due to data protection.

    + +

    When your application should be able to run in the background on a locked device, it has to catch this error, and, for example, wait for UIApplicationDelegate.applicationProtectedDataDidBecomeAvailable(_:) or UIApplicationProtectedDataDidBecomeAvailable notification and retry the failed database operation.

    + +

    This error can also be prevented altogether by using a more relaxed file protection.

    +

    What Are Experimental Features?

    + +

    Since GRDB 1.0, all backwards compatibility guarantees of semantic versioning apply: no breaking change will happen until the next major version of the library.

    + +

    There is an exception, though: experimental features, marked with the **:fire: EXPERIMENTAL** badge. Those are advanced features that are too young, or lack user feedback. They are not stabilized yet.

    + +

    Those experimental features are not protected by semantic versioning, and may break between two minor releases of the library. To help them becoming stable, your feedback is greatly appreciated.

    +

    Sample Code

    + + + +
    + +

    Thanks

    + + +

    Legacy

    +

    Changes Tracking

    + +

    This chapter has been renamed Record Comparison.

    +

    Persistable Protocol

    + +

    This protocol has been renamed PersistableRecord in GRDB 3.0.

    +

    RowConvertible Protocol

    + +

    This protocol has been renamed FetchableRecord in GRDB 3.0.

    +

    TableMapping Protocol

    + +

    This protocol has been renamed TableRecord in GRDB 3.0.

    +

    Customized Decoding of Database Rows

    + +

    This chapter has been renamed Beyond FetchableRecord.

    + +
    +
    + +
    +
    + + + diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/js/jazzy.js b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/js/jazzy.js new file mode 100755 index 000000000..3965b5fb6 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/js/jazzy.js @@ -0,0 +1,46 @@ +window.jazzy = {'docset': false} +if (typeof window.dash != 'undefined') { + document.documentElement.className += ' dash' + window.jazzy.docset = true +} +if (navigator.userAgent.match(/xcode/i)) { + document.documentElement.className += ' xcode' + window.jazzy.docset = true +} + +// On doc load, toggle the URL hash discussion if present +$(document).ready(function() { + if (!window.jazzy.docset) { + var linkToHash = $('a[href="' + window.location.hash +'"]'); + linkToHash.trigger("click"); + } +}); + +// On token click, toggle its discussion and animate token.marginLeft +$(".token").click(function(event) { + if (window.jazzy.docset) { + return; + } + var link = $(this); + var animationDuration = 300; + var tokenOffset = "15px"; + var original = link.css('marginLeft') == tokenOffset; + link.animate({'margin-left':original ? "0px" : tokenOffset}, animationDuration); + $content = link.parent().parent().next(); + $content.slideToggle(animationDuration); + + // Keeps the document from jumping to the hash. + var href = $(this).attr('href'); + if (history.pushState) { + history.pushState({}, '', href); + } else { + location.hash = href; + } + event.preventDefault(); +}); + +// Dumb down quotes within code blocks that delimit strings instead of quotations +// https://github.com/realm/jazzy/issues/714 +$("code q").replaceWith(function () { + return ["\"", $(this).contents(), "\""]; +}); diff --git a/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/js/jquery.min.js b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/js/jquery.min.js new file mode 100755 index 000000000..ab28a2472 --- /dev/null +++ b/docs/3.3/docsets/GRDB.docset/Contents/Resources/Documents/js/jquery.min.js @@ -0,0 +1,4 @@ +/*! jQuery v1.11.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ +!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.1",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="
    ",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h; +if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.lengthh;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML="
    a",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/\s*$/g,rb={option:[1,""],legend:[1,"
    ","
    "],area:[1,"",""],param:[1,"",""],thead:[1,"","
    "],tr:[2,"","
    "],col:[2,"","
    "],td:[3,"","
    "],_default:k.htmlSerialize?[0,"",""]:[1,"X
    ","
    "]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?""!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("