This cursor forwards its next() method to an arbitrary underlying cursor
+having the same Element type, hiding the specifics of the underlying
+cursor.
A subclass of Statement that fetches database rows.
+
+
You create SelectStatement with the Database.makeSelectStatement() method:
+
+
try dbQueue.inDatabase { db in
+ let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM persons WHERE age > ?")
+ let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
+ let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
+}
+
This cursor forwards its next() method to an arbitrary underlying cursor
+having the same Element type, hiding the specifics of the underlying
+cursor.
The total number of rows modified, inserted or deleted by all successful
+INSERT, UPDATE or DELETE statements since the database connection was
+opened.
The transaction type (default nil). If nil, the transaction type is configuration.defaultTransactionKind, which itself defaults to .immediate. See https://www.sqlite.org/lang_transaction.html for more information.
+
+
+
+
+
+
+
+ block
+
+
+
+
+
A block that executes SQL statements and return either .commit or .rollback.
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 elements, provided is not nil.
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.
Synchronously executes a read-only block in a protected dispatch queue,
+and returns its result. The block is wrapped in a deferred transaction.
+
+
let persons = try dbPool.read { db in
+ try Person.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
+ // `wines` table is modified between the two requests:
+ let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
+ let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
+}
+
+try dbPool.read { db in
+ // Now this value may be different:
+ let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
+}
+
+
+
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.
+
+
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 wines")!
+ let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
+}
+
+
+
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.
+
+
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.write { db in
+ try db.execute(...)
+}
+
+
+
To maintain database integrity, and preserve eventual concurrent reads
+from seeing an inconsistent database state, prefer the
+writeInTransaction method.
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 readers do not see partial changes:
+
+
dbPool.writeInTransaction { db in
+ // Eventually preserve a zero balance
+ try db.execute(db, "INSERT INTO credits ...", arguments: [amount])
+ try db.execute(db, "INSERT INTO debits ...", arguments: [amount])
+}
+
+dbPool.read { db in
+ // Here the balance is guaranteed to be zero
+}
+
+
+
This method is not reentrant.
+
+
+
Throws
+ The error thrown by the block, or any error establishing the
+transaction.
+
+
The transaction type (default nil). If nil, the transaction type is configuration.defaultTransactionKind, which itself defaults to .immediate. See https://www.sqlite.org/lang_transaction.html for more information.
+
+
+
+
+
+
+
+ block
+
+
+
+
+
A block that executes SQL statements and return either .commit or .rollback.
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.
+
+
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 persons")
+ try dbPool.readFromCurrentState { db in
+ // Guaranteed to be zero
+ try Int.fetchOne(db, "SELECT COUNT(*) FROM persons")!
+ }
+ try db.execute("INSERT INTO persons ...")
+}
+
+
+
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.
+
+
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
+ db.execute(...)
+ return .commit
+}
+
The transaction type (default nil). If nil, the transaction type is configuration.defaultTransactionKind, which itself defaults to .immediate. See https://www.sqlite.org/lang_transaction.html for more information.
+
+
+
+
+
+
+
+ block
+
+
+
+
+
A block that executes SQL statements and return either .commit or .rollback.
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.
Synchronously executes a read-only block in a protected dispatch queue,
+and returns its result.
+
+
let persons = try dbQueue.read { db in
+ try Person.fetchAll(...)
+}
+
+
+
This method is not reentrant.
+
+
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.
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.
+
+
This method must be called from the protected database dispatch queue.
+See DatabaseWriter.readFromCurrentState.
Synchronizes the full-text table with the content of an external
+table.
+
+
The full-text table is initially populated with the existing
+content in the external table. SQL triggers make sure that the
+full-text table is kept up to date with the external table.
Creates a fetched records controller initialized from a SQL query and
+its eventual arguments.
+
+
let controller = FetchedRecordsController<Wine>(
+ dbQueue,
+ sql: "SELECT * FROM wines WHERE color = ? ORDER BY name",
+ arguments: [Color.red],
+ isSameRecord: { (wine1, wine2) in wine1.id == wine2.id })
+
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.
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).
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.
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).
Creates a fetched records controller initialized from a SQL query and
+its eventual arguments.
+
+
let controller = FetchedRecordsController<Wine>(
+ dbQueue,
+ sql: "SELECT * FROM wines 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 wines table has an `id` primary key:
+let controller = FetchedRecordsController<Wine>(
+ dbQueue,
+ sql: "SELECT * FROM wines WHERE color = ? ORDER BY name",
+ arguments: [Color.red],
+ isSameRecord: { (wine1, wine2) in wine1.id == wine2.id })
+
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 wines table has an `id` primary key:
+let controller = FetchedRecordsController<Wine>(
+ dbQueue,
+ request: request,
+ isSameRecord: { (wine1, wine2) in wine1.id == wine2.id })
+
The input row may not come straight from the database. When you want to
+complete your initialization after being fetched, override
+awakeFromFetch(row:).
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.
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 Person : Record {
+ var id: Int64?
+ var name: String?
+
+ func didInsert(with rowID: Int64, for column: String?) {
+ id = rowID
+ }
+}
+
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 its persistentDictionary has been changed
+since last database synchronization (fetch, update, insert). Comparison
+is performed on values: setting a property to the same value does not
+trigger the edited 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.
On success, this method sets the hasPersistentChangedValues 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.
+
+
On success, this method sets the hasPersistentChangedValues 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.
+
+
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().
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.
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).
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).
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.
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).
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).
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.
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).
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).
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.
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.
Returns a cursor over rows fetched from a prepared statement.
+
+
let statement = try db.makeSelectStatement("SELECT ...")
+let rows = try Row.fetchCursor(statement) // DatabaseCursor<Row>
+while let row = try rows.next() { // Row
+ let id: Int64 = row.value(atIndex: 0)
+ let name: String = row.value(atIndex: 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.
+
+
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.
+
+
Returns a cursor over rows fetched from an SQL query.
+
+
let rows = try Row.fetchCursor(db, "SELECT id, name FROM persons") // DatabaseCursor<Row>
+while let row = try rows.next() { // Row
+ let id: Int64 = row.value(atIndex: 0)
+ let name: String = row.value(atIndex: 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.
+
+
A subclass of Statement that fetches database rows.
+
+
You create SelectStatement with the Database.makeSelectStatement() method:
+
+
try dbQueue.inDatabase { db in
+ let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM persons WHERE age > ?")
+ let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
+ let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
+}
+
try db.create(table: "persons") { t in
+ t.column("personalPhone", .text)
+ t.column("workPhone", .text)
+ t.check(sql: "personalPhone IS NOT NULL OR workPhone IS NOT NULL")
+}
+
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.
Returns a cursor over optional values fetched from an SQL query.
+
+
let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // DatabaseCursor<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.
+
+
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.
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.
Types that adopt MutablePersistable can be inserted, updated, and deleted.
+
+
This protocol is intented for types that have an INTEGER PRIMARY KEY, and
+are interested in the inserted RowID: they can mutate themselves upon
+successful insertion with the didInsert(with:for:) method.
+
+
The insert() and save() methods are mutating methods.
SQLSpecificExpressible is a protocol for all query interface types that can
+be turned into an SQL expression. Other types whose existence is not purely
+dedicated to the query interface should adopt the SQLExpressible
+protocol instead.
+
+
For example, Column is a type that only exists to help you build requests,
+and it adopts SQLSpecificExpressible.
+
+
On the other side, Int adopts SQLExpressible (via DatabaseValueConvertible).
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.
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.
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
+ // `wines` table is modified between the two requests:
+ let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
+ let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
+}
+
+try reader.read { db in
+ // Now this value may be different:
+ let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
+}
+
+
+
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.
+
+
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 wines")!
+ let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
+}
+
+
+
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.
+
+
let collation = DatabaseCollation("localized_standard") { (string1, string2) in
+ return (string1 as NSString).localizedStandardCompare(string2)
+}
+reader.add(collation: collation)
+try reader.execute("SELECT * FROM files ORDER BY name COLLATE localized_standard")
+
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.
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.
Synchronously or asynchronously executes a read-only block that takes a
+database connection.
+
+
This method must be called from a writing dispatch queue.
+
+
The block argument is guaranteed to see the database in the state it
+has at the moment this method is called (see below). Eventual concurrent
+database updates are not visible inside the block.
+
+
What is the current state of the database?
+
+
+
When this method is called outside of any transaction, the current
+state is the last committed state.
+
try writer.write { db in
+ try db.execute("DELETE FROM persons")
+ try writer.readFromCurrentState { db in
+ // Guaranteed to be zero
+ try Int.fetchOne(db, "SELECT COUNT(*) FROM persons")!
+ }
+ try db.execute("INSERT INTO persons ...")
+}
+
+
When this method is called inside an uncommitted transation, the
+current state depends on the caller:
+
+
DatabasePool.readFromCurrentState runs block asynchronously in a
+concurrent reader dispatch queue, and release the writing dispatch
+queue early, before the block has finished. In the example below,
+the insertion runs concurrently with the select, and the select sees
+the database in its last committed state.
+
try dbPool.write { db in
+ try db.execute("DELETE FROM persons")
+ db.inTransaction {
+ try db.execute("INSERT INTO persons ...")
+ try dbPool.readFromCurrentState { db in
+ // Zero
+ try Int.fetchOne(db, "SELECT COUNT(*) FROM persons")!
+ }
+ return .commit
+ }
+}
+
+
+
DatabaseQueue.readFromCurrentState simply runs block synchronously,
+and returns when the block has completed. In the example below, the
+select sees the uncommitted state of the database, and the insertion
+is run after the select.
+
try dbQueue.write { db in
+ try db.execute("DELETE FROM persons")
+ db.inTransaction {
+ try db.execute("INSERT INTO persons ...")
+ try dbQueue.readFromCurrentState { db in
+ // One
+ try Int.fetchOne(db, "SELECT COUNT(*) FROM persons")!
+ }
+ return .commit
+ }
+}
+
Types that adopt MutablePersistable can be inserted, updated, and deleted.
+
+
This protocol is intented for types that have an INTEGER PRIMARY KEY, and
+are interested in the inserted RowID: they can mutate themselves upon
+successful insertion with the didInsert(with:for:) method.
+
+
The insert() and save() methods are mutating methods.
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.
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 Person : MutablePersistable {
+ 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.
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().
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.
+
+
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().
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().
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().
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.
+
+
Don’t invoke this method directly: it is an internal method for types
+that adopt MutablePersistable.
+
+
performInsert() provides the default implementation for insert(). Types
+that adopt MutablePersistable can invoke performInsert() in their
+implementation of insert(). They should not provide their own
+implementation of performInsert().
Don’t invoke this method directly: it is an internal method for types
+that adopt MutablePersistable.
+
+
performUpdate() provides the default implementation for update(). Types
+that adopt MutablePersistable 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.
+
+
Don’t invoke this method directly: it is an internal method for types
+that adopt MutablePersistable.
+
+
performSave() provides the default implementation for save(). Types
+that adopt MutablePersistable 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.
Don’t invoke this method directly: it is an internal method for types
+that adopt MutablePersistable.
+
+
performDelete() provides the default implementation for deelte(). Types
+that adopt MutablePersistable can invoke performDelete() in
+their implementation of delete(). They should not provide their own
+implementation of performDelete().
Don’t invoke this method directly: it is an internal method for types
+that adopt MutablePersistable.
+
+
performExists() provides the default implementation for exists(). Types
+that adopt MutablePersistable can invoke performExists() in
+their implementation of exists(). They should not provide their own
+implementation of performExists().
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
+MutablePersistable protocol instead.
+
+
+
Default Implementation
+
+
Notifies the record that it was succesfully inserted.
+
+
The default implementation does nothing.
+
+
+
+
Declaration
+
+
Swift
+
funcdidInsert(withrowID:Int64,forcolumn:String?)
+
+
+
+
+
Parameters
+
+
+
+
+
+ rowID
+
+
+
+
+
The inserted rowID.
+
+
+
+
+
+
+
+ column
+
+
+
+
+
The name of the eventual INTEGER PRIMARY KEY column.
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().
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().
Don’t invoke this method directly: it is an internal method for types
+that adopt Persistable.
+
+
performInsert() provides the default implementation for insert(). Types
+that adopt Persistable can invoke performInsert() in their
+implementation of insert(). They should not provide their own
+implementation of performInsert().
Don’t invoke this method directly: it is an internal method for types
+that adopt Persistable.
+
+
performSave() provides the default implementation for save(). Types
+that adopt Persistable 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.
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")])
+ }
+}
+
+// <Row foo:1>
+try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: FirstColumnAdapter())
+
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().
Returns a cursor over records fetched from an SQL query.
+
+
let persons = try Person.fetchCursor(db, "SELECT * FROM persons") // DatabaseCursor<Person>
+while let person = try persons.next() { // Person
+ ...
+}
+
+
+
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.
+
+
SQLSpecificExpressible is a protocol for all query interface types that can
+be turned into an SQL expression. Other types whose existence is not purely
+dedicated to the query interface should adopt the SQLExpressible
+protocol instead.
+
+
For example, Column is a type that only exists to help you build requests,
+and it adopts SQLSpecificExpressible.
+
+
On the other side, Int adopts SQLExpressible (via DatabaseValueConvertible).
let request: ... // Some TypedRequest that fetches Person
+let persons = try request.fetchCursor(db) // DatabaseCursor<Person>
+while let person = try persons.next() { // Person
+ ...
+}
+
+
+
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.
+
+
let request: ... // Some TypedRequest that fetches Row
+let rows = try request.fetchCursor(db) // DatabaseCursor<Row>
+while let row = try rows.next() { // Row
+ let id: Int64 = row.value(atIndex: 0)
+ let name: String = row.value(atIndex: 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.
+
+
do {
+ ...
+} catch let error as DatabaseError where error.resultCode == .SQL_CONSTRAINT {
+ // A constraint error
+}
+
+
+
This property returns a primary result code, that is to say the least
+significant 8 bits of any SQLite result code. See
+https://www.sqlite.org/rescode.html for more information.
do {
+ ...
+} catch let error as DatabaseError where error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY {
+ // A foreign key constraint error
+}
+
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:
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.
Returns an ordering suitable for QueryInterfaceRequest.order()
+
+
let email: SQLCollatedExpression = Column("email").collating(.nocase)
+
+// SELECT * FROM persons ORDER BY email COLLATE NOCASE ASC
+Persons.order(email.asc)
+
Returns an ordering suitable for QueryInterfaceRequest.order()
+
+
let email: SQLCollatedExpression = Column("email").collating(.nocase)
+
+// SELECT * FROM persons ORDER BY email COLLATE NOCASE DESC
+Persons.order(email.desc)
+
This cursor forwards its next() method to an arbitrary underlying cursor
+having the same Element type, hiding the specifics of the underlying
+cursor.
A subclass of Statement that fetches database rows.
+
+
You create SelectStatement with the Database.makeSelectStatement() method:
+
+
try dbQueue.inDatabase { db in
+ let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM persons WHERE age > ?")
+ let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
+ let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
+}
+
This cursor forwards its next() method to an arbitrary underlying cursor
+having the same Element type, hiding the specifics of the underlying
+cursor.
The total number of rows modified, inserted or deleted by all successful
+INSERT, UPDATE or DELETE statements since the database connection was
+opened.
The transaction type (default nil). If nil, the transaction type is configuration.defaultTransactionKind, which itself defaults to .immediate. See https://www.sqlite.org/lang_transaction.html for more information.
+
+
+
+
+
+
+
+ block
+
+
+
+
+
A block that executes SQL statements and return either .commit or .rollback.
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 elements, provided is not nil.
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.
Synchronously executes a read-only block in a protected dispatch queue,
+and returns its result. The block is wrapped in a deferred transaction.
+
+
let persons = try dbPool.read { db in
+ try Person.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
+ // `wines` table is modified between the two requests:
+ let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
+ let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
+}
+
+try dbPool.read { db in
+ // Now this value may be different:
+ let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
+}
+
+
+
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.
+
+
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 wines")!
+ let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
+}
+
+
+
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.
+
+
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.write { db in
+ try db.execute(...)
+}
+
+
+
To maintain database integrity, and preserve eventual concurrent reads
+from seeing an inconsistent database state, prefer the
+writeInTransaction method.
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 readers do not see partial changes:
+
+
dbPool.writeInTransaction { db in
+ // Eventually preserve a zero balance
+ try db.execute(db, "INSERT INTO credits ...", arguments: [amount])
+ try db.execute(db, "INSERT INTO debits ...", arguments: [amount])
+}
+
+dbPool.read { db in
+ // Here the balance is guaranteed to be zero
+}
+
+
+
This method is not reentrant.
+
+
+
Throws
+ The error thrown by the block, or any error establishing the
+transaction.
+
+
The transaction type (default nil). If nil, the transaction type is configuration.defaultTransactionKind, which itself defaults to .immediate. See https://www.sqlite.org/lang_transaction.html for more information.
+
+
+
+
+
+
+
+ block
+
+
+
+
+
A block that executes SQL statements and return either .commit or .rollback.
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.
+
+
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 persons")
+ try dbPool.readFromCurrentState { db in
+ // Guaranteed to be zero
+ try Int.fetchOne(db, "SELECT COUNT(*) FROM persons")!
+ }
+ try db.execute("INSERT INTO persons ...")
+}
+
+
+
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.
+
+
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
+ db.execute(...)
+ return .commit
+}
+
The transaction type (default nil). If nil, the transaction type is configuration.defaultTransactionKind, which itself defaults to .immediate. See https://www.sqlite.org/lang_transaction.html for more information.
+
+
+
+
+
+
+
+ block
+
+
+
+
+
A block that executes SQL statements and return either .commit or .rollback.
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.
Synchronously executes a read-only block in a protected dispatch queue,
+and returns its result.
+
+
let persons = try dbQueue.read { db in
+ try Person.fetchAll(...)
+}
+
+
+
This method is not reentrant.
+
+
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.
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.
+
+
This method must be called from the protected database dispatch queue.
+See DatabaseWriter.readFromCurrentState.
Synchronizes the full-text table with the content of an external
+table.
+
+
The full-text table is initially populated with the existing
+content in the external table. SQL triggers make sure that the
+full-text table is kept up to date with the external table.
Creates a fetched records controller initialized from a SQL query and
+its eventual arguments.
+
+
let controller = FetchedRecordsController<Wine>(
+ dbQueue,
+ sql: "SELECT * FROM wines WHERE color = ? ORDER BY name",
+ arguments: [Color.red],
+ isSameRecord: { (wine1, wine2) in wine1.id == wine2.id })
+
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.
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).
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.
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).
Creates a fetched records controller initialized from a SQL query and
+its eventual arguments.
+
+
let controller = FetchedRecordsController<Wine>(
+ dbQueue,
+ sql: "SELECT * FROM wines 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 wines table has an `id` primary key:
+let controller = FetchedRecordsController<Wine>(
+ dbQueue,
+ sql: "SELECT * FROM wines WHERE color = ? ORDER BY name",
+ arguments: [Color.red],
+ isSameRecord: { (wine1, wine2) in wine1.id == wine2.id })
+
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 wines table has an `id` primary key:
+let controller = FetchedRecordsController<Wine>(
+ dbQueue,
+ request: request,
+ isSameRecord: { (wine1, wine2) in wine1.id == wine2.id })
+
The input row may not come straight from the database. When you want to
+complete your initialization after being fetched, override
+awakeFromFetch(row:).
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.
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 Person : Record {
+ var id: Int64?
+ var name: String?
+
+ func didInsert(with rowID: Int64, for column: String?) {
+ id = rowID
+ }
+}
+
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 its persistentDictionary has been changed
+since last database synchronization (fetch, update, insert). Comparison
+is performed on values: setting a property to the same value does not
+trigger the edited 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.
On success, this method sets the hasPersistentChangedValues 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.
+
+
On success, this method sets the hasPersistentChangedValues 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.
+
+
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().
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.
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).
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).
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.
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).
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).
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.
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).
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).
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.
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.
Returns a cursor over rows fetched from a prepared statement.
+
+
let statement = try db.makeSelectStatement("SELECT ...")
+let rows = try Row.fetchCursor(statement) // DatabaseCursor<Row>
+while let row = try rows.next() { // Row
+ let id: Int64 = row.value(atIndex: 0)
+ let name: String = row.value(atIndex: 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.
+
+
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.
+
+
Returns a cursor over rows fetched from an SQL query.
+
+
let rows = try Row.fetchCursor(db, "SELECT id, name FROM persons") // DatabaseCursor<Row>
+while let row = try rows.next() { // Row
+ let id: Int64 = row.value(atIndex: 0)
+ let name: String = row.value(atIndex: 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.
+
+
A subclass of Statement that fetches database rows.
+
+
You create SelectStatement with the Database.makeSelectStatement() method:
+
+
try dbQueue.inDatabase { db in
+ let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM persons WHERE age > ?")
+ let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
+ let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
+}
+
try db.create(table: "persons") { t in
+ t.column("personalPhone", .text)
+ t.column("workPhone", .text)
+ t.check(sql: "personalPhone IS NOT NULL OR workPhone IS NOT NULL")
+}
+
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.
Returns a cursor over optional values fetched from an SQL query.
+
+
let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // DatabaseCursor<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.
+
+
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.
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.
Types that adopt MutablePersistable can be inserted, updated, and deleted.
+
+
This protocol is intented for types that have an INTEGER PRIMARY KEY, and
+are interested in the inserted RowID: they can mutate themselves upon
+successful insertion with the didInsert(with:for:) method.
+
+
The insert() and save() methods are mutating methods.
SQLSpecificExpressible is a protocol for all query interface types that can
+be turned into an SQL expression. Other types whose existence is not purely
+dedicated to the query interface should adopt the SQLExpressible
+protocol instead.
+
+
For example, Column is a type that only exists to help you build requests,
+and it adopts SQLSpecificExpressible.
+
+
On the other side, Int adopts SQLExpressible (via DatabaseValueConvertible).
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.
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.
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
+ // `wines` table is modified between the two requests:
+ let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
+ let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
+}
+
+try reader.read { db in
+ // Now this value may be different:
+ let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
+}
+
+
+
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.
+
+
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 wines")!
+ let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
+}
+
+
+
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.
+
+
let collation = DatabaseCollation("localized_standard") { (string1, string2) in
+ return (string1 as NSString).localizedStandardCompare(string2)
+}
+reader.add(collation: collation)
+try reader.execute("SELECT * FROM files ORDER BY name COLLATE localized_standard")
+
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.
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.
Synchronously or asynchronously executes a read-only block that takes a
+database connection.
+
+
This method must be called from a writing dispatch queue.
+
+
The block argument is guaranteed to see the database in the state it
+has at the moment this method is called (see below). Eventual concurrent
+database updates are not visible inside the block.
+
+
What is the current state of the database?
+
+
+
When this method is called outside of any transaction, the current
+state is the last committed state.
+
try writer.write { db in
+ try db.execute("DELETE FROM persons")
+ try writer.readFromCurrentState { db in
+ // Guaranteed to be zero
+ try Int.fetchOne(db, "SELECT COUNT(*) FROM persons")!
+ }
+ try db.execute("INSERT INTO persons ...")
+}
+
+
When this method is called inside an uncommitted transation, the
+current state depends on the caller:
+
+
DatabasePool.readFromCurrentState runs block asynchronously in a
+concurrent reader dispatch queue, and release the writing dispatch
+queue early, before the block has finished. In the example below,
+the insertion runs concurrently with the select, and the select sees
+the database in its last committed state.
+
try dbPool.write { db in
+ try db.execute("DELETE FROM persons")
+ db.inTransaction {
+ try db.execute("INSERT INTO persons ...")
+ try dbPool.readFromCurrentState { db in
+ // Zero
+ try Int.fetchOne(db, "SELECT COUNT(*) FROM persons")!
+ }
+ return .commit
+ }
+}
+
+
+
DatabaseQueue.readFromCurrentState simply runs block synchronously,
+and returns when the block has completed. In the example below, the
+select sees the uncommitted state of the database, and the insertion
+is run after the select.
+
try dbQueue.write { db in
+ try db.execute("DELETE FROM persons")
+ db.inTransaction {
+ try db.execute("INSERT INTO persons ...")
+ try dbQueue.readFromCurrentState { db in
+ // One
+ try Int.fetchOne(db, "SELECT COUNT(*) FROM persons")!
+ }
+ return .commit
+ }
+}
+
Types that adopt MutablePersistable can be inserted, updated, and deleted.
+
+
This protocol is intented for types that have an INTEGER PRIMARY KEY, and
+are interested in the inserted RowID: they can mutate themselves upon
+successful insertion with the didInsert(with:for:) method.
+
+
The insert() and save() methods are mutating methods.
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.
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 Person : MutablePersistable {
+ 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.
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().
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.
+
+
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().
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().
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().
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.
+
+
Don’t invoke this method directly: it is an internal method for types
+that adopt MutablePersistable.
+
+
performInsert() provides the default implementation for insert(). Types
+that adopt MutablePersistable can invoke performInsert() in their
+implementation of insert(). They should not provide their own
+implementation of performInsert().
Don’t invoke this method directly: it is an internal method for types
+that adopt MutablePersistable.
+
+
performUpdate() provides the default implementation for update(). Types
+that adopt MutablePersistable 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.
+
+
Don’t invoke this method directly: it is an internal method for types
+that adopt MutablePersistable.
+
+
performSave() provides the default implementation for save(). Types
+that adopt MutablePersistable 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.
Don’t invoke this method directly: it is an internal method for types
+that adopt MutablePersistable.
+
+
performDelete() provides the default implementation for deelte(). Types
+that adopt MutablePersistable can invoke performDelete() in
+their implementation of delete(). They should not provide their own
+implementation of performDelete().
Don’t invoke this method directly: it is an internal method for types
+that adopt MutablePersistable.
+
+
performExists() provides the default implementation for exists(). Types
+that adopt MutablePersistable can invoke performExists() in
+their implementation of exists(). They should not provide their own
+implementation of performExists().
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
+MutablePersistable protocol instead.
+
+
+
Default Implementation
+
+
Notifies the record that it was succesfully inserted.
+
+
The default implementation does nothing.
+
+
+
+
Declaration
+
+
Swift
+
funcdidInsert(withrowID:Int64,forcolumn:String?)
+
+
+
+
+
Parameters
+
+
+
+
+
+ rowID
+
+
+
+
+
The inserted rowID.
+
+
+
+
+
+
+
+ column
+
+
+
+
+
The name of the eventual INTEGER PRIMARY KEY column.
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().
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().
Don’t invoke this method directly: it is an internal method for types
+that adopt Persistable.
+
+
performInsert() provides the default implementation for insert(). Types
+that adopt Persistable can invoke performInsert() in their
+implementation of insert(). They should not provide their own
+implementation of performInsert().
Don’t invoke this method directly: it is an internal method for types
+that adopt Persistable.
+
+
performSave() provides the default implementation for save(). Types
+that adopt Persistable 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.
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")])
+ }
+}
+
+// <Row foo:1>
+try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: FirstColumnAdapter())
+
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().
Returns a cursor over records fetched from an SQL query.
+
+
let persons = try Person.fetchCursor(db, "SELECT * FROM persons") // DatabaseCursor<Person>
+while let person = try persons.next() { // Person
+ ...
+}
+
+
+
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.
+
+
SQLSpecificExpressible is a protocol for all query interface types that can
+be turned into an SQL expression. Other types whose existence is not purely
+dedicated to the query interface should adopt the SQLExpressible
+protocol instead.
+
+
For example, Column is a type that only exists to help you build requests,
+and it adopts SQLSpecificExpressible.
+
+
On the other side, Int adopts SQLExpressible (via DatabaseValueConvertible).
let request: ... // Some TypedRequest that fetches Person
+let persons = try request.fetchCursor(db) // DatabaseCursor<Person>
+while let person = try persons.next() { // Person
+ ...
+}
+
+
+
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.
+
+
let request: ... // Some TypedRequest that fetches Row
+let rows = try request.fetchCursor(db) // DatabaseCursor<Row>
+while let row = try rows.next() { // Row
+ let id: Int64 = row.value(atIndex: 0)
+ let name: String = row.value(atIndex: 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.
+
+
do {
+ ...
+} catch let error as DatabaseError where error.resultCode == .SQL_CONSTRAINT {
+ // A constraint error
+}
+
+
+
This property returns a primary result code, that is to say the least
+significant 8 bits of any SQLite result code. See
+https://www.sqlite.org/rescode.html for more information.
do {
+ ...
+} catch let error as DatabaseError where error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY {
+ // A foreign key constraint error
+}
+
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:
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.
Returns an ordering suitable for QueryInterfaceRequest.order()
+
+
let email: SQLCollatedExpression = Column("email").collating(.nocase)
+
+// SELECT * FROM persons ORDER BY email COLLATE NOCASE ASC
+Persons.order(email.asc)
+
Returns an ordering suitable for QueryInterfaceRequest.order()
+
+
let email: SQLCollatedExpression = Column("email").collating(.nocase)
+
+// SELECT * FROM persons ORDER BY email COLLATE NOCASE DESC
+Persons.order(email.desc)
+
Follow @groue on Twitter for release announcements and usage tips.
+
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.
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 inDatabase and inTransaction methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue. They safely serialize the database accesses:
+
// Execute database statements:
+trydbQueue.inDatabase{dbin
+ trydb.create(table:"pointOfInterests"){...}
+ tryPointOfInterest(...).insert(db)
+}
+
+// Wrap database statements in a transaction:
+trydbQueue.inTransaction{dbin
+ ifletpoi=tryPointOfInterest.fetchOne(db,key:1){
+ trypoi.delete(db)
+ }
+ return.commit
+}
+
+// Read values:
+trydbQueue.inDatabase{dbin
+ letpois=tryPointOfInterest.fetchAll(db)
+ letpoiCount=tryPointOfInterest.fetchCount(db)
+}
+
+// Extract a value from the database:
+letpoiCount=trydbQueue.inDatabase{dbin
+ tryPointOfInterest.fetchCount(db)
+}
+
+
+
A database queue needs your application to follow rules in order to deliver its safety guarantees. Please refer to the Concurrency chapter.
A Database Pool allows concurrent database accesses.
+
+
When more efficient than database queues, database pools also require a good mastery of database transactions. Details follow. If you don’t feel comfortable with transactions, use a database queue instead.
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 read, write and writeInTransaction methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue. They safely isolate the database accesses:
+
// Execute database statements:
+trydbPool.write{dbin
+ trydb.create(table:"pointOfInterests"){...}
+ tryPointOfInterest(...).insert(db)
+}
+
+// Wrap database statements in a transaction:
+trydbPool.writeInTransaction{dbin
+ ifletpoi=tryPointOfInterest.fetchOne(db,key:1){
+ trypoi.delete(db)
+ }
+ return.commit
+}
+
+// Read values:
+trydbPool.read{dbin
+ letpois=tryPointOfInterest.fetchAll(db)
+ letpoiCount=tryPointOfInterest.fetchCount(db)
+}
+
+// Extract a value from the database:
+letpoiCount=trydbPool.read{dbin
+ tryPointOfInterest.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.
+
+
The total number of concurrent reads is limited. When the maximum number has been reached, a read waits for another read to complete. That maximum number can be configured.
+
Conversely, writes are serialized. They don’t block reads, but GRDB guarantees read closures an immutable view of the last committed state of the database.
+
+
:point_up: To provide read closures an immutable view of the last executed writing block as a whole, use writeInTransaction instead of write.
+
+
+
A database pool needs your application to follow rules in order to deliver its safety guarantees. Please refer to the Concurrency chapter.
For a sample code that sets up a database pool on iOS, see DemoApps/GRDBDemoiOS/Database.swift, and replace DatabaseQueue with DatabasePool.
+
DatabasePool Configuration
+
varconfig=Configuration()
+config.readonly=true
+config.foreignKeysEnabled=true// Default is already true
+config.trace={print($0)}// Prints all SQL statements
+config.maximumReaderCount=10// The default is 5
+
+letdbPool=tryDatabasePool(
+ path:"/path/to/database.sqlite",
+ configuration:config)
+
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:
+
trydb.execute(
+ "CREATE TABLE persons ("+
+ "id INTEGER PRIMARY KEY,"+
+ "name TEXT NOT NULL,"+
+ "age INT"+
+ ")")
+
+trydb.execute(
+ "INSERT INTO persons (name, age) VALUES (:name, :age)",
+ arguments:["name":"Barbara","age":39])
+
+// Join multiple statements with a semicolon:
+trydb.execute(
+ "INSERT INTO persons (name, age) VALUES (?, ?); "+
+ "INSERT INTO persons (name, age) VALUES (?, ?)",
+ arguments:["Arthur",36,"Barbara",39])
+
+
+
The ? and colon-prefixed keys like :name 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.).
+
+
Never ever embed values directly in your SQL strings, and always use arguments instead. See Avoiding SQL Injection for more information.
+
+
After an INSERT statement, you can get the row ID of the inserted row:
Whenever you consume several rows from the database, you can fetch a Cursor, or an Array.
+
+
Arrays contain copies of database values and may be consumed on any thread. But they can take a lot of memory. Conversely, cursors iterate over database results in a lazy fashion, don’t consume much memory, and are generally more efficient. But they must be consumed in a protected dispatch queue:
Cursors come with default implementations for many operations similar to those defined by lazy sequences of the Swift Standard Library: contains, enumerated, filter, first, flatMap, forEach, joined, map, reduce:
+
// Enumerate all Github links
+tryURL.fetchCursor(db,"SELECT url FROM links")
+ .filter{urlinurl.host=="github.com"}
+ .enumerated()
+ .forEach{(index,url)in...}
+
Arguments are optional arrays or dictionaries that fill the positional ? and colon-prefixed keys like :name in the query:
+
letrows=tryRow.fetchAll(db,
+ "SELECT * FROM persons WHERE name = ?",
+ arguments:["Arthur"])
+
+letrows=tryRow.fetchAll(db,
+ "SELECT * FROM persons 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 row cursor into an array, with Array(rowCursor) for example: you would not get the distinct rows you expect. To get a row array, 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:
+
letname:String=row.value(atIndex:0)// 0 is the leftmost column
+letname:String=row.value(named:"name")// Leftmost matching column - lookup is case-insensitive
+letname:String=row.value(Column("name"))// Using query interface's Column
+
+
+
Make sure to ask for an optional when the value may be NULL:
+
letname:String?=row.value(named:"name")
+
+
+
The value function returns the type you ask for. See Values for more information on supported value types:
+
letbookCount:Int=row.value(named:"bookCount")
+letbookCount64:Int64=row.value(named:"bookCount")
+lethasBooks:Bool=row.value(named:"bookCount")// false when 0
+
+letstring:String=row.value(named:"date")// "2015-09-11 18:14:15.123"
+letdate:Date=row.value(named:"date")// Date
+self.date=row.value(named:"date")// Depends on the type of the property.
+
+
+
You can also use the as type casting operator:
+
row.value(...)asInt
+row.value(...)asInt?
+
+
+
+
:warning: Warning: avoid the as! and as? operators, because they misbehave in the context of type inference (see rdar://21676393):
+
ifletint=row.value(...)as?Int{...}// BAD - doesn't work
+ifletint=row.value(...)asInt?{...}// 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.
+
letrow=tryRow.fetchOne(db,"SELECT NULL")!
+row.value(atIndex:0)asInt?// nil
+row.value(atIndex:0)asInt// fatal error: could not convert NULL to Int.
+
+
+
There is one exception, though: the DatabaseValue type:
letrow=tryRow.fetchOne(db,"SELECT 'foo' AS foo")!
+row.value(named:"missing")asString?// nil
+row.value(named:"missing")asString// fatal error: no such column: missing
+
+
+
You can explicitly check for a column presence with the hasColumn method.
+
Invalid conversions throw a fatal error.
+
letrow=tryRow.fetchOne(db,"SELECT 'Mom’s birthday'")!
+row.value(atIndex:0)asString// "Mom’s birthday"
+row.value(atIndex:0)asDate?// fatal error: could not convert "Mom’s birthday" to Date.
+row.value(atIndex:0)asDate// fatal error: could not convert "Mom’s birthday" to Date.
+
SQLite has a weak type system, and provides convenience conversions that can turn Blob to String, String to Int, etc.
+
+
GRDB will sometimes let those conversions go through:
+
letrows=tryRow.fetchCursor(db,"SELECT '20 small cigars'")
+whileletrow=tryrows.next(){
+ row.value(atIndex:0)asInt// 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:
+
letdbv:DatabaseValue=row.value(atIndex:0)
+letdbv:DatabaseValue=row.value(named:"name")
+
+// Check for NULL:
+dbv.isNull// Bool
+
+// All the five storage classes supported by SQLite:
+switchdbv.storage{
+case.null:print("NULL")
+case.int64(letint64):print("Int64: \(int64)")
+case.double(letdouble):print("Double: \(double)")
+case.string(letstring):print("String: \(string)")
+case.blob(letdata):print("Data: \(data)")
+}
+
This turns out useful when you process untrusted databases. Compare:
+
letdate:Date?=row.value(atIndex:0)// fatal error: could not convert "Mom’s birthday" to Date.
+letdate=Date.fromDatabaseValue(row.value(atIndex:0))// nil
+
+
Rows as Dictionaries
+
+
Row adopts the standard Collection protocol, and can be seen as a dictionary of DatabaseValue:
+
// All the (columnName, databaseValue) tuples, from left to right:
+for(columnName,databaseValue)inrow{
+ ...
+}
+
+
+
You can build rows from dictionaries (standard Swift dictionaries and NSDictionary). See Values for more information on supported types:
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:
At each step of the request iteration, the row.value method 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:
Yet this format may not fit your needs. For example, you may want to store dates as timestamps. In this case, store and load Doubles instead of Date, and perform the required conversions.
+
+
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:
+
letcomponents=DateComponents()
+components.year=1973
+components.month=9
+components.day=18
+
+// Store "1973-09-18"
+letdbComponents=DatabaseDateComponents(components,format:.YMD)
+trydb.execute(
+ "INSERT INTO persons (birthDate, ...) VALUES (?, ...)",
+ arguments:[dbComponents,...])
+
+// Read "1973-09-18"
+letrow=tryRow.fetchOne(db,"SELECT birthDate ...")!
+letdbComponents:DatabaseDateComponents=row.value(named:"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:
+
CREATETABLEtransfers(
+ amountDECIMAL(10,5)-- will store integer or double, actually
+)
+
+
+
This means that computations will not be exact:
+
trydb.execute("INSERT INTO transfers (amount) VALUES (0.1)")
+trydb.execute("INSERT INTO transfers (amount) VALUES (0.2)")
+letsum=tryNSDecimalNumber.fetchOne(db,"SELECT SUM(amount) FROM transfers")!
+
+// 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:
+
// Store
+letamount=NSDecimalNumber(string:"0.1")// 0.1
+letintegerAmount=amount.multiplying(byPowerOf10:2).int64Value// 100
+trydb.execute("INSERT INTO transfers (amount) VALUES (?)",arguments:[integerAmount])
+
+// Read
+letintegerAmount=tryInt64.fetchOne(db,"SELECT SUM(amount) FROM transfers")!// 100
+letamount=NSDecimalNumber(value:integerAmount).multiplying(byPowerOf10:-2)// 0.1
+
+
UUID
+
+
UUID can be stored and fetched from the database just like other values. GRDB stores uuids as 16-bytes data blobs.
+
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:
letrow=tryRow.fetchOne(db,"SELECT 'syrah'")!
+
+row.value(atIndex:0)asString// "syrah"
+row.value(atIndex:0)asGrape?// fatal error: could not convert "syrah" to Grape.
+row.value(atIndex:0)asGrape// fatal error: could not convert "syrah" to Grape.
+Grape.fromDatabaseValue(row.value(atIndex:0))// nil
+
+
Transactions and Savepoints
+
+
The DatabaseQueue.inTransaction() and DatabasePool.writeInTransaction() methods open an SQLite transaction and run their closure argument in a protected dispatch queue. They block the current thread until your database statements are executed:
If an error is thrown within the transaction body, the transaction is rollbacked and the error is rethrown by the inTransaction method. If you return .rollback from your closure, the transaction is also rollbacked, but no error is thrown.
+
+
If you want to insert a transaction between other database statements, you can use the Database.inTransaction() function, or even raw SQL statements:
+
trydbQueue.inDatabase{dbin// or dbPool.write { db in
+ ...
+ trydb.inTransaction{
+ ...
+ return.commit
+ }
+ ...
+ trydb.execute("BEGIN TRANSACTION")
+ ...
+ trydb.execute("COMMIT")
+}
+
+
+
You can ask a database if a transaction is currently opened:
Yet, you have a better option than checking for transactions: critical sections of your application should use savepoints, described below:
+
funcmyCriticalMethod(_db:Database)throws{
+ trydb.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:
+
trydbQueue.inTransaction{dbin
+ trydb.inSavepoint{
+ trydb.execute("DELETE ...")
+ trydb.execute("INSERT ...")// need to rollback the delete above if this fails
+ return.commit
+ }
+
+ // Other savepoints, etc...
+ return.commit
+}
+
+
+
If an error is thrown within the savepoint body, the savepoint is rollbacked and the error is rethrown by the inSavepoint method. If you return .rollback from your closure, the body 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 committed to disk when the outermost savepoint is committed:
SQLite savepoints are more than nested transactions, though. For advanced savepoints uses, use SQL queries.
+
Transaction Kinds
+
+
SQLite supports three kinds of transactions: deferred, immediate, and exclusive. GRDB defaults to immediate.
+
+
The transaction kind can be changed in the database configuration, or for each transaction:
+
// A connection with default DEFERRED transactions:
+varconfig=Configuration()
+config.defaultTransactionKind=.deferred
+letdbQueue=tryDatabaseQueue(path:"...",configuration:config)
+
+// Opens a DEFERRED transaction:
+dbQueue.inTransaction{dbin...}
+
+// Opens an EXCLUSIVE transaction:
+dbQueue.inTransaction(.exclusive){dbin...}
+
+
Custom Value Types
+
+
Conversion to and from the database is based on the DatabaseValueConvertible protocol:
+
protocolDatabaseValueConvertible{
+ /// Returns a value that can be stored in the database.
+ vardatabaseValue:DatabaseValue{get}
+
+ /// Returns a value initialized from databaseValue, if possible.
+ staticfuncfromDatabaseValue(_databaseValue: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 databaseValue contains a suitable value. If the databaseValue does not contain a suitable value, such as foo for Date, fromDatabaseValuemust return nil (GRDB will interpret this nil result as a conversion error, and react accordingly).
+
+
The GRDB Extension Guide contains sample code that has UIColor adopt DatabaseValueConvertible.
+
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:
+
trydbQueue.inDatabase{dbin
+ letupdateSQL="INSERT INTO persons (name, age) VALUES (:name, :age)"
+ letupdateStatement=trydb.makeUpdateStatement(updateSQL)
+
+ letselectSQL="SELECT * FROM persons WHERE name = ?"
+ letselectStatement=trydb.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).
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:
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:
trydb.tableExists("persons")// Bool, true if the table exists
+trydb.columnCount(in:"persons")// Int, the number of columns in table
+trydb.indexes(on:"persons")// [IndexInfo], the indexes defined on the table
+trydb.table("persons",hasUniqueKey:["email"])// Bool, true if column(s) is a unique key
+trydb.primaryKey("persons")// PrimaryKeyInfo?
+
Primary keys have one or several columns. Single-column primary keys may contain the auto-incremented row id:
+
// CREATE TABLE persons (
+// id INTEGER PRIMARY KEY,
+// name TEXT
+// )
+letpersonPk=trydb.primaryKey("persons")!
+personPk.columns// ["id"]
+personPk.rowIDColumn// "id"
+
+// CREATE TABLE countries (
+// isoCode TEXT NOT NULL PRIMARY KEY
+// name TEXT
+// )
+letcountryPk=db.primaryKey("countries")!
+countryPk.columns// ["isoCode"]
+countryPk.rowIDColumn// nil
+
+// CREATE TABLE citizenships (
+// personID INTEGER NOT NULL REFERENCES persons(id)
+// countryIsoCode TEXT NOT NULL REFERENCES countries(isoCode)
+// PRIMARY KEY (personID, countryIsoCode)
+// )
+letcitizenshipsPk=db.primaryKey("citizenships")!
+citizenshipsPk.columns// ["personID", "countryIsoCode"]
+citizenshipsPk.rowIDColumn// nil
+
+
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:
+letadapter=ColumnMapping(["consumed":"produced"])
+letrow=tryRow.fetchOne(db,"SELECT 'Hello' AS produced",adapter:adapter)!
+row.value(named:"consumed")// "Hello"
+row.value(named:"produced")// nil
+
+
+
Row adapters are values that adopt the RowAdapter protocol. You can implement your own custom adapters, or use one of the four built-in adapters:
+
ColumnMapping
+
+
ColumnMapping renames columns. Build one with a dictionary whose keys are adapted column names, and values the column names in the raw row:
+
// <Row newName:"Hello">
+letadapter=ColumnMapping(["newName":"oldName"])
+letrow=tryRow.fetchOne(db,"SELECT 'Hello' AS oldName",adapter:adapter)!
+
+
SuffixRowAdapter
+
+
SuffixRowAdapter hides the first columns in a row:
+
// <Row b:1 c:2>
+letadapter=SuffixRowAdapter(fromIndex:1)
+letrow=tryRow.fetchOne(db,"SELECT 0 AS a, 1 AS b, 2 AS c",adapter:adapter)!
+
+
RangeRowAdapter
+
+
RangeRowAdapter only exposes a range of columns.
+
// <Row b:1>
+letadapter=RangeRowAdapter(1..<2)
+letrow=tryRow.fetchOne(db,"SELECT 0 AS a, 1 AS b, 2 AS c",adapter:adapter)!
+
+
ScopeAdapter
+
+
ScopeAdapter defines row scopes:
+
letadapter=ScopeAdapter([
+ "left":RangeRowAdapter(0..<2),
+ "right":RangeRowAdapter(2..<4)])
+letrow=tryRow.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 with the scoped(on:) method. It returns an optional Row, which is nil if the scope is missing.
// Just enough for SQLCipher and custom SQLite builds:
+importGRDBCipher// or import GRDBCustomSQLite
+
+letsqliteVersion=String(cString:sqlite3_libversion())
+
+
+
Otherwise (the regular case):
+
+
+
Link your application with the SQLite library that ships with your SDK: add libsqlite3.tbd to the Linked Frameworks and Libraries of the General tab of your target.
+
Import the SQLite module in the file that uses the SQLite C Interface. That module, unfortunately, changes name depending on your platform:
The Database.sqliteConnection and Statement.sqliteStatement properties provide the raw pointers that are suitable for the SQLite C functions:
+
trydbQueue.inDatabase{dbin
+ // The raw pointer to a database connection:
+ letsqliteConnection=db.sqliteConnection
+
+ // The raw pointer to a statement:
+ letstatement=trydb.makeSelectStatement("SELECT ...")
+ letsqliteStatement=statement.sqliteStatement
+}
+
+
+
+
:point_up: Notes
+
+
+
Those pointers are owned by GRDB: don’t close connections or finalize statements created by GRDB.
+
SQLite connections are opened 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:
+
+
+
sqlite3_backup_finish, sqlite3_backup_init, sqlite3_backup_step: see Backup
sqlite3_preupdate_count, sqlite3_preupdate_depth, sqlite3_preupdate_hook, sqlite3_preupdate_new, sqlite3_preupdate_old: see Support for SQLite Pre-Update Hooks
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 changes tracking. 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, and do not auto-update. 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.
The RowConvertible protocol grants fetching methods to any type that can be built from a database row:
+
protocolRowConvertible{
+ /// Row initializer
+ init(row:Row)
+
+ /// Optional method which gives adopting types an opportunity to complete
+ /// their initialization after being fetched. Do not call it directly.
+ mutatingfuncawakeFromFetch(row:Row)
+}
+
+
+
To use RowConvertible, subclass the Record class, or adopt it explicitely. For example:
See column values for more information about the row.value() method.
+
+
+
: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().
+
+
+
RowConvertible allows adopting types to be fetched from SQL queries:
See fetching methods for information about the fetchCursor, fetchAll and fetchOne methods. See StatementArguments for more information about the query arguments.
+
RowConvertible and Row Adapters
+
+
RowConvertible types usually consume rows by column name:
Occasionnally, you’ll want to write a complex SQL query that uses different column names. In this case, row adapters are there to help you mapping raw column names to the names expected by your RowConvertible types.
The databaseTableName type property is the name of a database table. selectsRowID is optional, and documented in the The Implicit RowID Primary Key chapter.
+
+
To use TableMapping, subclass the Record class, or adopt it explicitely. For example:
When the table has no explicit primary key, GRDB uses the hidden rowid column:
+
// SELECT * FROM documents WHERE rowid = 1
+tryDocument.fetchOne(db,key:1)// Document?
+
+// DELETE FROM documents WHERE rowid = 1
+tryDocument.deleteOne(db,key:1)
+
+
+
For multiple-column primary keys and unique keys defined by unique indexes, provide a dictionary:
+
// SELECT * FROM citizenships WHERE personID = 1 AND countryISOCode = 'FR'
+tryCitizenship.fetchOne(db,key:["personID":1,"countryISOCode":"FR"])// Citizenship?
+
+// DELETE FROM persons WHERE email = 'arthur@example.com'
+tryPerson.deleteOne(db,key:["email":"arthur@example.com"])
+
+
Persistable Protocol
+
+
GRDB provides two protocols that let adopting types store themselves in the database:
+
protocolMutablePersistable:TableMapping{
+ /// The name of the database table (from TableMapping)
+ staticvardatabaseTableName:String{get}
+
+ /// The values persisted in the database
+ varpersistentDictionary:[String:DatabaseValueConvertible?]{get}
+
+ /// Optional method that lets your adopting type store its rowID upon
+ /// successful insertion. Don't call it directly: it is called for you.
+ mutatingfuncdidInsert(withrowID:Int64,forcolumn:String?)
+}
+
+
protocolPersistable:MutablePersistable{
+ /// Non-mutating version of the optional didInsert(with:for:)
+ funcdidInsert(withrowID:Int64,forcolumn: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 struct that mutates on insertion, choose MutablePersistable.
+
+
For example, your table has an INTEGER PRIMARY KEY and you want to store the inserted id on successful insertion. Or your table has a UUID primary key, and you want to automatically generate one on insertion.
+
Otherwise, stick with Persistable. Particularly if your type is a class.
+
+
+
The persistentDictionary property returns a dictionary whose keys are column names, and values any DatabaseValueConvertible value (Bool, Int, String, Date, Swift enums, etc.) See Values for more information.
+
+
The optional didInsert method lets the adopting type store its rowID after successful insertion. If your table has an INTEGER PRIMARY KEY column, you are likely to define this method. Otherwise, you can safely ignore it. It is called from a protected dispatch queue, and serialized with all database updates.
+
+
To use those protocols, subclass the Record class, or adopt one of them explicitely. For example:
+
extensionPointOfInterest:MutablePersistable{
+
+ /// The values persisted in the database
+ varpersistentDictionary:[String:DatabaseValueConvertible?]{
+ return[
+ "id":id,
+ "title":title,
+ "latitude":coordinate.latitude,
+ "longitude":coordinate.longitude]
+ }
+
+ // Update id upon successful insertion:
+ mutatingfuncdidInsert(withrowID:Int64,forcolumn:String?){
+ id=rowID
+ }
+}
+
+varparis=PointOfInterest(
+ id:nil,
+ title:"Paris",
+ coordinate:CLLocationCoordinate2DMake(48.8534100,2.3488000))
+
+tryparis.insert(db)
+paris.id// some value
+
+
+
When your record has many columns, the Swift compiler may take a long time compiling the persistentDictionary property:
+
// May be long to compile
+varpersistentDictionary:[String:DatabaseValueConvertible?]{
+ return[
+ "id":id,
+ "title":title,
+ // many other columns
+ ]
+}
+
insert, update, save and delete can throw a DatabaseError whenever an SQLite integrity check fails.
+
update can also throw a PersistenceError of type recordNotFound, 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:
: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.
+
+
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.
SQLite let you specify conflict policies at two different places:
+
+
+
At the table level
+
// CREATE TABLE persons (
+// id INTEGER PRIMARY KEY,
+// email TEXT UNIQUE ON CONFLICT REPLACE
+// )
+trydb.create(table:"persons"){tin
+ t.column("id",.integer).primaryKey()
+ t.column("email",.text).unique(onConflict:.replace)// <--
+}
+
+// Despite the unique index on email, both inserts succeed.
+// The second insert replaces the first row:
+trydb.execute("INSERT INTO persons (email) VALUES (?)",arguments:["arthur@example.com"])
+trydb.execute("INSERT INTO persons (email) VALUES (?)",arguments:["arthur@example.com"])
+
+
At the query level:
+
// CREATE TABLE persons (
+// id INTEGER PRIMARY KEY,
+// email TEXT UNIQUE
+// )
+trydb.create(table:"persons"){tin
+ t.column("id",.integer).primaryKey()
+ t.column("email",.text)
+}
+
+// Again, despite the unique index on email, both inserts succeed.
+trydb.execute("INSERT OR REPLACE INTO persons (email) VALUES (?)",arguments:["arthur@example.com"])
+trydb.execute("INSERT OR REPLACE INTO persons (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 MutablePersistable or Persistable protocol. It will alter the INSERT and UPDATE queries run by the insert, update and savepersistence methods:
+
protocolMutablePersistable{
+ /// 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.
+ staticvarpersistenceConflictPolicy:PersistenceConflictPolicy{get}
+}
+
+structPerson:MutablePersistable{
+ staticletpersistenceConflictPolicy=PersistenceConflictPolicy(
+ insert:.replace,
+ update:.replace)
+}
+
+// INSERT OR REPLACE INTO persons (...) VALUES (...)
+tryperson.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 at the table level, 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.
+
+
+
:warning: Warning: ON CONFLICT REPLACE may 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).
+
+
Record Class
+
+
Record is a class that is designed to be subclassed, and provides the full toolkit in one go: fetching and persistence methods, as well as changes tracking (see the list of record methods for an overview).
+
+
Record subclasses inherit their features from the RowConvertible, TableMapping, and Persistable protocols. Check their documentation for more information.
+
+
For example, here is a fully functional Record subclass:
+
classPointOfInterest:Record{
+ varid:Int64?
+ vartitle:String
+ varcoordinate:CLLocationCoordinate2D
+
+ /// The table name
+ overrideclassvardatabaseTableName:String{
+ return"pointOfInterests"
+ }
+
+ /// Initialize from a database row
+ requiredinit(row:Row){
+ id=row.value(named:"id")
+ title=row.value(named:"title")
+ coordinate=CLLocationCoordinate2DMake(
+ row.value(named:"latitude"),
+ row.value(named:"longitude"))
+ super.init(row:row)
+ }
+
+ /// The values persisted in the database
+ overridevarpersistentDictionary:[String:DatabaseValueConvertible?]{
+ return[
+ "id":id,
+ "title":title,
+ "latitude":coordinate.latitude,
+ "longitude":coordinate.longitude]
+ }
+
+ /// Update record ID after a successful insertion
+ overridefuncdidInsert(withrowID:Int64,forcolumn:String?){
+ id=rowID
+ }
+}
+
The update()method always executes an UPDATE statement. When the record has not been edited, this costly database access is generally useless.
+
+
Avoid it with the hasPersistentChangedValues property, which returns whether the record has changes that have not been saved:
+
// Saves the person if it has changes that have not been saved:
+ifperson.hasPersistentChangedValues{
+ tryperson.save(db)
+}
+
+
+
The hasPersistentChangedValues flag is false after a record has been fetched or saved into the database. Subsequent modifications may set it, or not: hasPersistentChangedValues is based on value comparison. Setting a property to the same value does not set the changed flag:
For an efficient algorithm which synchronizes the content of a database table with a JSON payload, check JSONSynchronization.playground.
+
The Implicit RowID Primary Key
+
+
All SQLite tables have a primary key. Even when the primary key is not explicit:
+
// No explicit primary key
+trydb.create(table:"events"){tin
+ t.column("message",.text)
+ t.column("date",.datetime)
+}
+
+// No way to define an explicit primary key
+trydb.create(virtualTable:"books",using:FTS4()){tin
+ 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 events WHERE rowid = 1
+letevent=tryEvent.fetchOne(db,key:1)
+
+// DELETE FROM books WHERE rowid = 1
+tryBook.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:
+
+
+
Have the selectsRowID static property from the TableMapping protocol be true.
+
structEvent:TableMapping{
+ staticletselectsRowID=true
+}
+
+// When you subclass Record, you need an override:
+classBook:Record{
+ overrideclassvarselectsRowID:Bool{
+ returntrue
+ }
+}
+
+
+
GRDB will then select the rowid column by default:
+
// SELECT *, rowid FROM events
+letevents=tryEvent.fetchAll(db)
+
+
Have init(row:) from the RowConvertible protocol consume the rowid column:
If you prefer using the Column type from the query interface, use the Column.rowID constant:
+
init(row:Row){
+ id=row.value(Column.rowID)
+}
+
+
+
Your fetched records will then know their ids:
+
letevent=tryEvent.fetchOne(db)!
+event.id// some value
+
+
Include the rowid in your persistentDictionary, and keep it in the didInsert(with:for:) method (both from the Persistable and MutablePersistable protocols):
You will then be able to track your record ids, update them, or check for their existence:
+
letevent=Event(message:"foo",date:Date())
+
+// Insertion sets the record id:
+tryevent.insert(db)
+event.id// some value
+
+// Record can be updated:
+event.message="bar"
+tryevent.update(db)
+
+// Record knows if it exists:
+event.exists(db)// true
+
+
+
List of Record Methods
+
+
This is the list of record methods, along with their required protocols. The Record Class adopts all these protocols.
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:
+
trydb.execute("CREATE TABLE wines (...)")
+letcount=tryWine.filter(sql:"color = ?",arguments:[Color.red]).fetchCount(db)
+letwines=tryWine.fetchAll(db,"SELECT * FROM wines WHERE origin = ? ORDER BY price",arguments:["Burgundy"])
+trydb.execute("DELETE FROM wines WHERE corked")
+
// CREATE TABLE example ( ... )
+trydb.create(table:"example"){tin...}
+
+// CREATE TEMPORARY TABLE example IF NOT EXISTS (
+trydb.create(table:"example",temporary:true,ifNotExists:true){tin
+
+
+
Add regular columns with their name and type (text, integer, double, numeric, boolean, blob, date and datetime) - see SQLite data types:
// 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,
+ t.column("id",.integer).primaryKey()
+
+ // email TEXT UNIQUE,
+ t.column("email",.text).unique()
+
+ // countryCode TEXT REFERENCES countries(code) ON DELETE CASCADE,
+ t.column("countryCode",.text).references("countries",onDelete:.cascade)
+
+
+
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)
+ // age INTEGER CHECK (age > 0)
+ t.column("name",.text).check{length($0)>0}
+ t.column("age",.integer).check(sql:"age > 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:"parent")
+
+ // 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 referers RENAME TO referrers
+trydb.rename(table:"referers",to:"referrers")
+
+// ALTER TABLE persons ADD COLUMN url TEXT
+trydb.alter(table:"persons"){tin
+ 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:
+
trydb.drop(table:"obsolete")
+
+
Create Indexes
+
+
Create indexes with the create(index:) method:
+
// CREATE UNIQUE INDEX byEmail ON users(email)
+trydb.create(index:"byEmail",on:"users",columns:["email"],unique:true)
+
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: Person.select(...).filter(...).order(...).
+
+
+
all(), none(): the requests for all rows, or no row.
+
// SELECT * FROM persons
+Person.all()
+
+
+
The hidden rowid column can be selected as well when you need it.
+
select(expression, ...) defines the selected columns.
+
// SELECT id, name FROM persons
+Person.select(idColumn,nameColumn)
+
+// SELECT MAX(age) AS maxAge FROM persons
+Person.select(max(ageColumn).aliased("maxAge"))
+
+
distinct() performs uniquing.
+
// SELECT DISTINCT name FROM persons
+Person.select(nameColumn).distinct()
+
+
filter(expression) applies conditions.
+
// SELECT * FROM persons WHERE id IN (1, 2, 3)
+Person.filter([1,2,3].contains(idColumn))
+
+// SELECT * FROM persons WHERE (name IS NOT NULL) AND (height > 1.75)
+Person.filter(nameColumn!=nil&&heightColumn>1.75)
+
// SELECT * FROM documents WHERE documents MATCH 'sqlite database'
+letpattern=FTS3Pattern(matchingAllTokensIn:"SQLite database")
+Document.matching(pattern)
+
+
+
When the pattern is nil, no row will match.
+
group(expression, ...) groups rows.
+
// SELECT name, MAX(age) FROM persons GROUP BY name
+Person
+ .select(nameColumn,max(ageColumn))
+ .group(nameColumn)
+
+
having(expression) applies conditions on grouped rows.
+
// SELECT name, MAX(age) FROM persons GROUP BY name HAVING MIN(age) >= 18
+Person
+ .select(nameColumn,max(ageColumn))
+ .group(nameColumn)
+ .having(min(ageColumn)>=18)
+
+
order(ordering, ...) sorts.
+
// SELECT * FROM persons ORDER BY name
+Person.order(nameColumn)
+
+// SELECT * FROM persons ORDER BY score DESC, name
+Person.order(scoreColumn.desc,nameColumn)
+
+
+
Each order call clears any previous ordering:
+
// SELECT * FROM persons ORDER BY name
+Person.order(scoreColumn).order(nameColumn)
+
+
reversed() reverses the eventual orderings.
+
// SELECT * FROM persons ORDER BY score ASC, name DESC
+Person.order(scoreColumn.desc,nameColumn).reversed()
+
+
+
If no ordering was specified, the result is ordered by rowID in reverse order.
+
// SELECT * FROM persons ORDER BY _rowid_ DESC
+Person.all().reversed()
+
+
limit(limit, offset: offset) limits and pages results.
+
// SELECT * FROM persons LIMIT 5
+Person.limit(5)
+
+// SELECT * FROM persons LIMIT 5 OFFSET 10
+Person.limit(5,offset:10)
+
+
+
+
You can refine requests by chaining those methods:
+
// SELECT * FROM persons WHERE (email IS NOT NULL) ORDER BY name
+Person.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:
+
Person// SELECT * FROM persons
+ .filter(nameColumn!=nil)// WHERE (name IS NOT NULL)
+ .filter(emailColumn!=nil)// AND (email IS NOT NULL)
+ .order(nameColumn)// - ignored -
+ .order(ageColumn)// ORDER BY age
+ .limit(20,offset:40)// - ignored -
+ .limit(10)// LIMIT 10
+
+
+
Raw SQL snippets are also accepted, with eventual arguments:
+
// SELECT DATE(creationDate), COUNT(*) FROM persons WHERE name = 'Arthur' GROUP BY date(creationDate)
+Person
+ .select(sql:"DATE(creationDate), COUNT(*)")
+ .filter(sql:"name = ?",arguments:["Arthur"])
+ .group(sql:"DATE(creationDate)")
+
+
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 persons WHERE (name = 'Arthur')
+Person.filter(nameColumn=="Arthur")
+
+// SELECT * FROM persons WHERE (name IS NULL)
+Person.filter(nameColumn==nil)
+
+// SELECT * FROM persons WHERE (age IS 18)
+Person.filter(ageColumn===18)
+
+// SELECT * FROM rectangles 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 persons
+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 persons WHERE ((NOT verified) OR (age < 18))
+Person.filter(!verifiedColumn||ageColumn<18)
+
+
BETWEEN, IN, IN (subquery), NOT IN, NOT IN (subquery)
+
+
To check inclusion in a collection, call the contains method on any Swift sequence:
+
// SELECT * FROM persons WHERE id IN (1, 2, 3)
+Person.filter([1,2,3].contains(idColumn))
+
+// SELECT * FROM persons WHERE id NOT IN (1, 2, 3)
+Person.filter(![1,2,3].contains(idColumn))
+
+// SELECT * FROM persons WHERE age BETWEEN 0 AND 17
+Person.filter((0...17).contains(ageColumn))
+
+// SELECT * FROM persons WHERE (age >= 0) AND (age < 18)
+Person.filter((0..<18).contains(ageColumn))
+
+// SELECT * FROM persons WHERE name BETWEEN 'A' AND 'z'
+Person.filter(("A"..."z").contains(nameColumn))
+
+// SELECT * FROM persons WHERE (name >= 'A') AND (name < 'z')
+Person.filter(("A"..<"z").contains(nameColumn))
+
+
+
+
:point_up: Note: SQLite string comparison, by default, is case-sensitive and not Unicode-aware. See string comparison if you need more control.
+
+
+
To check inclusion in a subquery, call the contains method on another request:
+
// SELECT * FROM events
+// WHERE userId IN (SELECT id FROM persons WHERE verified)
+letverifiedUserIds=User.select(idColumn).filter(verifiedColumn)
+Event.filter(verifiedUserIds.contains(userIdColumn))
+
+
EXISTS (subquery), NOT EXISTS (subquery)
+
+
To check is a subquery would return any row, use the exists property on another request:
+
// SELECT * FROM persons
+// WHERE EXISTS (SELECT * FROM books
+// WHERE books.ownerId = persons.id)
+Person.filter(Book.filter(sql:"books.ownerId = persons.id").exists)
+
+
LIKE
+
+
The SQLite LIKE operator is available as the like method:
+
// SELECT * FROM persons WHERE (email LIKE '%@example.com')
+Person.filter(emailColumn.like("%@example.com"))
+
+
+
+
:point_up: Note: the SQLite LIKE operator is case-unsensitive 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:
+
letpattern=FTS3Pattern(matchingAllTokensIn:"SQLite database")
+
+// SELECT * FROM documents WHERE documents MATCH 'sqlite database'
+Document.matching(pattern)
+
+// SELECT * FROM documents WHERE content MATCH 'sqlite database'
+Document.filter(contentColumn.match(pattern))
+
+
+
FTS5:
+
letpattern=FTS5Pattern(matchingAllTokensIn:"SQLite database")
+
+// SELECT * FROM documents WHERE documents 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(age), MAX(age) FROM persons
+Person.select(min(ageColumn),max(ageColumn))
+
+// SELECT COUNT(name) FROM persons
+Person.select(count(nameColumn))
+
+// SELECT COUNT(DISTINCT name) FROM persons
+Person.select(count(distinct:nameColumn))
+
+
IFNULL
+
+
Use the Swift ?? operator:
+
// SELECT IFNULL(name, 'Anonymous') FROM persons
+Person.select(nameColumn??"Anonymous")
+
+// SELECT IFNULL(name, email) FROM persons
+Person.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:
+
Person.select(nameColumn.uppercased())
+
+
+
+
:point_up: Note: When comparing strings, you’d rather use a collation:
When the selected columns don’t fit the source type, change your target: any other type that adopts the RowConvertible protocol, plain database rows, and even values:
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 persons WHERE id = 1
+tryPerson.fetchOne(db,key:1)// Person?
+
+// SELECT * FROM persons WHERE id IN (1, 2, 3)
+tryPerson.fetchAll(db,keys:[1,2,3])// [Person]
+
+// SELECT * FROM persons WHERE isoCode = 'FR'
+tryCountry.fetchOne(db,key:"FR")// Country?
+
+// SELECT * FROM countries WHERE isoCode IN ('FR', 'US')
+tryCountry.fetchAll(db,keys:["FR","US"])// [Country]
+
+
+
When the table has no explicit primary key, GRDB uses the hidden rowid column:
+
// SELECT * FROM documents WHERE rowid = 1
+tryDocument.fetchOne(db,key:1)// Document?
+
+
+
For multiple-column primary keys and unique keys defined by unique indexes, provide a dictionary:
+
// SELECT * FROM citizenships WHERE personID = 1 AND countryISOCode = 'FR'
+tryCitizenship.fetchOne(db,key:["personID":1,"countryISOCode":"FR"])// Citizenship?
+
+// SELECT * FROM persons WHERE email = 'arthur@example.com'
+tryPerson.fetchOne(db,key:["email":"arthur@example.com"])// Person?
+
+
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 persons
+letcount=tryPerson.fetchCount(db)// Int
+
+// SELECT COUNT(*) FROM persons WHERE email IS NOT NULL
+letcount=tryPerson.filter(emailColumn!=nil).fetchCount(db)
+
+// SELECT COUNT(DISTINCT name) FROM persons
+letcount=tryPerson.select(nameColumn).distinct().fetchCount(db)
+
+// SELECT COUNT(*) FROM (SELECT DISTINCT name, age FROM persons)
+letcount=tryPerson.select(nameColumn,ageColumn).distinct().fetchCount(db)
+
+
+
Other aggregated values can also be selected and fetched (see SQL Functions):
Requests can delete records, with the deleteAll() method:
+
// DELETE FROM persons WHERE email IS NULL
+letrequest=Person.filter(emailColumn==nil)
+tryrequest.deleteAll(db)
+
+
+
Deleting records according to their primary key is also quite common. It has a shortcut which accepts any single-column primary key:
+
// DELETE FROM persons WHERE id = 1
+tryPerson.deleteOne(db,key:1)
+
+// DELETE FROM persons WHERE id IN (1, 2, 3)
+tryPerson.deleteAll(db,keys:[1,2,3])
+
+// DELETE FROM persons WHERE isoCode = 'FR'
+tryCountry.deleteOne(db,key:"FR")
+
+// DELETE FROM countries WHERE isoCode IN ('FR', 'US')
+tryCountry.deleteAll(db,keys:["FR","US"])
+
+
+
When the table has no explicit primary key, GRDB uses the hidden rowid column:
+
// DELETE FROM documents WHERE rowid = 1
+tryDocument.deleteOne(db,key:1)
+
+
+
For multiple-column primary keys and unique keys defined by unique indexes, provide a dictionary:
+
// DELETE FROM citizenships WHERE personID = 1 AND countryISOCode = 'FR'
+tryCitizenship.deleteOne(db,key:["personID":1,"countryISOCode":"FR"])
+
+// DELETE FROM persons WHERE email = 'arthur@example.com'
+Person.deleteOne(db,key:["email":"arthur@example.com"])
+
+
Custom Requests
+
+
Until now, we have seen requests created from any type that adopts the TableMapping protocol:
Those requests of type QueryInterfaceRequest can fetch, count, and delete records:
+
tryrequest.fetchCursor(db)// DatabaseCursor<Person>
+tryrequest.fetchAll()// [Person]
+tryrequest.fetchOne()// Person?
+tryrequest.fetchCount()// Int
+tryrequest.deleteAll()
+
+
+
When the query interface can not generate the SQL you need, you can still fallback to raw SQL:
+
// Custom SQL is always welcome
+tryPerson.fetchAll(db,"SELECT ...")// [Person]
+
+
+
But you may prefer to bring some elegance back in, and build custom requests on top of the Request and TypedRequest protocols:
+
// No custom SQL in sight
+tryPerson.customRequest().fetchAll(db)// [Person]
+
+
+
Unlike QueryInterfaceRequest, these protocols can’t delete. But they can fetch and count:
+
/// The protocol for all types that define a way to fetch values from
+/// a database.
+protocolRequest{
+ /// A tuple that contains a prepared statement that is ready to be
+ /// executed, and an eventual row adapter.
+ funcprepare(_db:Database)throws->(SelectStatement,RowAdapter?)
+
+ /// The number of rows fetched by the request.
+ funcfetchCount(_db:Database)throws->Int
+}
+
+/// The protocol for typed fetch requests.
+protocolTypedRequest:Request{
+ /// The fetched type
+ associatedtypeFetched
+}
+
+
+
The prepare method returns a tuple made of a prepared statement and an optional row adapter. The prepared statement tells which SQL query should be executed. The row adapter can help presenting the fetched rows in the way expected by the row consumers (we’ll see an example below).
+
+
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.
+
Fetching From Custom Requests
+
+
A Request doesn’t know what to fetch, but it can feed the fetching methods of any fetchable type (Row, value, or record):
A TypedRequest knows exactly what it has to do when its Fetched associated type is fetchable (Row, value, or record):
+
letrequest=...// Some TypedRequest that fetches Person
+tryrequest.fetchCursor(db)// DatabaseCursor<Person>
+tryrequest.fetchAll(db)// [Person]
+tryrequest.fetchOne(db)// Person?
+
+
Building Custom Requests
+
+
To build custom requests, you can create your own type that adopts the protocols, or derive requests from other requests, or use one of the built-in concrete types:
On top of the APIs described above, GRDB provides a toolkit for applications. While none of those are mandatory, all of them help dealing with the database:
+
+
+
Migrations: Transform your database as your application evolves.
+
Full-Text Search: Perform efficient and customizable full-text searches.
varmigrator=DatabaseMigrator()
+
+// v1 database
+migrator.registerMigration("v1"){dbin
+ trydb.create(table:"persons"){tin...}
+ trydb.create(table:"books"){tin...}
+ trydb.create(index:...)
+}
+
+// v2 database
+migrator.registerMigration("v2"){dbin
+ trydb.alter(table:"persons"){tin...}
+}
+
+// Migrations for future versions will be inserted here:
+//
+// // v3 database
+// migrator.registerMigration("v3") { db in
+// ...
+// }
+
+trymigrator.migrate(dbQueue)// or migrator.migrate(dbPool)
+
+
+
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).
+
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 persons.name:
+migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName"){dbin
+ trydb.create(table:"new_persons"){tin
+ t.column("id",.integer).primaryKey()
+ t.column("name",.text).notNull()
+ }
+ trydb.execute("INSERT INTO new_persons SELECT * FROM persons")
+ trydb.drop(table:"persons")
+ trydb.rename(table:"new_persons",to:"persons")
+}
+
+
+
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
+
+
Full-Text Search is an efficient way to search a corpus of textual documents.
+
// Create full-text tables
+trydb.create(virtualTable:"books",using:FTS4()){tin// or FTS3(), or FTS5()
+ t.column("author")
+ t.column("title")
+ t.column("body")
+}
+
+// Populate full-text table with records or SQL
+tryBook(...).insert(db)
+trydb.execute(
+ "INSERT INTO books (author, title, body) VALUES (?, ?, ?)",
+ arguments:[...])
+
+// Build search patterns
+letpattern=FTS3Pattern(matchingPhrase:"Moby-Dick")
+
+// Search with the query interface or SQL
+letbooks=tryBook.matching(pattern).fetchAll(db)
+letbooks=tryBook.fetchAll(db,
+ "SELECT * FROM books WHERE books MATCH ?",
+ arguments:[pattern])
+
Custom Tokenizers: FTS5. Leverage extra full-text features such as synonyms or stop words. Avoid unicode gotchas.
+
Sample Code: WWDC Companion, an iOS app that stores, displays, and lets the user search the WWDC 2016 sessions.
+
+
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 Needs
+
FTS3
+
FTS4
+
FTS5
+
+
+
+
:question: Queries
+
+
+
+
+
+
Words searches (documents that contain database)
+
X
+
X
+
X
+
+
+
Prefix searches (documents that contain a word starting with data)
+
X
+
X
+
X
+
+
+
Phrases searches (documents that contain the phrase SQLite database)
+
X
+
X
+
X
+
+
+
Boolean searches (documents that contain SQLite or database)
+
X
+
X
+
X
+
+
+
Proximity search (documents that contain SQLite near database)
+
X
+
X
+
X
+
+
+
:scissors: Tokenization
+
+
+
+
+
+
Ascii case insensitivity (have DATABASE match database)
+
X
+
X
+
X
+
+
+
Unicode case insensitivity (have ÉLÉGANCE match élégance)
+
X
+
X
+
X
+
+
+
Latin diacritics insensitivity (have elegance match élégance)
+
X
+
X
+
X
+
+
+
English Stemming (have frustration match frustrated)
+
X
+
X
+
X
+
+
+
English Stemming and Ascii case insensitivity
+
X
+
X
+
X
+
+
+
English Stemming and Unicode case insensitivity
+
+
+
X
+
+
+
English Stemming and Latin diacritics insensitivity
+
+
+
X
+
+
+
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)
+
X
+
X
+
X
+
+
+
+
¹ Requires extra setup, possibly hard to implement.
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 support FTS3 and FTS4 out of the box, but not FTS5. To use FTS5, you’ll need a custom SQLite build that activates the SQLITE_ENABLE_FTS5 compilation option.
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.
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.
The first initializer validates your raw patterns against the query grammar, and may throw a DatabaseError:
+
// OK: FTS3Pattern
+letpattern=tryFTS3Pattern(rawPattern:"sqlite AND database")
+// DatabaseError: malformed MATCH expression: [AND]
+letpattern=tryFTS3Pattern(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:
+
letquery="SQLite database"
+// Matches documents that contain "SQLite" or "database"
+letpattern=FTS3Pattern(matchingAnyTokenIn:query)
+// Matches documents that contain both "SQLite" and "database"
+letpattern=FTS3Pattern(matchingAllTokensIn:query)
+// Matches documents that contain "SQLite database"
+letpattern=FTS3Pattern(matchingPhrase:query)
+
+
+
They return nil when no pattern could be built from the input string:
// Search in all columns
+letdocuments=tryDocument.matching(pattern).fetchAll(db)
+
+// Search in a specific column:
+letdocuments=tryDocument.filter(Column("content").match(pattern)).fetchAll(db)
+
+
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:
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.
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.
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).
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
+trydb.makeFTS5Pattern(rawPattern:"sqlite",forTable:"books")
+// DatabaseError: syntax error near \"AND\"
+trydb.makeFTS5Pattern(rawPattern:"AND",forTable:"books")
+// DatabaseError: no such column: missing
+trydb.makeFTS5Pattern(rawPattern:"missing: sqlite",forTable:"books")
+
+
+
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:
+
letquery="SQLite database"
+// Matches documents that contain "SQLite" or "database"
+letpattern=FTS5Pattern(matchingAnyTokenIn:query)
+// Matches documents that contain both "SQLite" and "database"
+letpattern=FTS5Pattern(matchingAllTokensIn:query)
+// Matches documents that contain "SQLite database"
+letpattern=FTS5Pattern(matchingPhrase:query)
+
+
+
They return nil when no pattern could be built from the input string:
FTS5 can sort results by relevance (most to least relevant):
+
// SQL
+letdocuments=tryDocument.fetchAll(db,
+ "SELECT * FROM documents WHERE documents MATCH ? ORDER BY rank",
+ arguments:[pattern])
+
+// Query Interface
+letdocuments=tryDocument.matching(pattern).order(Column.rank).fetchAll(db)
+
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
+trydb.create(table:"books"){tin
+ t.column("author",.text)
+ t.column("title",.text)
+ t.column("content",.text)
+ ...
+}
+
+// A full-text table synchronized with the regular table
+trydb.create(virtualTable:"books_ft",using:FTS4()){tin// or FTS5()
+ t.synchronize(withTable:"books")
+ 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 by the mean of SQL triggers.
+
+
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 2016 sessions.
+
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 books WHERE books MATCH '...'
+letbooks=Book.matching(pattern).fetchAll(db)
+
+
+
The solution is to perform a joined request, using raw SQL:
+
letsql="SELECT books.* "+
+ "FROM books "+
+ "JOIN books_ft ON "+
+ "books_ft.rowid = books.rowid AND "+
+ "books_ft MATCH ?"
+letbooks=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!
+
Database Changes Observation
+
+
The TransactionObserver protocol lets you observe database changes:
+
protocolTransactionObserver:class{
+ /// Filters database changes that should be notified the the
+ /// `databaseDidChange(with:)` method.
+ funcobserves(eventsOfKindeventKind:DatabaseEventKind)->Bool
+
+ /// 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().
+ funcdatabaseDidChange(withevent:DatabaseEvent)
+
+ /// An opportunity to rollback pending changes by throwing an error.
+ funcdatabaseWillCommit()throws
+
+ /// Database changes have been committed.
+ funcdatabaseDidCommit(_db:Database)
+
+ /// Database changes have been rollbacked.
+ funcdatabaseDidRollback(_db:Database)
+}
+
+
+
To activate a transaction observer, add it to the database queue or pool:
Database holds weak references to its transaction observers: they are not retained, and stop getting notifications after they are deallocated.
+
+
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.
+
+
+
: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 databaseDidCommit is called. On the other side, databaseDidRollback confirms their invalidation:
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:
Eventual errors thrown from databaseWillCommit are exposed to the application code:
+
do{
+ trydbQueue.inTransaction{dbin
+ ...
+ 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.
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 some database changes they are not interested in.
+
+
At first sight, this looks somewhat redundant with the checks that observers can perform in their databaseDidChange method. But the code below is inefficient:
+
// BAD: An inefficient way to track the "persons" table:
+classPersonObserver:TransactionObserver{
+ varpersonsTableModified=false
+
+ funcobserves(eventsOfKindeventKind:DatabaseEventKind)->Bool{
+ // Observe all events
+ returntrue
+ }
+
+ funcdatabaseDidChange(withevent:DatabaseEvent){
+ ifevent.tableName=="persons"{
+ personsTableModified=true
+ }
+ }
+
+ funcdatabaseDidRollback(_db:Database){
+ // Get ready for next transaction
+ personsTableModified=false
+ }
+
+ funcdatabaseDidCommit(_db:Database){
+ ifpersonsTableModified{
+ // Process committed changes to the persons table
+ }
+
+ // Get ready for next transaction
+ personsTableModified=false
+ }
+}
+
+
+
The databaseDidChange method is invoked for each insertion, deletion, and update of individual rows, of any table. When there are many changed rows, the observer will spend of a lot of time performing the same check again and again.
+
+
Instead, filter events in the observes(eventsOfKind:) method. This will prevent databaseDidChange from being called for changes you’re not interested into, and is much more efficient:
+
// GOOD: An efficient way to track the "persons" table:
+classPersonObserver:TransactionObserver{
+ varpersonsTableModified=false
+
+ funcobserves(eventsOfKindeventKind:DatabaseEventKind)->Bool{
+ // Only observe changes to the "persons" table.
+ returneventKind.tableName=="persons"
+ }
+
+ funcdatabaseDidChange(withevent:DatabaseEvent){
+ personsTableModified=true// Guaranteed
+ }
+
+ funcdatabaseDidRollback(_db:Database){
+ // Get ready for next transaction
+ personsTableModified=false
+ }
+
+ funcdatabaseDidCommit(_db:Database){
+ ifpersonsTableModified{
+ // Process committed changes to the persons table
+ }
+
+ // Get ready for next transaction
+ personsTableModified=false
+ }
+}
+
+
+
The observes(eventsOfKind:) method is also able to inspect the columns that are about to be changed:
+
classPersonObserver:TransactionObserver{
+ funcobserves(eventsOfKindeventKind:DatabaseEventKind)->Bool{
+ // Only observe changes to the "name" column of the "persons" table.
+ switcheventKind{
+ case.insert(lettableName):
+ returntableName=="persons"
+ case.delete(lettableName):
+ returntableName=="persons"
+ case.update(lettableName,letcolumnNames):
+ returntableName=="persons"&&columnNames.contains("name")
+ }
+ }
+}
+
+
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:
+
protocolTransactionObserverType: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().
+ funcdatabaseWillChange(withevent: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.
Given a fetch request, and a type that adopts the RowConvertible 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.
The type of the fetched records. It must be a type that adopts the RowConvertible protocol, such as a subclass of the Record class
+
A fetch request
+
+
classPerson:Record{...}
+letdbQueue=DatabaseQueue(...)// Or DatabasePool
+
+// Using a Request from the Query Interface:
+letcontroller=FetchedRecordsController(
+ dbQueue,
+ request:Person.order(Column("name")))
+
+// Using SQL, and eventual arguments:
+letcontroller=FetchedRecordsController<Person>(
+ dbQueue,
+ sql:"SELECT * FROM persons ORDER BY name WHERE countryIsoCode = ?",
+ 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.
+
letcontroller=FetchedRecordsController<Person>(
+ dbQueue,
+ sql:"SELECT persons.name, COUNT(books.id) AS bookCount "+
+ "FROM persons "+
+ "LEFT JOIN books ON books.authorId = persons.id "+
+ "GROUP BY persons.id "+
+ "ORDER BY persons.name")
+
+
+
After creating an instance, you invoke performFetch() to actually execute
+the fetch.
+
trycontroller.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. Transactions can be explicit, or implicit:
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:
+
letcontroller=tryFetchedRecordsController(...)
+
+controller.trackChanges(
+ // controller's records are about to change:
+ willChange:{controllerin...},
+
+ // notification of individual record changes:
+ onChange:{(controller,record,change)in...},
+
+ // controller's records have changed:
+ didChange:{controllerin...})
+
+trycontroller.performFetch()
+
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:{dbin
+ // Fetch any extra value, for example the number of fetched records:
+ returntryPerson.fetchCount(db)
+ },
+ didChange:{(controller,count)in
+ // The extra value is the second argument.
+ letrecordsCount=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.
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(Person.order(Column("name")))
+// Here callbacks have not been called yet.
+// You can cancel them, and refresh records immediately:
+trycontroller.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 TableMapping protocol, they are automatically compared according to their primary key:
: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:
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:{[unownedself]_in
+ self.tableView.beginUpdates()
+ },
+
+ // notification of individual record changes:
+ onChange:{[unownedself](controller,record,change)in
+ switchchange{
+ case.insertion(letindexPath):
+ self.tableView.insertRows(at:[indexPath],with:.fade)
+
+ case.deletion(letindexPath):
+ self.tableView.deleteRows(at:[indexPath],with:.fade)
+
+ case.update(letindexPath,_):
+ ifletcell=self.tableView.cellForRow(at:indexPath){
+ self.configure(cell,at:indexPath)
+ }
+
+ case.move(letindexPath,letnewIndexPath,_):
+ 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:{[unownedself]_in
+ self.tableView.endUpdates()
+ })
+
+
+
See GRDBDemoiOS for an sample app that uses FetchedRecordsController.
+
+
+
: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:
+trydbQueue.inDatabase{dbin
+ tryPerson(...).insert(db)
+}
+// Here callbacks have not been called yet.
+// You can cancel them, and refresh records immediately:
+trycontroller.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.
You can change the passphrase of an already encrypted database:
+
trydbQueue.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
+letclearDBQueue=tryDatabaseQueue(path:"/path/to/clear.db")
+
+// The encrypted database, at some distinct location:
+varconfiguration=Configuration()
+configuration.passphrase="secret"
+letencryptedDBQueue=tryDatabaseQueue(path:"/path/to/encrypted.db",configuration:config)
+
+tryclearDBQueue.inDatabase{dbin
+ trydb.execute("ATTACH DATABASE ? AS encrypted KEY ?",arguments:[encryptedDBQueue.path,"secret"])
+ trydb.execute("SELECT sqlcipher_export('encrypted')")
+ trydb.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.
+
letsource:DatabaseQueue=...// or DatabasePool
+letdestination:DatabaseQueue=...// or DatabasePool
+trysource.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.
+
Good To Know
+
+
This chapter covers general topics that you should be aware of.
Here is an example of code that is vulnerable to SQL injection:
+
// BAD BAD BAD
+letname=textField.text
+trydbQueue.inDatabase{dbin
+ trydb.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:
+
UPDATEstudentsSETname='Robert';
+DROPTABLEstudents;
+--' 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 SQL queries:
+
// Good
+letname=textField.text
+trydbQueue.inDatabase{dbin
+ trydb.execute(
+ "UPDATE students SET name = ? WHERE id = ?",
+ arguments:[name,id])
+}
+
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.
SQLite uses codes to distinguish between various errors:
+
do{
+ try...
+}catchleterrorasDatabaseErrorwhereerror.extendedResultCode==.SQLITE_CONSTRAINT_FOREIGNKEY{
+ // foreign key constraint error
+}catchleterrorasDatabaseErrorwhereerror.resultCode==.SQLITE_CONSTRAINT{
+ // any other constraint error
+}catchleterrorasDatabaseError{
+ // 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...
+}catchleterrorasDatabaseError{
+ switcherror.extendedResultCode{
+ caseResultCode.SQLITE_CONSTRAINT_FOREIGNKEY:
+ // foreign key constraint error
+ caseResultCode.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 Persistable protocol, in a single case: when the update method could not find any row to update:
+
do{
+ tryperson.update(db)
+}catchPersistenceError.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.
+letname:String=row.value(named:"name")
+
+
+
Solution: fix the contents of the database, use NOT NULL constraints, or load an optional:
+
letname:String?=row.value(named:"name")
+
+
The code asks for a Date, when the database contains garbage:
+
// fatal error: could not convert "Mom’s birthday" to Date.
+letdate:Date?=row.value(named:"date")
+
+
+
Solution: fix the contents of the database, or use DatabaseValue to handle all possible cases:
+
letdbv:DatabaseValue=row.value(named:"date")
+ifdbv.isNull{
+ // Handle NULL
+ifletdate=Date.fromDatabaseValue(dbv){
+ // Handle valid date
+}else{
+ // Handle invalid date
+}
+
+
The database can’t guarantee that the code does what it says:
+
// fatal error: table persons has no unique index on column email
+tryPerson.deleteOne(db,key:["email":"arthur@example.com"])
+
+
+
Solution: add a unique index to the persons.email column, or use the deleteAll method to make it clear that you may delete more than one row:
// fatal error: Database methods are not reentrant.
+dbQueue.inDatabase{dbin
+ dbQueue.inDatabase{dbin
+ ...
+ }
+}
+
+
+
Solution: avoid reentrancy, and instead pass a database connection along.
+
+
How to Deal with Untrusted Inputs
+
+
Let’s consider the code below:
+
letsql="SELECT ..."
+
+// Some untrusted arguments for the query
+letarguments:[String:Any]=...
+letrows=tryRow.fetchCursor(db,sql,arguments:StatementArguments(arguments))
+
+whileletrow=tryrows.next(){
+ // Some untrusted database value:
+ letdate:Date?=row.value(atIndex: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:
GRDB extends SQLite with SQL functions that call the Swift built-in string functions capitalized, lowercased, uppercased, localizedCapitalized, localizedLowercased and localizedUppercased:
Those unicode-aware string functions are also readily available in the query interface:
+
Person.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:
+
trydb.create(table:"persons"){tin
+ // 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)
+}
+
+// Persons are sorted in a localized case insensitive way:
+letpersons=tryPerson.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:
+
letcollation=DatabaseCollation.localizedCaseInsensitiveCompare
+letpersons=tryPerson.fetchAll(db,
+ "SELECT * FROM persons ORDER BY name COLLATE \(collation.name))")
+letpersons=tryPerson.order(nameColumn.collating(collation)).fetchAll(db)
+
+
+
You can also define your own collations:
+
letcollation=DatabaseCollation("customCollation"){(lhs,rhs)->NSComparisonResultin
+ // 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.sharedApplication())
+
+
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 explicitely use complete protection:
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.
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.
+
+
+
Both 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.
+
: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:
+
trydbPool.read{dbin// or dbQueue.inDatabase { ... }
+ // Guaranteed to be equal
+ letcount1=tryPerson.fetchCount(db)
+ letcount2=tryPerson.fetchCount(db)
+}
+
+
: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/Database.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 access the same database, a multi-threaded application will eventually face database is locked errors. See Dealing with External Connections.
+
// SAFE CONCURRENCY
+funccurrentUser(_db:Database)throws->User?{
+ returntryUser.fetchOne(db)
+}
+// dbQueue is a singleton defined somewhere in your app
+letuser=trydbQueue.inDatabase{dbin// or dbPool.read { ... }
+ trycurrentUser(db)
+}
+
+// UNSAFE CONCURRENCY
+// This method fails when some other thread is currently writing into
+// the database.
+funccurrentUser()throws->User?{
+ letdbQueue=tryDatabaseQueue(...)
+ returntrydbQueue.inDatabase{dbin
+ tryUser.fetchOne(db)
+ }
+}
+letuser=trycurrentUser()
+
+
:point_up: Rule 2: Group related statements within a single call to a DatabaseQueue or DatabasePool database access method.
+
+
Those 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
+trydbPool.read{dbin// or dbQueue.inDatabase { ... }
+ // Guaranteed to be equal:
+ letcount1=tryPointOfInterest.fetchCount(db)
+ letcount2=tryPointOfInterest.fetchCount(db)
+}
+
+// UNSAFE CONCURRENCY
+// Those two values may be different because some other thread may have
+// modified the database between the two blocks:
+letcount1=trydbPool.read{dbintryPointOfInterest.fetchCount(db)}
+letcount2=trydbPool.read{dbintryPointOfInterest.fetchCount(db)}
+
+
+
In the same vein, when you fetch values that depends on some database updates, group them:
+
// SAFE CONCURRENCY
+trydbPool.write{dbin
+ // The count is guaranteed to be non-zero
+ tryPointOfInterest(...).insert(db)
+ letcount=tryPointOfInterest.fetchCount(db)
+}
+
+// UNSAFE CONCURRENCY
+// The count may be zero because some other thread may have performed
+// a deletion between the two blocks:
+trydbPool.write{dbintryPointOfInterest(...).insert(db)}
+letcount=trydbPool.read{dbintryPointOfInterest.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, group those modifications within a transaction:
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.
+
+
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:
+
trydbPool.write{dbin
+ // Increment the number of persons
+ tryPerson(...).insert(db)
+
+ // Read the number of persons. The writer queue is still locked :-(
+ letcount=tryPerson.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
+trydbPool.write{dbin
+ // Increment the number of persons
+ tryPerson(...).insert(db)
+}
+trydbPool.read{dbin
+ // Read some random value :-(
+ letcount=tryPerson.fetchCount(db)
+}
+
+
+
The correct solution is the readFromCurrentState method, which must be called from within a write block:
+
// CORRECT
+trydbPool.write{dbin
+ // Increment the number of persons
+ tryPerson(...).insert(db)
+
+ trydbPool.readFromCurrentState{db
+ // Read the number of persons. The writer queue has been unlocked :-)
+ letcount=tryPerson.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 persons is guaranteed to be non-zero, even though it is fetched concurrently with the person deletion:
+
trydbPool.write{dbin
+ // Increment the number of persons
+ tryPerson(...).insert(db)
+
+ trydbPool.readFromCurrentState{db
+ // Guaranteed to be non-zero
+ letcount=tryPerson.fetchCount(db)
+ }
+
+ tryPerson.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.
These protocols provide a unified API that lets you write safe concurrent code that targets both classes.
+
+
However, database queues are not database pools, 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.
+
The definition of current state in DatabaseWriter.readFromCurrentState is delicate.
+
+
+
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 reusable agnostic code that has both queues and pools in mind. For example, GRDB uses those protocols for migrations and FetchedRecordsController, two tools that accept both queues and pools.
+
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:
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.inDatabase{dbin
+ // 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:
// SELECT * FROM persons
+tryPerson.fetchAll(db)
+
+// SELECT id, name FROM persons
+tryPerson.select(idColumn,nameColumn).fetchAll(db)
+
+
+
If your Person type can’t be built without other columns (it has non-optional properties for other columns), do define and use a different type.
+
+
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
+letpersons=tryPerson.order(scoreColumn.desc).fetchAll(db)
+lethallOfFame=persons.prefix(5)
+
+// Better way
+lethallOfFame=tryPerson.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.
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 authors
+letauthors=tryAuthor.fetchAll(db)
+forauthorinauthors{
+ // SELECT COUNT(*) FROM books WHERE authorId = ...
+ author.bookCount=tryBook.filter(authorIdColumn==author.id).fetchCount(db)
+}
+
+
+
Instead, perform a single query:
+
letsql="SELECT authors.*, COUNT(books.id) AS bookCount "+
+ "FROM authors "+
+ "LEFT JOIN books ON books.authorId = authors.id "+
+ "GROUP BY authors.id"
+letauthors=tryAuthor.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:
When inserting values, use reusable prepared statements, and set statements values with an array:
+
// Strings & dictionaries
+forpersoninpersons{
+ tryperson.insert(db)
+}
+
+// Prepared statement
+letinsertStatement=db.prepareStatement("INSERT INTO persons (name, email) VALUES (?, ?)")
+forpersoninpersons{
+ // 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([person.name,person.email])
+ tryinsertStatement.execute()
+}
+
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 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:
If the application should modify the database, you need to copy it to a place where it can be modified. For example, in the Documents folder. Only then, open a connection:
Initializes arguments from a sequence of (key, value) dictionary, such as","parent_name":"StatementArguments"},"Structs/StatementArguments.html#/s:FV4GRDB18StatementArgumentscuRxs8SequenceWx8Iterator7Element_zTSSGSqPS_24DatabaseValueConvertible___rFxS0_":{"name":"init(_:)","abstract":"
Initializes arguments from a sequence of (key, value) pairs, such as","parent_name":"StatementArguments"},"Structs/StatementArguments.html#/s:FV4GRDB18StatementArgumentscFGVs10DictionaryVs11AnyHashableP__GSqS0__":{"name":"init(_:)","abstract":"
Creates a new StatementArguments by extending the left-hand size","parent_name":"StatementArguments"},"Structs/StatementArguments.html#/s:ZFV4GRDB18StatementArgumentsoi2apFTS0_S0__S0_":{"name":"&+(_:_:)","abstract":"
Creates a new StatementArguments by extending the left-hand size","parent_name":"StatementArguments"},"Structs/StatementArguments.html#/s:ZFV4GRDB18StatementArgumentsoi2peFTRS0_S0__T_":{"name":"+=(_:_:)","abstract":"
Extends the left-hand size arguments with the right-hand side arguments.
This function is an implementation detail of the query interface.","parent_name":"SQLExpressionFunction"},"Structs/SQLFunctionName.html#/s:vV4GRDB15SQLFunctionName3sqlSS":{"name":"sql","abstract":"
Creates an expression that checks if a subquery would return rows","parent_name":"SQLExpressionExists"},"Structs/SQLExpressionExists.html#/s:FV4GRDB19SQLExpressionExists13expressionSQLFRGSqVS_18StatementArguments_SS":{"name":"expressionSQL(_:)","abstract":"
This function is an implementation detail of the query interface.","parent_name":"SQLExpressionExists"},"Structs/SQLExpressionExists.html#/s:vV4GRDB19SQLExpressionExists7negatedPS_13SQLExpression_":{"name":"negated","abstract":"
This property is an implementation detail of the query interface.","parent_name":"SQLExpressionExists"},"Structs/SQLExpressionBinary.html#/s:vV4GRDB19SQLExpressionBinary3lhsPS_13SQLExpression_":{"name":"lhs","abstract":"
Creates an expression made of two expressions joined with a","parent_name":"SQLExpressionBinary"},"Structs/SQLExpressionBinary.html#/s:FV4GRDB19SQLExpressionBinary13expressionSQLFRGSqVS_18StatementArguments_SS":{"name":"expressionSQL(_:)","abstract":"
This function is an implementation detail of the query interface.","parent_name":"SQLExpressionBinary"},"Structs/SQLExpressionBinary.html#/s:vV4GRDB19SQLExpressionBinary7negatedPS_13SQLExpression_":{"name":"negated","abstract":"
This property is an implementation detail of the query interface.","parent_name":"SQLExpressionBinary"},"Structs/SQLBinaryOperator.html#/s:vV4GRDB17SQLBinaryOperator3sqlSS":{"name":"sql","abstract":"
Creates an expression made of an unary operator and","parent_name":"SQLExpressionUnary"},"Structs/SQLExpressionUnary.html#/s:FV4GRDB18SQLExpressionUnary13expressionSQLFRGSqVS_18StatementArguments_SS":{"name":"expressionSQL(_:)","abstract":"
This function is an implementation detail of the query interface.","parent_name":"SQLExpressionUnary"},"Structs/SQLUnaryOperator.html#/s:vV4GRDB16SQLUnaryOperator3sqlSS":{"name":"sql","abstract":"
Eventual arguments that feed the ? and colon-prefixed tokens in the","parent_name":"SQLExpressionLiteral"},"Structs/SQLExpressionLiteral.html#/s:FV4GRDB20SQLExpressionLiteralcFTSS9argumentsGSqVS_18StatementArguments__S0_":{"name":"init(_:arguments:)","abstract":"
This function is an implementation detail of the query interface.","parent_name":"SQLExpressionLiteral"},"Structs/SQLCollatedExpression.html#/s:vV4GRDB21SQLCollatedExpression10expressionPS_13SQLExpression_":{"name":"expression","abstract":"
This method is an implementation detail of the query interface.","parent_name":"SQLCollatedExpression"},"Structs/ScopeAdapter.html#/s:FV4GRDB12ScopeAdaptercFGVs10DictionarySSPS_10RowAdapter__S0_":{"name":"init(_:)","abstract":"
Creates a SuffixRowAdapter that hides all columns before the","parent_name":"SuffixRowAdapter"},"Structs/SuffixRowAdapter.html#/s:FV4GRDB16SuffixRowAdapter15layoutedAdapterFzT4fromPS_9RowLayout__PS_18LayoutedRowAdapter_":{"name":"layoutedAdapter(from:)","abstract":"
Creates a ColumnMapping with a dictionary from mapped column names to","parent_name":"ColumnMapping"},"Structs/ColumnMapping.html#/s:FV4GRDB13ColumnMapping15layoutedAdapterFzT4fromPS_9RowLayout__PS_18LayoutedRowAdapter_":{"name":"layoutedAdapter(from:)","abstract":"
An array of (baseIndex, mappedName) pairs, where baseIndex is the index","parent_name":"LayoutedColumnMapping"},"Structs/LayoutedColumnMapping.html#/s:FV4GRDB21LayoutedColumnMappingcuRxs8SequenceWx8Iterator7Element_zTSiSS_rFT13layoutColumnsx_S0_":{"name":"init(layoutColumns:)","abstract":"
Creates an LayoutedColumnMapping from an array of (baseIndex, mappedName)","parent_name":"LayoutedColumnMapping"},"Structs/LayoutedColumnMapping.html#/s:vV4GRDB21LayoutedColumnMapping7mappingS0_":{"name":"mapping","abstract":"
Part of the LayoutedRowAdapter protocol; returns self.
Part of the RowLayout protocol; returns the index of the leftmost column","parent_name":"LayoutedColumnMapping"},"Structs/RowIndex.html#/s:ZFPs9Equatableoi2eeFTxx_Sb":{"name":"==(_:_:)","abstract":"
Indexes to (columnName, databaseValue) pairs in a database row.
Creates a new request whose prepare() method wraps and forwards","parent_name":"AnyTypedRequest"},"Structs/AnyTypedRequest.html#/s:FV4GRDB15AnyTypedRequest7prepareFzCS_8DatabaseTCS_15SelectStatementGSqPS_10RowAdapter___":{"name":"prepare(_:)","abstract":"
A tuple that contains a prepared statement that is ready to be","parent_name":"AnyTypedRequest"},"Structs/SQLRequest.html#/s:FV4GRDB10SQLRequestcFTSS9argumentsGSqVS_18StatementArguments_7adapterGSqPS_10RowAdapter___S0_":{"name":"init(_:arguments:adapter:)","abstract":"
Creates a new request from an SQL string, optional arguments, and","parent_name":"SQLRequest"},"Structs/SQLRequest.html#/s:FV4GRDB10SQLRequest7prepareFzCS_8DatabaseTCS_15SelectStatementGSqPS_10RowAdapter___":{"name":"prepare(_:)","abstract":"
A tuple that contains a prepared statement that is ready to be","parent_name":"SQLRequest"},"Structs/AnyRequest.html#/s:FV4GRDB10AnyRequestcFPS_7Request_S0_":{"name":"init(_:)","abstract":"
Creates a new request that wraps and forwards operations to request.
Creates a new request whose prepare() method wraps and forwards","parent_name":"AnyRequest"},"Structs/AnyRequest.html#/s:FV4GRDB10AnyRequest7prepareFzCS_8DatabaseTCS_15SelectStatementGSqPS_10RowAdapter___":{"name":"prepare(_:)","abstract":"
A tuple that contains a prepared statement that is ready to be","parent_name":"AnyRequest"},"Structs/PersistenceConflictPolicy.html#/s:vV4GRDB25PersistenceConflictPolicy27conflictResolutionForInsertOCS_8Database18ConflictResolution":{"name":"conflictResolutionForInsert","abstract":"
Creates a FTS4 module suitable for the Database","parent_name":"FTS4"},"Structs/FTS4.html#/s:vV4GRDB4FTS410moduleNameSS":{"name":"moduleName","abstract":"
This function is an implementation detail of the query interface.","parent_name":"Column"},"Structs/Column.html#/s:ZvV4GRDB6Column5rowIDS0_":{"name":"rowID","abstract":"
Returns a new QueryInterfaceRequest with a matching predicate added","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:FV4GRDB21QueryInterfaceRequest14selectQuerySQLFRGSqVS_18StatementArguments_SS":{"name":"selectQuerySQL(_:)","abstract":"
This function is an implementation detail of the query interface.","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:FV4GRDB21QueryInterfaceRequest6selectFtGSaPS_13SQLSelectable___GS0_x_":{"name":"select(_:)","abstract":"
A new QueryInterfaceRequest with a new net of selected columns.
A new QueryInterfaceRequest with the provided predicate added to the","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:FV4GRDB21QueryInterfaceRequest6filterFT3sqlSS9argumentsGSqVS_18StatementArguments__GS0_x_":{"name":"filter(sql:arguments:)","abstract":"
A new QueryInterfaceRequest with the provided predicate added to the","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:FV4GRDB21QueryInterfaceRequest5groupFtGSaPS_14SQLExpressible___GS0_x_":{"name":"group(_:)","abstract":"
A new QueryInterfaceRequest grouped according to expressions.
A new QueryInterfaceRequest with the provided predicate added to the","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:FV4GRDB21QueryInterfaceRequest6havingFT3sqlSS9argumentsGSqVS_18StatementArguments__GS0_x_":{"name":"having(sql:arguments:)","abstract":"
A new QueryInterfaceRequest with the provided sql added to the","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:FV4GRDB21QueryInterfaceRequest5orderFtGSaPS_15SQLOrderingTerm___GS0_x_":{"name":"order(_:)","abstract":"
A new QueryInterfaceRequest with the provided orderings.
A QueryInterfaceRequest which fetches limit rows, starting","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:FV4GRDB21QueryInterfaceRequest10fetchCountFzCS_8DatabaseSi":{"name":"fetchCount(_:)","abstract":"
Creates a pattern from a raw pattern string; throws DatabaseError on","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/init(matchingAnyTokenIn:)":{"name":"init(matchingAnyTokenIn:)","abstract":"Undocumented","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/init(matchingAllTokensIn:)":{"name":"init(matchingAllTokensIn:)","abstract":"Undocumented","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/init(matchingPhrase:)":{"name":"init(matchingPhrase:)","abstract":"Undocumented","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/s:FV4GRDB11FTS3PatterncFT18matchingAnyTokenInSS_GSqS0__":{"name":"init(matchingAnyTokenIn:)","abstract":"
Creates a pattern that matches any token found in the input string;","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/s:FV4GRDB11FTS3PatterncFT19matchingAllTokensInSS_GSqS0__":{"name":"init(matchingAllTokensIn:)","abstract":"
Creates a pattern that matches all tokens found in the input string;","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/s:FV4GRDB11FTS3PatterncFT14matchingPhraseSS_GSqS0__":{"name":"init(matchingPhrase:)","abstract":"
Creates a pattern that matches a contiguous string; returns nil if no","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/s:vV4GRDB11FTS3Pattern13databaseValueVS_13DatabaseValue":{"name":"databaseValue","abstract":"
Returns a value that can be stored in the database.
Returns an FTS3Pattern initialized from databaseValue, if it contains","parent_name":"FTS3Pattern"},"Structs/FTS3.html#/s:FV4GRDB4FTS3cFT_S0_":{"name":"init()","abstract":"
Creates a FTS3 module suitable for the Database","parent_name":"FTS3"},"Structs/FTS3.html#/s:vV4GRDB4FTS310moduleNameSS":{"name":"moduleName","abstract":"
This property is an implementation detail of the query interface.","parent_name":"DatabaseValue"},"Structs/DatabaseValue.html#/s:vV4GRDB13DatabaseValue11descriptionSS":{"name":"description","abstract":"
This function is an implementation detail of the query interface.","parent_name":"DatabaseValue"},"Structs/DatabaseValue.html#/s:vV4GRDB13DatabaseValue7negatedPS_13SQLExpression_":{"name":"negated","abstract":"
This property is an implementation detail of the query interface.","parent_name":"DatabaseValue"},"Structs/DatabaseMigrator.html#/s:FV4GRDB16DatabaseMigratorcFT_S0_":{"name":"init()","abstract":"
Iterate migrations in the same order as they were registered. If a","parent_name":"DatabaseMigrator"},"Structs/DatabaseError.html#/s:vV4GRDB13DatabaseError10resultCodeVS_10ResultCode":{"name":"resultCode","abstract":"
The SQLite error code (see","parent_name":"DatabaseError"},"Structs/DatabaseError.html#/s:vV4GRDB13DatabaseError18extendedResultCodeVS_10ResultCode":{"name":"extendedResultCode","abstract":"
The SQLite extended error code (see","parent_name":"DatabaseError"},"Structs/DatabaseError.html#/s:vV4GRDB13DatabaseError7messageGSqSS_":{"name":"message","abstract":"
A result code limited to the least significant 8 bits of the receiver.","parent_name":"ResultCode"},"Structs/ResultCode.html#/s:vPs23CustomStringConvertible11descriptionSS":{"name":"description","abstract":"
A result code limited to the least significant 8 bits of the receiver.","parent_name":"ResultCode"},"Structs/ResultCode.html#/s:ZFPs9Equatableoi2eeFTxx_Sb":{"name":"==(_:_:)","abstract":"
A result code limited to the least significant 8 bits of the receiver.","parent_name":"ResultCode"},"Structs/ResultCode.html#/s:ZFV4GRDB10ResultCodeoi2teFTS0_S0__Sb":{"name":"~=(_:_:)","abstract":"
Returns true if the code on the left matches the code on the right.
Returns a DatabaseDateComponents if databaseValue contains a","parent_name":"DatabaseDateComponents"},"Structs/DatabaseCoder.html#/s:vV4GRDB13DatabaseCoder6objectP_":{"name":"object","abstract":"
The maximum number of concurrent readers (applies to database","parent_name":"Configuration"},"Structs/Configuration.html#/s:FV4GRDB13ConfigurationcFT_S0_":{"name":"init()","abstract":"
DatabaseCoder reads and stores objects that conform to NSCoding in"},"Structs/DatabaseDateComponents.html":{"name":"DatabaseDateComponents","abstract":"
DatabaseDateComponents reads and stores DateComponents in the database.
SQLCollatedExpression taints an expression so that every derived expression"},"Structs/SQLExpressionLiteral.html":{"name":"SQLExpressionLiteral","abstract":"
This type is an implementation detail of the query interface."},"Structs/SQLUnaryOperator.html":{"name":"SQLUnaryOperator","abstract":"
This type is an implementation detail of the query interface."},"Structs/SQLExpressionUnary.html":{"name":"SQLExpressionUnary","abstract":"
This type is an implementation detail of the query interface."},"Structs/SQLBinaryOperator.html":{"name":"SQLBinaryOperator","abstract":"
This type is an implementation detail of the query interface."},"Structs/SQLExpressionBinary.html":{"name":"SQLExpressionBinary","abstract":"
This type is an implementation detail of the query interface."},"Structs/SQLExpressionExists.html":{"name":"SQLExpressionExists","abstract":"
This type is an implementation detail of the query interface."},"Structs/SQLFunctionName.html":{"name":"SQLFunctionName","abstract":"
This type is an implementation detail of the query interface."},"Structs/SQLExpressionFunction.html":{"name":"SQLExpressionFunction","abstract":"
This type is an implementation detail of the query interface."},"Structs/StatementArguments.html":{"name":"StatementArguments","abstract":"
StatementArguments provide values to argument placeholders in raw"},"Protocols/VirtualTableModule.html#/s:vP4GRDB18VirtualTableModule10moduleNameSS":{"name":"moduleName","abstract":"
The type of the closure argument in the","parent_name":"VirtualTableModule"},"Protocols/VirtualTableModule.html#/s:FP4GRDB18VirtualTableModule19makeTableDefinitionFT_wx15TableDefinition":{"name":"makeTableDefinition()","abstract":"
Returns a table definition that is passed as the closure argument in the","parent_name":"VirtualTableModule"},"Protocols/VirtualTableModule.html#/s:FP4GRDB18VirtualTableModule15moduleArgumentsFzT3forwx15TableDefinition2inCS_8Database_GSaSS_":{"name":"moduleArguments(for:in:)","abstract":"
Returns the module arguments for the CREATE VIRTUAL TABLE query.
Execute any relevant database statement after the virtual table has","parent_name":"VirtualTableModule"},"Protocols/StatementColumnConvertible.html#/s:FP4GRDB26StatementColumnConvertiblecFT15sqliteStatementVs13OpaquePointer5indexVs5Int32_x":{"name":"init(sqliteStatement:index:)","abstract":"
Returns a value initialized from a raw SQLite statement pointer.
This function is an implementation detail of the query interface.","parent_name":"SQLSelectQuery"},"Protocols/SQLSelectQuery.html#/s:FE4GRDBPS_14SQLSelectQuery6existsFT_PS_13SQLExpression_":{"name":"exists()","abstract":"
Returns an SQL expression that checks whether the receiver, as a","parent_name":"SQLSelectQuery"},"Protocols/SQLSelectQuery.html#/s:FE4GRDBPS_14SQLSelectQuery13collectionSQLFRGSqVS_18StatementArguments_SS":{"name":"collectionSQL(_:)","abstract":"
This function is an implementation detail of the query interface.","parent_name":"SQLSelectQuery"},"Protocols/SQLSelectQuery.html#/s:FE4GRDBPS_14SQLSelectQuery7prepareFzCS_8DatabaseTCS_15SelectStatementGSqPS_10RowAdapter___":{"name":"prepare(_:)","abstract":"
A tuple that contains a prepared statement that is ready to be","parent_name":"SQLSelectQuery"},"Protocols/SQLSelectable.html#/s:FP4GRDB13SQLSelectable15resultColumnSQLFRGSqVS_18StatementArguments_SS":{"name":"resultColumnSQL(_:)","abstract":"Undocumented","parent_name":"SQLSelectable"},"Protocols/SQLSelectable.html#/s:FP4GRDB13SQLSelectable10countedSQLFRGSqVS_18StatementArguments_SS":{"name":"countedSQL(_:)","abstract":"Undocumented","parent_name":"SQLSelectable"},"Protocols/SQLSelectable.html#/s:FP4GRDB13SQLSelectable18countingSelectableFT8distinctSb4fromSS7aliasedGSqSS__GSqPS0___":{"name":"countingSelectable(distinct:from:aliased:)","abstract":"Undocumented","parent_name":"SQLSelectable"},"Protocols/SQLOrderingTerm.html#/s:vP4GRDB15SQLOrderingTerm8reversedPS0__":{"name":"reversed","abstract":"Undocumented","parent_name":"SQLOrderingTerm"},"Protocols/SQLOrderingTerm.html#/s:FP4GRDB15SQLOrderingTerm15orderingTermSQLFRGSqVS_18StatementArguments_SS":{"name":"orderingTermSQL(_:)","abstract":"Undocumented","parent_name":"SQLOrderingTerm"},"Protocols/SQLSpecificExpressible.html#/s:vE4GRDBPS_22SQLSpecificExpressible11capitalizedPS_13SQLExpression_":{"name":"capitalized","abstract":"
Returns an SQL expression that applies the Swift’s built-in","parent_name":"SQLSpecificExpressible"},"Protocols/SQLSpecificExpressible.html#/s:vE4GRDBPS_22SQLSpecificExpressible10lowercasedPS_13SQLExpression_":{"name":"lowercased","abstract":"
Returns an SQL expression that applies the Swift’s built-in","parent_name":"SQLSpecificExpressible"},"Protocols/SQLSpecificExpressible.html#/s:vE4GRDBPS_22SQLSpecificExpressible10uppercasedPS_13SQLExpression_":{"name":"uppercased","abstract":"
Returns an SQL expression that applies the Swift’s built-in","parent_name":"SQLSpecificExpressible"},"Protocols/SQLSpecificExpressible.html#/s:vE4GRDBPS_22SQLSpecificExpressible20localizedCapitalizedPS_13SQLExpression_":{"name":"localizedCapitalized","abstract":"
Returns an SQL expression that applies the Swift’s built-in","parent_name":"SQLSpecificExpressible"},"Protocols/SQLSpecificExpressible.html#/s:vE4GRDBPS_22SQLSpecificExpressible19localizedLowercasedPS_13SQLExpression_":{"name":"localizedLowercased","abstract":"
Returns an SQL expression that applies the Swift’s built-in","parent_name":"SQLSpecificExpressible"},"Protocols/SQLSpecificExpressible.html#/s:vE4GRDBPS_22SQLSpecificExpressible19localizedUppercasedPS_13SQLExpression_":{"name":"localizedUppercased","abstract":"
Returns an SQL expression that applies the Swift’s built-in","parent_name":"SQLSpecificExpressible"},"Protocols/SQLSpecificExpressible.html#/s:FE4GRDBPS_22SQLSpecificExpressible4likeFPS_14SQLExpressible_PS_13SQLExpression_":{"name":"like(_:)","abstract":"
This method is an implementation detail of the query interface.","parent_name":"SQLSpecificExpressible"},"Protocols/SQLSpecificExpressible.html#/s:FE4GRDBPS_22SQLSpecificExpressible9collatingFCS_17DatabaseCollationVS_21SQLCollatedExpression":{"name":"collating(_:)","abstract":"
This method is an implementation detail of the query interface.","parent_name":"SQLSpecificExpressible"},"Protocols/SQLExpression.html#/s:FP4GRDB13SQLExpression13expressionSQLFRGSqVS_18StatementArguments_SS":{"name":"expressionSQL(_:)","abstract":"
This function is an implementation detail of the query interface.","parent_name":"SQLExpression"},"Protocols/SQLExpression.html#/s:vP4GRDB13SQLExpression7negatedPS0__":{"name":"negated","abstract":"
This property is an implementation detail of the query interface.","parent_name":"SQLExpression"},"Protocols/SQLExpression.html#/s:vE4GRDBPS_13SQLExpression7literalVS_20SQLExpressionLiteral":{"name":"literal","abstract":"
This property is an implementation detail of the query interface.","parent_name":"SQLExpression"},"Protocols/SQLExpression.html#/s:vE4GRDBPS_13SQLExpression13sqlExpressionPS0__":{"name":"sqlExpression","abstract":"
This property is an implementation detail of the query interface.","parent_name":"SQLExpression"},"Protocols/SQLExpression.html#/s:FE4GRDBPS_13SQLExpression18countingSelectableFT8distinctSb4fromSS7aliasedGSqSS__GSqPS_13SQLSelectable__":{"name":"countingSelectable(distinct:from:aliased:)","abstract":"
This function is an implementation detail of the query interface.","parent_name":"SQLExpression"},"Protocols/SQLCollection.html#/s:FP4GRDB13SQLCollection13collectionSQLFRGSqVS_18StatementArguments_SS":{"name":"collectionSQL(_:)","abstract":"
This function is an implementation detail of the query interface.","parent_name":"SQLCollection"},"Protocols/SQLCollection.html#/s:FP4GRDB13SQLCollection8containsFPS_14SQLExpressible_PS_13SQLExpression_":{"name":"contains(_:)","abstract":"
Returns an expression that check whether the collection contains","parent_name":"SQLCollection"},"Protocols/RowConvertible.html#/s:FP4GRDB14RowConvertiblecFT3rowCS_3Row_x":{"name":"init(row:)","abstract":"
Returns a cursor over records identified by the provided unique keys","parent_name":"RowConvertible"},"Protocols/RowConvertible.html#/s:ZFe4GRDBRxS_14RowConvertiblexS_12TableMappingrS0_8fetchAllFzTCS_8Database4keysGSaGVs10DictionarySSGSqPS_24DatabaseValueConvertible_____GSax_":{"name":"fetchAll(_:keys:)","abstract":"
Returns an array of records identified by the provided unique keys","parent_name":"RowConvertible"},"Protocols/RowConvertible.html#/s:ZFe4GRDBRxS_14RowConvertiblexS_12TableMappingrS0_8fetchOneFzTCS_8Database3keyGVs10DictionarySSGSqPS_24DatabaseValueConvertible____GSqx_":{"name":"fetchOne(_:key:)","abstract":"
Returns a single record identified by a unique key (the primary key or","parent_name":"RowConvertible"},"Protocols/RowAdapter.html#/s:FP4GRDB10RowAdapter15layoutedAdapterFzT4fromPS_9RowLayout__PS_18LayoutedRowAdapter_":{"name":"layoutedAdapter(from:)","abstract":"
You never call this method directly. It is called for you whenever an","parent_name":"RowAdapter"},"Protocols/RowAdapter.html#/s:FE4GRDBPS_10RowAdapter12addingScopesFGVs10DictionarySSPS0___PS0__":{"name":"addingScopes(_:)","abstract":"
Returns an adapter based on self, with added scopes.
An array of (baseIndex, name) pairs, where baseIndex is the index","parent_name":"RowLayout"},"Protocols/RowLayout.html#/s:FP4GRDB9RowLayout11layoutIndexFT8ofColumnSS_GSqSi_":{"name":"layoutIndex(ofColumn:)","abstract":"
Returns the index of the leftmost column named name, in a","parent_name":"RowLayout"},"Protocols/LayoutedRowAdapter.html#/s:vP4GRDB18LayoutedRowAdapter7mappingVS_21LayoutedColumnMapping":{"name":"mapping","abstract":"
A LayoutedColumnMapping that defines how to map a column name to a","parent_name":"LayoutedRowAdapter"},"Protocols/LayoutedRowAdapter.html#/s:vP4GRDB18LayoutedRowAdapter6scopesGVs10DictionarySSPS0___":{"name":"scopes","abstract":"
A tuple that contains a prepared statement that is ready to be","parent_name":"Request"},"Protocols/Request.html#/s:FP4GRDB7Request10fetchCountFzCS_8DatabaseSi":{"name":"fetchCount(_:)","abstract":"
Executes an INSERT or an UPDATE statement so that self is saved in","parent_name":"Persistable"},"Protocols/Persistable.html#/s:FE4GRDBPS_11Persistable13performInsertFzCS_8DatabaseT_":{"name":"performInsert(_:)","abstract":"
Don’t invoke this method directly: it is an internal method for types","parent_name":"Persistable"},"Protocols/Persistable.html#/s:FE4GRDBPS_11Persistable11performSaveFzCS_8DatabaseT_":{"name":"performSave(_:)","abstract":"
Don’t invoke this method directly: it is an internal method for types","parent_name":"Persistable"},"Protocols/MutablePersistable.html#/s:ZvP4GRDB18MutablePersistable25persistenceConflictPolicyVS_25PersistenceConflictPolicy":{"name":"persistenceConflictPolicy","abstract":"
The policy that handles SQLite conflicts when records are inserted","parent_name":"MutablePersistable"},"Protocols/MutablePersistable.html#/s:vP4GRDB18MutablePersistable20persistentDictionaryGVs10DictionarySSGSqPS_24DatabaseValueConvertible___":{"name":"persistentDictionary","abstract":"
Returns the values that should be stored in the database.
Executes an INSERT or an UPDATE statement so that self is saved in","parent_name":"MutablePersistable"},"Protocols/MutablePersistable.html#/s:FP4GRDB18MutablePersistable6deleteFzCS_8DatabaseSb":{"name":"delete(_:)","abstract":"
Returns true if and only if the primary key matches a row in","parent_name":"MutablePersistable"},"Protocols/MutablePersistable.html#/s:FE4GRDBPS_18MutablePersistable6updateFzCS_8DatabaseT_":{"name":"update(_:)","abstract":"
Executes an UPDATE statement that updates all table columns.
Don’t invoke this method directly: it is an internal method for types","parent_name":"MutablePersistable"},"Protocols/MutablePersistable.html#/s:FE4GRDBPS_18MutablePersistable13performUpdateFzTCS_8Database7columnsGVs3SetSS__T_":{"name":"performUpdate(_:columns:)","abstract":"
Don’t invoke this method directly: it is an internal method for types","parent_name":"MutablePersistable"},"Protocols/MutablePersistable.html#/s:FE4GRDBPS_18MutablePersistable11performSaveFzCS_8DatabaseT_":{"name":"performSave(_:)","abstract":"
Don’t invoke this method directly: it is an internal method for types","parent_name":"MutablePersistable"},"Protocols/MutablePersistable.html#/s:FE4GRDBPS_18MutablePersistable13performDeleteFzCS_8DatabaseSb":{"name":"performDelete(_:)","abstract":"
Don’t invoke this method directly: it is an internal method for types","parent_name":"MutablePersistable"},"Protocols/MutablePersistable.html#/s:FE4GRDBPS_18MutablePersistable13performExistsFzCS_8DatabaseSb":{"name":"performExists(_:)","abstract":"
Don’t invoke this method directly: it is an internal method for types","parent_name":"MutablePersistable"},"Protocols/FTS5WrapperTokenizer.html#/wrappedTokenizer":{"name":"wrappedTokenizer","abstract":"Undocumented","parent_name":"FTS5WrapperTokenizer"},"Protocols/FTS5WrapperTokenizer.html#/accept(token:flags:for:tokenCallback:)":{"name":"accept(token:flags:for:tokenCallback:)","abstract":"Undocumented","parent_name":"FTS5WrapperTokenizer"},"Protocols/FTS5WrapperTokenizer.html#/tokenize(context:tokenization:pText:nText:tokenCallback:)":{"name":"tokenize(context:tokenization:pText:nText:tokenCallback:)","abstract":"Undocumented","parent_name":"FTS5WrapperTokenizer"},"Protocols/FTS5Tokenizer.html#/tokenize(context:tokenization:pText:nText:tokenCallback:)":{"name":"tokenize(context:tokenization:pText:nText:tokenCallback:)","abstract":"Undocumented","parent_name":"FTS5Tokenizer"},"Protocols/FTS5CustomTokenizer.html#/name":{"name":"name","abstract":"Undocumented","parent_name":"FTS5CustomTokenizer"},"Protocols/FTS5CustomTokenizer.html#/init(db:arguments:)":{"name":"init(db:arguments:)","abstract":"Undocumented","parent_name":"FTS5CustomTokenizer"},"Protocols/FTS5CustomTokenizer.html#/tokenizerDescriptor(arguments:)":{"name":"tokenizerDescriptor(arguments:)","abstract":"Undocumented","parent_name":"FTS5CustomTokenizer"},"Protocols/TableMapping.html#/s:ZvP4GRDB12TableMapping17databaseTableNameSS":{"name":"databaseTableName","abstract":"
This flag tells whether the hidden rowid column should be fetched","parent_name":"TableMapping"},"Protocols/TableMapping.html#/s:ZFE4GRDBPS_12TableMapping8matchingFGSqVS_11FTS3Pattern_GVS_21QueryInterfaceRequestx_":{"name":"matching(_:)","abstract":"
Returns a QueryInterfaceRequest with a matching predicate.
Creates a QueryInterfaceRequest sorted according to the","parent_name":"TableMapping"},"Protocols/TableMapping.html#/s:ZFE4GRDBPS_12TableMapping5orderFGSaPS_15SQLOrderingTerm__GVS_21QueryInterfaceRequestx_":{"name":"order(_:)","abstract":"
Creates a QueryInterfaceRequest sorted according to the","parent_name":"TableMapping"},"Protocols/TableMapping.html#/s:ZFE4GRDBPS_12TableMapping5orderFT3sqlSS9argumentsGSqVS_18StatementArguments__GVS_21QueryInterfaceRequestx_":{"name":"order(sql:arguments:)","abstract":"
Creates a QueryInterfaceRequest sorted according to sql.
Creates a QueryInterfaceRequest which fetches limit rows, starting at","parent_name":"TableMapping"},"Protocols/TableMapping.html#/s:ZFE4GRDBPS_12TableMapping10fetchCountFzCS_8DatabaseSi":{"name":"fetchCount(_:)","abstract":"
Delete records identified by their primary keys; returns the number of","parent_name":"TableMapping"},"Protocols/TableMapping.html#/s:ZFE4GRDBPS_12TableMapping9deleteOneuRd__S_24DatabaseValueConvertiblerFzTCS_8Database3keyGSqqd____Sb":{"name":"deleteOne(_:key:)","abstract":"
Delete a record, identified by its primary key; returns whether a","parent_name":"TableMapping"},"Protocols/TableMapping.html#/s:ZFE4GRDBPS_12TableMapping9deleteAllFzTCS_8Database4keysGSaGVs10DictionarySSGSqPS_24DatabaseValueConvertible_____Si":{"name":"deleteAll(_:keys:)","abstract":"
Delete records identified by the provided unique keys (primary key or","parent_name":"TableMapping"},"Protocols/TableMapping.html#/s:ZFE4GRDBPS_12TableMapping9deleteOneFzTCS_8Database3keyGVs10DictionarySSGSqPS_24DatabaseValueConvertible____Sb":{"name":"deleteOne(_:key:)","abstract":"
Delete a record, identified by a unique key (the primary key or any key","parent_name":"TableMapping"},"Protocols/DatabaseWriter.html#/s:FP4GRDB14DatabaseWriter5writeurFzFzCS_8Databaseqd__qd__":{"name":"write(_:)","abstract":"
Synchronously executes a block that takes a database connection, and","parent_name":"DatabaseWriter"},"Protocols/DatabaseWriter.html#/s:FP4GRDB14DatabaseWriter20readFromCurrentStateFzFCS_8DatabaseT_T_":{"name":"readFromCurrentState(_:)","abstract":"
Synchronously or asynchronously executes a read-only block that takes a","parent_name":"DatabaseWriter"},"Protocols/DatabaseWriter.html#/s:FE4GRDBPS_14DatabaseWriter3addFT19transactionObserverPS_19TransactionObserver__T_":{"name":"add(transactionObserver:)","abstract":"
Add a transaction observer, so that it gets notified of","parent_name":"DatabaseWriter"},"Protocols/DatabaseWriter.html#/s:FE4GRDBPS_14DatabaseWriter6removeFT19transactionObserverPS_19TransactionObserver__T_":{"name":"remove(transactionObserver:)","abstract":"
This property is an implementation detail of the query interface.","parent_name":"DatabaseValueConvertible"},"Protocols/DatabaseValueConvertible.html#/s:ZFE4GRDBPS_24DatabaseValueConvertible11fetchCursorFzTCS_15SelectStatement9argumentsGSqVS_18StatementArguments_7adapterGSqPS_10RowAdapter___GCS_14DatabaseCursorx_":{"name":"fetchCursor(_:arguments:adapter:)","abstract":"
Returns a cursor over values fetched from a prepared statement.
This property is an implementation detail of the query interface.","parent_name":"SQLExpressible"},"Protocols/SQLExpressible.html#/s:Fe4GRDBRxS_14SQLExpressiblexS_15SQLOrderingTermrS0_15orderingTermSQLFRGSqVS_18StatementArguments_SS":{"name":"orderingTermSQL(_:)","abstract":"
This method is an implementation detail of the query interface.","parent_name":"SQLExpressible"},"Protocols/SQLExpressible.html#/s:Fe4GRDBRxS_14SQLExpressiblexS_13SQLSelectablerS0_15resultColumnSQLFRGSqVS_18StatementArguments_SS":{"name":"resultColumnSQL(_:)","abstract":"
This method is an implementation detail of the query interface.","parent_name":"SQLExpressible"},"Protocols/SQLExpressible.html#/s:Fe4GRDBRxS_14SQLExpressiblexS_13SQLSelectablerS0_10countedSQLFRGSqVS_18StatementArguments_SS":{"name":"countedSQL(_:)","abstract":"
This method is an implementation detail of the query interface.","parent_name":"SQLExpressible"},"Protocols/SQLExpressible.html#/s:Fe4GRDBRxS_14SQLExpressiblexS_13SQLSelectablerS0_18countingSelectableFT8distinctSb4fromSS7aliasedGSqSS__GSqPS1___":{"name":"countingSelectable(distinct:from:aliased:)","abstract":"
This method is an implementation detail of the query interface.","parent_name":"SQLExpressible"},"Protocols/DatabaseReader.html#/s:FP4GRDB14DatabaseReader4readurFzFzCS_8Databaseqd__qd__":{"name":"read(_:)","abstract":"
Synchronously executes a read-only block that takes a database","parent_name":"DatabaseReader"},"Protocols/DatabaseReader.html#/s:FP4GRDB14DatabaseReader10unsafeReadurFzFzCS_8Databaseqd__qd__":{"name":"unsafeRead(_:)","abstract":"
Synchronously executes a read-only block that takes a database","parent_name":"DatabaseReader"},"Protocols/DatabaseReader.html#/s:FP4GRDB14DatabaseReader3addFT8functionCS_16DatabaseFunction_T_":{"name":"add(function:)","abstract":"
Filters database changes that should be notified the the","parent_name":"TransactionObserver"},"Protocols/TransactionObserver.html#/s:FP4GRDB19TransactionObserver17databaseDidChangeFT4withVS_13DatabaseEvent_T_":{"name":"databaseDidChange(with:)","abstract":"
Notifies a database change (insert, update, or delete).
When a transaction is about to be committed, the transaction observer","parent_name":"TransactionObserver"},"Protocols/TransactionObserver.html#/s:FP4GRDB19TransactionObserver17databaseDidCommitFCS_8DatabaseT_":{"name":"databaseDidCommit(_:)","abstract":"
Advances to the next element and returns it, or nil if no next element","parent_name":"Cursor"},"Protocols/Cursor.html#/s:P4GRDB6Cursor7Element":{"name":"Element","abstract":"
Returns a Boolean value indicating whether the cursor contains an","parent_name":"Cursor"},"Protocols/Cursor.html#/s:FE4GRDBPS_6Cursor10enumeratedFT_GCS_16EnumeratedCursorx_":{"name":"enumerated()","abstract":"
Returns a cursor of pairs (n, x), where n represents a consecutive","parent_name":"Cursor"},"Protocols/Cursor.html#/s:FE4GRDBPS_6Cursor6filterFFzwx7ElementSbGCS_12FilterCursorx_":{"name":"filter(_:)","abstract":"
Returns the elements of the cursor that satisfy the given predicate.
Returns the first element of the cursor that satisfies the given","parent_name":"Cursor"},"Protocols/Cursor.html#/s:FE4GRDBPS_6Cursor7flatMapurFFzwx7ElementGSqqd___GCS_9MapCursorGCS_12FilterCursorGS2_xGSqqd_____qd___":{"name":"flatMap(_:)","abstract":"
Returns a cursor over the concatenated non-nil results of mapping","parent_name":"Cursor"},"Protocols/Cursor.html#/s:FE4GRDBPS_6Cursor7flatMapuRd__s8SequencerFFzwx7Elementqd__GCS_13FlattenCursorGCS_9MapCursorxGCS_14IteratorCursorwd__8Iterator___":{"name":"flatMap(_:)","abstract":"
Returns a cursor over the concatenated results of mapping transform","parent_name":"Cursor"},"Protocols/Cursor.html#/s:FE4GRDBPS_6Cursor7flatMapuRd__S0_rFFzwx7Elementqd__GCS_13FlattenCursorGCS_9MapCursorxqd____":{"name":"flatMap(_:)","abstract":"
Returns a cursor over the concatenated results of mapping transform","parent_name":"Cursor"},"Protocols/Cursor.html#/s:FE4GRDBPS_6Cursor7forEachFzFzwx7ElementT_T_":{"name":"forEach(_:)","abstract":"
Calls the given closure on each element in the cursor.
Returns a cursor over the results of the transform function applied to","parent_name":"Cursor"},"Protocols/Cursor.html#/s:FE4GRDBPS_6Cursor6reduceurFzTqd__FzTqd__wx7Element_qd___qd__":{"name":"reduce(_:_:)","abstract":"
Returns the result of calling the given combining closure with each","parent_name":"Cursor"},"Protocols/Cursor.html#/s:Fe4GRDBRxS_6Cursorwx7Elements9EquatablerS0_8containsFzwxS1_Sb":{"name":"contains(_:)","abstract":"
Returns a Boolean value indicating whether the cursor contains the","parent_name":"Cursor"},"Protocols/Cursor.html#/s:Fe4GRDBRxS_6Cursorwx7ElementS0_rS0_6joinedFT_GCS_13FlattenCursorx_":{"name":"joined()","abstract":"
Returns the elements of this cursor of cursors, concatenated.
Types that adopt TableMapping declare a particular relationship with"},"Protocols/FTS5CustomTokenizer.html":{"name":"FTS5CustomTokenizer","abstract":"Undocumented"},"Protocols/FTS5Tokenizer.html":{"name":"FTS5Tokenizer","abstract":"Undocumented"},"Protocols/FTS5WrapperTokenizer.html":{"name":"FTS5WrapperTokenizer","abstract":"Undocumented"},"Protocols/MutablePersistable.html":{"name":"MutablePersistable","abstract":"
Types that adopt MutablePersistable can be inserted, updated, and deleted.
The protocol for all types that define a way to fetch values from"},"Protocols/TypedRequest.html":{"name":"TypedRequest","abstract":"
The protocol for all types that define a way to fetch values from"},"Protocols.html#/s:P4GRDB18_OptionalFetchable":{"name":"_OptionalFetchable","abstract":"
This protocol is an implementation detail of GRDB. Don’t use it.
This protocol is an implementation detail of the query interface."},"Protocols/SQLExpression.html":{"name":"SQLExpression","abstract":"
This protocol is an implementation detail of the query interface."},"Protocols/SQLSpecificExpressible.html":{"name":"SQLSpecificExpressible","abstract":"
This protocol is an implementation detail of the query interface."},"Protocols/SQLOrderingTerm.html":{"name":"SQLOrderingTerm","abstract":"
This protocol is an implementation detail of the query interface."},"Protocols/SQLSelectable.html":{"name":"SQLSelectable","abstract":"
This protocol is an implementation detail of the query interface."},"Protocols/SQLSelectQuery.html":{"name":"SQLSelectQuery","abstract":"
This protocol is an implementation detail of the query interface."},"Protocols/StatementColumnConvertible.html":{"name":"StatementColumnConvertible","abstract":"
When a type adopts both DatabaseValueConvertible and"},"Protocols/VirtualTableModule.html":{"name":"VirtualTableModule","abstract":"
The protocol for SQLite virtual table modules. It lets you define a DSL for"},"Functions.html#/s:F4GRDB3absFPS_22SQLSpecificExpressible_PS_13SQLExpression_":{"name":"abs(_:)","abstract":"
Returns an expression that evaluates the ABS SQL function.
Returns a value that can be stored in the database.","parent_name":"NSURL"},"Extensions/NSURL.html#/s:ZFE4GRDBCSo5NSURL17fromDatabaseValueFVS_13DatabaseValueGSqDS0__":{"name":"fromDatabaseValue(_:)","abstract":"
Returns an NSURL initialized from databaseValue, if possible.
Returns the receiver, quoted for safe insertion as an identifier in an","parent_name":"String"},"Extensions/Float.html#/s:FE4GRDBSfcFT15sqliteStatementVs13OpaquePointer5indexVs5Int32_Sf":{"name":"init(sqliteStatement:index:)","abstract":"
Returns a value initialized from a raw SQLite statement pointer.
Returns an NSData initialized from databaseValue, if it contains","parent_name":"NSData"},"Extensions/TableMapping.html#/matching(_:)":{"name":"matching(_:)","abstract":"Undocumented","parent_name":"TableMapping"},"Extensions/QueryInterfaceRequest.html#/matching(_:)":{"name":"matching(_:)","abstract":"Undocumented","parent_name":"QueryInterfaceRequest"},"Extensions/Database.html#/add(tokenizer:)":{"name":"add(tokenizer:)","abstract":"Undocumented","parent_name":"Database"},"Extensions/Database.html#/makeFTS5Pattern(rawPattern:forTable:)":{"name":"makeFTS5Pattern(rawPattern:forTable:)","abstract":"Undocumented","parent_name":"Database"},"Extensions/Database.html#/makeTokenizer(_:)":{"name":"makeTokenizer(_:)","abstract":"Undocumented","parent_name":"Database"},"Extensions/Column.html#/rank":{"name":"rank","abstract":"Undocumented","parent_name":"Column"},"Extensions/NSDate.html#/s:vE4GRDBCSo6NSDate13databaseValueVS_13DatabaseValue":{"name":"databaseValue","abstract":"
Returns a value that can be stored in the database.
Returns a Data initialized from databaseValue, if it contains","parent_name":"Data"},"Extensions/Sequence.html#/s:FE4GRDBPs8Sequence7flatMapuRd__S_6CursorrFFzWx8Iterator7Element_qd__GCS_13FlattenCursorGCS_9MapCursorGCS_14IteratorCursorwxS2__qd____":{"name":"flatMap(_:)","abstract":"
Returns a cursor over the concatenated results of mapping transform","parent_name":"Sequence"},"Extensions/Sequence.html#/s:Fe4GRDBRxs8SequenceWx8Iterator7Element_S_14SQLExpressiblerS0_8containsFPS_22SQLSpecificExpressible_PS_13SQLExpression_":{"name":"contains(_:)","abstract":"
An SQL expression that checks the inclusion of an expression in","parent_name":"Sequence"},"Extensions/Sequence.html#/s:Fe4GRDBRxs8SequenceWx8Iterator7Element_S_14SQLExpressiblerS0_8containsFVS_21SQLCollatedExpressionPS_13SQLExpression_":{"name":"contains(_:)","abstract":"
An SQL expression that checks the inclusion of an expression in","parent_name":"Sequence"},"Extensions/Array.html#/s:FE4GRDBSacuRd__S_6Cursorxzwd__7ElementrFzqd__GSax_":{"name":"init(_:)","abstract":"
Creates an array containing the elements of a cursor.
Thrown by MutablePersistable.update() when no matching row could be","parent_name":"PersistenceError"},"Enums/PersistenceError.html#/s:vO4GRDB16PersistenceError11descriptionSS":{"name":"description","abstract":"
A move event, from indexPath to newIndexPath. The changes are a","parent_name":"FetchedRecordChange"},"Enums/FetchedRecordChange.html#/s:FO4GRDB19FetchedRecordChange6updateFMS0_FT9indexPathV10Foundation9IndexPath7changesGVs10DictionarySSVS_13DatabaseValue__S0_":{"name":"update","abstract":"
An update event, at given indexPath. The changes are a dictionary","parent_name":"FetchedRecordChange"},"Enums/FetchedRecordChange.html#/s:vO4GRDB19FetchedRecordChange11descriptionSS":{"name":"description","abstract":"
Advances to the next element and returns it, or nil if no next element","parent_name":"DatabaseCursor"},"Classes/Statement.html#/s:vC4GRDB9Statement15sqliteStatementVs13OpaquePointer":{"name":"sqliteStatement","abstract":"
The raw SQLite statement, suitable for the SQLite C API.
Throws a DatabaseError of code SQLITE_ERROR if arguments don’t fill all","parent_name":"Statement"},"Classes/Statement.html#/s:FC4GRDB9Statement18unsafeSetArgumentsFVS_18StatementArgumentsT_":{"name":"unsafeSetArguments(_:)","abstract":"
Set arguments without any validation. Trades safety for performance.
Returns Int64, Double, String, Data or nil, depending on the value","parent_name":"Row"},"Classes/Row.html#/s:FC4GRDB3Row5valueuRxS_24DatabaseValueConvertiblerFT7atIndexSi_GSqx_":{"name":"value(atIndex:)","abstract":"
Returns the value at given index, converted to the requested type.
Returns Int64, Double, String, Data or nil, depending on the value","parent_name":"Row"},"Classes/Row.html#/s:FC4GRDB3Row5valueuRxS_24DatabaseValueConvertiblerFT5namedSS_GSqx_":{"name":"value(named:)","abstract":"
Returns the value at given column, converted to the requested type.
Returns Int64, Double, String, NSData or nil, depending on the value","parent_name":"Row"},"Classes/Row.html#/s:FC4GRDB3Row5valueuRxS_24DatabaseValueConvertiblerFVS_6ColumnGSqx_":{"name":"value(_:)","abstract":"
Returns the value at given column, converted to the requested type.
Returns a scoped row, if the row was fetched along with a row adapter","parent_name":"Row"},"Classes/Row.html#/s:ZFC4GRDB3Row11fetchCursorFzTCS_15SelectStatement9argumentsGSqVS_18StatementArguments_7adapterGSqPS_10RowAdapter___GCS_14DatabaseCursorS0__":{"name":"fetchCursor(_:arguments:adapter:)","abstract":"
Returns a cursor over rows fetched from a prepared statement.
Creates a row initialized with elements. Column order is preserved, and","parent_name":"Row"},"Classes/Row.html#/s:iC4GRDB3Row9subscriptFVS_8RowIndexTSSVS_13DatabaseValue_":{"name":"subscript(_:)","abstract":"
Accesses the (ColumnName, DatabaseValue) pair at given index.
The past-the-end index, successor of the index of the last","parent_name":"Row"},"Classes/Row.html#/s:FC4GRDB3Row5indexFT5afterVS_8RowIndex_S1_":{"name":"index(after:)","abstract":"
Returns true if and only if both rows have the same columns and values,","parent_name":"Row"},"Classes/Row.html#/s:vC4GRDB3Row9hashValueSi":{"name":"hashValue","abstract":"
The policy that handles SQLite conflicts when records are inserted","parent_name":"Record"},"Classes/Record.html#/s:ZvC4GRDB6Record12selectsRowIDSb":{"name":"selectsRowID","abstract":"
This flag tells whether the hidden rowid column should be fetched","parent_name":"Record"},"Classes/Record.html#/s:vC4GRDB6Record20persistentDictionaryGVs10DictionarySSGSqPS_24DatabaseValueConvertible___":{"name":"persistentDictionary","abstract":"
Returns a copy of self, initialized from the values of","parent_name":"Record"},"Classes/Record.html#/s:vC4GRDB6Record26hasPersistentChangedValuesSb":{"name":"hasPersistentChangedValues","abstract":"
A boolean that indicates whether the record has changes that have not","parent_name":"Record"},"Classes/Record.html#/s:vC4GRDB6Record23persistentChangedValuesGVs10DictionarySSGSqVS_13DatabaseValue__":{"name":"persistentChangedValues","abstract":"
Executes an INSERT or an UPDATE statement so that self is saved in","parent_name":"Record"},"Classes/Record.html#/s:FC4GRDB6Record6deleteFzCS_8DatabaseSb":{"name":"delete(_:)","abstract":"
Synchronizes the full-text table with the content of an external","parent_name":"FTS4TableDefinition"},"Classes/FTS3TableDefinition.html#/s:vC4GRDB19FTS3TableDefinition9tokenizerGSqVS_23FTS3TokenizerDescriptor_":{"name":"tokenizer","abstract":"
Creates a fetched records controller initialized from a SQL query and","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:FC4GRDB24FetchedRecordsControllercuRd__S_12TypedRequestxzwd__7FetchedrFzTPS_14DatabaseWriter_7requestqd__5queueCSo13DispatchQueue12isSameRecordGSqFTxx_Sb__GS0_x_":{"name":"init(_:request:queue:isSameRecord:)","abstract":"
Creates a fetched records controller initialized from a fetch request","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:FC4GRDB24FetchedRecordsController12performFetchFzT_T_":{"name":"performFetch()","abstract":"
Updates the fetch request, and eventually notifies the tracking","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:FC4GRDB24FetchedRecordsController10setRequestFzT3sqlSS9argumentsGSqVS_18StatementArguments_7adapterGSqPS_10RowAdapter___T_":{"name":"setRequest(sql:arguments:adapter:)","abstract":"
Updates the fetch request, and eventually notifies the tracking","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:FC4GRDB24FetchedRecordsController12trackChangesFT10willChangeGSqFGS0_x_T__8onChangeGSqFTGS0_x_xOS_19FetchedRecordChange_T__9didChangeGSqFGS0_x_T___T_":{"name":"trackChanges(willChange:onChange:didChange:)","abstract":"
Call this method when changes performed while the application is","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:vC4GRDB24FetchedRecordsController14fetchedRecordsGSax_":{"name":"fetchedRecords","abstract":"
Creates a fetched records controller initialized from a SQL query and","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:Fe4GRDBRxS_14RowConvertiblexS_12TableMappingrCS_24FetchedRecordsControllercuRd__S_12TypedRequestxzwd__7FetchedrFzTPS_14DatabaseWriter_7requestqd__5queueCSo13DispatchQueue_GS2_x_":{"name":"init(_:request:queue:)","abstract":"
Creates a fetched records controller initialized from a fetch request","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:FC4GRDB24FetchedRecordsController6recordFT2atV10Foundation9IndexPath_x":{"name":"record(at:)","abstract":"
Synchronously executes a block in a protected dispatch queue, and","parent_name":"DatabaseQueue"},"Classes/DatabaseQueue.html#/s:FC4GRDB13DatabaseQueue13inTransactionFzTGSqOCS_8Database15TransactionKind_FzS1_OS1_21TransactionCompletion_T_":{"name":"inTransaction(_:_:)","abstract":"
Synchronously executes a block in a protected dispatch queue, wrapped","parent_name":"DatabaseQueue"},"Classes/DatabaseQueue.html#/s:FC4GRDB13DatabaseQueue13releaseMemoryFT_T_":{"name":"releaseMemory()","abstract":"
Listens to UIApplicationDidEnterBackgroundNotification and","parent_name":"DatabaseQueue"},"Classes/DatabaseQueue.html#/setupMemoryManagement(in:)":{"name":"setupMemoryManagement(in:)","abstract":"Undocumented","parent_name":"DatabaseQueue"},"Classes/DatabaseQueue.html#/s:FC4GRDB13DatabaseQueue4readurFzFzCS_8Databasexx":{"name":"read(_:)","abstract":"
Synchronously executes a read-only block in a protected dispatch queue,","parent_name":"DatabaseQueue"},"Classes/DatabaseQueue.html#/s:FC4GRDB13DatabaseQueue10unsafeReadurFzFzCS_8Databasexx":{"name":"unsafeRead(_:)","abstract":"
Alias for inDatabase. See DatabaseReader.unsafeRead.
Listens to UIApplicationDidEnterBackgroundNotification and","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/setupMemoryManagement(in:)":{"name":"setupMemoryManagement(in:)","abstract":"Undocumented","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:FC4GRDB12DatabasePool4readurFzFzCS_8Databasexx":{"name":"read(_:)","abstract":"
Synchronously executes a read-only block in a protected dispatch queue,","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:FC4GRDB12DatabasePool10unsafeReadurFzFzCS_8Databasexx":{"name":"unsafeRead(_:)","abstract":"
Synchronously executes a read-only block in a protected dispatch queue,","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:FC4GRDB12DatabasePool3addFT8functionCS_16DatabaseFunction_T_":{"name":"add(function:)","abstract":"
Synchronously executes an update block in a protected dispatch queue,","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:FC4GRDB12DatabasePool18writeInTransactionFzTGSqOCS_8Database15TransactionKind_FzS1_OS1_21TransactionCompletion_T_":{"name":"writeInTransaction(_:_:)","abstract":"
Synchronously executes a block in a protected dispatch queue, wrapped","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:FC4GRDB12DatabasePool20readFromCurrentStateFzFCS_8DatabaseT_T_":{"name":"readFromCurrentState(_:)","abstract":"
Asynchronously executes a read-only block in a protected dispatch queue,","parent_name":"DatabasePool"},"Classes/DatabaseCollation.html#/s:vC4GRDB17DatabaseCollation4nameSS":{"name":"name","abstract":"Undocumented","parent_name":"DatabaseCollation"},"Classes/DatabaseCollation.html#/s:FC4GRDB17DatabaseCollationcFTSS8functionFTSSSS_OSC16ComparisonResult_S0_":{"name":"init(_:function:)","abstract":"
A collation, or SQL string comparison function, that compares strings","parent_name":"DatabaseCollation"},"Classes/DatabaseCollation.html#/s:ZvC4GRDB17DatabaseCollation22caseInsensitiveCompareS0_":{"name":"caseInsensitiveCompare","abstract":"
A collation, or SQL string comparison function, that compares strings","parent_name":"DatabaseCollation"},"Classes/DatabaseCollation.html#/s:ZvC4GRDB17DatabaseCollation31localizedCaseInsensitiveCompareS0_":{"name":"localizedCaseInsensitiveCompare","abstract":"
A collation, or SQL string comparison function, that compares strings","parent_name":"DatabaseCollation"},"Classes/DatabaseCollation.html#/s:ZvC4GRDB17DatabaseCollation16localizedCompareS0_":{"name":"localizedCompare","abstract":"
A collation, or SQL string comparison function, that compares strings","parent_name":"DatabaseCollation"},"Classes/DatabaseCollation.html#/s:ZvC4GRDB17DatabaseCollation24localizedStandardCompareS0_":{"name":"localizedStandardCompare","abstract":"
A collation, or SQL string comparison function, that compares strings","parent_name":"DatabaseCollation"},"Classes/DatabaseFunction.html#/s:vC4GRDB16DatabaseFunction4nameSS":{"name":"name","abstract":"Undocumented","parent_name":"DatabaseFunction"},"Classes/DatabaseFunction.html#/s:FC4GRDB16DatabaseFunctioncFTSS13argumentCountGSqVs5Int32_4pureSb8functionFzGSaVS_13DatabaseValue_GSqPS_24DatabaseValueConvertible___S0_":{"name":"init(_:argumentCount:pure:function:)","abstract":"
An SQL function that returns the Swift built-in capitalized","parent_name":"DatabaseFunction"},"Classes/DatabaseFunction.html#/s:ZvC4GRDB16DatabaseFunction9lowercaseS0_":{"name":"lowercase","abstract":"
An SQL function that returns the Swift built-in lowercased","parent_name":"DatabaseFunction"},"Classes/DatabaseFunction.html#/s:ZvC4GRDB16DatabaseFunction9uppercaseS0_":{"name":"uppercase","abstract":"
An SQL function that returns the Swift built-in uppercased","parent_name":"DatabaseFunction"},"Classes/DatabaseFunction.html#/s:ZvC4GRDB16DatabaseFunction19localizedCapitalizeS0_":{"name":"localizedCapitalize","abstract":"
An SQL function that returns the Swift built-in","parent_name":"DatabaseFunction"},"Classes/DatabaseFunction.html#/s:ZvC4GRDB16DatabaseFunction18localizedLowercaseS0_":{"name":"localizedLowercase","abstract":"
An SQL function that returns the Swift built-in","parent_name":"DatabaseFunction"},"Classes/DatabaseFunction.html#/s:ZvC4GRDB16DatabaseFunction18localizedUppercaseS0_":{"name":"localizedUppercase","abstract":"
An SQL function that returns the Swift built-in","parent_name":"DatabaseFunction"},"Classes/Database/TransactionCompletion.html#/s:FOC4GRDB8Database21TransactionCompletion6commitFMS1_S1_":{"name":"commit","abstract":"Undocumented","parent_name":"TransactionCompletion"},"Classes/Database/TransactionCompletion.html#/s:FOC4GRDB8Database21TransactionCompletion8rollbackFMS1_S1_":{"name":"rollback","abstract":"Undocumented","parent_name":"TransactionCompletion"},"Classes/Database/TransactionKind.html#/s:FOC4GRDB8Database15TransactionKind8deferredFMS1_S1_":{"name":"deferred","abstract":"Undocumented","parent_name":"TransactionKind"},"Classes/Database/TransactionKind.html#/s:FOC4GRDB8Database15TransactionKind9immediateFMS1_S1_":{"name":"immediate","abstract":"Undocumented","parent_name":"TransactionKind"},"Classes/Database/TransactionKind.html#/s:FOC4GRDB8Database15TransactionKind9exclusiveFMS1_S1_":{"name":"exclusive","abstract":"Undocumented","parent_name":"TransactionKind"},"Classes/Database/ForeignKeyAction.html#/s:FOC4GRDB8Database16ForeignKeyAction7cascadeFMS1_S1_":{"name":"cascade","abstract":"Undocumented","parent_name":"ForeignKeyAction"},"Classes/Database/ForeignKeyAction.html#/s:FOC4GRDB8Database16ForeignKeyAction8restrictFMS1_S1_":{"name":"restrict","abstract":"Undocumented","parent_name":"ForeignKeyAction"},"Classes/Database/ForeignKeyAction.html#/s:FOC4GRDB8Database16ForeignKeyAction7setNullFMS1_S1_":{"name":"setNull","abstract":"Undocumented","parent_name":"ForeignKeyAction"},"Classes/Database/ForeignKeyAction.html#/s:FOC4GRDB8Database16ForeignKeyAction10setDefaultFMS1_S1_":{"name":"setDefault","abstract":"Undocumented","parent_name":"ForeignKeyAction"},"Classes/Database/ColumnType.html#/s:vPs16RawRepresentable8rawValuewx8RawValue":{"name":"rawValue","abstract":"
The SQLITE_BUSY error is immediately returned to the connection that","parent_name":"BusyMode"},"Classes/Database/BusyMode.html#/s:FOC4GRDB8Database8BusyMode7timeoutFMS1_FSdS1_":{"name":"timeout","abstract":"
The SQLITE_BUSY error will be returned only if the database remains","parent_name":"BusyMode"},"Classes/Database/BusyMode.html#/s:FOC4GRDB8Database8BusyMode8callbackFMS1_FFSiSbS1_":{"name":"callback","abstract":"
A custom callback that is called when a database is locked.","parent_name":"BusyMode"},"Classes/Database.html#/s:C4GRDB8Database12BusyCallback":{"name":"BusyCallback","abstract":"
When there are several connections to a database, a connection may try","parent_name":"Database"},"Classes/Database/CheckpointMode.html":{"name":"CheckpointMode","abstract":"
The number of rows modified, inserted or deleted by the most recent","parent_name":"Database"},"Classes/Database.html#/s:vC4GRDB8Database17totalChangesCountSi":{"name":"totalChangesCount","abstract":"
The total number of rows modified, inserted or deleted by all successful","parent_name":"Database"},"Classes/Database.html#/s:vC4GRDB8Database19isInsideTransactionSb":{"name":"isInsideTransaction","abstract":"
True if the database connection is currently in a transaction.
The primary key for table named tableName; nil if table has no","parent_name":"Database"},"Classes/Database.html#/s:FC4GRDB8Database11columnCountFzT2inSS_Si":{"name":"columnCount(in:)","abstract":"
The number of columns in the table named tableName.
The indexes on table named tableName; returns the empty array if the","parent_name":"Database"},"Classes/Database.html#/s:FC4GRDB8Database5tableuRxs8SequenceWx8Iterator7Element_zSSrFzTSS12hasUniqueKeyx_Sb":{"name":"table(_:hasUniqueKey:)","abstract":"
True if a sequence of columns uniquely identifies a row, that is to say","parent_name":"Database"},"Classes/Database.html#/s:FC4GRDB8Database13inTransactionFzTGSqOS0_15TransactionKind_FzT_OS0_21TransactionCompletion_T_":{"name":"inTransaction(_:_:)","abstract":"
Add a transaction observer, so that it gets notified of","parent_name":"Database"},"Classes/Database.html#/s:FC4GRDB8Database6removeFT19transactionObserverPS_19TransactionObserver__T_":{"name":"remove(transactionObserver:)","abstract":"
Advances to the next element and returns it, or nil if no next","parent_name":"IteratorCursor"},"Classes/MapCursor.html#/s:FC4GRDB9MapCursor4nextFzT_GSqq__":{"name":"next()","abstract":"
Advances to the next element and returns it, or nil if no next","parent_name":"MapCursor"},"Classes/FlattenCursor.html#/s:FC4GRDB13FlattenCursor4nextFzT_GSqWx7ElementS1___":{"name":"next()","abstract":"
Advances to the next element and returns it, or nil if no next","parent_name":"FlattenCursor"},"Classes/FilterCursor.html#/s:FC4GRDB12FilterCursor4nextFzT_GSqwx7Element_":{"name":"next()","abstract":"
Advances to the next element and returns it, or nil if no next","parent_name":"FilterCursor"},"Classes/EnumeratedCursor.html#/s:FC4GRDB16EnumeratedCursor4nextFzT_GSqTSiwx7Element__":{"name":"next()","abstract":"
Advances to the next element and returns it, or nil if no next","parent_name":"EnumeratedCursor"},"Classes/AnyCursor.html#/s:FC4GRDB9AnyCursorcuRd__S_6Cursorxzwd__7ElementrFqd__GS0_x_":{"name":"init(_:)","abstract":"
Creates a cursor that wraps a base cursor but whose type depends only on","parent_name":"AnyCursor"},"Classes/AnyCursor.html#/s:FC4GRDB9AnyCursorcFFzT_GSqx_GS0_x_":{"name":"init(_:)","abstract":"
Creates a cursor that wraps the given closure in its next() method
The FTS4ColumnDefinition class lets you refine a column of an FTS4"},"Classes/FTS5TableDefinition.html":{"name":"FTS5TableDefinition","abstract":"Undocumented"},"Classes/FTS5ColumnDefinition.html":{"name":"FTS5ColumnDefinition","abstract":"Undocumented"},"Classes/Record.html":{"name":"Record","abstract":"
Record is a class that wraps a table row, or the result of any query. It is"},"Classes/Row.html":{"name":"Row","abstract":"
Follow @groue on Twitter for release announcements and usage tips.
+
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.
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 inDatabase and inTransaction methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue. They safely serialize the database accesses:
+
// Execute database statements:
+trydbQueue.inDatabase{dbin
+ trydb.create(table:"pointOfInterests"){...}
+ tryPointOfInterest(...).insert(db)
+}
+
+// Wrap database statements in a transaction:
+trydbQueue.inTransaction{dbin
+ ifletpoi=tryPointOfInterest.fetchOne(db,key:1){
+ trypoi.delete(db)
+ }
+ return.commit
+}
+
+// Read values:
+trydbQueue.inDatabase{dbin
+ letpois=tryPointOfInterest.fetchAll(db)
+ letpoiCount=tryPointOfInterest.fetchCount(db)
+}
+
+// Extract a value from the database:
+letpoiCount=trydbQueue.inDatabase{dbin
+ tryPointOfInterest.fetchCount(db)
+}
+
+
+
A database queue needs your application to follow rules in order to deliver its safety guarantees. Please refer to the Concurrency chapter.
A Database Pool allows concurrent database accesses.
+
+
When more efficient than database queues, database pools also require a good mastery of database transactions. Details follow. If you don’t feel comfortable with transactions, use a database queue instead.
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 read, write and writeInTransaction methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue. They safely isolate the database accesses:
+
// Execute database statements:
+trydbPool.write{dbin
+ trydb.create(table:"pointOfInterests"){...}
+ tryPointOfInterest(...).insert(db)
+}
+
+// Wrap database statements in a transaction:
+trydbPool.writeInTransaction{dbin
+ ifletpoi=tryPointOfInterest.fetchOne(db,key:1){
+ trypoi.delete(db)
+ }
+ return.commit
+}
+
+// Read values:
+trydbPool.read{dbin
+ letpois=tryPointOfInterest.fetchAll(db)
+ letpoiCount=tryPointOfInterest.fetchCount(db)
+}
+
+// Extract a value from the database:
+letpoiCount=trydbPool.read{dbin
+ tryPointOfInterest.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.
+
+
The total number of concurrent reads is limited. When the maximum number has been reached, a read waits for another read to complete. That maximum number can be configured.
+
Conversely, writes are serialized. They don’t block reads, but GRDB guarantees read closures an immutable view of the last committed state of the database.
+
+
:point_up: To provide read closures an immutable view of the last executed writing block as a whole, use writeInTransaction instead of write.
+
+
+
A database pool needs your application to follow rules in order to deliver its safety guarantees. Please refer to the Concurrency chapter.
For a sample code that sets up a database pool on iOS, see DemoApps/GRDBDemoiOS/Database.swift, and replace DatabaseQueue with DatabasePool.
+
DatabasePool Configuration
+
varconfig=Configuration()
+config.readonly=true
+config.foreignKeysEnabled=true// Default is already true
+config.trace={print($0)}// Prints all SQL statements
+config.maximumReaderCount=10// The default is 5
+
+letdbPool=tryDatabasePool(
+ path:"/path/to/database.sqlite",
+ configuration:config)
+
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:
+
trydb.execute(
+ "CREATE TABLE persons ("+
+ "id INTEGER PRIMARY KEY,"+
+ "name TEXT NOT NULL,"+
+ "age INT"+
+ ")")
+
+trydb.execute(
+ "INSERT INTO persons (name, age) VALUES (:name, :age)",
+ arguments:["name":"Barbara","age":39])
+
+// Join multiple statements with a semicolon:
+trydb.execute(
+ "INSERT INTO persons (name, age) VALUES (?, ?); "+
+ "INSERT INTO persons (name, age) VALUES (?, ?)",
+ arguments:["Arthur",36,"Barbara",39])
+
+
+
The ? and colon-prefixed keys like :name 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.).
+
+
Never ever embed values directly in your SQL strings, and always use arguments instead. See Avoiding SQL Injection for more information.
+
+
After an INSERT statement, you can get the row ID of the inserted row:
Whenever you consume several rows from the database, you can fetch a Cursor, or an Array.
+
+
Arrays contain copies of database values and may be consumed on any thread. But they can take a lot of memory. Conversely, cursors iterate over database results in a lazy fashion, don’t consume much memory, and are generally more efficient. But they must be consumed in a protected dispatch queue:
Cursors come with default implementations for many operations similar to those defined by lazy sequences of the Swift Standard Library: contains, enumerated, filter, first, flatMap, forEach, joined, map, reduce:
+
// Enumerate all Github links
+tryURL.fetchCursor(db,"SELECT url FROM links")
+ .filter{urlinurl.host=="github.com"}
+ .enumerated()
+ .forEach{(index,url)in...}
+
Arguments are optional arrays or dictionaries that fill the positional ? and colon-prefixed keys like :name in the query:
+
letrows=tryRow.fetchAll(db,
+ "SELECT * FROM persons WHERE name = ?",
+ arguments:["Arthur"])
+
+letrows=tryRow.fetchAll(db,
+ "SELECT * FROM persons 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 row cursor into an array, with Array(rowCursor) for example: you would not get the distinct rows you expect. To get a row array, 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:
+
letname:String=row.value(atIndex:0)// 0 is the leftmost column
+letname:String=row.value(named:"name")// Leftmost matching column - lookup is case-insensitive
+letname:String=row.value(Column("name"))// Using query interface's Column
+
+
+
Make sure to ask for an optional when the value may be NULL:
+
letname:String?=row.value(named:"name")
+
+
+
The value function returns the type you ask for. See Values for more information on supported value types:
+
letbookCount:Int=row.value(named:"bookCount")
+letbookCount64:Int64=row.value(named:"bookCount")
+lethasBooks:Bool=row.value(named:"bookCount")// false when 0
+
+letstring:String=row.value(named:"date")// "2015-09-11 18:14:15.123"
+letdate:Date=row.value(named:"date")// Date
+self.date=row.value(named:"date")// Depends on the type of the property.
+
+
+
You can also use the as type casting operator:
+
row.value(...)asInt
+row.value(...)asInt?
+
+
+
+
:warning: Warning: avoid the as! and as? operators, because they misbehave in the context of type inference (see rdar://21676393):
+
ifletint=row.value(...)as?Int{...}// BAD - doesn't work
+ifletint=row.value(...)asInt?{...}// 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.
+
letrow=tryRow.fetchOne(db,"SELECT NULL")!
+row.value(atIndex:0)asInt?// nil
+row.value(atIndex:0)asInt// fatal error: could not convert NULL to Int.
+
+
+
There is one exception, though: the DatabaseValue type:
letrow=tryRow.fetchOne(db,"SELECT 'foo' AS foo")!
+row.value(named:"missing")asString?// nil
+row.value(named:"missing")asString// fatal error: no such column: missing
+
+
+
You can explicitly check for a column presence with the hasColumn method.
+
Invalid conversions throw a fatal error.
+
letrow=tryRow.fetchOne(db,"SELECT 'Mom’s birthday'")!
+row.value(atIndex:0)asString// "Mom’s birthday"
+row.value(atIndex:0)asDate?// fatal error: could not convert "Mom’s birthday" to Date.
+row.value(atIndex:0)asDate// fatal error: could not convert "Mom’s birthday" to Date.
+
SQLite has a weak type system, and provides convenience conversions that can turn Blob to String, String to Int, etc.
+
+
GRDB will sometimes let those conversions go through:
+
letrows=tryRow.fetchCursor(db,"SELECT '20 small cigars'")
+whileletrow=tryrows.next(){
+ row.value(atIndex:0)asInt// 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:
+
letdbv:DatabaseValue=row.value(atIndex:0)
+letdbv:DatabaseValue=row.value(named:"name")
+
+// Check for NULL:
+dbv.isNull// Bool
+
+// All the five storage classes supported by SQLite:
+switchdbv.storage{
+case.null:print("NULL")
+case.int64(letint64):print("Int64: \(int64)")
+case.double(letdouble):print("Double: \(double)")
+case.string(letstring):print("String: \(string)")
+case.blob(letdata):print("Data: \(data)")
+}
+
This turns out useful when you process untrusted databases. Compare:
+
letdate:Date?=row.value(atIndex:0)// fatal error: could not convert "Mom’s birthday" to Date.
+letdate=Date.fromDatabaseValue(row.value(atIndex:0))// nil
+
+
Rows as Dictionaries
+
+
Row adopts the standard Collection protocol, and can be seen as a dictionary of DatabaseValue:
+
// All the (columnName, databaseValue) tuples, from left to right:
+for(columnName,databaseValue)inrow{
+ ...
+}
+
+
+
You can build rows from dictionaries (standard Swift dictionaries and NSDictionary). See Values for more information on supported types:
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:
At each step of the request iteration, the row.value method 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:
Yet this format may not fit your needs. For example, you may want to store dates as timestamps. In this case, store and load Doubles instead of Date, and perform the required conversions.
+
+
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:
+
letcomponents=DateComponents()
+components.year=1973
+components.month=9
+components.day=18
+
+// Store "1973-09-18"
+letdbComponents=DatabaseDateComponents(components,format:.YMD)
+trydb.execute(
+ "INSERT INTO persons (birthDate, ...) VALUES (?, ...)",
+ arguments:[dbComponents,...])
+
+// Read "1973-09-18"
+letrow=tryRow.fetchOne(db,"SELECT birthDate ...")!
+letdbComponents:DatabaseDateComponents=row.value(named:"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:
+
CREATETABLEtransfers(
+ amountDECIMAL(10,5)-- will store integer or double, actually
+)
+
+
+
This means that computations will not be exact:
+
trydb.execute("INSERT INTO transfers (amount) VALUES (0.1)")
+trydb.execute("INSERT INTO transfers (amount) VALUES (0.2)")
+letsum=tryNSDecimalNumber.fetchOne(db,"SELECT SUM(amount) FROM transfers")!
+
+// 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:
+
// Store
+letamount=NSDecimalNumber(string:"0.1")// 0.1
+letintegerAmount=amount.multiplying(byPowerOf10:2).int64Value// 100
+trydb.execute("INSERT INTO transfers (amount) VALUES (?)",arguments:[integerAmount])
+
+// Read
+letintegerAmount=tryInt64.fetchOne(db,"SELECT SUM(amount) FROM transfers")!// 100
+letamount=NSDecimalNumber(value:integerAmount).multiplying(byPowerOf10:-2)// 0.1
+
+
UUID
+
+
UUID can be stored and fetched from the database just like other values. GRDB stores uuids as 16-bytes data blobs.
+
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:
letrow=tryRow.fetchOne(db,"SELECT 'syrah'")!
+
+row.value(atIndex:0)asString// "syrah"
+row.value(atIndex:0)asGrape?// fatal error: could not convert "syrah" to Grape.
+row.value(atIndex:0)asGrape// fatal error: could not convert "syrah" to Grape.
+Grape.fromDatabaseValue(row.value(atIndex:0))// nil
+
+
Transactions and Savepoints
+
+
The DatabaseQueue.inTransaction() and DatabasePool.writeInTransaction() methods open an SQLite transaction and run their closure argument in a protected dispatch queue. They block the current thread until your database statements are executed:
If an error is thrown within the transaction body, the transaction is rollbacked and the error is rethrown by the inTransaction method. If you return .rollback from your closure, the transaction is also rollbacked, but no error is thrown.
+
+
If you want to insert a transaction between other database statements, you can use the Database.inTransaction() function, or even raw SQL statements:
+
trydbQueue.inDatabase{dbin// or dbPool.write { db in
+ ...
+ trydb.inTransaction{
+ ...
+ return.commit
+ }
+ ...
+ trydb.execute("BEGIN TRANSACTION")
+ ...
+ trydb.execute("COMMIT")
+}
+
+
+
You can ask a database if a transaction is currently opened:
Yet, you have a better option than checking for transactions: critical sections of your application should use savepoints, described below:
+
funcmyCriticalMethod(_db:Database)throws{
+ trydb.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:
+
trydbQueue.inTransaction{dbin
+ trydb.inSavepoint{
+ trydb.execute("DELETE ...")
+ trydb.execute("INSERT ...")// need to rollback the delete above if this fails
+ return.commit
+ }
+
+ // Other savepoints, etc...
+ return.commit
+}
+
+
+
If an error is thrown within the savepoint body, the savepoint is rollbacked and the error is rethrown by the inSavepoint method. If you return .rollback from your closure, the body 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 committed to disk when the outermost savepoint is committed:
SQLite savepoints are more than nested transactions, though. For advanced savepoints uses, use SQL queries.
+
Transaction Kinds
+
+
SQLite supports three kinds of transactions: deferred, immediate, and exclusive. GRDB defaults to immediate.
+
+
The transaction kind can be changed in the database configuration, or for each transaction:
+
// A connection with default DEFERRED transactions:
+varconfig=Configuration()
+config.defaultTransactionKind=.deferred
+letdbQueue=tryDatabaseQueue(path:"...",configuration:config)
+
+// Opens a DEFERRED transaction:
+dbQueue.inTransaction{dbin...}
+
+// Opens an EXCLUSIVE transaction:
+dbQueue.inTransaction(.exclusive){dbin...}
+
+
Custom Value Types
+
+
Conversion to and from the database is based on the DatabaseValueConvertible protocol:
+
protocolDatabaseValueConvertible{
+ /// Returns a value that can be stored in the database.
+ vardatabaseValue:DatabaseValue{get}
+
+ /// Returns a value initialized from databaseValue, if possible.
+ staticfuncfromDatabaseValue(_databaseValue: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 databaseValue contains a suitable value. If the databaseValue does not contain a suitable value, such as foo for Date, fromDatabaseValuemust return nil (GRDB will interpret this nil result as a conversion error, and react accordingly).
+
+
The GRDB Extension Guide contains sample code that has UIColor adopt DatabaseValueConvertible.
+
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:
+
trydbQueue.inDatabase{dbin
+ letupdateSQL="INSERT INTO persons (name, age) VALUES (:name, :age)"
+ letupdateStatement=trydb.makeUpdateStatement(updateSQL)
+
+ letselectSQL="SELECT * FROM persons WHERE name = ?"
+ letselectStatement=trydb.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).
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:
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:
trydb.tableExists("persons")// Bool, true if the table exists
+trydb.columnCount(in:"persons")// Int, the number of columns in table
+trydb.indexes(on:"persons")// [IndexInfo], the indexes defined on the table
+trydb.table("persons",hasUniqueKey:["email"])// Bool, true if column(s) is a unique key
+trydb.primaryKey("persons")// PrimaryKeyInfo?
+
Primary keys have one or several columns. Single-column primary keys may contain the auto-incremented row id:
+
// CREATE TABLE persons (
+// id INTEGER PRIMARY KEY,
+// name TEXT
+// )
+letpersonPk=trydb.primaryKey("persons")!
+personPk.columns// ["id"]
+personPk.rowIDColumn// "id"
+
+// CREATE TABLE countries (
+// isoCode TEXT NOT NULL PRIMARY KEY
+// name TEXT
+// )
+letcountryPk=db.primaryKey("countries")!
+countryPk.columns// ["isoCode"]
+countryPk.rowIDColumn// nil
+
+// CREATE TABLE citizenships (
+// personID INTEGER NOT NULL REFERENCES persons(id)
+// countryIsoCode TEXT NOT NULL REFERENCES countries(isoCode)
+// PRIMARY KEY (personID, countryIsoCode)
+// )
+letcitizenshipsPk=db.primaryKey("citizenships")!
+citizenshipsPk.columns// ["personID", "countryIsoCode"]
+citizenshipsPk.rowIDColumn// nil
+
+
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:
+letadapter=ColumnMapping(["consumed":"produced"])
+letrow=tryRow.fetchOne(db,"SELECT 'Hello' AS produced",adapter:adapter)!
+row.value(named:"consumed")// "Hello"
+row.value(named:"produced")// nil
+
+
+
Row adapters are values that adopt the RowAdapter protocol. You can implement your own custom adapters, or use one of the four built-in adapters:
+
ColumnMapping
+
+
ColumnMapping renames columns. Build one with a dictionary whose keys are adapted column names, and values the column names in the raw row:
+
// <Row newName:"Hello">
+letadapter=ColumnMapping(["newName":"oldName"])
+letrow=tryRow.fetchOne(db,"SELECT 'Hello' AS oldName",adapter:adapter)!
+
+
SuffixRowAdapter
+
+
SuffixRowAdapter hides the first columns in a row:
+
// <Row b:1 c:2>
+letadapter=SuffixRowAdapter(fromIndex:1)
+letrow=tryRow.fetchOne(db,"SELECT 0 AS a, 1 AS b, 2 AS c",adapter:adapter)!
+
+
RangeRowAdapter
+
+
RangeRowAdapter only exposes a range of columns.
+
// <Row b:1>
+letadapter=RangeRowAdapter(1..<2)
+letrow=tryRow.fetchOne(db,"SELECT 0 AS a, 1 AS b, 2 AS c",adapter:adapter)!
+
+
ScopeAdapter
+
+
ScopeAdapter defines row scopes:
+
letadapter=ScopeAdapter([
+ "left":RangeRowAdapter(0..<2),
+ "right":RangeRowAdapter(2..<4)])
+letrow=tryRow.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 with the scoped(on:) method. It returns an optional Row, which is nil if the scope is missing.
// Just enough for SQLCipher and custom SQLite builds:
+importGRDBCipher// or import GRDBCustomSQLite
+
+letsqliteVersion=String(cString:sqlite3_libversion())
+
+
+
Otherwise (the regular case):
+
+
+
Link your application with the SQLite library that ships with your SDK: add libsqlite3.tbd to the Linked Frameworks and Libraries of the General tab of your target.
+
Import the SQLite module in the file that uses the SQLite C Interface. That module, unfortunately, changes name depending on your platform:
The Database.sqliteConnection and Statement.sqliteStatement properties provide the raw pointers that are suitable for the SQLite C functions:
+
trydbQueue.inDatabase{dbin
+ // The raw pointer to a database connection:
+ letsqliteConnection=db.sqliteConnection
+
+ // The raw pointer to a statement:
+ letstatement=trydb.makeSelectStatement("SELECT ...")
+ letsqliteStatement=statement.sqliteStatement
+}
+
+
+
+
:point_up: Notes
+
+
+
Those pointers are owned by GRDB: don’t close connections or finalize statements created by GRDB.
+
SQLite connections are opened 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:
+
+
+
sqlite3_backup_finish, sqlite3_backup_init, sqlite3_backup_step: see Backup
sqlite3_preupdate_count, sqlite3_preupdate_depth, sqlite3_preupdate_hook, sqlite3_preupdate_new, sqlite3_preupdate_old: see Support for SQLite Pre-Update Hooks
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 changes tracking. 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, and do not auto-update. 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.
The RowConvertible protocol grants fetching methods to any type that can be built from a database row:
+
protocolRowConvertible{
+ /// Row initializer
+ init(row:Row)
+
+ /// Optional method which gives adopting types an opportunity to complete
+ /// their initialization after being fetched. Do not call it directly.
+ mutatingfuncawakeFromFetch(row:Row)
+}
+
+
+
To use RowConvertible, subclass the Record class, or adopt it explicitely. For example:
See column values for more information about the row.value() method.
+
+
+
: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().
+
+
+
RowConvertible allows adopting types to be fetched from SQL queries:
See fetching methods for information about the fetchCursor, fetchAll and fetchOne methods. See StatementArguments for more information about the query arguments.
+
RowConvertible and Row Adapters
+
+
RowConvertible types usually consume rows by column name:
Occasionnally, you’ll want to write a complex SQL query that uses different column names. In this case, row adapters are there to help you mapping raw column names to the names expected by your RowConvertible types.
The databaseTableName type property is the name of a database table. selectsRowID is optional, and documented in the The Implicit RowID Primary Key chapter.
+
+
To use TableMapping, subclass the Record class, or adopt it explicitely. For example:
When the table has no explicit primary key, GRDB uses the hidden rowid column:
+
// SELECT * FROM documents WHERE rowid = 1
+tryDocument.fetchOne(db,key:1)// Document?
+
+// DELETE FROM documents WHERE rowid = 1
+tryDocument.deleteOne(db,key:1)
+
+
+
For multiple-column primary keys and unique keys defined by unique indexes, provide a dictionary:
+
// SELECT * FROM citizenships WHERE personID = 1 AND countryISOCode = 'FR'
+tryCitizenship.fetchOne(db,key:["personID":1,"countryISOCode":"FR"])// Citizenship?
+
+// DELETE FROM persons WHERE email = 'arthur@example.com'
+tryPerson.deleteOne(db,key:["email":"arthur@example.com"])
+
+
Persistable Protocol
+
+
GRDB provides two protocols that let adopting types store themselves in the database:
+
protocolMutablePersistable:TableMapping{
+ /// The name of the database table (from TableMapping)
+ staticvardatabaseTableName:String{get}
+
+ /// The values persisted in the database
+ varpersistentDictionary:[String:DatabaseValueConvertible?]{get}
+
+ /// Optional method that lets your adopting type store its rowID upon
+ /// successful insertion. Don't call it directly: it is called for you.
+ mutatingfuncdidInsert(withrowID:Int64,forcolumn:String?)
+}
+
+
protocolPersistable:MutablePersistable{
+ /// Non-mutating version of the optional didInsert(with:for:)
+ funcdidInsert(withrowID:Int64,forcolumn: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 struct that mutates on insertion, choose MutablePersistable.
+
+
For example, your table has an INTEGER PRIMARY KEY and you want to store the inserted id on successful insertion. Or your table has a UUID primary key, and you want to automatically generate one on insertion.
+
Otherwise, stick with Persistable. Particularly if your type is a class.
+
+
+
The persistentDictionary property returns a dictionary whose keys are column names, and values any DatabaseValueConvertible value (Bool, Int, String, Date, Swift enums, etc.) See Values for more information.
+
+
The optional didInsert method lets the adopting type store its rowID after successful insertion. If your table has an INTEGER PRIMARY KEY column, you are likely to define this method. Otherwise, you can safely ignore it. It is called from a protected dispatch queue, and serialized with all database updates.
+
+
To use those protocols, subclass the Record class, or adopt one of them explicitely. For example:
+
extensionPointOfInterest:MutablePersistable{
+
+ /// The values persisted in the database
+ varpersistentDictionary:[String:DatabaseValueConvertible?]{
+ return[
+ "id":id,
+ "title":title,
+ "latitude":coordinate.latitude,
+ "longitude":coordinate.longitude]
+ }
+
+ // Update id upon successful insertion:
+ mutatingfuncdidInsert(withrowID:Int64,forcolumn:String?){
+ id=rowID
+ }
+}
+
+varparis=PointOfInterest(
+ id:nil,
+ title:"Paris",
+ coordinate:CLLocationCoordinate2DMake(48.8534100,2.3488000))
+
+tryparis.insert(db)
+paris.id// some value
+
+
+
When your record has many columns, the Swift compiler may take a long time compiling the persistentDictionary property:
+
// May be long to compile
+varpersistentDictionary:[String:DatabaseValueConvertible?]{
+ return[
+ "id":id,
+ "title":title,
+ // many other columns
+ ]
+}
+
insert, update, save and delete can throw a DatabaseError whenever an SQLite integrity check fails.
+
update can also throw a PersistenceError of type recordNotFound, 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:
: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.
+
+
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.
SQLite let you specify conflict policies at two different places:
+
+
+
At the table level
+
// CREATE TABLE persons (
+// id INTEGER PRIMARY KEY,
+// email TEXT UNIQUE ON CONFLICT REPLACE
+// )
+trydb.create(table:"persons"){tin
+ t.column("id",.integer).primaryKey()
+ t.column("email",.text).unique(onConflict:.replace)// <--
+}
+
+// Despite the unique index on email, both inserts succeed.
+// The second insert replaces the first row:
+trydb.execute("INSERT INTO persons (email) VALUES (?)",arguments:["arthur@example.com"])
+trydb.execute("INSERT INTO persons (email) VALUES (?)",arguments:["arthur@example.com"])
+
+
At the query level:
+
// CREATE TABLE persons (
+// id INTEGER PRIMARY KEY,
+// email TEXT UNIQUE
+// )
+trydb.create(table:"persons"){tin
+ t.column("id",.integer).primaryKey()
+ t.column("email",.text)
+}
+
+// Again, despite the unique index on email, both inserts succeed.
+trydb.execute("INSERT OR REPLACE INTO persons (email) VALUES (?)",arguments:["arthur@example.com"])
+trydb.execute("INSERT OR REPLACE INTO persons (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 MutablePersistable or Persistable protocol. It will alter the INSERT and UPDATE queries run by the insert, update and savepersistence methods:
+
protocolMutablePersistable{
+ /// 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.
+ staticvarpersistenceConflictPolicy:PersistenceConflictPolicy{get}
+}
+
+structPerson:MutablePersistable{
+ staticletpersistenceConflictPolicy=PersistenceConflictPolicy(
+ insert:.replace,
+ update:.replace)
+}
+
+// INSERT OR REPLACE INTO persons (...) VALUES (...)
+tryperson.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 at the table level, 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.
+
+
+
:warning: Warning: ON CONFLICT REPLACE may 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).
+
+
Record Class
+
+
Record is a class that is designed to be subclassed, and provides the full toolkit in one go: fetching and persistence methods, as well as changes tracking (see the list of record methods for an overview).
+
+
Record subclasses inherit their features from the RowConvertible, TableMapping, and Persistable protocols. Check their documentation for more information.
+
+
For example, here is a fully functional Record subclass:
+
classPointOfInterest:Record{
+ varid:Int64?
+ vartitle:String
+ varcoordinate:CLLocationCoordinate2D
+
+ /// The table name
+ overrideclassvardatabaseTableName:String{
+ return"pointOfInterests"
+ }
+
+ /// Initialize from a database row
+ requiredinit(row:Row){
+ id=row.value(named:"id")
+ title=row.value(named:"title")
+ coordinate=CLLocationCoordinate2DMake(
+ row.value(named:"latitude"),
+ row.value(named:"longitude"))
+ super.init(row:row)
+ }
+
+ /// The values persisted in the database
+ overridevarpersistentDictionary:[String:DatabaseValueConvertible?]{
+ return[
+ "id":id,
+ "title":title,
+ "latitude":coordinate.latitude,
+ "longitude":coordinate.longitude]
+ }
+
+ /// Update record ID after a successful insertion
+ overridefuncdidInsert(withrowID:Int64,forcolumn:String?){
+ id=rowID
+ }
+}
+
The update()method always executes an UPDATE statement. When the record has not been edited, this costly database access is generally useless.
+
+
Avoid it with the hasPersistentChangedValues property, which returns whether the record has changes that have not been saved:
+
// Saves the person if it has changes that have not been saved:
+ifperson.hasPersistentChangedValues{
+ tryperson.save(db)
+}
+
+
+
The hasPersistentChangedValues flag is false after a record has been fetched or saved into the database. Subsequent modifications may set it, or not: hasPersistentChangedValues is based on value comparison. Setting a property to the same value does not set the changed flag:
For an efficient algorithm which synchronizes the content of a database table with a JSON payload, check JSONSynchronization.playground.
+
The Implicit RowID Primary Key
+
+
All SQLite tables have a primary key. Even when the primary key is not explicit:
+
// No explicit primary key
+trydb.create(table:"events"){tin
+ t.column("message",.text)
+ t.column("date",.datetime)
+}
+
+// No way to define an explicit primary key
+trydb.create(virtualTable:"books",using:FTS4()){tin
+ 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 events WHERE rowid = 1
+letevent=tryEvent.fetchOne(db,key:1)
+
+// DELETE FROM books WHERE rowid = 1
+tryBook.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:
+
+
+
Have the selectsRowID static property from the TableMapping protocol be true.
+
structEvent:TableMapping{
+ staticletselectsRowID=true
+}
+
+// When you subclass Record, you need an override:
+classBook:Record{
+ overrideclassvarselectsRowID:Bool{
+ returntrue
+ }
+}
+
+
+
GRDB will then select the rowid column by default:
+
// SELECT *, rowid FROM events
+letevents=tryEvent.fetchAll(db)
+
+
Have init(row:) from the RowConvertible protocol consume the rowid column:
If you prefer using the Column type from the query interface, use the Column.rowID constant:
+
init(row:Row){
+ id=row.value(Column.rowID)
+}
+
+
+
Your fetched records will then know their ids:
+
letevent=tryEvent.fetchOne(db)!
+event.id// some value
+
+
Include the rowid in your persistentDictionary, and keep it in the didInsert(with:for:) method (both from the Persistable and MutablePersistable protocols):
You will then be able to track your record ids, update them, or check for their existence:
+
letevent=Event(message:"foo",date:Date())
+
+// Insertion sets the record id:
+tryevent.insert(db)
+event.id// some value
+
+// Record can be updated:
+event.message="bar"
+tryevent.update(db)
+
+// Record knows if it exists:
+event.exists(db)// true
+
+
+
List of Record Methods
+
+
This is the list of record methods, along with their required protocols. The Record Class adopts all these protocols.
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:
+
trydb.execute("CREATE TABLE wines (...)")
+letcount=tryWine.filter(sql:"color = ?",arguments:[Color.red]).fetchCount(db)
+letwines=tryWine.fetchAll(db,"SELECT * FROM wines WHERE origin = ? ORDER BY price",arguments:["Burgundy"])
+trydb.execute("DELETE FROM wines WHERE corked")
+
// CREATE TABLE example ( ... )
+trydb.create(table:"example"){tin...}
+
+// CREATE TEMPORARY TABLE example IF NOT EXISTS (
+trydb.create(table:"example",temporary:true,ifNotExists:true){tin
+
+
+
Add regular columns with their name and type (text, integer, double, numeric, boolean, blob, date and datetime) - see SQLite data types:
// 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,
+ t.column("id",.integer).primaryKey()
+
+ // email TEXT UNIQUE,
+ t.column("email",.text).unique()
+
+ // countryCode TEXT REFERENCES countries(code) ON DELETE CASCADE,
+ t.column("countryCode",.text).references("countries",onDelete:.cascade)
+
+
+
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)
+ // age INTEGER CHECK (age > 0)
+ t.column("name",.text).check{length($0)>0}
+ t.column("age",.integer).check(sql:"age > 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:"parent")
+
+ // 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 referers RENAME TO referrers
+trydb.rename(table:"referers",to:"referrers")
+
+// ALTER TABLE persons ADD COLUMN url TEXT
+trydb.alter(table:"persons"){tin
+ 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:
+
trydb.drop(table:"obsolete")
+
+
Create Indexes
+
+
Create indexes with the create(index:) method:
+
// CREATE UNIQUE INDEX byEmail ON users(email)
+trydb.create(index:"byEmail",on:"users",columns:["email"],unique:true)
+
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: Person.select(...).filter(...).order(...).
+
+
+
all(), none(): the requests for all rows, or no row.
+
// SELECT * FROM persons
+Person.all()
+
+
+
The hidden rowid column can be selected as well when you need it.
+
select(expression, ...) defines the selected columns.
+
// SELECT id, name FROM persons
+Person.select(idColumn,nameColumn)
+
+// SELECT MAX(age) AS maxAge FROM persons
+Person.select(max(ageColumn).aliased("maxAge"))
+
+
distinct() performs uniquing.
+
// SELECT DISTINCT name FROM persons
+Person.select(nameColumn).distinct()
+
+
filter(expression) applies conditions.
+
// SELECT * FROM persons WHERE id IN (1, 2, 3)
+Person.filter([1,2,3].contains(idColumn))
+
+// SELECT * FROM persons WHERE (name IS NOT NULL) AND (height > 1.75)
+Person.filter(nameColumn!=nil&&heightColumn>1.75)
+
// SELECT * FROM documents WHERE documents MATCH 'sqlite database'
+letpattern=FTS3Pattern(matchingAllTokensIn:"SQLite database")
+Document.matching(pattern)
+
+
+
When the pattern is nil, no row will match.
+
group(expression, ...) groups rows.
+
// SELECT name, MAX(age) FROM persons GROUP BY name
+Person
+ .select(nameColumn,max(ageColumn))
+ .group(nameColumn)
+
+
having(expression) applies conditions on grouped rows.
+
// SELECT name, MAX(age) FROM persons GROUP BY name HAVING MIN(age) >= 18
+Person
+ .select(nameColumn,max(ageColumn))
+ .group(nameColumn)
+ .having(min(ageColumn)>=18)
+
+
order(ordering, ...) sorts.
+
// SELECT * FROM persons ORDER BY name
+Person.order(nameColumn)
+
+// SELECT * FROM persons ORDER BY score DESC, name
+Person.order(scoreColumn.desc,nameColumn)
+
+
+
Each order call clears any previous ordering:
+
// SELECT * FROM persons ORDER BY name
+Person.order(scoreColumn).order(nameColumn)
+
+
reversed() reverses the eventual orderings.
+
// SELECT * FROM persons ORDER BY score ASC, name DESC
+Person.order(scoreColumn.desc,nameColumn).reversed()
+
+
+
If no ordering was specified, the result is ordered by rowID in reverse order.
+
// SELECT * FROM persons ORDER BY _rowid_ DESC
+Person.all().reversed()
+
+
limit(limit, offset: offset) limits and pages results.
+
// SELECT * FROM persons LIMIT 5
+Person.limit(5)
+
+// SELECT * FROM persons LIMIT 5 OFFSET 10
+Person.limit(5,offset:10)
+
+
+
+
You can refine requests by chaining those methods:
+
// SELECT * FROM persons WHERE (email IS NOT NULL) ORDER BY name
+Person.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:
+
Person// SELECT * FROM persons
+ .filter(nameColumn!=nil)// WHERE (name IS NOT NULL)
+ .filter(emailColumn!=nil)// AND (email IS NOT NULL)
+ .order(nameColumn)// - ignored -
+ .order(ageColumn)// ORDER BY age
+ .limit(20,offset:40)// - ignored -
+ .limit(10)// LIMIT 10
+
+
+
Raw SQL snippets are also accepted, with eventual arguments:
+
// SELECT DATE(creationDate), COUNT(*) FROM persons WHERE name = 'Arthur' GROUP BY date(creationDate)
+Person
+ .select(sql:"DATE(creationDate), COUNT(*)")
+ .filter(sql:"name = ?",arguments:["Arthur"])
+ .group(sql:"DATE(creationDate)")
+
+
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 persons WHERE (name = 'Arthur')
+Person.filter(nameColumn=="Arthur")
+
+// SELECT * FROM persons WHERE (name IS NULL)
+Person.filter(nameColumn==nil)
+
+// SELECT * FROM persons WHERE (age IS 18)
+Person.filter(ageColumn===18)
+
+// SELECT * FROM rectangles 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 persons
+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 persons WHERE ((NOT verified) OR (age < 18))
+Person.filter(!verifiedColumn||ageColumn<18)
+
+
BETWEEN, IN, IN (subquery), NOT IN, NOT IN (subquery)
+
+
To check inclusion in a collection, call the contains method on any Swift sequence:
+
// SELECT * FROM persons WHERE id IN (1, 2, 3)
+Person.filter([1,2,3].contains(idColumn))
+
+// SELECT * FROM persons WHERE id NOT IN (1, 2, 3)
+Person.filter(![1,2,3].contains(idColumn))
+
+// SELECT * FROM persons WHERE age BETWEEN 0 AND 17
+Person.filter((0...17).contains(ageColumn))
+
+// SELECT * FROM persons WHERE (age >= 0) AND (age < 18)
+Person.filter((0..<18).contains(ageColumn))
+
+// SELECT * FROM persons WHERE name BETWEEN 'A' AND 'z'
+Person.filter(("A"..."z").contains(nameColumn))
+
+// SELECT * FROM persons WHERE (name >= 'A') AND (name < 'z')
+Person.filter(("A"..<"z").contains(nameColumn))
+
+
+
+
:point_up: Note: SQLite string comparison, by default, is case-sensitive and not Unicode-aware. See string comparison if you need more control.
+
+
+
To check inclusion in a subquery, call the contains method on another request:
+
// SELECT * FROM events
+// WHERE userId IN (SELECT id FROM persons WHERE verified)
+letverifiedUserIds=User.select(idColumn).filter(verifiedColumn)
+Event.filter(verifiedUserIds.contains(userIdColumn))
+
+
EXISTS (subquery), NOT EXISTS (subquery)
+
+
To check is a subquery would return any row, use the exists property on another request:
+
// SELECT * FROM persons
+// WHERE EXISTS (SELECT * FROM books
+// WHERE books.ownerId = persons.id)
+Person.filter(Book.filter(sql:"books.ownerId = persons.id").exists)
+
+
LIKE
+
+
The SQLite LIKE operator is available as the like method:
+
// SELECT * FROM persons WHERE (email LIKE '%@example.com')
+Person.filter(emailColumn.like("%@example.com"))
+
+
+
+
:point_up: Note: the SQLite LIKE operator is case-unsensitive 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:
+
letpattern=FTS3Pattern(matchingAllTokensIn:"SQLite database")
+
+// SELECT * FROM documents WHERE documents MATCH 'sqlite database'
+Document.matching(pattern)
+
+// SELECT * FROM documents WHERE content MATCH 'sqlite database'
+Document.filter(contentColumn.match(pattern))
+
+
+
FTS5:
+
letpattern=FTS5Pattern(matchingAllTokensIn:"SQLite database")
+
+// SELECT * FROM documents WHERE documents 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(age), MAX(age) FROM persons
+Person.select(min(ageColumn),max(ageColumn))
+
+// SELECT COUNT(name) FROM persons
+Person.select(count(nameColumn))
+
+// SELECT COUNT(DISTINCT name) FROM persons
+Person.select(count(distinct:nameColumn))
+
+
IFNULL
+
+
Use the Swift ?? operator:
+
// SELECT IFNULL(name, 'Anonymous') FROM persons
+Person.select(nameColumn??"Anonymous")
+
+// SELECT IFNULL(name, email) FROM persons
+Person.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:
+
Person.select(nameColumn.uppercased())
+
+
+
+
:point_up: Note: When comparing strings, you’d rather use a collation:
When the selected columns don’t fit the source type, change your target: any other type that adopts the RowConvertible protocol, plain database rows, and even values:
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 persons WHERE id = 1
+tryPerson.fetchOne(db,key:1)// Person?
+
+// SELECT * FROM persons WHERE id IN (1, 2, 3)
+tryPerson.fetchAll(db,keys:[1,2,3])// [Person]
+
+// SELECT * FROM persons WHERE isoCode = 'FR'
+tryCountry.fetchOne(db,key:"FR")// Country?
+
+// SELECT * FROM countries WHERE isoCode IN ('FR', 'US')
+tryCountry.fetchAll(db,keys:["FR","US"])// [Country]
+
+
+
When the table has no explicit primary key, GRDB uses the hidden rowid column:
+
// SELECT * FROM documents WHERE rowid = 1
+tryDocument.fetchOne(db,key:1)// Document?
+
+
+
For multiple-column primary keys and unique keys defined by unique indexes, provide a dictionary:
+
// SELECT * FROM citizenships WHERE personID = 1 AND countryISOCode = 'FR'
+tryCitizenship.fetchOne(db,key:["personID":1,"countryISOCode":"FR"])// Citizenship?
+
+// SELECT * FROM persons WHERE email = 'arthur@example.com'
+tryPerson.fetchOne(db,key:["email":"arthur@example.com"])// Person?
+
+
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 persons
+letcount=tryPerson.fetchCount(db)// Int
+
+// SELECT COUNT(*) FROM persons WHERE email IS NOT NULL
+letcount=tryPerson.filter(emailColumn!=nil).fetchCount(db)
+
+// SELECT COUNT(DISTINCT name) FROM persons
+letcount=tryPerson.select(nameColumn).distinct().fetchCount(db)
+
+// SELECT COUNT(*) FROM (SELECT DISTINCT name, age FROM persons)
+letcount=tryPerson.select(nameColumn,ageColumn).distinct().fetchCount(db)
+
+
+
Other aggregated values can also be selected and fetched (see SQL Functions):
Requests can delete records, with the deleteAll() method:
+
// DELETE FROM persons WHERE email IS NULL
+letrequest=Person.filter(emailColumn==nil)
+tryrequest.deleteAll(db)
+
+
+
Deleting records according to their primary key is also quite common. It has a shortcut which accepts any single-column primary key:
+
// DELETE FROM persons WHERE id = 1
+tryPerson.deleteOne(db,key:1)
+
+// DELETE FROM persons WHERE id IN (1, 2, 3)
+tryPerson.deleteAll(db,keys:[1,2,3])
+
+// DELETE FROM persons WHERE isoCode = 'FR'
+tryCountry.deleteOne(db,key:"FR")
+
+// DELETE FROM countries WHERE isoCode IN ('FR', 'US')
+tryCountry.deleteAll(db,keys:["FR","US"])
+
+
+
When the table has no explicit primary key, GRDB uses the hidden rowid column:
+
// DELETE FROM documents WHERE rowid = 1
+tryDocument.deleteOne(db,key:1)
+
+
+
For multiple-column primary keys and unique keys defined by unique indexes, provide a dictionary:
+
// DELETE FROM citizenships WHERE personID = 1 AND countryISOCode = 'FR'
+tryCitizenship.deleteOne(db,key:["personID":1,"countryISOCode":"FR"])
+
+// DELETE FROM persons WHERE email = 'arthur@example.com'
+Person.deleteOne(db,key:["email":"arthur@example.com"])
+
+
Custom Requests
+
+
Until now, we have seen requests created from any type that adopts the TableMapping protocol:
Those requests of type QueryInterfaceRequest can fetch, count, and delete records:
+
tryrequest.fetchCursor(db)// DatabaseCursor<Person>
+tryrequest.fetchAll()// [Person]
+tryrequest.fetchOne()// Person?
+tryrequest.fetchCount()// Int
+tryrequest.deleteAll()
+
+
+
When the query interface can not generate the SQL you need, you can still fallback to raw SQL:
+
// Custom SQL is always welcome
+tryPerson.fetchAll(db,"SELECT ...")// [Person]
+
+
+
But you may prefer to bring some elegance back in, and build custom requests on top of the Request and TypedRequest protocols:
+
// No custom SQL in sight
+tryPerson.customRequest().fetchAll(db)// [Person]
+
+
+
Unlike QueryInterfaceRequest, these protocols can’t delete. But they can fetch and count:
+
/// The protocol for all types that define a way to fetch values from
+/// a database.
+protocolRequest{
+ /// A tuple that contains a prepared statement that is ready to be
+ /// executed, and an eventual row adapter.
+ funcprepare(_db:Database)throws->(SelectStatement,RowAdapter?)
+
+ /// The number of rows fetched by the request.
+ funcfetchCount(_db:Database)throws->Int
+}
+
+/// The protocol for typed fetch requests.
+protocolTypedRequest:Request{
+ /// The fetched type
+ associatedtypeFetched
+}
+
+
+
The prepare method returns a tuple made of a prepared statement and an optional row adapter. The prepared statement tells which SQL query should be executed. The row adapter can help presenting the fetched rows in the way expected by the row consumers (we’ll see an example below).
+
+
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.
+
Fetching From Custom Requests
+
+
A Request doesn’t know what to fetch, but it can feed the fetching methods of any fetchable type (Row, value, or record):
A TypedRequest knows exactly what it has to do when its Fetched associated type is fetchable (Row, value, or record):
+
letrequest=...// Some TypedRequest that fetches Person
+tryrequest.fetchCursor(db)// DatabaseCursor<Person>
+tryrequest.fetchAll(db)// [Person]
+tryrequest.fetchOne(db)// Person?
+
+
Building Custom Requests
+
+
To build custom requests, you can create your own type that adopts the protocols, or derive requests from other requests, or use one of the built-in concrete types:
On top of the APIs described above, GRDB provides a toolkit for applications. While none of those are mandatory, all of them help dealing with the database:
+
+
+
Migrations: Transform your database as your application evolves.
+
Full-Text Search: Perform efficient and customizable full-text searches.
varmigrator=DatabaseMigrator()
+
+// v1 database
+migrator.registerMigration("v1"){dbin
+ trydb.create(table:"persons"){tin...}
+ trydb.create(table:"books"){tin...}
+ trydb.create(index:...)
+}
+
+// v2 database
+migrator.registerMigration("v2"){dbin
+ trydb.alter(table:"persons"){tin...}
+}
+
+// Migrations for future versions will be inserted here:
+//
+// // v3 database
+// migrator.registerMigration("v3") { db in
+// ...
+// }
+
+trymigrator.migrate(dbQueue)// or migrator.migrate(dbPool)
+
+
+
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).
+
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 persons.name:
+migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName"){dbin
+ trydb.create(table:"new_persons"){tin
+ t.column("id",.integer).primaryKey()
+ t.column("name",.text).notNull()
+ }
+ trydb.execute("INSERT INTO new_persons SELECT * FROM persons")
+ trydb.drop(table:"persons")
+ trydb.rename(table:"new_persons",to:"persons")
+}
+
+
+
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
+
+
Full-Text Search is an efficient way to search a corpus of textual documents.
+
// Create full-text tables
+trydb.create(virtualTable:"books",using:FTS4()){tin// or FTS3(), or FTS5()
+ t.column("author")
+ t.column("title")
+ t.column("body")
+}
+
+// Populate full-text table with records or SQL
+tryBook(...).insert(db)
+trydb.execute(
+ "INSERT INTO books (author, title, body) VALUES (?, ?, ?)",
+ arguments:[...])
+
+// Build search patterns
+letpattern=FTS3Pattern(matchingPhrase:"Moby-Dick")
+
+// Search with the query interface or SQL
+letbooks=tryBook.matching(pattern).fetchAll(db)
+letbooks=tryBook.fetchAll(db,
+ "SELECT * FROM books WHERE books MATCH ?",
+ arguments:[pattern])
+
Custom Tokenizers: FTS5. Leverage extra full-text features such as synonyms or stop words. Avoid unicode gotchas.
+
Sample Code: WWDC Companion, an iOS app that stores, displays, and lets the user search the WWDC 2016 sessions.
+
+
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 Needs
+
FTS3
+
FTS4
+
FTS5
+
+
+
+
:question: Queries
+
+
+
+
+
+
Words searches (documents that contain database)
+
X
+
X
+
X
+
+
+
Prefix searches (documents that contain a word starting with data)
+
X
+
X
+
X
+
+
+
Phrases searches (documents that contain the phrase SQLite database)
+
X
+
X
+
X
+
+
+
Boolean searches (documents that contain SQLite or database)
+
X
+
X
+
X
+
+
+
Proximity search (documents that contain SQLite near database)
+
X
+
X
+
X
+
+
+
:scissors: Tokenization
+
+
+
+
+
+
Ascii case insensitivity (have DATABASE match database)
+
X
+
X
+
X
+
+
+
Unicode case insensitivity (have ÉLÉGANCE match élégance)
+
X
+
X
+
X
+
+
+
Latin diacritics insensitivity (have elegance match élégance)
+
X
+
X
+
X
+
+
+
English Stemming (have frustration match frustrated)
+
X
+
X
+
X
+
+
+
English Stemming and Ascii case insensitivity
+
X
+
X
+
X
+
+
+
English Stemming and Unicode case insensitivity
+
+
+
X
+
+
+
English Stemming and Latin diacritics insensitivity
+
+
+
X
+
+
+
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)
+
X
+
X
+
X
+
+
+
+
¹ Requires extra setup, possibly hard to implement.
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 support FTS3 and FTS4 out of the box, but not FTS5. To use FTS5, you’ll need a custom SQLite build that activates the SQLITE_ENABLE_FTS5 compilation option.
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.
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.
The first initializer validates your raw patterns against the query grammar, and may throw a DatabaseError:
+
// OK: FTS3Pattern
+letpattern=tryFTS3Pattern(rawPattern:"sqlite AND database")
+// DatabaseError: malformed MATCH expression: [AND]
+letpattern=tryFTS3Pattern(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:
+
letquery="SQLite database"
+// Matches documents that contain "SQLite" or "database"
+letpattern=FTS3Pattern(matchingAnyTokenIn:query)
+// Matches documents that contain both "SQLite" and "database"
+letpattern=FTS3Pattern(matchingAllTokensIn:query)
+// Matches documents that contain "SQLite database"
+letpattern=FTS3Pattern(matchingPhrase:query)
+
+
+
They return nil when no pattern could be built from the input string:
// Search in all columns
+letdocuments=tryDocument.matching(pattern).fetchAll(db)
+
+// Search in a specific column:
+letdocuments=tryDocument.filter(Column("content").match(pattern)).fetchAll(db)
+
+
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:
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.
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.
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).
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
+trydb.makeFTS5Pattern(rawPattern:"sqlite",forTable:"books")
+// DatabaseError: syntax error near \"AND\"
+trydb.makeFTS5Pattern(rawPattern:"AND",forTable:"books")
+// DatabaseError: no such column: missing
+trydb.makeFTS5Pattern(rawPattern:"missing: sqlite",forTable:"books")
+
+
+
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:
+
letquery="SQLite database"
+// Matches documents that contain "SQLite" or "database"
+letpattern=FTS5Pattern(matchingAnyTokenIn:query)
+// Matches documents that contain both "SQLite" and "database"
+letpattern=FTS5Pattern(matchingAllTokensIn:query)
+// Matches documents that contain "SQLite database"
+letpattern=FTS5Pattern(matchingPhrase:query)
+
+
+
They return nil when no pattern could be built from the input string:
FTS5 can sort results by relevance (most to least relevant):
+
// SQL
+letdocuments=tryDocument.fetchAll(db,
+ "SELECT * FROM documents WHERE documents MATCH ? ORDER BY rank",
+ arguments:[pattern])
+
+// Query Interface
+letdocuments=tryDocument.matching(pattern).order(Column.rank).fetchAll(db)
+
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
+trydb.create(table:"books"){tin
+ t.column("author",.text)
+ t.column("title",.text)
+ t.column("content",.text)
+ ...
+}
+
+// A full-text table synchronized with the regular table
+trydb.create(virtualTable:"books_ft",using:FTS4()){tin// or FTS5()
+ t.synchronize(withTable:"books")
+ 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 by the mean of SQL triggers.
+
+
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 2016 sessions.
+
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 books WHERE books MATCH '...'
+letbooks=Book.matching(pattern).fetchAll(db)
+
+
+
The solution is to perform a joined request, using raw SQL:
+
letsql="SELECT books.* "+
+ "FROM books "+
+ "JOIN books_ft ON "+
+ "books_ft.rowid = books.rowid AND "+
+ "books_ft MATCH ?"
+letbooks=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!
+
Database Changes Observation
+
+
The TransactionObserver protocol lets you observe database changes:
+
protocolTransactionObserver:class{
+ /// Filters database changes that should be notified the the
+ /// `databaseDidChange(with:)` method.
+ funcobserves(eventsOfKindeventKind:DatabaseEventKind)->Bool
+
+ /// 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().
+ funcdatabaseDidChange(withevent:DatabaseEvent)
+
+ /// An opportunity to rollback pending changes by throwing an error.
+ funcdatabaseWillCommit()throws
+
+ /// Database changes have been committed.
+ funcdatabaseDidCommit(_db:Database)
+
+ /// Database changes have been rollbacked.
+ funcdatabaseDidRollback(_db:Database)
+}
+
+
+
To activate a transaction observer, add it to the database queue or pool:
Database holds weak references to its transaction observers: they are not retained, and stop getting notifications after they are deallocated.
+
+
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.
+
+
+
: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 databaseDidCommit is called. On the other side, databaseDidRollback confirms their invalidation:
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:
Eventual errors thrown from databaseWillCommit are exposed to the application code:
+
do{
+ trydbQueue.inTransaction{dbin
+ ...
+ 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.
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 some database changes they are not interested in.
+
+
At first sight, this looks somewhat redundant with the checks that observers can perform in their databaseDidChange method. But the code below is inefficient:
+
// BAD: An inefficient way to track the "persons" table:
+classPersonObserver:TransactionObserver{
+ varpersonsTableModified=false
+
+ funcobserves(eventsOfKindeventKind:DatabaseEventKind)->Bool{
+ // Observe all events
+ returntrue
+ }
+
+ funcdatabaseDidChange(withevent:DatabaseEvent){
+ ifevent.tableName=="persons"{
+ personsTableModified=true
+ }
+ }
+
+ funcdatabaseDidRollback(_db:Database){
+ // Get ready for next transaction
+ personsTableModified=false
+ }
+
+ funcdatabaseDidCommit(_db:Database){
+ ifpersonsTableModified{
+ // Process committed changes to the persons table
+ }
+
+ // Get ready for next transaction
+ personsTableModified=false
+ }
+}
+
+
+
The databaseDidChange method is invoked for each insertion, deletion, and update of individual rows, of any table. When there are many changed rows, the observer will spend of a lot of time performing the same check again and again.
+
+
Instead, filter events in the observes(eventsOfKind:) method. This will prevent databaseDidChange from being called for changes you’re not interested into, and is much more efficient:
+
// GOOD: An efficient way to track the "persons" table:
+classPersonObserver:TransactionObserver{
+ varpersonsTableModified=false
+
+ funcobserves(eventsOfKindeventKind:DatabaseEventKind)->Bool{
+ // Only observe changes to the "persons" table.
+ returneventKind.tableName=="persons"
+ }
+
+ funcdatabaseDidChange(withevent:DatabaseEvent){
+ personsTableModified=true// Guaranteed
+ }
+
+ funcdatabaseDidRollback(_db:Database){
+ // Get ready for next transaction
+ personsTableModified=false
+ }
+
+ funcdatabaseDidCommit(_db:Database){
+ ifpersonsTableModified{
+ // Process committed changes to the persons table
+ }
+
+ // Get ready for next transaction
+ personsTableModified=false
+ }
+}
+
+
+
The observes(eventsOfKind:) method is also able to inspect the columns that are about to be changed:
+
classPersonObserver:TransactionObserver{
+ funcobserves(eventsOfKindeventKind:DatabaseEventKind)->Bool{
+ // Only observe changes to the "name" column of the "persons" table.
+ switcheventKind{
+ case.insert(lettableName):
+ returntableName=="persons"
+ case.delete(lettableName):
+ returntableName=="persons"
+ case.update(lettableName,letcolumnNames):
+ returntableName=="persons"&&columnNames.contains("name")
+ }
+ }
+}
+
+
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:
+
protocolTransactionObserverType: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().
+ funcdatabaseWillChange(withevent: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.
Given a fetch request, and a type that adopts the RowConvertible 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.
The type of the fetched records. It must be a type that adopts the RowConvertible protocol, such as a subclass of the Record class
+
A fetch request
+
+
classPerson:Record{...}
+letdbQueue=DatabaseQueue(...)// Or DatabasePool
+
+// Using a Request from the Query Interface:
+letcontroller=FetchedRecordsController(
+ dbQueue,
+ request:Person.order(Column("name")))
+
+// Using SQL, and eventual arguments:
+letcontroller=FetchedRecordsController<Person>(
+ dbQueue,
+ sql:"SELECT * FROM persons ORDER BY name WHERE countryIsoCode = ?",
+ 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.
+
letcontroller=FetchedRecordsController<Person>(
+ dbQueue,
+ sql:"SELECT persons.name, COUNT(books.id) AS bookCount "+
+ "FROM persons "+
+ "LEFT JOIN books ON books.authorId = persons.id "+
+ "GROUP BY persons.id "+
+ "ORDER BY persons.name")
+
+
+
After creating an instance, you invoke performFetch() to actually execute
+the fetch.
+
trycontroller.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. Transactions can be explicit, or implicit:
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:
+
letcontroller=tryFetchedRecordsController(...)
+
+controller.trackChanges(
+ // controller's records are about to change:
+ willChange:{controllerin...},
+
+ // notification of individual record changes:
+ onChange:{(controller,record,change)in...},
+
+ // controller's records have changed:
+ didChange:{controllerin...})
+
+trycontroller.performFetch()
+
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:{dbin
+ // Fetch any extra value, for example the number of fetched records:
+ returntryPerson.fetchCount(db)
+ },
+ didChange:{(controller,count)in
+ // The extra value is the second argument.
+ letrecordsCount=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.
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(Person.order(Column("name")))
+// Here callbacks have not been called yet.
+// You can cancel them, and refresh records immediately:
+trycontroller.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 TableMapping protocol, they are automatically compared according to their primary key:
: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:
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:{[unownedself]_in
+ self.tableView.beginUpdates()
+ },
+
+ // notification of individual record changes:
+ onChange:{[unownedself](controller,record,change)in
+ switchchange{
+ case.insertion(letindexPath):
+ self.tableView.insertRows(at:[indexPath],with:.fade)
+
+ case.deletion(letindexPath):
+ self.tableView.deleteRows(at:[indexPath],with:.fade)
+
+ case.update(letindexPath,_):
+ ifletcell=self.tableView.cellForRow(at:indexPath){
+ self.configure(cell,at:indexPath)
+ }
+
+ case.move(letindexPath,letnewIndexPath,_):
+ 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:{[unownedself]_in
+ self.tableView.endUpdates()
+ })
+
+
+
See GRDBDemoiOS for an sample app that uses FetchedRecordsController.
+
+
+
: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:
+trydbQueue.inDatabase{dbin
+ tryPerson(...).insert(db)
+}
+// Here callbacks have not been called yet.
+// You can cancel them, and refresh records immediately:
+trycontroller.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.
You can change the passphrase of an already encrypted database:
+
trydbQueue.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
+letclearDBQueue=tryDatabaseQueue(path:"/path/to/clear.db")
+
+// The encrypted database, at some distinct location:
+varconfiguration=Configuration()
+configuration.passphrase="secret"
+letencryptedDBQueue=tryDatabaseQueue(path:"/path/to/encrypted.db",configuration:config)
+
+tryclearDBQueue.inDatabase{dbin
+ trydb.execute("ATTACH DATABASE ? AS encrypted KEY ?",arguments:[encryptedDBQueue.path,"secret"])
+ trydb.execute("SELECT sqlcipher_export('encrypted')")
+ trydb.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.
+
letsource:DatabaseQueue=...// or DatabasePool
+letdestination:DatabaseQueue=...// or DatabasePool
+trysource.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.
+
Good To Know
+
+
This chapter covers general topics that you should be aware of.
Here is an example of code that is vulnerable to SQL injection:
+
// BAD BAD BAD
+letname=textField.text
+trydbQueue.inDatabase{dbin
+ trydb.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:
+
UPDATEstudentsSETname='Robert';
+DROPTABLEstudents;
+--' 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 SQL queries:
+
// Good
+letname=textField.text
+trydbQueue.inDatabase{dbin
+ trydb.execute(
+ "UPDATE students SET name = ? WHERE id = ?",
+ arguments:[name,id])
+}
+
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.
SQLite uses codes to distinguish between various errors:
+
do{
+ try...
+}catchleterrorasDatabaseErrorwhereerror.extendedResultCode==.SQLITE_CONSTRAINT_FOREIGNKEY{
+ // foreign key constraint error
+}catchleterrorasDatabaseErrorwhereerror.resultCode==.SQLITE_CONSTRAINT{
+ // any other constraint error
+}catchleterrorasDatabaseError{
+ // 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...
+}catchleterrorasDatabaseError{
+ switcherror.extendedResultCode{
+ caseResultCode.SQLITE_CONSTRAINT_FOREIGNKEY:
+ // foreign key constraint error
+ caseResultCode.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 Persistable protocol, in a single case: when the update method could not find any row to update:
+
do{
+ tryperson.update(db)
+}catchPersistenceError.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.
+letname:String=row.value(named:"name")
+
+
+
Solution: fix the contents of the database, use NOT NULL constraints, or load an optional:
+
letname:String?=row.value(named:"name")
+
+
The code asks for a Date, when the database contains garbage:
+
// fatal error: could not convert "Mom’s birthday" to Date.
+letdate:Date?=row.value(named:"date")
+
+
+
Solution: fix the contents of the database, or use DatabaseValue to handle all possible cases:
+
letdbv:DatabaseValue=row.value(named:"date")
+ifdbv.isNull{
+ // Handle NULL
+ifletdate=Date.fromDatabaseValue(dbv){
+ // Handle valid date
+}else{
+ // Handle invalid date
+}
+
+
The database can’t guarantee that the code does what it says:
+
// fatal error: table persons has no unique index on column email
+tryPerson.deleteOne(db,key:["email":"arthur@example.com"])
+
+
+
Solution: add a unique index to the persons.email column, or use the deleteAll method to make it clear that you may delete more than one row:
// fatal error: Database methods are not reentrant.
+dbQueue.inDatabase{dbin
+ dbQueue.inDatabase{dbin
+ ...
+ }
+}
+
+
+
Solution: avoid reentrancy, and instead pass a database connection along.
+
+
How to Deal with Untrusted Inputs
+
+
Let’s consider the code below:
+
letsql="SELECT ..."
+
+// Some untrusted arguments for the query
+letarguments:[String:Any]=...
+letrows=tryRow.fetchCursor(db,sql,arguments:StatementArguments(arguments))
+
+whileletrow=tryrows.next(){
+ // Some untrusted database value:
+ letdate:Date?=row.value(atIndex: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:
GRDB extends SQLite with SQL functions that call the Swift built-in string functions capitalized, lowercased, uppercased, localizedCapitalized, localizedLowercased and localizedUppercased:
Those unicode-aware string functions are also readily available in the query interface:
+
Person.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:
+
trydb.create(table:"persons"){tin
+ // 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)
+}
+
+// Persons are sorted in a localized case insensitive way:
+letpersons=tryPerson.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:
+
letcollation=DatabaseCollation.localizedCaseInsensitiveCompare
+letpersons=tryPerson.fetchAll(db,
+ "SELECT * FROM persons ORDER BY name COLLATE \(collation.name))")
+letpersons=tryPerson.order(nameColumn.collating(collation)).fetchAll(db)
+
+
+
You can also define your own collations:
+
letcollation=DatabaseCollation("customCollation"){(lhs,rhs)->NSComparisonResultin
+ // 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.sharedApplication())
+
+
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 explicitely use complete protection:
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.
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.
+
+
+
Both 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.
+
: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:
+
trydbPool.read{dbin// or dbQueue.inDatabase { ... }
+ // Guaranteed to be equal
+ letcount1=tryPerson.fetchCount(db)
+ letcount2=tryPerson.fetchCount(db)
+}
+
+
: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/Database.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 access the same database, a multi-threaded application will eventually face database is locked errors. See Dealing with External Connections.
+
// SAFE CONCURRENCY
+funccurrentUser(_db:Database)throws->User?{
+ returntryUser.fetchOne(db)
+}
+// dbQueue is a singleton defined somewhere in your app
+letuser=trydbQueue.inDatabase{dbin// or dbPool.read { ... }
+ trycurrentUser(db)
+}
+
+// UNSAFE CONCURRENCY
+// This method fails when some other thread is currently writing into
+// the database.
+funccurrentUser()throws->User?{
+ letdbQueue=tryDatabaseQueue(...)
+ returntrydbQueue.inDatabase{dbin
+ tryUser.fetchOne(db)
+ }
+}
+letuser=trycurrentUser()
+
+
:point_up: Rule 2: Group related statements within a single call to a DatabaseQueue or DatabasePool database access method.
+
+
Those 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
+trydbPool.read{dbin// or dbQueue.inDatabase { ... }
+ // Guaranteed to be equal:
+ letcount1=tryPointOfInterest.fetchCount(db)
+ letcount2=tryPointOfInterest.fetchCount(db)
+}
+
+// UNSAFE CONCURRENCY
+// Those two values may be different because some other thread may have
+// modified the database between the two blocks:
+letcount1=trydbPool.read{dbintryPointOfInterest.fetchCount(db)}
+letcount2=trydbPool.read{dbintryPointOfInterest.fetchCount(db)}
+
+
+
In the same vein, when you fetch values that depends on some database updates, group them:
+
// SAFE CONCURRENCY
+trydbPool.write{dbin
+ // The count is guaranteed to be non-zero
+ tryPointOfInterest(...).insert(db)
+ letcount=tryPointOfInterest.fetchCount(db)
+}
+
+// UNSAFE CONCURRENCY
+// The count may be zero because some other thread may have performed
+// a deletion between the two blocks:
+trydbPool.write{dbintryPointOfInterest(...).insert(db)}
+letcount=trydbPool.read{dbintryPointOfInterest.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, group those modifications within a transaction:
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.
+
+
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:
+
trydbPool.write{dbin
+ // Increment the number of persons
+ tryPerson(...).insert(db)
+
+ // Read the number of persons. The writer queue is still locked :-(
+ letcount=tryPerson.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
+trydbPool.write{dbin
+ // Increment the number of persons
+ tryPerson(...).insert(db)
+}
+trydbPool.read{dbin
+ // Read some random value :-(
+ letcount=tryPerson.fetchCount(db)
+}
+
+
+
The correct solution is the readFromCurrentState method, which must be called from within a write block:
+
// CORRECT
+trydbPool.write{dbin
+ // Increment the number of persons
+ tryPerson(...).insert(db)
+
+ trydbPool.readFromCurrentState{db
+ // Read the number of persons. The writer queue has been unlocked :-)
+ letcount=tryPerson.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 persons is guaranteed to be non-zero, even though it is fetched concurrently with the person deletion:
+
trydbPool.write{dbin
+ // Increment the number of persons
+ tryPerson(...).insert(db)
+
+ trydbPool.readFromCurrentState{db
+ // Guaranteed to be non-zero
+ letcount=tryPerson.fetchCount(db)
+ }
+
+ tryPerson.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.
These protocols provide a unified API that lets you write safe concurrent code that targets both classes.
+
+
However, database queues are not database pools, 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.
+
The definition of current state in DatabaseWriter.readFromCurrentState is delicate.
+
+
+
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 reusable agnostic code that has both queues and pools in mind. For example, GRDB uses those protocols for migrations and FetchedRecordsController, two tools that accept both queues and pools.
+
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:
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.inDatabase{dbin
+ // 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:
// SELECT * FROM persons
+tryPerson.fetchAll(db)
+
+// SELECT id, name FROM persons
+tryPerson.select(idColumn,nameColumn).fetchAll(db)
+
+
+
If your Person type can’t be built without other columns (it has non-optional properties for other columns), do define and use a different type.
+
+
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
+letpersons=tryPerson.order(scoreColumn.desc).fetchAll(db)
+lethallOfFame=persons.prefix(5)
+
+// Better way
+lethallOfFame=tryPerson.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.
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 authors
+letauthors=tryAuthor.fetchAll(db)
+forauthorinauthors{
+ // SELECT COUNT(*) FROM books WHERE authorId = ...
+ author.bookCount=tryBook.filter(authorIdColumn==author.id).fetchCount(db)
+}
+
+
+
Instead, perform a single query:
+
letsql="SELECT authors.*, COUNT(books.id) AS bookCount "+
+ "FROM authors "+
+ "LEFT JOIN books ON books.authorId = authors.id "+
+ "GROUP BY authors.id"
+letauthors=tryAuthor.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:
When inserting values, use reusable prepared statements, and set statements values with an array:
+
// Strings & dictionaries
+forpersoninpersons{
+ tryperson.insert(db)
+}
+
+// Prepared statement
+letinsertStatement=db.prepareStatement("INSERT INTO persons (name, email) VALUES (?, ?)")
+forpersoninpersons{
+ // 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([person.name,person.email])
+ tryinsertStatement.execute()
+}
+
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 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:
If the application should modify the database, you need to copy it to a place where it can be modified. For example, in the Documents folder. Only then, open a connection:
Initializes arguments from a sequence of (key, value) dictionary, such as","parent_name":"StatementArguments"},"Structs/StatementArguments.html#/s:FV4GRDB18StatementArgumentscuRxs8SequenceWx8Iterator7Element_zTSSGSqPS_24DatabaseValueConvertible___rFxS0_":{"name":"init(_:)","abstract":"
Initializes arguments from a sequence of (key, value) pairs, such as","parent_name":"StatementArguments"},"Structs/StatementArguments.html#/s:FV4GRDB18StatementArgumentscFGVs10DictionaryVs11AnyHashableP__GSqS0__":{"name":"init(_:)","abstract":"
Creates a new StatementArguments by extending the left-hand size","parent_name":"StatementArguments"},"Structs/StatementArguments.html#/s:ZFV4GRDB18StatementArgumentsoi2apFTS0_S0__S0_":{"name":"&+(_:_:)","abstract":"
Creates a new StatementArguments by extending the left-hand size","parent_name":"StatementArguments"},"Structs/StatementArguments.html#/s:ZFV4GRDB18StatementArgumentsoi2peFTRS0_S0__T_":{"name":"+=(_:_:)","abstract":"
Extends the left-hand size arguments with the right-hand side arguments.
This function is an implementation detail of the query interface.","parent_name":"SQLExpressionFunction"},"Structs/SQLFunctionName.html#/s:vV4GRDB15SQLFunctionName3sqlSS":{"name":"sql","abstract":"
Creates an expression that checks if a subquery would return rows","parent_name":"SQLExpressionExists"},"Structs/SQLExpressionExists.html#/s:FV4GRDB19SQLExpressionExists13expressionSQLFRGSqVS_18StatementArguments_SS":{"name":"expressionSQL(_:)","abstract":"
This function is an implementation detail of the query interface.","parent_name":"SQLExpressionExists"},"Structs/SQLExpressionExists.html#/s:vV4GRDB19SQLExpressionExists7negatedPS_13SQLExpression_":{"name":"negated","abstract":"
This property is an implementation detail of the query interface.","parent_name":"SQLExpressionExists"},"Structs/SQLExpressionBinary.html#/s:vV4GRDB19SQLExpressionBinary3lhsPS_13SQLExpression_":{"name":"lhs","abstract":"
Creates an expression made of two expressions joined with a","parent_name":"SQLExpressionBinary"},"Structs/SQLExpressionBinary.html#/s:FV4GRDB19SQLExpressionBinary13expressionSQLFRGSqVS_18StatementArguments_SS":{"name":"expressionSQL(_:)","abstract":"
This function is an implementation detail of the query interface.","parent_name":"SQLExpressionBinary"},"Structs/SQLExpressionBinary.html#/s:vV4GRDB19SQLExpressionBinary7negatedPS_13SQLExpression_":{"name":"negated","abstract":"
This property is an implementation detail of the query interface.","parent_name":"SQLExpressionBinary"},"Structs/SQLBinaryOperator.html#/s:vV4GRDB17SQLBinaryOperator3sqlSS":{"name":"sql","abstract":"
Creates an expression made of an unary operator and","parent_name":"SQLExpressionUnary"},"Structs/SQLExpressionUnary.html#/s:FV4GRDB18SQLExpressionUnary13expressionSQLFRGSqVS_18StatementArguments_SS":{"name":"expressionSQL(_:)","abstract":"
This function is an implementation detail of the query interface.","parent_name":"SQLExpressionUnary"},"Structs/SQLUnaryOperator.html#/s:vV4GRDB16SQLUnaryOperator3sqlSS":{"name":"sql","abstract":"
Eventual arguments that feed the ? and colon-prefixed tokens in the","parent_name":"SQLExpressionLiteral"},"Structs/SQLExpressionLiteral.html#/s:FV4GRDB20SQLExpressionLiteralcFTSS9argumentsGSqVS_18StatementArguments__S0_":{"name":"init(_:arguments:)","abstract":"
This function is an implementation detail of the query interface.","parent_name":"SQLExpressionLiteral"},"Structs/SQLCollatedExpression.html#/s:vV4GRDB21SQLCollatedExpression10expressionPS_13SQLExpression_":{"name":"expression","abstract":"
This method is an implementation detail of the query interface.","parent_name":"SQLCollatedExpression"},"Structs/ScopeAdapter.html#/s:FV4GRDB12ScopeAdaptercFGVs10DictionarySSPS_10RowAdapter__S0_":{"name":"init(_:)","abstract":"
Creates a SuffixRowAdapter that hides all columns before the","parent_name":"SuffixRowAdapter"},"Structs/SuffixRowAdapter.html#/s:FV4GRDB16SuffixRowAdapter15layoutedAdapterFzT4fromPS_9RowLayout__PS_18LayoutedRowAdapter_":{"name":"layoutedAdapter(from:)","abstract":"
Creates a ColumnMapping with a dictionary from mapped column names to","parent_name":"ColumnMapping"},"Structs/ColumnMapping.html#/s:FV4GRDB13ColumnMapping15layoutedAdapterFzT4fromPS_9RowLayout__PS_18LayoutedRowAdapter_":{"name":"layoutedAdapter(from:)","abstract":"
An array of (baseIndex, mappedName) pairs, where baseIndex is the index","parent_name":"LayoutedColumnMapping"},"Structs/LayoutedColumnMapping.html#/s:FV4GRDB21LayoutedColumnMappingcuRxs8SequenceWx8Iterator7Element_zTSiSS_rFT13layoutColumnsx_S0_":{"name":"init(layoutColumns:)","abstract":"
Creates an LayoutedColumnMapping from an array of (baseIndex, mappedName)","parent_name":"LayoutedColumnMapping"},"Structs/LayoutedColumnMapping.html#/s:vV4GRDB21LayoutedColumnMapping7mappingS0_":{"name":"mapping","abstract":"
Part of the LayoutedRowAdapter protocol; returns self.
Part of the RowLayout protocol; returns the index of the leftmost column","parent_name":"LayoutedColumnMapping"},"Structs/RowIndex.html#/s:ZFPs9Equatableoi2eeFTxx_Sb":{"name":"==(_:_:)","abstract":"
Indexes to (columnName, databaseValue) pairs in a database row.
Creates a new request whose prepare() method wraps and forwards","parent_name":"AnyTypedRequest"},"Structs/AnyTypedRequest.html#/s:FV4GRDB15AnyTypedRequest7prepareFzCS_8DatabaseTCS_15SelectStatementGSqPS_10RowAdapter___":{"name":"prepare(_:)","abstract":"
A tuple that contains a prepared statement that is ready to be","parent_name":"AnyTypedRequest"},"Structs/SQLRequest.html#/s:FV4GRDB10SQLRequestcFTSS9argumentsGSqVS_18StatementArguments_7adapterGSqPS_10RowAdapter___S0_":{"name":"init(_:arguments:adapter:)","abstract":"
Creates a new request from an SQL string, optional arguments, and","parent_name":"SQLRequest"},"Structs/SQLRequest.html#/s:FV4GRDB10SQLRequest7prepareFzCS_8DatabaseTCS_15SelectStatementGSqPS_10RowAdapter___":{"name":"prepare(_:)","abstract":"
A tuple that contains a prepared statement that is ready to be","parent_name":"SQLRequest"},"Structs/AnyRequest.html#/s:FV4GRDB10AnyRequestcFPS_7Request_S0_":{"name":"init(_:)","abstract":"
Creates a new request that wraps and forwards operations to request.
Creates a new request whose prepare() method wraps and forwards","parent_name":"AnyRequest"},"Structs/AnyRequest.html#/s:FV4GRDB10AnyRequest7prepareFzCS_8DatabaseTCS_15SelectStatementGSqPS_10RowAdapter___":{"name":"prepare(_:)","abstract":"
A tuple that contains a prepared statement that is ready to be","parent_name":"AnyRequest"},"Structs/PersistenceConflictPolicy.html#/s:vV4GRDB25PersistenceConflictPolicy27conflictResolutionForInsertOCS_8Database18ConflictResolution":{"name":"conflictResolutionForInsert","abstract":"
Creates a FTS4 module suitable for the Database","parent_name":"FTS4"},"Structs/FTS4.html#/s:vV4GRDB4FTS410moduleNameSS":{"name":"moduleName","abstract":"
This function is an implementation detail of the query interface.","parent_name":"Column"},"Structs/Column.html#/s:ZvV4GRDB6Column5rowIDS0_":{"name":"rowID","abstract":"
Returns a new QueryInterfaceRequest with a matching predicate added","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:FV4GRDB21QueryInterfaceRequest14selectQuerySQLFRGSqVS_18StatementArguments_SS":{"name":"selectQuerySQL(_:)","abstract":"
This function is an implementation detail of the query interface.","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:FV4GRDB21QueryInterfaceRequest6selectFtGSaPS_13SQLSelectable___GS0_x_":{"name":"select(_:)","abstract":"
A new QueryInterfaceRequest with a new net of selected columns.
A new QueryInterfaceRequest with the provided predicate added to the","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:FV4GRDB21QueryInterfaceRequest6filterFT3sqlSS9argumentsGSqVS_18StatementArguments__GS0_x_":{"name":"filter(sql:arguments:)","abstract":"
A new QueryInterfaceRequest with the provided predicate added to the","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:FV4GRDB21QueryInterfaceRequest5groupFtGSaPS_14SQLExpressible___GS0_x_":{"name":"group(_:)","abstract":"
A new QueryInterfaceRequest grouped according to expressions.
A new QueryInterfaceRequest with the provided predicate added to the","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:FV4GRDB21QueryInterfaceRequest6havingFT3sqlSS9argumentsGSqVS_18StatementArguments__GS0_x_":{"name":"having(sql:arguments:)","abstract":"
A new QueryInterfaceRequest with the provided sql added to the","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:FV4GRDB21QueryInterfaceRequest5orderFtGSaPS_15SQLOrderingTerm___GS0_x_":{"name":"order(_:)","abstract":"
A new QueryInterfaceRequest with the provided orderings.
A QueryInterfaceRequest which fetches limit rows, starting","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:FV4GRDB21QueryInterfaceRequest10fetchCountFzCS_8DatabaseSi":{"name":"fetchCount(_:)","abstract":"
Creates a pattern from a raw pattern string; throws DatabaseError on","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/init(matchingAnyTokenIn:)":{"name":"init(matchingAnyTokenIn:)","abstract":"Undocumented","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/init(matchingAllTokensIn:)":{"name":"init(matchingAllTokensIn:)","abstract":"Undocumented","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/init(matchingPhrase:)":{"name":"init(matchingPhrase:)","abstract":"Undocumented","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/s:FV4GRDB11FTS3PatterncFT18matchingAnyTokenInSS_GSqS0__":{"name":"init(matchingAnyTokenIn:)","abstract":"
Creates a pattern that matches any token found in the input string;","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/s:FV4GRDB11FTS3PatterncFT19matchingAllTokensInSS_GSqS0__":{"name":"init(matchingAllTokensIn:)","abstract":"
Creates a pattern that matches all tokens found in the input string;","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/s:FV4GRDB11FTS3PatterncFT14matchingPhraseSS_GSqS0__":{"name":"init(matchingPhrase:)","abstract":"
Creates a pattern that matches a contiguous string; returns nil if no","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/s:vV4GRDB11FTS3Pattern13databaseValueVS_13DatabaseValue":{"name":"databaseValue","abstract":"
Returns a value that can be stored in the database.
Returns an FTS3Pattern initialized from databaseValue, if it contains","parent_name":"FTS3Pattern"},"Structs/FTS3.html#/s:FV4GRDB4FTS3cFT_S0_":{"name":"init()","abstract":"
Creates a FTS3 module suitable for the Database","parent_name":"FTS3"},"Structs/FTS3.html#/s:vV4GRDB4FTS310moduleNameSS":{"name":"moduleName","abstract":"
This property is an implementation detail of the query interface.","parent_name":"DatabaseValue"},"Structs/DatabaseValue.html#/s:vV4GRDB13DatabaseValue11descriptionSS":{"name":"description","abstract":"
This function is an implementation detail of the query interface.","parent_name":"DatabaseValue"},"Structs/DatabaseValue.html#/s:vV4GRDB13DatabaseValue7negatedPS_13SQLExpression_":{"name":"negated","abstract":"
This property is an implementation detail of the query interface.","parent_name":"DatabaseValue"},"Structs/DatabaseMigrator.html#/s:FV4GRDB16DatabaseMigratorcFT_S0_":{"name":"init()","abstract":"
Iterate migrations in the same order as they were registered. If a","parent_name":"DatabaseMigrator"},"Structs/DatabaseError.html#/s:vV4GRDB13DatabaseError10resultCodeVS_10ResultCode":{"name":"resultCode","abstract":"
The SQLite error code (see","parent_name":"DatabaseError"},"Structs/DatabaseError.html#/s:vV4GRDB13DatabaseError18extendedResultCodeVS_10ResultCode":{"name":"extendedResultCode","abstract":"
The SQLite extended error code (see","parent_name":"DatabaseError"},"Structs/DatabaseError.html#/s:vV4GRDB13DatabaseError7messageGSqSS_":{"name":"message","abstract":"
A result code limited to the least significant 8 bits of the receiver.","parent_name":"ResultCode"},"Structs/ResultCode.html#/s:vPs23CustomStringConvertible11descriptionSS":{"name":"description","abstract":"
A result code limited to the least significant 8 bits of the receiver.","parent_name":"ResultCode"},"Structs/ResultCode.html#/s:ZFPs9Equatableoi2eeFTxx_Sb":{"name":"==(_:_:)","abstract":"
A result code limited to the least significant 8 bits of the receiver.","parent_name":"ResultCode"},"Structs/ResultCode.html#/s:ZFV4GRDB10ResultCodeoi2teFTS0_S0__Sb":{"name":"~=(_:_:)","abstract":"
Returns true if the code on the left matches the code on the right.
Returns a DatabaseDateComponents if databaseValue contains a","parent_name":"DatabaseDateComponents"},"Structs/DatabaseCoder.html#/s:vV4GRDB13DatabaseCoder6objectP_":{"name":"object","abstract":"
The maximum number of concurrent readers (applies to database","parent_name":"Configuration"},"Structs/Configuration.html#/s:FV4GRDB13ConfigurationcFT_S0_":{"name":"init()","abstract":"
DatabaseCoder reads and stores objects that conform to NSCoding in"},"Structs/DatabaseDateComponents.html":{"name":"DatabaseDateComponents","abstract":"
DatabaseDateComponents reads and stores DateComponents in the database.
SQLCollatedExpression taints an expression so that every derived expression"},"Structs/SQLExpressionLiteral.html":{"name":"SQLExpressionLiteral","abstract":"
This type is an implementation detail of the query interface."},"Structs/SQLUnaryOperator.html":{"name":"SQLUnaryOperator","abstract":"
This type is an implementation detail of the query interface."},"Structs/SQLExpressionUnary.html":{"name":"SQLExpressionUnary","abstract":"
This type is an implementation detail of the query interface."},"Structs/SQLBinaryOperator.html":{"name":"SQLBinaryOperator","abstract":"
This type is an implementation detail of the query interface."},"Structs/SQLExpressionBinary.html":{"name":"SQLExpressionBinary","abstract":"
This type is an implementation detail of the query interface."},"Structs/SQLExpressionExists.html":{"name":"SQLExpressionExists","abstract":"
This type is an implementation detail of the query interface."},"Structs/SQLFunctionName.html":{"name":"SQLFunctionName","abstract":"
This type is an implementation detail of the query interface."},"Structs/SQLExpressionFunction.html":{"name":"SQLExpressionFunction","abstract":"
This type is an implementation detail of the query interface."},"Structs/StatementArguments.html":{"name":"StatementArguments","abstract":"
StatementArguments provide values to argument placeholders in raw"},"Protocols/VirtualTableModule.html#/s:vP4GRDB18VirtualTableModule10moduleNameSS":{"name":"moduleName","abstract":"
The type of the closure argument in the","parent_name":"VirtualTableModule"},"Protocols/VirtualTableModule.html#/s:FP4GRDB18VirtualTableModule19makeTableDefinitionFT_wx15TableDefinition":{"name":"makeTableDefinition()","abstract":"
Returns a table definition that is passed as the closure argument in the","parent_name":"VirtualTableModule"},"Protocols/VirtualTableModule.html#/s:FP4GRDB18VirtualTableModule15moduleArgumentsFzT3forwx15TableDefinition2inCS_8Database_GSaSS_":{"name":"moduleArguments(for:in:)","abstract":"
Returns the module arguments for the CREATE VIRTUAL TABLE query.
Execute any relevant database statement after the virtual table has","parent_name":"VirtualTableModule"},"Protocols/StatementColumnConvertible.html#/s:FP4GRDB26StatementColumnConvertiblecFT15sqliteStatementVs13OpaquePointer5indexVs5Int32_x":{"name":"init(sqliteStatement:index:)","abstract":"
Returns a value initialized from a raw SQLite statement pointer.
This function is an implementation detail of the query interface.","parent_name":"SQLSelectQuery"},"Protocols/SQLSelectQuery.html#/s:FE4GRDBPS_14SQLSelectQuery6existsFT_PS_13SQLExpression_":{"name":"exists()","abstract":"
Returns an SQL expression that checks whether the receiver, as a","parent_name":"SQLSelectQuery"},"Protocols/SQLSelectQuery.html#/s:FE4GRDBPS_14SQLSelectQuery13collectionSQLFRGSqVS_18StatementArguments_SS":{"name":"collectionSQL(_:)","abstract":"
This function is an implementation detail of the query interface.","parent_name":"SQLSelectQuery"},"Protocols/SQLSelectQuery.html#/s:FE4GRDBPS_14SQLSelectQuery7prepareFzCS_8DatabaseTCS_15SelectStatementGSqPS_10RowAdapter___":{"name":"prepare(_:)","abstract":"
A tuple that contains a prepared statement that is ready to be","parent_name":"SQLSelectQuery"},"Protocols/SQLSelectable.html#/s:FP4GRDB13SQLSelectable15resultColumnSQLFRGSqVS_18StatementArguments_SS":{"name":"resultColumnSQL(_:)","abstract":"Undocumented","parent_name":"SQLSelectable"},"Protocols/SQLSelectable.html#/s:FP4GRDB13SQLSelectable10countedSQLFRGSqVS_18StatementArguments_SS":{"name":"countedSQL(_:)","abstract":"Undocumented","parent_name":"SQLSelectable"},"Protocols/SQLSelectable.html#/s:FP4GRDB13SQLSelectable18countingSelectableFT8distinctSb4fromSS7aliasedGSqSS__GSqPS0___":{"name":"countingSelectable(distinct:from:aliased:)","abstract":"Undocumented","parent_name":"SQLSelectable"},"Protocols/SQLOrderingTerm.html#/s:vP4GRDB15SQLOrderingTerm8reversedPS0__":{"name":"reversed","abstract":"Undocumented","parent_name":"SQLOrderingTerm"},"Protocols/SQLOrderingTerm.html#/s:FP4GRDB15SQLOrderingTerm15orderingTermSQLFRGSqVS_18StatementArguments_SS":{"name":"orderingTermSQL(_:)","abstract":"Undocumented","parent_name":"SQLOrderingTerm"},"Protocols/SQLSpecificExpressible.html#/s:vE4GRDBPS_22SQLSpecificExpressible11capitalizedPS_13SQLExpression_":{"name":"capitalized","abstract":"
Returns an SQL expression that applies the Swift’s built-in","parent_name":"SQLSpecificExpressible"},"Protocols/SQLSpecificExpressible.html#/s:vE4GRDBPS_22SQLSpecificExpressible10lowercasedPS_13SQLExpression_":{"name":"lowercased","abstract":"
Returns an SQL expression that applies the Swift’s built-in","parent_name":"SQLSpecificExpressible"},"Protocols/SQLSpecificExpressible.html#/s:vE4GRDBPS_22SQLSpecificExpressible10uppercasedPS_13SQLExpression_":{"name":"uppercased","abstract":"
Returns an SQL expression that applies the Swift’s built-in","parent_name":"SQLSpecificExpressible"},"Protocols/SQLSpecificExpressible.html#/s:vE4GRDBPS_22SQLSpecificExpressible20localizedCapitalizedPS_13SQLExpression_":{"name":"localizedCapitalized","abstract":"
Returns an SQL expression that applies the Swift’s built-in","parent_name":"SQLSpecificExpressible"},"Protocols/SQLSpecificExpressible.html#/s:vE4GRDBPS_22SQLSpecificExpressible19localizedLowercasedPS_13SQLExpression_":{"name":"localizedLowercased","abstract":"
Returns an SQL expression that applies the Swift’s built-in","parent_name":"SQLSpecificExpressible"},"Protocols/SQLSpecificExpressible.html#/s:vE4GRDBPS_22SQLSpecificExpressible19localizedUppercasedPS_13SQLExpression_":{"name":"localizedUppercased","abstract":"
Returns an SQL expression that applies the Swift’s built-in","parent_name":"SQLSpecificExpressible"},"Protocols/SQLSpecificExpressible.html#/s:FE4GRDBPS_22SQLSpecificExpressible4likeFPS_14SQLExpressible_PS_13SQLExpression_":{"name":"like(_:)","abstract":"
This method is an implementation detail of the query interface.","parent_name":"SQLSpecificExpressible"},"Protocols/SQLSpecificExpressible.html#/s:FE4GRDBPS_22SQLSpecificExpressible9collatingFCS_17DatabaseCollationVS_21SQLCollatedExpression":{"name":"collating(_:)","abstract":"
This method is an implementation detail of the query interface.","parent_name":"SQLSpecificExpressible"},"Protocols/SQLExpression.html#/s:FP4GRDB13SQLExpression13expressionSQLFRGSqVS_18StatementArguments_SS":{"name":"expressionSQL(_:)","abstract":"
This function is an implementation detail of the query interface.","parent_name":"SQLExpression"},"Protocols/SQLExpression.html#/s:vP4GRDB13SQLExpression7negatedPS0__":{"name":"negated","abstract":"
This property is an implementation detail of the query interface.","parent_name":"SQLExpression"},"Protocols/SQLExpression.html#/s:vE4GRDBPS_13SQLExpression7literalVS_20SQLExpressionLiteral":{"name":"literal","abstract":"
This property is an implementation detail of the query interface.","parent_name":"SQLExpression"},"Protocols/SQLExpression.html#/s:vE4GRDBPS_13SQLExpression13sqlExpressionPS0__":{"name":"sqlExpression","abstract":"
This property is an implementation detail of the query interface.","parent_name":"SQLExpression"},"Protocols/SQLExpression.html#/s:FE4GRDBPS_13SQLExpression18countingSelectableFT8distinctSb4fromSS7aliasedGSqSS__GSqPS_13SQLSelectable__":{"name":"countingSelectable(distinct:from:aliased:)","abstract":"
This function is an implementation detail of the query interface.","parent_name":"SQLExpression"},"Protocols/SQLCollection.html#/s:FP4GRDB13SQLCollection13collectionSQLFRGSqVS_18StatementArguments_SS":{"name":"collectionSQL(_:)","abstract":"
This function is an implementation detail of the query interface.","parent_name":"SQLCollection"},"Protocols/SQLCollection.html#/s:FP4GRDB13SQLCollection8containsFPS_14SQLExpressible_PS_13SQLExpression_":{"name":"contains(_:)","abstract":"
Returns an expression that check whether the collection contains","parent_name":"SQLCollection"},"Protocols/RowConvertible.html#/s:FP4GRDB14RowConvertiblecFT3rowCS_3Row_x":{"name":"init(row:)","abstract":"
Returns a cursor over records identified by the provided unique keys","parent_name":"RowConvertible"},"Protocols/RowConvertible.html#/s:ZFe4GRDBRxS_14RowConvertiblexS_12TableMappingrS0_8fetchAllFzTCS_8Database4keysGSaGVs10DictionarySSGSqPS_24DatabaseValueConvertible_____GSax_":{"name":"fetchAll(_:keys:)","abstract":"
Returns an array of records identified by the provided unique keys","parent_name":"RowConvertible"},"Protocols/RowConvertible.html#/s:ZFe4GRDBRxS_14RowConvertiblexS_12TableMappingrS0_8fetchOneFzTCS_8Database3keyGVs10DictionarySSGSqPS_24DatabaseValueConvertible____GSqx_":{"name":"fetchOne(_:key:)","abstract":"
Returns a single record identified by a unique key (the primary key or","parent_name":"RowConvertible"},"Protocols/RowAdapter.html#/s:FP4GRDB10RowAdapter15layoutedAdapterFzT4fromPS_9RowLayout__PS_18LayoutedRowAdapter_":{"name":"layoutedAdapter(from:)","abstract":"
You never call this method directly. It is called for you whenever an","parent_name":"RowAdapter"},"Protocols/RowAdapter.html#/s:FE4GRDBPS_10RowAdapter12addingScopesFGVs10DictionarySSPS0___PS0__":{"name":"addingScopes(_:)","abstract":"
Returns an adapter based on self, with added scopes.
An array of (baseIndex, name) pairs, where baseIndex is the index","parent_name":"RowLayout"},"Protocols/RowLayout.html#/s:FP4GRDB9RowLayout11layoutIndexFT8ofColumnSS_GSqSi_":{"name":"layoutIndex(ofColumn:)","abstract":"
Returns the index of the leftmost column named name, in a","parent_name":"RowLayout"},"Protocols/LayoutedRowAdapter.html#/s:vP4GRDB18LayoutedRowAdapter7mappingVS_21LayoutedColumnMapping":{"name":"mapping","abstract":"
A LayoutedColumnMapping that defines how to map a column name to a","parent_name":"LayoutedRowAdapter"},"Protocols/LayoutedRowAdapter.html#/s:vP4GRDB18LayoutedRowAdapter6scopesGVs10DictionarySSPS0___":{"name":"scopes","abstract":"
A tuple that contains a prepared statement that is ready to be","parent_name":"Request"},"Protocols/Request.html#/s:FP4GRDB7Request10fetchCountFzCS_8DatabaseSi":{"name":"fetchCount(_:)","abstract":"
Executes an INSERT or an UPDATE statement so that self is saved in","parent_name":"Persistable"},"Protocols/Persistable.html#/s:FE4GRDBPS_11Persistable13performInsertFzCS_8DatabaseT_":{"name":"performInsert(_:)","abstract":"
Don’t invoke this method directly: it is an internal method for types","parent_name":"Persistable"},"Protocols/Persistable.html#/s:FE4GRDBPS_11Persistable11performSaveFzCS_8DatabaseT_":{"name":"performSave(_:)","abstract":"
Don’t invoke this method directly: it is an internal method for types","parent_name":"Persistable"},"Protocols/MutablePersistable.html#/s:ZvP4GRDB18MutablePersistable25persistenceConflictPolicyVS_25PersistenceConflictPolicy":{"name":"persistenceConflictPolicy","abstract":"
The policy that handles SQLite conflicts when records are inserted","parent_name":"MutablePersistable"},"Protocols/MutablePersistable.html#/s:vP4GRDB18MutablePersistable20persistentDictionaryGVs10DictionarySSGSqPS_24DatabaseValueConvertible___":{"name":"persistentDictionary","abstract":"
Returns the values that should be stored in the database.
Executes an INSERT or an UPDATE statement so that self is saved in","parent_name":"MutablePersistable"},"Protocols/MutablePersistable.html#/s:FP4GRDB18MutablePersistable6deleteFzCS_8DatabaseSb":{"name":"delete(_:)","abstract":"
Returns true if and only if the primary key matches a row in","parent_name":"MutablePersistable"},"Protocols/MutablePersistable.html#/s:FE4GRDBPS_18MutablePersistable6updateFzCS_8DatabaseT_":{"name":"update(_:)","abstract":"
Executes an UPDATE statement that updates all table columns.
Don’t invoke this method directly: it is an internal method for types","parent_name":"MutablePersistable"},"Protocols/MutablePersistable.html#/s:FE4GRDBPS_18MutablePersistable13performUpdateFzTCS_8Database7columnsGVs3SetSS__T_":{"name":"performUpdate(_:columns:)","abstract":"
Don’t invoke this method directly: it is an internal method for types","parent_name":"MutablePersistable"},"Protocols/MutablePersistable.html#/s:FE4GRDBPS_18MutablePersistable11performSaveFzCS_8DatabaseT_":{"name":"performSave(_:)","abstract":"
Don’t invoke this method directly: it is an internal method for types","parent_name":"MutablePersistable"},"Protocols/MutablePersistable.html#/s:FE4GRDBPS_18MutablePersistable13performDeleteFzCS_8DatabaseSb":{"name":"performDelete(_:)","abstract":"
Don’t invoke this method directly: it is an internal method for types","parent_name":"MutablePersistable"},"Protocols/MutablePersistable.html#/s:FE4GRDBPS_18MutablePersistable13performExistsFzCS_8DatabaseSb":{"name":"performExists(_:)","abstract":"
Don’t invoke this method directly: it is an internal method for types","parent_name":"MutablePersistable"},"Protocols/FTS5WrapperTokenizer.html#/wrappedTokenizer":{"name":"wrappedTokenizer","abstract":"Undocumented","parent_name":"FTS5WrapperTokenizer"},"Protocols/FTS5WrapperTokenizer.html#/accept(token:flags:for:tokenCallback:)":{"name":"accept(token:flags:for:tokenCallback:)","abstract":"Undocumented","parent_name":"FTS5WrapperTokenizer"},"Protocols/FTS5WrapperTokenizer.html#/tokenize(context:tokenization:pText:nText:tokenCallback:)":{"name":"tokenize(context:tokenization:pText:nText:tokenCallback:)","abstract":"Undocumented","parent_name":"FTS5WrapperTokenizer"},"Protocols/FTS5Tokenizer.html#/tokenize(context:tokenization:pText:nText:tokenCallback:)":{"name":"tokenize(context:tokenization:pText:nText:tokenCallback:)","abstract":"Undocumented","parent_name":"FTS5Tokenizer"},"Protocols/FTS5CustomTokenizer.html#/name":{"name":"name","abstract":"Undocumented","parent_name":"FTS5CustomTokenizer"},"Protocols/FTS5CustomTokenizer.html#/init(db:arguments:)":{"name":"init(db:arguments:)","abstract":"Undocumented","parent_name":"FTS5CustomTokenizer"},"Protocols/FTS5CustomTokenizer.html#/tokenizerDescriptor(arguments:)":{"name":"tokenizerDescriptor(arguments:)","abstract":"Undocumented","parent_name":"FTS5CustomTokenizer"},"Protocols/TableMapping.html#/s:ZvP4GRDB12TableMapping17databaseTableNameSS":{"name":"databaseTableName","abstract":"
This flag tells whether the hidden rowid column should be fetched","parent_name":"TableMapping"},"Protocols/TableMapping.html#/s:ZFE4GRDBPS_12TableMapping8matchingFGSqVS_11FTS3Pattern_GVS_21QueryInterfaceRequestx_":{"name":"matching(_:)","abstract":"
Returns a QueryInterfaceRequest with a matching predicate.
Creates a QueryInterfaceRequest sorted according to the","parent_name":"TableMapping"},"Protocols/TableMapping.html#/s:ZFE4GRDBPS_12TableMapping5orderFGSaPS_15SQLOrderingTerm__GVS_21QueryInterfaceRequestx_":{"name":"order(_:)","abstract":"
Creates a QueryInterfaceRequest sorted according to the","parent_name":"TableMapping"},"Protocols/TableMapping.html#/s:ZFE4GRDBPS_12TableMapping5orderFT3sqlSS9argumentsGSqVS_18StatementArguments__GVS_21QueryInterfaceRequestx_":{"name":"order(sql:arguments:)","abstract":"
Creates a QueryInterfaceRequest sorted according to sql.
Creates a QueryInterfaceRequest which fetches limit rows, starting at","parent_name":"TableMapping"},"Protocols/TableMapping.html#/s:ZFE4GRDBPS_12TableMapping10fetchCountFzCS_8DatabaseSi":{"name":"fetchCount(_:)","abstract":"
Delete records identified by their primary keys; returns the number of","parent_name":"TableMapping"},"Protocols/TableMapping.html#/s:ZFE4GRDBPS_12TableMapping9deleteOneuRd__S_24DatabaseValueConvertiblerFzTCS_8Database3keyGSqqd____Sb":{"name":"deleteOne(_:key:)","abstract":"
Delete a record, identified by its primary key; returns whether a","parent_name":"TableMapping"},"Protocols/TableMapping.html#/s:ZFE4GRDBPS_12TableMapping9deleteAllFzTCS_8Database4keysGSaGVs10DictionarySSGSqPS_24DatabaseValueConvertible_____Si":{"name":"deleteAll(_:keys:)","abstract":"
Delete records identified by the provided unique keys (primary key or","parent_name":"TableMapping"},"Protocols/TableMapping.html#/s:ZFE4GRDBPS_12TableMapping9deleteOneFzTCS_8Database3keyGVs10DictionarySSGSqPS_24DatabaseValueConvertible____Sb":{"name":"deleteOne(_:key:)","abstract":"
Delete a record, identified by a unique key (the primary key or any key","parent_name":"TableMapping"},"Protocols/DatabaseWriter.html#/s:FP4GRDB14DatabaseWriter5writeurFzFzCS_8Databaseqd__qd__":{"name":"write(_:)","abstract":"
Synchronously executes a block that takes a database connection, and","parent_name":"DatabaseWriter"},"Protocols/DatabaseWriter.html#/s:FP4GRDB14DatabaseWriter20readFromCurrentStateFzFCS_8DatabaseT_T_":{"name":"readFromCurrentState(_:)","abstract":"
Synchronously or asynchronously executes a read-only block that takes a","parent_name":"DatabaseWriter"},"Protocols/DatabaseWriter.html#/s:FE4GRDBPS_14DatabaseWriter3addFT19transactionObserverPS_19TransactionObserver__T_":{"name":"add(transactionObserver:)","abstract":"
Add a transaction observer, so that it gets notified of","parent_name":"DatabaseWriter"},"Protocols/DatabaseWriter.html#/s:FE4GRDBPS_14DatabaseWriter6removeFT19transactionObserverPS_19TransactionObserver__T_":{"name":"remove(transactionObserver:)","abstract":"
This property is an implementation detail of the query interface.","parent_name":"DatabaseValueConvertible"},"Protocols/DatabaseValueConvertible.html#/s:ZFE4GRDBPS_24DatabaseValueConvertible11fetchCursorFzTCS_15SelectStatement9argumentsGSqVS_18StatementArguments_7adapterGSqPS_10RowAdapter___GCS_14DatabaseCursorx_":{"name":"fetchCursor(_:arguments:adapter:)","abstract":"
Returns a cursor over values fetched from a prepared statement.
This property is an implementation detail of the query interface.","parent_name":"SQLExpressible"},"Protocols/SQLExpressible.html#/s:Fe4GRDBRxS_14SQLExpressiblexS_15SQLOrderingTermrS0_15orderingTermSQLFRGSqVS_18StatementArguments_SS":{"name":"orderingTermSQL(_:)","abstract":"
This method is an implementation detail of the query interface.","parent_name":"SQLExpressible"},"Protocols/SQLExpressible.html#/s:Fe4GRDBRxS_14SQLExpressiblexS_13SQLSelectablerS0_15resultColumnSQLFRGSqVS_18StatementArguments_SS":{"name":"resultColumnSQL(_:)","abstract":"
This method is an implementation detail of the query interface.","parent_name":"SQLExpressible"},"Protocols/SQLExpressible.html#/s:Fe4GRDBRxS_14SQLExpressiblexS_13SQLSelectablerS0_10countedSQLFRGSqVS_18StatementArguments_SS":{"name":"countedSQL(_:)","abstract":"
This method is an implementation detail of the query interface.","parent_name":"SQLExpressible"},"Protocols/SQLExpressible.html#/s:Fe4GRDBRxS_14SQLExpressiblexS_13SQLSelectablerS0_18countingSelectableFT8distinctSb4fromSS7aliasedGSqSS__GSqPS1___":{"name":"countingSelectable(distinct:from:aliased:)","abstract":"
This method is an implementation detail of the query interface.","parent_name":"SQLExpressible"},"Protocols/DatabaseReader.html#/s:FP4GRDB14DatabaseReader4readurFzFzCS_8Databaseqd__qd__":{"name":"read(_:)","abstract":"
Synchronously executes a read-only block that takes a database","parent_name":"DatabaseReader"},"Protocols/DatabaseReader.html#/s:FP4GRDB14DatabaseReader10unsafeReadurFzFzCS_8Databaseqd__qd__":{"name":"unsafeRead(_:)","abstract":"
Synchronously executes a read-only block that takes a database","parent_name":"DatabaseReader"},"Protocols/DatabaseReader.html#/s:FP4GRDB14DatabaseReader3addFT8functionCS_16DatabaseFunction_T_":{"name":"add(function:)","abstract":"
Filters database changes that should be notified the the","parent_name":"TransactionObserver"},"Protocols/TransactionObserver.html#/s:FP4GRDB19TransactionObserver17databaseDidChangeFT4withVS_13DatabaseEvent_T_":{"name":"databaseDidChange(with:)","abstract":"
Notifies a database change (insert, update, or delete).
When a transaction is about to be committed, the transaction observer","parent_name":"TransactionObserver"},"Protocols/TransactionObserver.html#/s:FP4GRDB19TransactionObserver17databaseDidCommitFCS_8DatabaseT_":{"name":"databaseDidCommit(_:)","abstract":"
Advances to the next element and returns it, or nil if no next element","parent_name":"Cursor"},"Protocols/Cursor.html#/s:P4GRDB6Cursor7Element":{"name":"Element","abstract":"
Returns a Boolean value indicating whether the cursor contains an","parent_name":"Cursor"},"Protocols/Cursor.html#/s:FE4GRDBPS_6Cursor10enumeratedFT_GCS_16EnumeratedCursorx_":{"name":"enumerated()","abstract":"
Returns a cursor of pairs (n, x), where n represents a consecutive","parent_name":"Cursor"},"Protocols/Cursor.html#/s:FE4GRDBPS_6Cursor6filterFFzwx7ElementSbGCS_12FilterCursorx_":{"name":"filter(_:)","abstract":"
Returns the elements of the cursor that satisfy the given predicate.
Returns the first element of the cursor that satisfies the given","parent_name":"Cursor"},"Protocols/Cursor.html#/s:FE4GRDBPS_6Cursor7flatMapurFFzwx7ElementGSqqd___GCS_9MapCursorGCS_12FilterCursorGS2_xGSqqd_____qd___":{"name":"flatMap(_:)","abstract":"
Returns a cursor over the concatenated non-nil results of mapping","parent_name":"Cursor"},"Protocols/Cursor.html#/s:FE4GRDBPS_6Cursor7flatMapuRd__s8SequencerFFzwx7Elementqd__GCS_13FlattenCursorGCS_9MapCursorxGCS_14IteratorCursorwd__8Iterator___":{"name":"flatMap(_:)","abstract":"
Returns a cursor over the concatenated results of mapping transform","parent_name":"Cursor"},"Protocols/Cursor.html#/s:FE4GRDBPS_6Cursor7flatMapuRd__S0_rFFzwx7Elementqd__GCS_13FlattenCursorGCS_9MapCursorxqd____":{"name":"flatMap(_:)","abstract":"
Returns a cursor over the concatenated results of mapping transform","parent_name":"Cursor"},"Protocols/Cursor.html#/s:FE4GRDBPS_6Cursor7forEachFzFzwx7ElementT_T_":{"name":"forEach(_:)","abstract":"
Calls the given closure on each element in the cursor.
Returns a cursor over the results of the transform function applied to","parent_name":"Cursor"},"Protocols/Cursor.html#/s:FE4GRDBPS_6Cursor6reduceurFzTqd__FzTqd__wx7Element_qd___qd__":{"name":"reduce(_:_:)","abstract":"
Returns the result of calling the given combining closure with each","parent_name":"Cursor"},"Protocols/Cursor.html#/s:Fe4GRDBRxS_6Cursorwx7Elements9EquatablerS0_8containsFzwxS1_Sb":{"name":"contains(_:)","abstract":"
Returns a Boolean value indicating whether the cursor contains the","parent_name":"Cursor"},"Protocols/Cursor.html#/s:Fe4GRDBRxS_6Cursorwx7ElementS0_rS0_6joinedFT_GCS_13FlattenCursorx_":{"name":"joined()","abstract":"
Returns the elements of this cursor of cursors, concatenated.
Types that adopt TableMapping declare a particular relationship with"},"Protocols/FTS5CustomTokenizer.html":{"name":"FTS5CustomTokenizer","abstract":"Undocumented"},"Protocols/FTS5Tokenizer.html":{"name":"FTS5Tokenizer","abstract":"Undocumented"},"Protocols/FTS5WrapperTokenizer.html":{"name":"FTS5WrapperTokenizer","abstract":"Undocumented"},"Protocols/MutablePersistable.html":{"name":"MutablePersistable","abstract":"
Types that adopt MutablePersistable can be inserted, updated, and deleted.
The protocol for all types that define a way to fetch values from"},"Protocols/TypedRequest.html":{"name":"TypedRequest","abstract":"
The protocol for all types that define a way to fetch values from"},"Protocols.html#/s:P4GRDB18_OptionalFetchable":{"name":"_OptionalFetchable","abstract":"
This protocol is an implementation detail of GRDB. Don’t use it.
This protocol is an implementation detail of the query interface."},"Protocols/SQLExpression.html":{"name":"SQLExpression","abstract":"
This protocol is an implementation detail of the query interface."},"Protocols/SQLSpecificExpressible.html":{"name":"SQLSpecificExpressible","abstract":"
This protocol is an implementation detail of the query interface."},"Protocols/SQLOrderingTerm.html":{"name":"SQLOrderingTerm","abstract":"
This protocol is an implementation detail of the query interface."},"Protocols/SQLSelectable.html":{"name":"SQLSelectable","abstract":"
This protocol is an implementation detail of the query interface."},"Protocols/SQLSelectQuery.html":{"name":"SQLSelectQuery","abstract":"
This protocol is an implementation detail of the query interface."},"Protocols/StatementColumnConvertible.html":{"name":"StatementColumnConvertible","abstract":"
When a type adopts both DatabaseValueConvertible and"},"Protocols/VirtualTableModule.html":{"name":"VirtualTableModule","abstract":"
The protocol for SQLite virtual table modules. It lets you define a DSL for"},"Functions.html#/s:F4GRDB3absFPS_22SQLSpecificExpressible_PS_13SQLExpression_":{"name":"abs(_:)","abstract":"
Returns an expression that evaluates the ABS SQL function.
Returns a value that can be stored in the database.","parent_name":"NSURL"},"Extensions/NSURL.html#/s:ZFE4GRDBCSo5NSURL17fromDatabaseValueFVS_13DatabaseValueGSqDS0__":{"name":"fromDatabaseValue(_:)","abstract":"
Returns an NSURL initialized from databaseValue, if possible.
Returns the receiver, quoted for safe insertion as an identifier in an","parent_name":"String"},"Extensions/Float.html#/s:FE4GRDBSfcFT15sqliteStatementVs13OpaquePointer5indexVs5Int32_Sf":{"name":"init(sqliteStatement:index:)","abstract":"
Returns a value initialized from a raw SQLite statement pointer.
Returns an NSData initialized from databaseValue, if it contains","parent_name":"NSData"},"Extensions/TableMapping.html#/matching(_:)":{"name":"matching(_:)","abstract":"Undocumented","parent_name":"TableMapping"},"Extensions/QueryInterfaceRequest.html#/matching(_:)":{"name":"matching(_:)","abstract":"Undocumented","parent_name":"QueryInterfaceRequest"},"Extensions/Database.html#/add(tokenizer:)":{"name":"add(tokenizer:)","abstract":"Undocumented","parent_name":"Database"},"Extensions/Database.html#/makeFTS5Pattern(rawPattern:forTable:)":{"name":"makeFTS5Pattern(rawPattern:forTable:)","abstract":"Undocumented","parent_name":"Database"},"Extensions/Database.html#/makeTokenizer(_:)":{"name":"makeTokenizer(_:)","abstract":"Undocumented","parent_name":"Database"},"Extensions/Column.html#/rank":{"name":"rank","abstract":"Undocumented","parent_name":"Column"},"Extensions/NSDate.html#/s:vE4GRDBCSo6NSDate13databaseValueVS_13DatabaseValue":{"name":"databaseValue","abstract":"
Returns a value that can be stored in the database.
Returns a Data initialized from databaseValue, if it contains","parent_name":"Data"},"Extensions/Sequence.html#/s:FE4GRDBPs8Sequence7flatMapuRd__S_6CursorrFFzWx8Iterator7Element_qd__GCS_13FlattenCursorGCS_9MapCursorGCS_14IteratorCursorwxS2__qd____":{"name":"flatMap(_:)","abstract":"
Returns a cursor over the concatenated results of mapping transform","parent_name":"Sequence"},"Extensions/Sequence.html#/s:Fe4GRDBRxs8SequenceWx8Iterator7Element_S_14SQLExpressiblerS0_8containsFPS_22SQLSpecificExpressible_PS_13SQLExpression_":{"name":"contains(_:)","abstract":"
An SQL expression that checks the inclusion of an expression in","parent_name":"Sequence"},"Extensions/Sequence.html#/s:Fe4GRDBRxs8SequenceWx8Iterator7Element_S_14SQLExpressiblerS0_8containsFVS_21SQLCollatedExpressionPS_13SQLExpression_":{"name":"contains(_:)","abstract":"
An SQL expression that checks the inclusion of an expression in","parent_name":"Sequence"},"Extensions/Array.html#/s:FE4GRDBSacuRd__S_6Cursorxzwd__7ElementrFzqd__GSax_":{"name":"init(_:)","abstract":"
Creates an array containing the elements of a cursor.
Thrown by MutablePersistable.update() when no matching row could be","parent_name":"PersistenceError"},"Enums/PersistenceError.html#/s:vO4GRDB16PersistenceError11descriptionSS":{"name":"description","abstract":"
A move event, from indexPath to newIndexPath. The changes are a","parent_name":"FetchedRecordChange"},"Enums/FetchedRecordChange.html#/s:FO4GRDB19FetchedRecordChange6updateFMS0_FT9indexPathV10Foundation9IndexPath7changesGVs10DictionarySSVS_13DatabaseValue__S0_":{"name":"update","abstract":"
An update event, at given indexPath. The changes are a dictionary","parent_name":"FetchedRecordChange"},"Enums/FetchedRecordChange.html#/s:vO4GRDB19FetchedRecordChange11descriptionSS":{"name":"description","abstract":"
Advances to the next element and returns it, or nil if no next element","parent_name":"DatabaseCursor"},"Classes/Statement.html#/s:vC4GRDB9Statement15sqliteStatementVs13OpaquePointer":{"name":"sqliteStatement","abstract":"
The raw SQLite statement, suitable for the SQLite C API.
Throws a DatabaseError of code SQLITE_ERROR if arguments don’t fill all","parent_name":"Statement"},"Classes/Statement.html#/s:FC4GRDB9Statement18unsafeSetArgumentsFVS_18StatementArgumentsT_":{"name":"unsafeSetArguments(_:)","abstract":"
Set arguments without any validation. Trades safety for performance.
Returns Int64, Double, String, Data or nil, depending on the value","parent_name":"Row"},"Classes/Row.html#/s:FC4GRDB3Row5valueuRxS_24DatabaseValueConvertiblerFT7atIndexSi_GSqx_":{"name":"value(atIndex:)","abstract":"
Returns the value at given index, converted to the requested type.
Returns Int64, Double, String, Data or nil, depending on the value","parent_name":"Row"},"Classes/Row.html#/s:FC4GRDB3Row5valueuRxS_24DatabaseValueConvertiblerFT5namedSS_GSqx_":{"name":"value(named:)","abstract":"
Returns the value at given column, converted to the requested type.
Returns Int64, Double, String, NSData or nil, depending on the value","parent_name":"Row"},"Classes/Row.html#/s:FC4GRDB3Row5valueuRxS_24DatabaseValueConvertiblerFVS_6ColumnGSqx_":{"name":"value(_:)","abstract":"
Returns the value at given column, converted to the requested type.
Returns a scoped row, if the row was fetched along with a row adapter","parent_name":"Row"},"Classes/Row.html#/s:ZFC4GRDB3Row11fetchCursorFzTCS_15SelectStatement9argumentsGSqVS_18StatementArguments_7adapterGSqPS_10RowAdapter___GCS_14DatabaseCursorS0__":{"name":"fetchCursor(_:arguments:adapter:)","abstract":"
Returns a cursor over rows fetched from a prepared statement.
Creates a row initialized with elements. Column order is preserved, and","parent_name":"Row"},"Classes/Row.html#/s:iC4GRDB3Row9subscriptFVS_8RowIndexTSSVS_13DatabaseValue_":{"name":"subscript(_:)","abstract":"
Accesses the (ColumnName, DatabaseValue) pair at given index.
The past-the-end index, successor of the index of the last","parent_name":"Row"},"Classes/Row.html#/s:FC4GRDB3Row5indexFT5afterVS_8RowIndex_S1_":{"name":"index(after:)","abstract":"
Returns true if and only if both rows have the same columns and values,","parent_name":"Row"},"Classes/Row.html#/s:vC4GRDB3Row9hashValueSi":{"name":"hashValue","abstract":"
The policy that handles SQLite conflicts when records are inserted","parent_name":"Record"},"Classes/Record.html#/s:ZvC4GRDB6Record12selectsRowIDSb":{"name":"selectsRowID","abstract":"
This flag tells whether the hidden rowid column should be fetched","parent_name":"Record"},"Classes/Record.html#/s:vC4GRDB6Record20persistentDictionaryGVs10DictionarySSGSqPS_24DatabaseValueConvertible___":{"name":"persistentDictionary","abstract":"
Returns a copy of self, initialized from the values of","parent_name":"Record"},"Classes/Record.html#/s:vC4GRDB6Record26hasPersistentChangedValuesSb":{"name":"hasPersistentChangedValues","abstract":"
A boolean that indicates whether the record has changes that have not","parent_name":"Record"},"Classes/Record.html#/s:vC4GRDB6Record23persistentChangedValuesGVs10DictionarySSGSqVS_13DatabaseValue__":{"name":"persistentChangedValues","abstract":"
Executes an INSERT or an UPDATE statement so that self is saved in","parent_name":"Record"},"Classes/Record.html#/s:FC4GRDB6Record6deleteFzCS_8DatabaseSb":{"name":"delete(_:)","abstract":"
Synchronizes the full-text table with the content of an external","parent_name":"FTS4TableDefinition"},"Classes/FTS3TableDefinition.html#/s:vC4GRDB19FTS3TableDefinition9tokenizerGSqVS_23FTS3TokenizerDescriptor_":{"name":"tokenizer","abstract":"
Creates a fetched records controller initialized from a SQL query and","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:FC4GRDB24FetchedRecordsControllercuRd__S_12TypedRequestxzwd__7FetchedrFzTPS_14DatabaseWriter_7requestqd__5queueCSo13DispatchQueue12isSameRecordGSqFTxx_Sb__GS0_x_":{"name":"init(_:request:queue:isSameRecord:)","abstract":"
Creates a fetched records controller initialized from a fetch request","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:FC4GRDB24FetchedRecordsController12performFetchFzT_T_":{"name":"performFetch()","abstract":"
Updates the fetch request, and eventually notifies the tracking","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:FC4GRDB24FetchedRecordsController10setRequestFzT3sqlSS9argumentsGSqVS_18StatementArguments_7adapterGSqPS_10RowAdapter___T_":{"name":"setRequest(sql:arguments:adapter:)","abstract":"
Updates the fetch request, and eventually notifies the tracking","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:FC4GRDB24FetchedRecordsController12trackChangesFT10willChangeGSqFGS0_x_T__8onChangeGSqFTGS0_x_xOS_19FetchedRecordChange_T__9didChangeGSqFGS0_x_T___T_":{"name":"trackChanges(willChange:onChange:didChange:)","abstract":"
Call this method when changes performed while the application is","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:vC4GRDB24FetchedRecordsController14fetchedRecordsGSax_":{"name":"fetchedRecords","abstract":"
Creates a fetched records controller initialized from a SQL query and","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:Fe4GRDBRxS_14RowConvertiblexS_12TableMappingrCS_24FetchedRecordsControllercuRd__S_12TypedRequestxzwd__7FetchedrFzTPS_14DatabaseWriter_7requestqd__5queueCSo13DispatchQueue_GS2_x_":{"name":"init(_:request:queue:)","abstract":"
Creates a fetched records controller initialized from a fetch request","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:FC4GRDB24FetchedRecordsController6recordFT2atV10Foundation9IndexPath_x":{"name":"record(at:)","abstract":"
Synchronously executes a block in a protected dispatch queue, and","parent_name":"DatabaseQueue"},"Classes/DatabaseQueue.html#/s:FC4GRDB13DatabaseQueue13inTransactionFzTGSqOCS_8Database15TransactionKind_FzS1_OS1_21TransactionCompletion_T_":{"name":"inTransaction(_:_:)","abstract":"
Synchronously executes a block in a protected dispatch queue, wrapped","parent_name":"DatabaseQueue"},"Classes/DatabaseQueue.html#/s:FC4GRDB13DatabaseQueue13releaseMemoryFT_T_":{"name":"releaseMemory()","abstract":"
Listens to UIApplicationDidEnterBackgroundNotification and","parent_name":"DatabaseQueue"},"Classes/DatabaseQueue.html#/setupMemoryManagement(in:)":{"name":"setupMemoryManagement(in:)","abstract":"Undocumented","parent_name":"DatabaseQueue"},"Classes/DatabaseQueue.html#/s:FC4GRDB13DatabaseQueue4readurFzFzCS_8Databasexx":{"name":"read(_:)","abstract":"
Synchronously executes a read-only block in a protected dispatch queue,","parent_name":"DatabaseQueue"},"Classes/DatabaseQueue.html#/s:FC4GRDB13DatabaseQueue10unsafeReadurFzFzCS_8Databasexx":{"name":"unsafeRead(_:)","abstract":"
Alias for inDatabase. See DatabaseReader.unsafeRead.
Listens to UIApplicationDidEnterBackgroundNotification and","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/setupMemoryManagement(in:)":{"name":"setupMemoryManagement(in:)","abstract":"Undocumented","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:FC4GRDB12DatabasePool4readurFzFzCS_8Databasexx":{"name":"read(_:)","abstract":"
Synchronously executes a read-only block in a protected dispatch queue,","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:FC4GRDB12DatabasePool10unsafeReadurFzFzCS_8Databasexx":{"name":"unsafeRead(_:)","abstract":"
Synchronously executes a read-only block in a protected dispatch queue,","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:FC4GRDB12DatabasePool3addFT8functionCS_16DatabaseFunction_T_":{"name":"add(function:)","abstract":"
Synchronously executes an update block in a protected dispatch queue,","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:FC4GRDB12DatabasePool18writeInTransactionFzTGSqOCS_8Database15TransactionKind_FzS1_OS1_21TransactionCompletion_T_":{"name":"writeInTransaction(_:_:)","abstract":"
Synchronously executes a block in a protected dispatch queue, wrapped","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:FC4GRDB12DatabasePool20readFromCurrentStateFzFCS_8DatabaseT_T_":{"name":"readFromCurrentState(_:)","abstract":"
Asynchronously executes a read-only block in a protected dispatch queue,","parent_name":"DatabasePool"},"Classes/DatabaseCollation.html#/s:vC4GRDB17DatabaseCollation4nameSS":{"name":"name","abstract":"Undocumented","parent_name":"DatabaseCollation"},"Classes/DatabaseCollation.html#/s:FC4GRDB17DatabaseCollationcFTSS8functionFTSSSS_OSC16ComparisonResult_S0_":{"name":"init(_:function:)","abstract":"
A collation, or SQL string comparison function, that compares strings","parent_name":"DatabaseCollation"},"Classes/DatabaseCollation.html#/s:ZvC4GRDB17DatabaseCollation22caseInsensitiveCompareS0_":{"name":"caseInsensitiveCompare","abstract":"
A collation, or SQL string comparison function, that compares strings","parent_name":"DatabaseCollation"},"Classes/DatabaseCollation.html#/s:ZvC4GRDB17DatabaseCollation31localizedCaseInsensitiveCompareS0_":{"name":"localizedCaseInsensitiveCompare","abstract":"
A collation, or SQL string comparison function, that compares strings","parent_name":"DatabaseCollation"},"Classes/DatabaseCollation.html#/s:ZvC4GRDB17DatabaseCollation16localizedCompareS0_":{"name":"localizedCompare","abstract":"
A collation, or SQL string comparison function, that compares strings","parent_name":"DatabaseCollation"},"Classes/DatabaseCollation.html#/s:ZvC4GRDB17DatabaseCollation24localizedStandardCompareS0_":{"name":"localizedStandardCompare","abstract":"
A collation, or SQL string comparison function, that compares strings","parent_name":"DatabaseCollation"},"Classes/DatabaseFunction.html#/s:vC4GRDB16DatabaseFunction4nameSS":{"name":"name","abstract":"Undocumented","parent_name":"DatabaseFunction"},"Classes/DatabaseFunction.html#/s:FC4GRDB16DatabaseFunctioncFTSS13argumentCountGSqVs5Int32_4pureSb8functionFzGSaVS_13DatabaseValue_GSqPS_24DatabaseValueConvertible___S0_":{"name":"init(_:argumentCount:pure:function:)","abstract":"
An SQL function that returns the Swift built-in capitalized","parent_name":"DatabaseFunction"},"Classes/DatabaseFunction.html#/s:ZvC4GRDB16DatabaseFunction9lowercaseS0_":{"name":"lowercase","abstract":"
An SQL function that returns the Swift built-in lowercased","parent_name":"DatabaseFunction"},"Classes/DatabaseFunction.html#/s:ZvC4GRDB16DatabaseFunction9uppercaseS0_":{"name":"uppercase","abstract":"
An SQL function that returns the Swift built-in uppercased","parent_name":"DatabaseFunction"},"Classes/DatabaseFunction.html#/s:ZvC4GRDB16DatabaseFunction19localizedCapitalizeS0_":{"name":"localizedCapitalize","abstract":"
An SQL function that returns the Swift built-in","parent_name":"DatabaseFunction"},"Classes/DatabaseFunction.html#/s:ZvC4GRDB16DatabaseFunction18localizedLowercaseS0_":{"name":"localizedLowercase","abstract":"
An SQL function that returns the Swift built-in","parent_name":"DatabaseFunction"},"Classes/DatabaseFunction.html#/s:ZvC4GRDB16DatabaseFunction18localizedUppercaseS0_":{"name":"localizedUppercase","abstract":"
An SQL function that returns the Swift built-in","parent_name":"DatabaseFunction"},"Classes/Database/TransactionCompletion.html#/s:FOC4GRDB8Database21TransactionCompletion6commitFMS1_S1_":{"name":"commit","abstract":"Undocumented","parent_name":"TransactionCompletion"},"Classes/Database/TransactionCompletion.html#/s:FOC4GRDB8Database21TransactionCompletion8rollbackFMS1_S1_":{"name":"rollback","abstract":"Undocumented","parent_name":"TransactionCompletion"},"Classes/Database/TransactionKind.html#/s:FOC4GRDB8Database15TransactionKind8deferredFMS1_S1_":{"name":"deferred","abstract":"Undocumented","parent_name":"TransactionKind"},"Classes/Database/TransactionKind.html#/s:FOC4GRDB8Database15TransactionKind9immediateFMS1_S1_":{"name":"immediate","abstract":"Undocumented","parent_name":"TransactionKind"},"Classes/Database/TransactionKind.html#/s:FOC4GRDB8Database15TransactionKind9exclusiveFMS1_S1_":{"name":"exclusive","abstract":"Undocumented","parent_name":"TransactionKind"},"Classes/Database/ForeignKeyAction.html#/s:FOC4GRDB8Database16ForeignKeyAction7cascadeFMS1_S1_":{"name":"cascade","abstract":"Undocumented","parent_name":"ForeignKeyAction"},"Classes/Database/ForeignKeyAction.html#/s:FOC4GRDB8Database16ForeignKeyAction8restrictFMS1_S1_":{"name":"restrict","abstract":"Undocumented","parent_name":"ForeignKeyAction"},"Classes/Database/ForeignKeyAction.html#/s:FOC4GRDB8Database16ForeignKeyAction7setNullFMS1_S1_":{"name":"setNull","abstract":"Undocumented","parent_name":"ForeignKeyAction"},"Classes/Database/ForeignKeyAction.html#/s:FOC4GRDB8Database16ForeignKeyAction10setDefaultFMS1_S1_":{"name":"setDefault","abstract":"Undocumented","parent_name":"ForeignKeyAction"},"Classes/Database/ColumnType.html#/s:vPs16RawRepresentable8rawValuewx8RawValue":{"name":"rawValue","abstract":"
The SQLITE_BUSY error is immediately returned to the connection that","parent_name":"BusyMode"},"Classes/Database/BusyMode.html#/s:FOC4GRDB8Database8BusyMode7timeoutFMS1_FSdS1_":{"name":"timeout","abstract":"
The SQLITE_BUSY error will be returned only if the database remains","parent_name":"BusyMode"},"Classes/Database/BusyMode.html#/s:FOC4GRDB8Database8BusyMode8callbackFMS1_FFSiSbS1_":{"name":"callback","abstract":"
A custom callback that is called when a database is locked.","parent_name":"BusyMode"},"Classes/Database.html#/s:C4GRDB8Database12BusyCallback":{"name":"BusyCallback","abstract":"
When there are several connections to a database, a connection may try","parent_name":"Database"},"Classes/Database/CheckpointMode.html":{"name":"CheckpointMode","abstract":"
The number of rows modified, inserted or deleted by the most recent","parent_name":"Database"},"Classes/Database.html#/s:vC4GRDB8Database17totalChangesCountSi":{"name":"totalChangesCount","abstract":"
The total number of rows modified, inserted or deleted by all successful","parent_name":"Database"},"Classes/Database.html#/s:vC4GRDB8Database19isInsideTransactionSb":{"name":"isInsideTransaction","abstract":"
True if the database connection is currently in a transaction.
The primary key for table named tableName; nil if table has no","parent_name":"Database"},"Classes/Database.html#/s:FC4GRDB8Database11columnCountFzT2inSS_Si":{"name":"columnCount(in:)","abstract":"
The number of columns in the table named tableName.
The indexes on table named tableName; returns the empty array if the","parent_name":"Database"},"Classes/Database.html#/s:FC4GRDB8Database5tableuRxs8SequenceWx8Iterator7Element_zSSrFzTSS12hasUniqueKeyx_Sb":{"name":"table(_:hasUniqueKey:)","abstract":"
True if a sequence of columns uniquely identifies a row, that is to say","parent_name":"Database"},"Classes/Database.html#/s:FC4GRDB8Database13inTransactionFzTGSqOS0_15TransactionKind_FzT_OS0_21TransactionCompletion_T_":{"name":"inTransaction(_:_:)","abstract":"
Add a transaction observer, so that it gets notified of","parent_name":"Database"},"Classes/Database.html#/s:FC4GRDB8Database6removeFT19transactionObserverPS_19TransactionObserver__T_":{"name":"remove(transactionObserver:)","abstract":"
Advances to the next element and returns it, or nil if no next","parent_name":"IteratorCursor"},"Classes/MapCursor.html#/s:FC4GRDB9MapCursor4nextFzT_GSqq__":{"name":"next()","abstract":"
Advances to the next element and returns it, or nil if no next","parent_name":"MapCursor"},"Classes/FlattenCursor.html#/s:FC4GRDB13FlattenCursor4nextFzT_GSqWx7ElementS1___":{"name":"next()","abstract":"
Advances to the next element and returns it, or nil if no next","parent_name":"FlattenCursor"},"Classes/FilterCursor.html#/s:FC4GRDB12FilterCursor4nextFzT_GSqwx7Element_":{"name":"next()","abstract":"
Advances to the next element and returns it, or nil if no next","parent_name":"FilterCursor"},"Classes/EnumeratedCursor.html#/s:FC4GRDB16EnumeratedCursor4nextFzT_GSqTSiwx7Element__":{"name":"next()","abstract":"
Advances to the next element and returns it, or nil if no next","parent_name":"EnumeratedCursor"},"Classes/AnyCursor.html#/s:FC4GRDB9AnyCursorcuRd__S_6Cursorxzwd__7ElementrFqd__GS0_x_":{"name":"init(_:)","abstract":"
Creates a cursor that wraps a base cursor but whose type depends only on","parent_name":"AnyCursor"},"Classes/AnyCursor.html#/s:FC4GRDB9AnyCursorcFFzT_GSqx_GS0_x_":{"name":"init(_:)","abstract":"
Creates a cursor that wraps the given closure in its next() method
The FTS4ColumnDefinition class lets you refine a column of an FTS4"},"Classes/FTS5TableDefinition.html":{"name":"FTS5TableDefinition","abstract":"Undocumented"},"Classes/FTS5ColumnDefinition.html":{"name":"FTS5ColumnDefinition","abstract":"Undocumented"},"Classes/Record.html":{"name":"Record","abstract":"
Record is a class that wraps a table row, or the result of any query. It is"},"Classes/Row.html":{"name":"Row","abstract":"