This cursor forwards its next() method to an arbitrary underlying cursor
+having the same Element type, hiding the specifics of the underlying
+cursor.
This cursor forwards its next() method to an arbitrary underlying cursor
+having the same Element type, hiding the specifics of the underlying
+cursor.
SQLite can be configured to invoke a callback function containing an
+error code and a terse error message whenever anomalies occur. This
+mechanism is very helpful in tracking obscure problems that occur
+rarely and in the field. Application developers are encouraged to take
+advantage of the error logging facility of SQLite in their products,
+as it is very low CPU and memory cost but can be a huge aid
+for debugging.
The total number of rows modified, inserted or deleted by all successful
+INSERT, UPDATE or DELETE statements since the database connection was
+opened.
Returns a new prepared statement that can be reused.
+
letstatement=trydb.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
+letmoreThanTwentyCount=tryInt.fetchOne(statement,arguments:[20])!
+letmoreThanThirtyCount=tryInt.fetchOne(statement,arguments:[30])!
+
+
+
Throws
+ A DatabaseError whenever SQLite could not parse the sql query.
+
+
letstatement=trydb.cachedSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
+letmoreThanTwentyCount=tryInt.fetchOne(statement,arguments:[20])!
+letmoreThanThirtyCount=tryInt.fetchOne(statement,arguments:[30])!
+
+
+
The returned statement may have already been used: it may or may not
+contain values for its eventual arguments.
+
+
Throws
+ A DatabaseError whenever SQLite could not parse the sql query.
+
+
Returns a new prepared statement that can be reused.
+
letstatement=trydb.makeUpdateStatement("INSERT INTO player (name) VALUES (?)")
+trystatement.execute(arguments:["Arthur"])
+trystatement.execute(arguments:["Barbara"])
+
+
+
Throws
+ A DatabaseError whenever SQLite could not parse the sql query.
+
+
letstatement=trydb.cachedUpdateStatement("INSERT INTO player (name) VALUES (?)")
+trystatement.execute(arguments:["Arthur"])
+trystatement.execute(arguments:["Barbara"])
+
+
+
The returned statement may have already been used: it may or may not
+contain values for its eventual arguments.
+
+
Throws
+ A DatabaseError whenever SQLite could not parse the sql query.
+
+
Executes one or several SQL statements, separated by semi-colons.
+
trydb.execute(
+ "INSERT INTO player (name) VALUES (:name)",
+ arguments:["name":"Arthur"])
+
+trydb.execute("""
+ INSERT INTO player (name) VALUES (?);
+ INSERT INTO player (name) VALUES (?);
+ INSERT INTO player (name) VALUES (?);
+ """,arguments;['Arthur','Barbara','Craig'])
+
+
+
This method may throw a DatabaseError.
+
+
Throws
+ A DatabaseError whenever an SQLite error occurs.
+
+
The transaction type (default nil). If nil, the transaction
+type is configuration.defaultTransactionKind, which itself
+defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
+for more information.
+
+
+
+
+
+
+ block
+
+
+
+
+
A block that executes SQL statements and return either
+.commit or .rollback.
The transaction type (default nil). If nil, the
+transaction type is configuration.defaultTransactionKind, which itself
+defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
+for more information.
The number of arguments of the function. If
+omitted, or nil, the function accepts any number of arguments.
+
+
+
+
+
+
+ pure
+
+
+
+
+
Whether the function is pure, which means that its results
+only depends on its inputs. When a function is pure, SQLite has
+the opportunity to perform additional optimizations. Default value
+is false.
+
+
+
+
+
+
+ function
+
+
+
+
+
A function that takes an array of DatabaseValue
+arguments, and returns an optional DatabaseValueConvertible such
+as Int, String, NSDate, etc. The array is guaranteed to have
+exactly argumentCount elements, provided argumentCount is
+not nil.
The number of arguments of the aggregate. If
+omitted, or nil, the aggregate accepts any number of arguments.
+
+
+
+
+
+
+ pure
+
+
+
+
+
Whether the aggregate is pure, which means that its
+results only depends on its inputs. When an aggregate is pure,
+SQLite has the opportunity to perform additional optimizations.
+Default value is false.
+
+
+
+
+
+
+ aggregate
+
+
+
+
+
A type that implements the DatabaseAggregate protocol.
+For each step of the aggregation, its step method is called with
+an array of DatabaseValue arguments. The array is guaranteed to
+have exactly argumentCount elements, provided argumentCount is
+not nil.
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.
The block is completely isolated. Eventual concurrent database updates
+are not visible inside the block:
+
trydbPool.read{dbin
+ // Those two values are guaranteed to be equal, even if the
+ // `wine` table is modified between the two requests:
+ letcount1=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+ letcount2=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+}
+
+trydbPool.read{dbin
+ // Now this value may be different:
+ letcount=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+}
+
+
+
This method is not reentrant.
+
+
Throws
+ The error thrown by the block, or any DatabaseError that would
+happen while establishing the read access to the database.
+
+
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:
+
trydbPool.unsafeRead{dbin
+ // Those two values may be different because some other thread
+ // may have inserted or deleted a wine between the two requests:
+ letcount1=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+ letcount2=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+}
+
+
+
Cursor iteration is safe, though:
+
trydbPool.unsafeRead{dbin
+ // No concurrent update can mess with this iteration:
+ letrows=tryRow.fetchCursor(db,"SELECT ...")
+ whileletrow=tryrows.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 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:
+
trydbPool.unsafeReentrantRead{dbin
+ // Those two values may be different because some other thread
+ // may have inserted or deleted a wine between the two requests:
+ letcount1=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+ letcount2=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+}
+
+
+
Cursor iteration is safe, though:
+
trydbPool.unsafeReentrantRead{dbin
+ // No concurrent update can mess with this iteration:
+ letrows=tryRow.fetchCursor(db,"SELECT ...")
+ whileletrow=tryrows.next(){...}
+}
+
+
+
This method is reentrant. It is unsafe because it fosters dangerous
+concurrency practices.
+
+
Throws
+ The error thrown by the block, or any DatabaseError that would
+happen while establishing the read access to the database.
+
+
This method is deprecated. Use concurrentRead instead.
+
+
Asynchronously executes a read-only block in a protected dispatch queue,
+wrapped in a deferred transaction.
+
+
This method must be called from the writing dispatch queue, outside of a
+transaction. You’ll get a fatal error otherwise.
+
+
The block argument is guaranteed to see the database in the last
+committed state at the moment this method is called. Eventual concurrent
+database updates are not visible inside the block.
+
trydbPool.write{dbin
+ trydb.execute("DELETE FROM player")
+ trydbPool.readFromCurrentState{dbin
+ // Guaranteed to be zero
+ tryInt.fetchOne(db,"SELECT COUNT(*) FROM player")!
+ }
+ trydb.execute("INSERT INTO player ...")
+}
+
+
+
This method blocks the current thread until the isolation guarantee has
+been established, and before the block argument has run.
+
+
Throws
+ The error thrown by the block, or any DatabaseError that would
+happen while establishing the read access to the database.
+
+
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.
The transaction type (default nil). If nil, the transaction
+type is configuration.defaultTransactionKind, which itself
+defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
+for more information.
+
+
+
+
+
+
+ block
+
+
+
+
+
A block that executes SQL statements and return either
+.commit or .rollback.
The snapshot sees an unchanging database content, as it existed at the
+moment it was created.
+
+
When you want to control the latest committed changes seen by a
+snapshot, create it from the pool’s writer protected dispatch queue:
+
letsnapshot1=trydbPool.write{db->DatabaseSnapshotin
+ tryPlayer.deleteAll()
+ returntrydbPool.makeSnapshot()
+}
+// <- Other threads may modify the database here
+letsnapshot2=trydbPool.makeSnapshot()
+
+trysnapshot1.read{dbin
+ // Guaranteed to be zero
+ tryPlayer.fetchCount(db)
+}
+
+trysnapshot2.read{dbin
+ // Could be anything
+ tryPlayer.fetchCount(db)
+}
+
+
+
It is forbidden to create a snapshot from the writer protected dispatch
+queue when a transaction is opened, though, because it is likely a
+programmer error:
+
trydbPool.write{dbin
+ trydb.inTransaction{
+ tryPlayer.deleteAll()
+ // fatal error: makeSnapshot() must not be called from inside a transaction
+ letsnapshot=trydbPool.makeSnapshot()
+ return.commit
+ }
+}
+
+
+
To avoid this fatal error, create the snapshot before or after the
+transaction:
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.
Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and
+SQLCipher), attempts to write in the database from this meethod throw a
+DatabaseError of resultCode SQLITE_READONLY.
This method is deprecated. Use concurrentRead instead.
+
+
Synchronously executes block.
+
+
This method must be called from the protected database dispatch queue,
+outside of a transaction. You’ll get a fatal error otherwise.
+
+
Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and
+SQLCipher), attempts to write in the database from this meethod throw a
+DatabaseError of resultCode SQLITE_READONLY.
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.
The transaction type (default nil). If nil, the transaction
+type is configuration.defaultTransactionKind, which itself
+defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
+for more information.
+
+
+
+
+
+
+ block
+
+
+
+
+
A block that executes SQL statements and return either
+.commit or .rollback.
letcollation=DatabaseCollation("localized_standard"){(string1,string2)in
+ return(string1asNSString).localizedStandardCompare(string2)
+}
+snapshot.add(collation:collation)
+letfiles=trysnapshot.read{dbin
+ tryFile.fetchAll(db,"SELECT * FROM file ORDER BY name COLLATE localized_standard")
+}
+
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.
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.
+
letcontroller=FetchedRecordsController<Wine>(
+ dbQueue,
+ sql:"SELECT * FROM wine WHERE color = ? ORDER BY name",
+ arguments:[Color.red],
+ isSameRecord:{(wine1,wine2)inwine1.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.
+
letcontroller=FetchedRecordsController<Wine>(
+ dbQueue,
+ sql:"SELECT * FROM wine WHERE color = ? ORDER BY name",
+ arguments:[Color.red])
+
+
+
The records are compared by primary key (single-column primary key,
+compound primary key, or implicit rowid). For a database table which
+has an id primary key, this initializer is equivalent to:
+
// Assuming the wine table has an `id` primary key:
+letcontroller=FetchedRecordsController<Wine>(
+ dbQueue,
+ sql:"SELECT * FROM wine WHERE color = ? ORDER BY name",
+ arguments:[Color.red],
+ isSameRecord:{(wine1,wine2)inwine1.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 wine table has an `id` primary key:
+letcontroller=FetchedRecordsController<Wine>(
+ dbQueue,
+ request:request,
+ isSameRecord:{(wine1,wine2)inwine1.id==wine2.id})
+
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.
A boolean that indicates whether the record has changes that have not
+been saved.
+
+
This flag is purely informative, and does not prevent insert(),
+update(), and save() from performing their database queries.
+
+
A record is edited if has been changed since last database
+synchronization (fetch, update, insert). Comparison
+is performed between values (values stored in the encode(to:)
+method, and values loaded from the database). Property setters do not
+trigger this flag.
+
+
You can rely on the Record base class to compute this flag for you, or
+you may set it to true or false when you know better. Setting it to
+false does not prevent it from turning true on subsequent modifications
+of the record.
On success, this method sets the hasDatabaseChanges flag to false.
+
+
This method is guaranteed to have inserted a row in the database if it
+returns without error.
+
+
Records whose primary key is declared as INTEGER PRIMARY KEY have
+their id automatically set after successful insertion, if it was nil
+before the insertion.
+
+
Throws
+ A DatabaseError whenever an SQLite error occurs.
+
+
On success, this method sets the hasDatabaseChanges flag to false.
+
+
This method is guaranteed to have updated a row in the database if it
+returns without error.
+
+
Throws
+ A DatabaseError is thrown whenever an SQLite error occurs.
+PersistenceError.recordNotFound is thrown if the primary key does not
+match any row in the database and record could not be updated.
+
+
If the record has been changed, executes an UPDATE statement so that
+those changes and only those changes are saved in the database.
+
+
On success, this method sets the hasDatabaseChanges flag to false.
+
+
This method is guaranteed to have saved the eventual changes in the
+database if it returns without error.
+
+
Throws
+ A DatabaseError is thrown whenever an SQLite error occurs.
+PersistenceError.recordNotFound is thrown if the primary key does not
+match any row in the database and record could not be updated.
+
+
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 true if and only if one column contains a non-null value, or if
+the row was fetched with a row adapter that defines a scoped row that
+contains a non-null value.
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 the record encoded in the given scope, if and only if the scope
+has been defined by a row adapter, and the scoped row contains a
+non-null value. Otherwise, return nil.
+
+
This subscript is designed to handle left joined records.
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.
+
letrows=tryRow.fetchCursor(db,"SELECT id, name FROM player")// RowCursor
+whileletrow=tryrows.next(){// Row
+ letid:Int64=row[0]
+ letname:String=row[1]
+}
+
+
+
Fetched rows are reused during the cursor iteration: don’t turn a row
+cursor into an array with Array(rows) or rows.filter { ... } since
+you would not get the distinct rows you expect. Use Row.fetchAll(...)
+instead.
+
+
For the same reason, make sure you make a copy whenever you extract a
+row for later use: row.copy().
+
+
If the database is modified during the cursor iteration, the remaining
+elements are undefined.
+
+
The cursor must be iterated in a protected dispath queue.
+
+
Throws
+ A DatabaseError is thrown whenever an SQLite error occurs.
+
+
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 the row associated with the given scope, by performing a
+breadth-first search in this row’s scopes and the scopes of its
+scoped rows, recursively.
The auto-incremented primary key is an integer primary key that
+automatically generates unused values when you do not explicitly
+provide one, and prevents the reuse of ids over the lifetime of
+the database.
+
+
It is the preferred way to define a numeric primary key.
+
+
The fact that an auto-incremented primary key prevents the reuse of
+ids is an excellent guard against data races that could happen when your
+application processes ids in an asynchronous way. The auto-incremented
+primary key provides the guarantee that a given id can’t reference a row
+that is different from the one it used to be at the beginning of the
+asynchronous process, even if this row gets deleted and a new one is
+inserted in between.
trydb.create(table:"player"){tin
+ t.column("personalPhone",.text)
+ t.column("workPhone",.text)
+ t.check(sql:"personalPhone IS NOT NULL OR workPhone IS NOT NULL")
+}
+
If the database value does not contain a suitable value, the function
+must return nil (GRDB will interpret this nil result as a conversion
+error, and react accordingly).
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.
Swift’s Optional comes with built-in methods that allow to fetch cursors
+and arrays of optional DatabaseValueConvertible:
+
tryOptional<String>.fetchCursor(db,"SELECT name FROM ...",arguments:...)// Cursor of String?
+tryOptional<String>.fetchAll(db,"SELECT name FROM ...",arguments:...)// [String?]
+
+letstatement=trydb.makeSelectStatement("SELECT name FROM ...")
+tryOptional<String>.fetchCursor(statement,arguments:...)// Cursor of String?
+tryOptional<String>.fetchAll(statement,arguments:...)// [String?]
+
+
+
DatabaseValueConvertible is adopted by Bool, Int, String, etc.
trydb.makeFTS5Pattern(rawPattern:"and",forTable:"document")// OK
+trydb.makeFTS5Pattern(rawPattern:"AND",forTable:"document")// malformed MATCH expression: [AND]
+
Returns a date initialized from dbValue, if possible.
+
+
If database value contains a number, that number is interpreted as a
+timeinterval since 00:00:00 UTC on 1 January 1970.
+
+
If database value contains a string, that string is interpreted as a
+SQLite date in the UTC time
+zone. Nil is returned if the date string does not contain at least the
+year, month and day components. Other components (minutes, etc.)
+are set to zero if missing.
Returns a date initialized from dbValue, if possible.
+
+
If database value contains a number, that number is interpreted as a
+timeinterval since 00:00:00 UTC on 1 January 1970.
+
+
If database value contains a string, that string is interpreted as a
+SQLite date in the UTC time
+zone. Nil is returned if the date string does not contain at least the
+year, month and day components. Other components (minutes, etc.)
+are set to zero if missing.
Swift’s Optional comes with built-in methods that allow to fetch cursors
+and arrays of optional DatabaseValueConvertible:
+
tryOptional<String>.fetchCursor(db,"SELECT name FROM ...",arguments:...)// Cursor of String?
+tryOptional<String>.fetchAll(db,"SELECT name FROM ...",arguments:...)// [String?]
+
+letstatement=trydb.makeSelectStatement("SELECT name FROM ...")
+tryOptional<String>.fetchCursor(statement,arguments:...)// Cursor of String?
+tryOptional<String>.fetchAll(statement,arguments:...)// [String?]
+
+
+
DatabaseValueConvertible is adopted by Bool, Int, String, etc.
Returns a cursor over optional values fetched from a prepared statement.
+
letstatement=trydb.makeSelectStatement("SELECT name FROM ...")
+letnames=tryOptional<String>.fetchCursor(statement)// Cursor of String?
+whileletname=trynames.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.
+
+
Returns a cursor over optional values fetched from a prepared statement.
+
letstatement=trydb.makeSelectStatement("SELECT name FROM ...")
+letnames=tryOptional<String>.fetchCursor(statement)// Cursor of String?
+whileletname=trynames.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.
+
+
Creates a request with a full-text predicate added to the eventual
+set of already applied predicates.
+
// SELECT * FROM book WHERE book MATCH '...'
+varrequest=Book.all()
+request=request.matching(pattern)
+
+
+
If the search pattern is nil, the request does not match any
+database row.
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
Returns an expression by joining all elements with an SQL
+logical operator.
+
+
For example:
+
// SELECT * FROM player
+// WHERE (registered
+// AND (score >= 1000)
+// AND (name IS NOT NULL))
+letconditions=[
+ Column("registered"),
+ Column("score")>=1000,
+ Column("name")!=nil]
+Player.filter(conditions.joined(operator:.and))
+
+
+
When the sequence is empty, joined(operator: .and) returns true,
+and joined(operator: .or) returns false:
+
// SELECT * FROM player WHERE 1
+Player.filter([].joined(operator:.and))
+
+// SELECT * FROM player WHERE 0
+Player.filter([].joined(operator:.or))
+
Relationship with standard Sequence and IteratorProtocol
+
+
Cursors share traits with lazy sequences and iterators from the Swift
+standard library. Differences are:
+
+
+
Cursor types are classes, and have a lifetime.
+
Cursor iteration may throw errors.
+
A cursor can not be repeated.
+
+
+
The protocol comes with default implementations for many operations similar
+to those defined by Swift’s Sequence protocol: contains, dropFirst,
+dropLast, drop(while:), enumerated, filter, first, flatMap,
+forEach, joined, joined(separator:), max, max(by:), min,
+min(by:), map, prefix, prefix(while:), reduce, reduce(into:),
+suffix.
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.
Types that adopt DatabaseValueConvertible can be initialized from
+database values.
+
+
The protocol comes with built-in methods that allow to fetch cursors,
+arrays, or single values:
+
tryString.fetchCursor(db,"SELECT name FROM ...",arguments:...)// Cursor of String
+tryString.fetchAll(db,"SELECT name FROM ...",arguments:...)// [String]
+tryString.fetchOne(db,"SELECT name FROM ...",arguments:...)// String?
+
+letstatement=trydb.makeSelectStatement("SELECT name FROM ...")
+tryString.fetchCursor(statement,arguments:...)// Cursor of String
+tryString.fetchAll(statement,arguments:...)// [String]
+tryString.fetchOne(statement,arguments:...)// String?
+
+
+
DatabaseValueConvertible is adopted by Bool, Int, String, etc.
The protocol for all requests that run from a single select statement, and
+tell how fetched rows should be interpreted.
+
structPlayer:FetchableRecord{...}
+letrequest:...// Some FetchRequest that fetches Player
+tryrequest.fetchCursor(db)// Cursor of Player
+tryrequest.fetchAll(db)// [Player]
+tryrequest.fetchOne(db)// Player?
+
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.
The StatementColumnConvertible protocol grants access to the low-level C
+interface that extracts values from query results:
+https://www.sqlite.org/c3ref/column_blob.html. It can bring performance
+improvements.
+
+
To use it, have a value type adopt both StatementColumnConvertible and
+DatabaseValueConvertible. GRDB will then automatically apply the
+optimization whenever direct access to SQLite is possible:
+
letrows=Row.fetchCursor(db,"SELECT ...")
+whileletrow=tryrows.next(){
+ letint:Int=row[0]// there
+}
+letints=Int.fetchAll(db,"SELECT ...")// there
+structPlayer{
+ init(row:Row){
+ name=row["name"]// there
+ score=row["score"]// there
+ }
+}
+
+
+
StatementColumnConvertible is already adopted by all Swift integer types,
+Float, Double, String, and Bool.
The association key defines how rows fetched from this association
+should be consumed.
+
+
For example:
+
structPlayer:TableRecord{
+ // The default key of this association is the name of the
+ // database table for teams, let's say "team":
+ staticletteam=belongsTo(Team.self)
+}
+print(Player.team.key)// Prints "team"
+
+// Consume rows:
+letrequest=Player.including(required:Player.team)
+forrowinRow.fetchAll(db,request){
+ letteam:Team=row["team"]// the association key
+}
+
Creates an association with the provided predicate promise added to
+the eventual set of already applied predicates.
+
structPlayer:TableRecord{
+ staticletteam=belongsTo(Team.self)
+}
+
+// SELECT player.*, team.*
+// FROM player
+// JOIN team ON team.id = player.teamId AND 1
+letassociation=Player.team.filter{dbintrue}
+varrequest=Player.including(required:association)
+
Creates an association with the provided orderings promise.
+
structPlayer:TableRecord{
+ staticletteam=belongsTo(Team.self)
+}
+
+// SELECT player.*, team.*
+// FROM player
+// JOIN team ON team.id = player.teamId
+// ORDER BY team.name
+letassociation=Player.team.order{_in[Column("name")]}
+varrequest=Player.including(required:association)
+
+
+
Any previous ordering is replaced:
+
// SELECT player.*, team.*
+// FROM player
+// JOIN team ON team.id = player.teamId
+// ORDER BY team.name
+letassociation=Player.team
+ .order{_in[Column("color")]}
+ .reversed()
+ .order{_in[Column("name")]}
+varrequest=Player.including(required:association)
+
Creates an association that reverses applied orderings.
+
structPlayer:TableRecord{
+ staticletteam=belongsTo(Team.self)
+}
+
+// SELECT player.*, team.*
+// FROM player
+// JOIN team ON team.id = player.teamId
+// ORDER BY team.name DESC
+letassociation=Player.team.order(Column("name")).reversed()
+varrequest=Player.including(required:association)
+
+
+
If no ordering was applied, the returned association is identical.
+
// SELECT player.*, team.*
+// FROM player
+// JOIN team ON team.id = player.teamId
+letassociation=Player.team.reversed()
+varrequest=Player.including(required:association)
+
Creates an association that includes another one. The columns of the
+associated record are selected. The returned association does not
+require that the associated database table contains a matching row.
Creates an association that includes another one. The columns of the
+associated record are selected. The returned association requires
+that the associated database table contains a matching row.
Creates an association that joins another one. The columns of the
+associated record are not selected. The returned association does not
+require that the associated database table contains a matching row.
Creates an association that joins another one. The columns of the
+associated record are not selected. The returned association requires
+that the associated database table contains a matching row.
Relationship with standard Sequence and IteratorProtocol
+
+
Cursors share traits with lazy sequences and iterators from the Swift
+standard library. Differences are:
+
+
+
Cursor types are classes, and have a lifetime.
+
Cursor iteration may throw errors.
+
A cursor can not be repeated.
+
+
+
The protocol comes with default implementations for many operations similar
+to those defined by Swift’s Sequence protocol: contains, dropFirst,
+dropLast, drop(while:), enumerated, filter, first, flatMap,
+forEach, joined, joined(separator:), max, max(by:), min,
+min(by:), map, prefix, prefix(while:), reduce, reduce(into:),
+suffix.
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.
A closure that takes an element of the cursir as
+its argument and returns true if the element should be skipped or
+false otherwise. Once predicate returns false it will not be
+called again.
A closure that takes an element of the cursor as
+its argument and returns true if the element should be included or
+false otherwise. Once predicate returns false it will not be
+called again.
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:
+
tryreader.read{dbin
+ // Those two values are guaranteed to be equal, even if the
+ // `wine` table is modified between the two requests:
+ letcount1=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+ letcount2=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+}
+
+tryreader.read{dbin
+ // Now this value may be different:
+ letcount=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+}
+
+
+
Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds
+and SQLCipher, attempts to write in the database throw a DatabaseError
+whose resultCode is SQLITE_READONLY.
+
+
Throws
+ The error thrown by the block, or any DatabaseError that would
+happen while establishing the read access to the database.
+
+
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:
+
tryreader.unsafeRead{dbin
+ // Those two values may be different because some other thread
+ // may have inserted or deleted a wine between the two requests:
+ letcount1=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+ letcount2=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+}
+
+
+
Cursor iterations are isolated, though:
+
tryreader.unsafeRead{dbin
+ // No concurrent update can mess with this iteration:
+ letrows=tryRow.fetchCursor(db,"SELECT ...")
+ whileletrow=tryrows.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.
+
+
Synchronously executes a block that takes a database connection, and
+returns its result.
+
+
The two guarantees of the safe read method are lifted:
+
+
The block argument is not isolated: eventual concurrent database updates
+are visible inside the block:
+
tryreader.unsafeReentrantRead{dbin
+ // Those two values may be different because some other thread
+ // may have inserted or deleted a wine between the two requests:
+ letcount1=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+ letcount2=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+}
+
+
+
Cursor iterations are isolated, though:
+
tryreader.unsafeReentrantRead{dbin
+ // No concurrent update can mess with this iteration:
+ letrows=tryRow.fetchCursor(db,"SELECT ...")
+ whileletrow=tryrows.next(){...}
+}
+
+
+
The block argument is not prevented from writing (DatabaseQueue, in
+particular, will accept database modifications in unsafeReentrantRead).
+
+
Throws
+ The error thrown by the block, or any DatabaseError that would
+happen while establishing the read access to the database.
+
+
+
+
This method is reentrant. It should be avoided because it fosters
+dangerous concurrency practices.
letcollation=DatabaseCollation("localized_standard"){(string1,string2)in
+ return(string1asNSString).localizedStandardCompare(string2)
+}
+reader.add(collation:collation)
+tryreader.execute("SELECT * FROM file 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.
Types that adopt DatabaseValueConvertible can be initialized from
+database values.
+
+
The protocol comes with built-in methods that allow to fetch cursors,
+arrays, or single values:
+
tryString.fetchCursor(db,"SELECT name FROM ...",arguments:...)// Cursor of String
+tryString.fetchAll(db,"SELECT name FROM ...",arguments:...)// [String]
+tryString.fetchOne(db,"SELECT name FROM ...",arguments:...)// String?
+
+letstatement=trydb.makeSelectStatement("SELECT name FROM ...")
+tryString.fetchCursor(statement,arguments:...)// Cursor of String
+tryString.fetchAll(statement,arguments:...)// [String]
+tryString.fetchOne(statement,arguments:...)// String?
+
+
+
DatabaseValueConvertible is adopted by Bool, Int, String, etc.
Returns a cursor over values fetched from a prepared statement.
+
letstatement=trydb.makeSelectStatement("SELECT name FROM ...")
+letnames=tryString.fetchCursor(statement)// Cursor of String
+whileletname=trynames.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.
+
+
Returns a cursor over values fetched from a prepared statement.
+
letstatement=trydb.makeSelectStatement("SELECT name FROM ...")
+letnames=tryString.fetchCursor(statement)// Cursor of String
+whileletname=trynames.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 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.
This method is deprecated. Use concurrentRead instead.
+
+
Synchronously or asynchronously executes a read-only block that takes a
+database connection.
+
+
This method must be called from a writing dispatch queue, outside of any
+transaction. You’ll get a fatal error otherwise.
+
+
The block argument is guaranteed to see the database in the last
+committed state at the moment this method is called. Eventual concurrent
+database updates are not visible inside the block.
+
+
For example:
+
trywriter.writeWithoutTransaction{dbin
+ trydb.execute("DELETE FROM player")
+ trywriter.readFromCurrentState{dbin
+ // Guaranteed to be zero
+ tryInt.fetchOne(db,"SELECT COUNT(*) FROM player")!
+ }
+ trydb.execute("INSERT INTO player ...")
+}
+
Concurrently executes a read-only block that takes a
+database connection.
+
+
This method must be called from a writing dispatch queue, outside of any
+transaction. You’ll get a fatal error otherwise.
+
+
The block argument is guaranteed to see the database in the last
+committed state at the moment this method is called. Eventual concurrent
+database updates are not visible inside the block.
+
+
This method returns as soon as the isolation guarantees described above
+are established. To access the fetched results, you call the wait()
+method of the returned future, on any dispatch queue.
+
+
In the example below, the number of players is fetched concurrently with
+the player insertion. Yet the future is guaranteed to return zero:
+
trywriter.writeWithoutTransaction{dbin
+ // Delete all players
+ tryPlayer.deleteAll()
+
+ // Count players concurrently
+ letfuture=writer.concurrentRead{dbin
+ returntryPlayer.fetchCount()
+ }
+
+ // Insert a player
+ tryPlayer(...).insert(db)
+
+ // Guaranteed to be zero
+ letcount=tryfuture.wait()
+}
+
The arguments parameter is an array of String built from the CREATE
+VIRTUAL TABLE statement. In the example below, the arguments will
+be ["arg1", "arg2"].
When implementing the accept method, there are a two rules
+to observe:
+
+
+
Errors thrown by the tokenCallback function must not be caught.
+
The input flags should be given unmodified to the tokenCallback
+function, unless you union it with the .colocated flag when the
+tokenizer produces synonyms (see
+https://www.sqlite.org/fts5.html#synonym_support).
The protocol for all requests that run from a single select statement, and
+tell how fetched rows should be interpreted.
+
structPlayer:FetchableRecord{...}
+letrequest:...// Some FetchRequest that fetches Player
+tryrequest.fetchCursor(db)// Cursor of Player
+tryrequest.fetchAll(db)// [Player]
+tryrequest.fetchOne(db)// Player?
+
letrequest:...// Some TypedRequest that fetches Row
+letrows=tryrequest.fetchCursor(db)// RowCursor
+whileletrow=tryrows.next(){// Row
+ letid:Int64=row[0]
+ letname:String=row[1]
+}
+
+
+
Fetched rows are reused during the cursor iteration: don’t turn a row
+cursor into an array with Array(rows) or rows.filter { ... } since
+you would not get the distinct rows you expect. Use Row.fetchAll(...)
+instead.
+
+
For the same reason, make sure you make a copy whenever you extract a
+row for later use: row.copy().
+
+
If the database is modified during the cursor iteration, the remaining
+elements are undefined.
+
+
The cursor must be iterated in a protected dispath queue.
+
+
Throws
+ A DatabaseError is thrown whenever an SQLite error occurs.
+
+
letrequest:...// Some TypedRequest that fetches Player
+letplayers=tryrequest.fetchCursor(db)// Cursor of Player
+whileletplayer=tryplayers.next(){// Player
+ ...
+}
+
+
+
If the database is modified during the cursor iteration, the remaining
+elements are undefined.
+
+
The cursor must be iterated in a protected dispath queue.
+
+
Throws
+ A DatabaseError is thrown whenever an SQLite error occurs.
+
+
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().
When the FetchableRecord type also adopts the standard Decodable
+protocol, you can use this dictionary to customize the decoding process
+from database rows.
+
+
For example:
+
// A key that holds a decoder's name
+letdecoderName=CodingUserInfoKey(rawValue:"decoderName")!
+
+// A FetchableRecord + Decodable record
+structPlayer:FetchableRecord,Decodable{
+ // Customize the decoder name when decoding a database row
+ staticletdatabaseDecodingUserInfo:[CodingUserInfoKey:Any]=[decoderName:"Database"]
+
+ init(fromdecoder:Decoder)throws{
+ // Print the decoder name
+ print(decoder.userInfo[decoderName])
+ ...
+ }
+}
+
+// prints "Database"
+letplayer=tryPlayer.fetchOne(db,...)
+
+// prints "JSON"
+letdecoder=JSONDecoder()
+decoder.userInfo=[decoderName:"JSON"]
+letplayer=trydecoder.decode(Player.self,from:...)
+
When the FetchableRecord type also adopts the standard Decodable
+protocol, this method controls the decoding process of nested properties
+from JSON database columns.
+
+
The default implementation returns a JSONDecoder with the
+following properties:
A cursor over all records fetched from the database.
+
// SELECT * FROM player
+letplayers=tryPlayer.fetchCursor(db)// Cursor of Player
+whileletplayer=tryplayers.next(){// Player
+ ...
+}
+
+
+
Records are iterated in the natural ordering of the table.
+
+
If the database is modified during the cursor iteration, the remaining
+elements are undefined.
+
+
The cursor must be iterated in a protected dispath queue.
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
+
+
Throws
+ A DatabaseError is thrown whenever an SQLite error occurs.
+
+
An array of all records fetched from the database.
+
// SELECT * FROM player
+letplayers=tryPlayer.fetchAll(db)// [Player]
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
+
+
Throws
+ A DatabaseError is thrown whenever an SQLite error occurs.
+
+
// SELECT * FROM player
+letplayer=tryPlayer.fetchOne(db)// Player?
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
+
+
Throws
+ A DatabaseError is thrown whenever an SQLite error occurs.
+
+
Returns a cursor over records identified by the provided unique keys
+(primary key or any key with a unique index on it).
+
letplayers=tryPlayer.fetchCursor(db,keys:[["email":"a@example.com"],["email":"b@example.com"]])// Cursor of Player
+whileletplayer=tryplayers.next(){// Player
+ ...
+}
+
+
+
Records are iterated in unspecified order.
+
+
Throws
+ A DatabaseError is thrown whenever an SQLite error occurs.
+
+
A cursor over records fetched from a prepared statement.
+
letstatement=trydb.makeSelectStatement("SELECT * FROM player")
+letplayers=tryPlayer.fetchCursor(statement)// Cursor of Player
+whileletplayer=tryplayers.next(){// Player
+ ...
+}
+
+
+
If the database is modified during the cursor iteration, the remaining
+elements are undefined.
+
+
The cursor must be iterated in a protected dispath queue.
+
+
Throws
+ A DatabaseError is thrown whenever an SQLite error occurs.
+
+
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.
It is undefined behavior to set different values for the same column.
+Column names are case insensitive, so defining both name and NAME
+is considered undefined behavior.
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.
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().
When the PersistableRecord type also adopts the standard Encodable
+protocol, you can use this dictionary to customize the encoding process
+into database rows.
+
+
For example:
+
// A key that holds a encoder's name
+letencoderName=CodingUserInfoKey(rawValue:"encoderName")!
+
+// A PersistableRecord + Encodable record
+structPlayer:PersistableRecord,Encodable{
+ // Customize the encoder name when encoding a database row
+ staticletdatabaseEncodingUserInfo:[CodingUserInfoKey:Any]=[encoderName:"Database"]
+
+ funcencode(toencoder:Encoder)throws{
+ // Print the encoder name
+ print(encoder.userInfo[encoderName])
+ ...
+ }
+}
+
+letplayer=Player(...)
+
+// prints "Database"
+tryplayer.insert(db)
+
+// prints "JSON"
+letencoder=JSONEncoder()
+encoder.userInfo=[encoderName:"JSON"]
+letdata=tryencoder.encode(player)
+
When the PersistableRecord type also adopts the standard Encodable
+protocol, this method controls the encoding process of nested properties
+into JSON database columns.
+
+
The default implementation returns a JSONEncoder with the
+following properties:
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.
+
+
If the record has differences from the other record, executes an UPDATE
+statement so that those changes and only those changes are saved in
+the database.
+
+
This method is guaranteed to have saved the eventual changes in the
+database if it returns without error.
+
+
Throws
+ A DatabaseError is thrown whenever an SQLite error occurs.
+PersistenceError.recordNotFound is thrown if the primary key does not
+match any row in the database and record could not be updated.
+
+
A dictionary of values changed from the other record.
+
+
Its keys are column names. Its values come from the other record.
+
+
Note that this method is not symmetrical, not only in terms of values,
+but also in terms of columns. When the two records don’t define the
+same set of columns in their encode(to:) method, only the columns
+defined by the receiver record are considered.
Don’t invoke this method directly: it is an internal method for types
+that adopt MutablePersistableRecord.
+
+
performInsert() provides the default implementation for insert(). Types
+that adopt MutablePersistableRecord can invoke performInsert() in their
+implementation of insert(). They should not provide their own
+implementation of performInsert().
Don’t invoke this method directly: it is an internal method for types
+that adopt MutablePersistableRecord.
+
+
performUpdate() provides the default implementation for update(). Types
+that adopt MutablePersistableRecord can invoke performUpdate() in their
+implementation of update(). They should not provide their own
+implementation of performUpdate().
+
+
Throws
+ A DatabaseError is thrown whenever an SQLite error occurs.
+PersistenceError.recordNotFound is thrown if the primary key does not
+match any row in the database.
+
+
Don’t invoke this method directly: it is an internal method for types
+that adopt MutablePersistableRecord.
+
+
performSave() provides the default implementation for save(). Types
+that adopt MutablePersistableRecord can invoke performSave() in their
+implementation of save(). They should not provide their own
+implementation of performSave().
+
+
This default implementation forwards the job to update or insert.
Don’t invoke this method directly: it is an internal method for types
+that adopt MutablePersistableRecord.
+
+
performDelete() provides the default implementation for deelte(). Types
+that adopt MutablePersistableRecord can invoke performDelete() in
+their implementation of delete(). They should not provide their own
+implementation of performDelete().
Don’t invoke this method directly: it is an internal method for types
+that adopt MutablePersistableRecord.
+
+
performExists() provides the default implementation for exists(). Types
+that adopt MutablePersistableRecord can invoke performExists() in
+their implementation of exists(). They should not provide their own
+implementation of performExists().
Delete records identified by their primary keys; returns the number of
+deleted rows.
+
// DELETE FROM player WHERE id IN (1, 2, 3)
+tryPlayer.deleteAll(db,keys:[1,2,3])
+
+// DELETE FROM country WHERE code IN ('FR', 'US', 'DE')
+tryCountry.deleteAll(db,keys:["FR","US","DE"])
+
+
+
When the table has no explicit primary key, GRDB uses the hidden
+rowid column:
+
// DELETE FROM document WHERE rowid IN (1, 2, 3)
+tryDocument.deleteAll(db,keys:[1,2,3])
+
Notifies the record that it was succesfully inserted.
+
+
Do not call this method directly: it is called for you, in a protected
+dispatch queue, with the inserted RowID and the eventual
+INTEGER PRIMARY KEY column name.
+
+
This method is optional: the default implementation does nothing.
+
+
If you need a mutating variant of this method, adopt the
+MutablePersistableRecord protocol instead.
+
+
+
Default Implementation
+
+
Notifies the record that it was succesfully inserted.
+
+
The default implementation does nothing.
+
+
+
+
Declaration
+
+
Swift
+
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 PersistableRecord.
+
+
performInsert() provides the default implementation for insert(). Types
+that adopt PersistableRecord can invoke performInsert() in their
+implementation of insert(). They should not provide their own
+implementation of performInsert().
Don’t invoke this method directly: it is an internal method for types
+that adopt PersistableRecord.
+
+
performSave() provides the default implementation for save(). Types
+that adopt PersistableRecord can invoke performSave() in their
+implementation of save(). They should not provide their own
+implementation of performSave().
+
+
This default implementation forwards the job to update or insert.
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.
+structFirstColumnAdapter:RowAdapter{
+ funclayoutedAdapter(fromlayout:RowLayout)throws->LayoutedRowAdapter{
+ returnLayoutedColumnMapping(layoutColumns:[(0,"foo")])
+ }
+}
+
+// [foo:1]
+tryRow.fetchOne(db,"SELECT 1, 2, 3",adapter:FirstColumnAdapter())
+
The StatementColumnConvertible protocol grants access to the low-level C
+interface that extracts values from query results:
+https://www.sqlite.org/c3ref/column_blob.html. It can bring performance
+improvements.
+
+
To use it, have a value type adopt both StatementColumnConvertible and
+DatabaseValueConvertible. GRDB will then automatically apply the
+optimization whenever direct access to SQLite is possible:
+
letrows=Row.fetchCursor(db,"SELECT ...")
+whileletrow=tryrows.next(){
+ letint:Int=row[0]// there
+}
+letints=Int.fetchAll(db,"SELECT ...")// there
+structPlayer{
+ init(row:Row){
+ name=row["name"]// there
+ score=row["score"]// there
+ }
+}
+
+
+
StatementColumnConvertible is already adopted by all Swift integer types,
+Float, Double, String, and Bool.
Unless said otherwise, requests select all columns:
+
// SELECT * FROM player
+tryPlayer.fetchAll(db)
+
+
+
You can provide a custom implementation and provide an explicit list
+of columns:
+
structRestrictedPlayer:TableRecord{
+ staticvardatabaseTableName="player"
+ staticvardatabaseSelection=[Column("id"),Column("name")]
+}
+
+// SELECT id, name FROM player
+tryRestrictedPlayer.fetchAll(db)
+
+
+
You can also add extra columns such as the rowid column:
+
structExtendedPlayer:TableRecord{
+ staticvardatabaseTableName="player"
+ staticletdatabaseSelection:[SQLSelectable]=[AllColumns(),Column.rowID]
+}
+
+// SELECT *, rowid FROM player
+tryExtendedPlayer.fetchAll(db)
+
The record type at the other side of the association.
+
+
+
+
+
+
+ key
+
+
+
+
+
An eventual decoding key for the association. By default, it
+is destination.databaseTableName.
+
+
+
+
+
+
+ foreignKey
+
+
+
+
+
An eventual foreign key. You need to provide an
+explicit foreign key when GRDB can’t infer one from the database
+schema. This happens when the schema does not define any foreign
+key to the destination table, or when the schema defines several
+foreign keys to the destination table.
The record type at the other side of the association.
+
+
+
+
+
+
+ key
+
+
+
+
+
An eventual decoding key for the association. By default, it
+is destination.databaseTableName.
+
+
+
+
+
+
+ foreignKey
+
+
+
+
+
An eventual foreign key. You need to provide an
+explicit foreign key when GRDB can’t infer one from the database
+schema. This happens when the schema does not define any foreign
+key from the destination table, or when the schema defines several
+foreign keys from the destination table.
The record type at the other side of the association.
+
+
+
+
+
+
+ key
+
+
+
+
+
An eventual decoding key for the association. By default, it
+is destination.databaseTableName.
+
+
+
+
+
+
+ foreignKey
+
+
+
+
+
An eventual foreign key. You need to provide an
+explicit foreign key when GRDB can’t infer one from the database
+schema. This happens when the schema does not define any foreign
+key from the destination table, or when the schema defines several
+foreign keys from the destination table.
Returns a QueryInterfaceRequest with a matching predicate.
+
// SELECT * FROM book WHERE book MATCH '...'
+varrequest=Book.matching(pattern)
+
+
+
If the search pattern is nil, the request does not match any
+database row.
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
Creates a request that includes an association. The columns of the
+associated record are selected. The returned association does not
+require that the associated database table contains a matching row.
Creates a request that includes an association. The columns of the
+associated record are selected. The returned association requires
+that the associated database table contains a matching row.
Creates a request that includes an association. The columns of the
+associated record are not selected. The returned association does not
+require that the associated database table contains a matching row.
Creates a request that includes an association. The columns of the
+associated record are not selected. The returned association requires
+that the associated database table contains a matching row.
Creates a request with aggregates appended to the selection.
+
// SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
+// FROM player LEFT JOIN book ...
+varrequest=Player.annotated(with:[Player.books.count])
+
Creates a request with the provided aggregate predicate.
+
// SELECT player.*
+// FROM player LEFT JOIN book ...
+// HAVING COUNT(DISTINCT book.rowid) = 0
+varrequest=Player.all()
+request=request.having(Player.books.isEmpty)
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
// SELECT * FROM player
+letrequest=Player.all()
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
// SELECT * FROM player WHERE email = 'arthur@example.com'
+letrequest=Player.filter(Column("email")=="arthur@example.com")
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
Creates a request with the provided primary key predicate.
+
// SELECT * FROM player WHERE id = 1
+letrequest=Player.filter(key:1)
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
Creates a request with the provided primary key predicate.
+
// SELECT * FROM player WHERE id IN (1, 2, 3)
+letrequest=Player.filter(keys:[1,2,3])
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
Creates a request with the provided primary key predicate.
+
// SELECT * FROM passport WHERE personId = 1 AND countryCode = 'FR'
+letrequest=Passport.filter(key:["personId":1,"countryCode":"FR"])
+
+
+
When executed, this request raises a fatal error if there is no unique
+index on the key columns.
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
Creates a request with the provided primary key predicate.
+
// SELECT * FROM passport WHERE (personId = 1 AND countryCode = 'FR') OR ...
+letrequest=Passport.filter(keys:[["personId":1,"countryCode":"FR"],...])
+
+
+
When executed, this request raises a fatal error if there is no unique
+index on the key columns.
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
// SELECT * FROM player WHERE email = 'arthur@example.com'
+letrequest=Player.filter(sql:"email = ?",arguments:["arthur@example.com"])
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
Creates a request sorted according to the
+provided orderings.
+
// SELECT * FROM player ORDER BY name
+letrequest=Player.order(Column("name"))
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
Creates a request sorted according to the
+provided orderings.
+
// SELECT * FROM player ORDER BY name
+letrequest=Player.order([Column("name")])
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
// SELECT * FROM player ORDER BY id
+letrequest=Player.orderByPrimaryKey()
+
+// SELECT * FROM country ORDER BY code
+letrequest=Country.orderByPrimaryKey()
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
// SELECT * FROM player ORDER BY name
+letrequest=Player.order(sql:"name")
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
Creates a request which fetches limit rows, starting at
+offset.
+
// SELECT * FROM player LIMIT 1
+letrequest=Player.limit(1)
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
structPlayer:TableRecord{
+ staticletdatabaseTableName="player"
+}
+
+// SELECT "player".* FROM player
+letsql="SELECT \(Player.selectionSQL()) FROM player"
+
+// SELECT "p".* FROM player AS p
+letsql="SELECT \(Player.selectionSQL(alias:"p")) FROM player p"
+
Notifies a database change (insert, update, or delete).
+
+
The change is pending until the current transaction ends. See
+databaseWillCommit, databaseDidCommit and databaseDidRollback.
+
+
This method is called in a protected dispatch queue, serialized will all
+database updates.
+
+
The event is only valid for the duration of this method call. If you
+need to keep it longer, store a copy: event.copy()
+
+
The observer has an opportunity to stop receiving further change events
+from the current transaction by calling the
+stopObservingDatabaseChangesUntilNextTransaction() method.
Notifies before a database change (insert, update, or delete)
+with change information (initial / final values for the row’s
+columns). (Called before databaseDidChangeWithEvent.)
+
+
The change is pending until the end of the current transaction,
+and you always get a second chance to get basic event information in
+the databaseDidChangeWithEvent callback.
+
+
This callback is mostly useful for calculating detailed change
+information for a row, and provides the initial / final values.
+
+
This method is called in a protected dispatch queue, serialized will all
+database updates.
+
+
The event is only valid for the duration of this method call. If you
+need to keep it longer, store a copy: event.copy()
+
+
Warning
+ this method must not change the database.
+
+
+
+
Availability Info
+
+
Requires SQLite 3.13.0 +
+Compiled with option SQLITE_ENABLE_PREUPDATE_HOOK
The databaseDidChangeWithEvent callback is always available,
+and may provide most/all of what you need.
+(For example, FetchedRecordsController is built without databaseWillChange)
DatabaseRegion defines a region in the database. DatabaseRegion is dedicated
+to help transaction observers recognize impactful database changes in their
+observes(eventsOfKind:) and databaseDidChange(with:) methods.
+
+
A database region is the union of any number of table regions, which can
+cover a full table, or the combination of columns and rows (identified by
+their rowids):
let request = Player.filter(key: 1)
+try print(request.databaseRegion(db))
+// prints player(*)[1]
+
+
+
Database regions returned by requests can be more precise than regions
+returned by select statements. Especially, regions returned by statements
+don’t know about rowids:
+
// A plain statement
+letstatement=db.makeSelectStatement("SELECT * FROM player WHERE id = 1")
+statement.databaseRegion// "player(*)"
+
+// A query interface request that executes the same statement:
+letrequest=Player.filter(key:1)
+tryrequest.databaseRegion(db)// "player(*)[1]"
+
ColumnMapping is a row adapter that maps column names.
+
letadapter=ColumnMapping(["foo":"bar"])
+letsql="SELECT 'foo' AS foo, 'bar' AS bar, 'baz' AS baz"
+
+// [foo:"bar"]
+tryRow.fetchOne(db,sql,adapter:adapter)
+
RangeRowAdapter is a row adapter that only exposes a range of columns.
+
letadapter=RangeRowAdapter(1..<3)
+letsql="SELECT 1 AS foo, 2 AS bar, 3 AS baz, 4 as qux"
+
+// [bar:2 baz:3]
+tryRow.fetchOne(db,sql,adapter:adapter)
+
+ and += operators consider that overriding named arguments is a
+programmer error:
+
vararguments:StatementArguments=["name":"Arthur"]
+arguments+=["name":"Barbara"]
+// fatal error: already defined statement argument: name
+
+
+
&+ and append(contentsOf:) allow overriding named arguments:
+
vararguments:StatementArguments=["name":"Arthur"]
+arguments=arguments&+["name":"Barbara"]
+print(arguments)
+// Prints ["name": "Barbara"]
+
+
Mixed Arguments
+
+
It is possible to mix named and positional arguments. Yet this is usually
+confusing, and it is best to avoid this practice:
+
letsql="SELECT ?2 AS two, :foo AS foo, ?1 AS one, :foo AS foo2, :bar AS bar"
+vararguments:StatementArguments=[1,2,"bar"]+["foo":"foo"]
+letrow=tryRow.fetchOne(db,sql,arguments:arguments)!
+print(row)
+// Prints [two:2 foo:"foo" one:1 foo2:"foo" bar:"bar"]
+
+
+
Mixed arguments exist as a support for requests like the following:
The BelongsTo association sets up a one-to-one connection from a record
+type to another record type, such as each instance of the declaring record
+belongs to an instance of the other record.
+
+
For example, if your application includes authors and books, and each book
+is assigned its author, you’d declare the association this way:
A BelongsTo associations should be supported by an SQLite foreign key.
+
+
Foreign keys are the recommended way to declare relationships between
+database tables because not only will SQLite guarantee the integrity of your
+data, but GRDB will be able to use those foreign keys to automatically
+configure your association.
+
+
You define the foreign key when you create database tables. For example:
The book.authorId column is used to link a book to the author it
+belongs to.
+
Make the book.authorId column not null if you want SQLite to guarantee
+that all books have an author.
+
Create an index on the book.authorId column in order to ease the
+selection of an author’s books.
+
Create a foreign key from book.authorId column to authors.id, so that
+SQLite guarantees that no book refers to a missing author. The
+onDelete: .cascade option has SQLite automatically delete all of an
+author’s books when that author is deleted.
+See https://sqlite.org/foreignkeys.html#fk_actions for more information.
+
+
+
The example above uses auto-incremented primary keys. But generally
+speaking, all primary keys are supported.
+
+
If the database schema does not define foreign keys between tables, you can
+still use BelongsTo associations. But your help is needed to define the
+missing foreign key:
A ForeignKey helps building associations when GRDB can’t infer a foreign
+key from the database schema.
+
+
Sometimes the database schema does not define any foreign key between two
+tables. And sometimes, there are several foreign keys from a table
+to another:
When this happens, associations can’t be automatically inferred from the
+database schema. GRDB will complain with a fatal error such as Ambiguous
+foreign key from book to person, or Could not infer foreign key from book
+to person.
+
+
Your help is needed. You have to instruct GRDB which foreign key to use:
Foreign keys are always defined from the table that contains the columns at
+the origin of the foreign key. Person’s symmetric HasMany associations reuse
+Book’s foreign keys:
The HasMany association indicates a one-to-many connection between two
+record types, such as each instance of the declaring record has many
+instances of the other record.
+
+
For example, if your application includes authors and books, and each author
+is assigned zero or more books, you’d declare the association this way:
HasMany associations should be supported by an SQLite foreign key.
+
+
Foreign keys are the recommended way to declare relationships between
+database tables because not only will SQLite guarantee the integrity of your
+data, but GRDB will be able to use those foreign keys to automatically
+configure your association.
+
+
You define the foreign key when you create database tables. For example:
The book.authorId column is used to link a book to the author it
+belongs to.
+
Make the book.authorId column not null if you want SQLite to guarantee
+that all books have an author.
+
Create an index on the book.authorId column in order to ease the
+selection of an author’s books.
+
Create a foreign key from book.authorId column to authors.id, so that
+SQLite guarantees that no book refers to a missing author. The
+onDelete: .cascade option has SQLite automatically delete all of an
+author’s books when that author is deleted.
+See https://sqlite.org/foreignkeys.html#fk_actions for more information.
+
+
+
The example above uses auto-incremented primary keys. But generally
+speaking, all primary keys are supported.
+
+
If the database schema does not define foreign keys between tables, you can
+still use HasMany associations. But your help is needed to define the
+missing foreign key:
The HasOne association indicates a one-to-one connection between two
+record types, such as each instance of the declaring record has one
+instances of the other record.
+
+
For example, if your application has one database table for countries, and
+another for their demographic profiles, you’d declare the association
+this way:
HasOne associations should be supported by an SQLite foreign key.
+
+
Foreign keys are the recommended way to declare relationships between
+database tables because not only will SQLite guarantee the integrity of your
+data, but GRDB will be able to use those foreign keys to automatically
+configure your association.
+
+
You define the foreign key when you create database tables. For example:
The demographics.countryCode column is used to link a demographic
+profile to the country it belongs to.
+
Make the demographics.countryCode column not null if you want SQLite to
+guarantee that all profiles are linked to a country.
+
Create a unique index on the demographics.countryCode column in order to
+guarantee the unicity of any country’s profile.
+
Create a foreign key from demographics.countryCode column to
+country.code, so that SQLite guarantees that no profile refers to a
+missing country. The onDelete: .cascade option has SQLite automatically
+delete a profile when its country is deleted.
+See https://sqlite.org/foreignkeys.html#fk_actions for more information.
+
+
+
The example above uses a string primary for the country table. But generally
+speaking, all primary keys are supported.
+
+
If the database schema does not follow this convention, and does not define
+foreign keys between tables, you can still use HasOne associations. But
+your help is needed to define the missing foreign key:
The BelongsTo association sets up a one-to-one connection from a record
+type to another record type, such as each instance of the declaring record
+belongs to an instance of the other record.
+
+
For example, if your application includes authors and books, and each book
+is assigned its author, you’d declare the association this way:
A BelongsTo associations should be supported by an SQLite foreign key.
+
+
Foreign keys are the recommended way to declare relationships between
+database tables because not only will SQLite guarantee the integrity of your
+data, but GRDB will be able to use those foreign keys to automatically
+configure your association.
+
+
You define the foreign key when you create database tables. For example:
The book.authorId column is used to link a book to the author it
+belongs to.
+
Make the book.authorId column not null if you want SQLite to guarantee
+that all books have an author.
+
Create an index on the book.authorId column in order to ease the
+selection of an author’s books.
+
Create a foreign key from book.authorId column to authors.id, so that
+SQLite guarantees that no book refers to a missing author. The
+onDelete: .cascade option has SQLite automatically delete all of an
+author’s books when that author is deleted.
+See https://sqlite.org/foreignkeys.html#fk_actions for more information.
+
+
+
The example above uses auto-incremented primary keys. But generally
+speaking, all primary keys are supported.
+
+
If the database schema does not define foreign keys between tables, you can
+still use BelongsTo associations. But your help is needed to define the
+missing foreign key:
The SQL snippet that defines the default value, if any.
+
+
When nil, the column has no default value.
+
+
When not nil, it contains an SQL string that defines an expression. That
+expression may be a literal, as 1, or 'foo'. It may also contain a
+non-constant expression such as CURRENT_TIMESTAMP.
+
+
For example:
+
trydb.execute("""
+ CREATE TABLE player(
+ id INTEGER PRIMARY KEY,
+ name TEXT DEFAULT 'Anonymous',
+ score INT DEFAULT 0,
+ creationDate DATE DEFAULT CURRENT_TIMESTAMP
+ )
+ """)
+letcolumnInfos=trydb.columns(in:"player")
+columnInfos[0].defaultValueSQL// nil
+columnInfos[1].defaultValueSQL// "'Anoynymous'"
+columnInfos[2].defaultValueSQL// "0"
+columnInfos[3].defaultValueSQL// "CURRENT_TIMESTAMP"
+
ColumnMapping is a row adapter that maps column names.
+
letadapter=ColumnMapping(["foo":"bar"])
+letsql="SELECT 'foo' AS foo, 'bar' AS bar, 'baz' AS baz"
+
+// [foo:"bar"]
+tryRow.fetchOne(db,sql,adapter:adapter)
+
The database label is also used to name the various dispatch queues
+created by GRDB, visible in debugging sessions and crash logs. However
+those dispatch queue labels are intended for debugging only. Their
+format may change between GRDB releases. Applications should not depend
+on the GRDB dispatch queue labels.
+
+
If the database label is nil, the current GRDB implementation uses the
+following dispatch queue labels:
+
+
+
GRDB.DatabaseQueue: the (unique) dispatch queue of a DatabaseQueue
+
GRDB.DatabasePool.writer: the (unique) writer dispatch queue of
+a DatabasePool
+
GRDB.DatabasePool.reader.N, where N is 1, 2, …: one of the reader
+dispatch queue(s) of a DatabasePool. N grows with the number of SQLite
+connections: it may get bigger than the maximum number of concurrent
+readers, as SQLite connections get closed and new ones are opened.
+
GRDB.DatabasePool.snapshot.N: the dispatch queue of a
+DatabaseSnapshot. N grows with the number of snapshots.
+
+
+
If the database label is not nil, for example MyDatabase, the current
+GRDB implementation uses the following dispatch queue labels:
+
+
+
MyDatabase: the (unique) dispatch queue of a DatabaseQueue
+
MyDatabase.writer: the (unique) writer dispatch queue of
+a DatabasePool
+
MyDatabase.reader.N, where N is 1, 2, …: one of the reader
+dispatch queue(s) of a DatabasePool. N grows with the number of SQLite
+connections: it may get bigger than the maximum number of concurrent
+readers, as SQLite connections get closed and new ones are opened.
+
MyDatabase.snapshot.N: the dispatch queue of a
+DatabaseSnapshot. N grows with the number of snapshots.
If false, it is a programmer error to leave a transaction opened at the
+end of a database access block.
+
+
For example:
+
letdbQueue=DatabaseQueue()
+
+// fatal error: A transaction has been left opened at the end of a database access
+trydbQueue.inDatabase{dbin
+ trydb.beginTransaction()
+}
+
+
+
If true, one can leave opened transaction at the end of database access
+blocks:
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.
When the eraseDatabaseOnSchemaChange flag is true, the migrator will
+automatically wipe out the full database content, and recreate the whole
+database from scratch, if it detects that a migration has changed its
+definition.
+
+
This flag can destroy your precious users’ data!
+
+
But it may be useful in two situations:
+
+
+
During application development, as you are still designing
+migrations, and the schema changes often.
+
+
In this case, it is recommended that you make sure this flag does
+not ship in the distributed application, in order to avoid undesired
+data loss:
+
varmigrator=DatabaseMigrator()
+#if DEBUG
+// Speed up development by nuking the database when migrations change
+migrator.eraseDatabaseOnSchemaChange=true
+#endif
+
+
When the database content can easily be recreated, such as a cache
+for some downloaded data.
Iterate migrations in the same order as they were registered, up to the
+provided target. If a migration has not yet been applied, its block is
+executed in a transaction.
+
targetIdentifier: The identifier of a registered migration.
+
+
Throws
+ An eventual error thrown by the registered migration blocks.
+
+
DatabaseRegion defines a region in the database. DatabaseRegion is dedicated
+to help transaction observers recognize impactful database changes in their
+observes(eventsOfKind:) and databaseDidChange(with:) methods.
+
+
A database region is the union of any number of table regions, which can
+cover a full table, or the combination of columns and rows (identified by
+their rowids):
let request = Player.filter(key: 1)
+try print(request.databaseRegion(db))
+// prints player(*)[1]
+
+
+
Database regions returned by requests can be more precise than regions
+returned by select statements. Especially, regions returned by statements
+don’t know about rowids:
+
// A plain statement
+letstatement=db.makeSelectStatement("SELECT * FROM player WHERE id = 1")
+statement.databaseRegion// "player(*)"
+
+// A query interface request that executes the same statement:
+letrequest=Player.filter(key:1)
+tryrequest.databaseRegion(db)// "player(*)[1]"
+
Returns whether the content in the region is impacted by this event.
+
+
Precondition
+ event has been filtered by the same region
+in the TransactionObserver.observes(eventsOfKind:) method, by calling
+region.isModified(byEventsOfKind:)
+
+
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.
A ForeignKey helps building associations when GRDB can’t infer a foreign
+key from the database schema.
+
+
Sometimes the database schema does not define any foreign key between two
+tables. And sometimes, there are several foreign keys from a table
+to another:
When this happens, associations can’t be automatically inferred from the
+database schema. GRDB will complain with a fatal error such as Ambiguous
+foreign key from book to person, or Could not infer foreign key from book
+to person.
+
+
Your help is needed. You have to instruct GRDB which foreign key to use:
Foreign keys are always defined from the table that contains the columns at
+the origin of the foreign key. Person’s symmetric HasMany associations reuse
+Book’s foreign keys:
The HasMany association indicates a one-to-many connection between two
+record types, such as each instance of the declaring record has many
+instances of the other record.
+
+
For example, if your application includes authors and books, and each author
+is assigned zero or more books, you’d declare the association this way:
HasMany associations should be supported by an SQLite foreign key.
+
+
Foreign keys are the recommended way to declare relationships between
+database tables because not only will SQLite guarantee the integrity of your
+data, but GRDB will be able to use those foreign keys to automatically
+configure your association.
+
+
You define the foreign key when you create database tables. For example:
The book.authorId column is used to link a book to the author it
+belongs to.
+
Make the book.authorId column not null if you want SQLite to guarantee
+that all books have an author.
+
Create an index on the book.authorId column in order to ease the
+selection of an author’s books.
+
Create a foreign key from book.authorId column to authors.id, so that
+SQLite guarantees that no book refers to a missing author. The
+onDelete: .cascade option has SQLite automatically delete all of an
+author’s books when that author is deleted.
+See https://sqlite.org/foreignkeys.html#fk_actions for more information.
+
+
+
The example above uses auto-incremented primary keys. But generally
+speaking, all primary keys are supported.
+
+
If the database schema does not define foreign keys between tables, you can
+still use HasMany associations. But your help is needed to define the
+missing foreign key:
The HasOne association indicates a one-to-one connection between two
+record types, such as each instance of the declaring record has one
+instances of the other record.
+
+
For example, if your application has one database table for countries, and
+another for their demographic profiles, you’d declare the association
+this way:
HasOne associations should be supported by an SQLite foreign key.
+
+
Foreign keys are the recommended way to declare relationships between
+database tables because not only will SQLite guarantee the integrity of your
+data, but GRDB will be able to use those foreign keys to automatically
+configure your association.
+
+
You define the foreign key when you create database tables. For example:
The demographics.countryCode column is used to link a demographic
+profile to the country it belongs to.
+
Make the demographics.countryCode column not null if you want SQLite to
+guarantee that all profiles are linked to a country.
+
Create a unique index on the demographics.countryCode column in order to
+guarantee the unicity of any country’s profile.
+
Create a foreign key from demographics.countryCode column to
+country.code, so that SQLite guarantees that no profile refers to a
+missing country. The onDelete: .cascade option has SQLite automatically
+delete a profile when its country is deleted.
+See https://sqlite.org/foreignkeys.html#fk_actions for more information.
+
+
+
The example above uses a string primary for the country table. But generally
+speaking, all primary keys are supported.
+
+
If the database schema does not follow this convention, and does not define
+foreign keys between tables, you can still use HasOne associations. But
+your help is needed to define the missing foreign key:
Accesses the value associated with the given column.
+
+
It is undefined behavior to set different values for the same column.
+Column names are case insensitive, so defining both name and NAME
+is considered undefined behavior.
Accesses the value associated with the given column.
+
+
It is undefined behavior to set different values for the same column.
+Column names are case insensitive, so defining both name and NAME
+is considered undefined behavior.
Creates a request that includes an association. The columns of the
+associated record are selected. The returned association does not
+require that the associated database table contains a matching row.
Creates a request that includes an association. The columns of the
+associated record are selected. The returned association requires
+that the associated database table contains a matching row.
Creates a request that includes an association. The columns of the
+associated record are not selected. The returned association does not
+require that the associated database table contains a matching row.
Creates a request that includes an association. The columns of the
+associated record are not selected. The returned association requires
+that the associated database table contains a matching row.
Creates a request which appends aggregates to the current selection.
+
// SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
+// FROM player LEFT JOIN book ...
+varrequest=Player.all()
+request=request.annotated(with:Player.books.count)
+
Creates a request which appends aggregates to the current selection.
+
// SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
+// FROM player LEFT JOIN book ...
+varrequest=Player.all()
+request=request.annotated(with:[Player.books.count])
+
Creates a request which appends the provided aggregate predicate to
+the eventual set of already applied predicates.
+
// SELECT player.*
+// FROM player LEFT JOIN book ...
+// HAVING COUNT(DISTINCT book.rowid) = 0
+varrequest=Player.all()
+request=request.having(Player.books.isEmpty)
+
// SELECT id, email, name FROM player
+varrequest=Player.all()
+request=request
+ .select([Column("id"),Column("email")])
+ .annotated(with:[Column("name")])
+
// SELECT DISTINCT * FROM player
+varrequest=Player.all()
+request=request.distinct()
+
+// SELECT DISTINCT name FROM player
+varrequest=Player.select(Column("name"))
+request=request.distinct()
+
RangeRowAdapter is a row adapter that only exposes a range of columns.
+
letadapter=RangeRowAdapter(1..<3)
+letsql="SELECT 1 AS foo, 2 AS bar, 3 AS baz, 4 as qux"
+
+// [bar:2 baz:3]
+tryRow.fetchOne(db,sql,adapter:adapter)
+
Returns true if the code on the left matches the code on the right.
+
+
Primary result codes match themselves and their extended result codes,
+while extended result codes match only themselves:
+
switcherror.extendedResultCode{
+case.SQLITE_CONSTRAINT_FOREIGNKEY:// foreign key constraint error
+case.SQLITE_CONSTRAINT:// any other constraint error
+default:// any other database error
+}
+
+ and += operators consider that overriding named arguments is a
+programmer error:
+
vararguments:StatementArguments=["name":"Arthur"]
+arguments+=["name":"Barbara"]
+// fatal error: already defined statement argument: name
+
+
+
&+ and append(contentsOf:) allow overriding named arguments:
+
vararguments:StatementArguments=["name":"Arthur"]
+arguments=arguments&+["name":"Barbara"]
+print(arguments)
+// Prints ["name": "Barbara"]
+
+
Mixed Arguments
+
+
It is possible to mix named and positional arguments. Yet this is usually
+confusing, and it is best to avoid this practice:
+
letsql="SELECT ?2 AS two, :foo AS foo, ?1 AS one, :foo AS foo2, :bar AS bar"
+vararguments:StatementArguments=[1,2,"bar"]+["foo":"foo"]
+letrow=tryRow.fetchOne(db,sql,arguments:arguments)!
+print(row)
+// Prints [two:2 foo:"foo" one:1 foo2:"foo" bar:"bar"]
+
+
+
Mixed arguments exist as a support for requests like the following:
This cursor forwards its next() method to an arbitrary underlying cursor
+having the same Element type, hiding the specifics of the underlying
+cursor.
This cursor forwards its next() method to an arbitrary underlying cursor
+having the same Element type, hiding the specifics of the underlying
+cursor.
SQLite can be configured to invoke a callback function containing an
+error code and a terse error message whenever anomalies occur. This
+mechanism is very helpful in tracking obscure problems that occur
+rarely and in the field. Application developers are encouraged to take
+advantage of the error logging facility of SQLite in their products,
+as it is very low CPU and memory cost but can be a huge aid
+for debugging.
The total number of rows modified, inserted or deleted by all successful
+INSERT, UPDATE or DELETE statements since the database connection was
+opened.
Returns a new prepared statement that can be reused.
+
letstatement=trydb.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
+letmoreThanTwentyCount=tryInt.fetchOne(statement,arguments:[20])!
+letmoreThanThirtyCount=tryInt.fetchOne(statement,arguments:[30])!
+
+
+
Throws
+ A DatabaseError whenever SQLite could not parse the sql query.
+
+
letstatement=trydb.cachedSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
+letmoreThanTwentyCount=tryInt.fetchOne(statement,arguments:[20])!
+letmoreThanThirtyCount=tryInt.fetchOne(statement,arguments:[30])!
+
+
+
The returned statement may have already been used: it may or may not
+contain values for its eventual arguments.
+
+
Throws
+ A DatabaseError whenever SQLite could not parse the sql query.
+
+
Returns a new prepared statement that can be reused.
+
letstatement=trydb.makeUpdateStatement("INSERT INTO player (name) VALUES (?)")
+trystatement.execute(arguments:["Arthur"])
+trystatement.execute(arguments:["Barbara"])
+
+
+
Throws
+ A DatabaseError whenever SQLite could not parse the sql query.
+
+
letstatement=trydb.cachedUpdateStatement("INSERT INTO player (name) VALUES (?)")
+trystatement.execute(arguments:["Arthur"])
+trystatement.execute(arguments:["Barbara"])
+
+
+
The returned statement may have already been used: it may or may not
+contain values for its eventual arguments.
+
+
Throws
+ A DatabaseError whenever SQLite could not parse the sql query.
+
+
Executes one or several SQL statements, separated by semi-colons.
+
trydb.execute(
+ "INSERT INTO player (name) VALUES (:name)",
+ arguments:["name":"Arthur"])
+
+trydb.execute("""
+ INSERT INTO player (name) VALUES (?);
+ INSERT INTO player (name) VALUES (?);
+ INSERT INTO player (name) VALUES (?);
+ """,arguments;['Arthur','Barbara','Craig'])
+
+
+
This method may throw a DatabaseError.
+
+
Throws
+ A DatabaseError whenever an SQLite error occurs.
+
+
The transaction type (default nil). If nil, the transaction
+type is configuration.defaultTransactionKind, which itself
+defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
+for more information.
+
+
+
+
+
+
+ block
+
+
+
+
+
A block that executes SQL statements and return either
+.commit or .rollback.
The transaction type (default nil). If nil, the
+transaction type is configuration.defaultTransactionKind, which itself
+defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
+for more information.
The number of arguments of the function. If
+omitted, or nil, the function accepts any number of arguments.
+
+
+
+
+
+
+ pure
+
+
+
+
+
Whether the function is pure, which means that its results
+only depends on its inputs. When a function is pure, SQLite has
+the opportunity to perform additional optimizations. Default value
+is false.
+
+
+
+
+
+
+ function
+
+
+
+
+
A function that takes an array of DatabaseValue
+arguments, and returns an optional DatabaseValueConvertible such
+as Int, String, NSDate, etc. The array is guaranteed to have
+exactly argumentCount elements, provided argumentCount is
+not nil.
The number of arguments of the aggregate. If
+omitted, or nil, the aggregate accepts any number of arguments.
+
+
+
+
+
+
+ pure
+
+
+
+
+
Whether the aggregate is pure, which means that its
+results only depends on its inputs. When an aggregate is pure,
+SQLite has the opportunity to perform additional optimizations.
+Default value is false.
+
+
+
+
+
+
+ aggregate
+
+
+
+
+
A type that implements the DatabaseAggregate protocol.
+For each step of the aggregation, its step method is called with
+an array of DatabaseValue arguments. The array is guaranteed to
+have exactly argumentCount elements, provided argumentCount is
+not nil.
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.
The block is completely isolated. Eventual concurrent database updates
+are not visible inside the block:
+
trydbPool.read{dbin
+ // Those two values are guaranteed to be equal, even if the
+ // `wine` table is modified between the two requests:
+ letcount1=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+ letcount2=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+}
+
+trydbPool.read{dbin
+ // Now this value may be different:
+ letcount=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+}
+
+
+
This method is not reentrant.
+
+
Throws
+ The error thrown by the block, or any DatabaseError that would
+happen while establishing the read access to the database.
+
+
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:
+
trydbPool.unsafeRead{dbin
+ // Those two values may be different because some other thread
+ // may have inserted or deleted a wine between the two requests:
+ letcount1=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+ letcount2=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+}
+
+
+
Cursor iteration is safe, though:
+
trydbPool.unsafeRead{dbin
+ // No concurrent update can mess with this iteration:
+ letrows=tryRow.fetchCursor(db,"SELECT ...")
+ whileletrow=tryrows.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 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:
+
trydbPool.unsafeReentrantRead{dbin
+ // Those two values may be different because some other thread
+ // may have inserted or deleted a wine between the two requests:
+ letcount1=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+ letcount2=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+}
+
+
+
Cursor iteration is safe, though:
+
trydbPool.unsafeReentrantRead{dbin
+ // No concurrent update can mess with this iteration:
+ letrows=tryRow.fetchCursor(db,"SELECT ...")
+ whileletrow=tryrows.next(){...}
+}
+
+
+
This method is reentrant. It is unsafe because it fosters dangerous
+concurrency practices.
+
+
Throws
+ The error thrown by the block, or any DatabaseError that would
+happen while establishing the read access to the database.
+
+
This method is deprecated. Use concurrentRead instead.
+
+
Asynchronously executes a read-only block in a protected dispatch queue,
+wrapped in a deferred transaction.
+
+
This method must be called from the writing dispatch queue, outside of a
+transaction. You’ll get a fatal error otherwise.
+
+
The block argument is guaranteed to see the database in the last
+committed state at the moment this method is called. Eventual concurrent
+database updates are not visible inside the block.
+
trydbPool.write{dbin
+ trydb.execute("DELETE FROM player")
+ trydbPool.readFromCurrentState{dbin
+ // Guaranteed to be zero
+ tryInt.fetchOne(db,"SELECT COUNT(*) FROM player")!
+ }
+ trydb.execute("INSERT INTO player ...")
+}
+
+
+
This method blocks the current thread until the isolation guarantee has
+been established, and before the block argument has run.
+
+
Throws
+ The error thrown by the block, or any DatabaseError that would
+happen while establishing the read access to the database.
+
+
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.
The transaction type (default nil). If nil, the transaction
+type is configuration.defaultTransactionKind, which itself
+defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
+for more information.
+
+
+
+
+
+
+ block
+
+
+
+
+
A block that executes SQL statements and return either
+.commit or .rollback.
The snapshot sees an unchanging database content, as it existed at the
+moment it was created.
+
+
When you want to control the latest committed changes seen by a
+snapshot, create it from the pool’s writer protected dispatch queue:
+
letsnapshot1=trydbPool.write{db->DatabaseSnapshotin
+ tryPlayer.deleteAll()
+ returntrydbPool.makeSnapshot()
+}
+// <- Other threads may modify the database here
+letsnapshot2=trydbPool.makeSnapshot()
+
+trysnapshot1.read{dbin
+ // Guaranteed to be zero
+ tryPlayer.fetchCount(db)
+}
+
+trysnapshot2.read{dbin
+ // Could be anything
+ tryPlayer.fetchCount(db)
+}
+
+
+
It is forbidden to create a snapshot from the writer protected dispatch
+queue when a transaction is opened, though, because it is likely a
+programmer error:
+
trydbPool.write{dbin
+ trydb.inTransaction{
+ tryPlayer.deleteAll()
+ // fatal error: makeSnapshot() must not be called from inside a transaction
+ letsnapshot=trydbPool.makeSnapshot()
+ return.commit
+ }
+}
+
+
+
To avoid this fatal error, create the snapshot before or after the
+transaction:
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.
Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and
+SQLCipher), attempts to write in the database from this meethod throw a
+DatabaseError of resultCode SQLITE_READONLY.
This method is deprecated. Use concurrentRead instead.
+
+
Synchronously executes block.
+
+
This method must be called from the protected database dispatch queue,
+outside of a transaction. You’ll get a fatal error otherwise.
+
+
Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and
+SQLCipher), attempts to write in the database from this meethod throw a
+DatabaseError of resultCode SQLITE_READONLY.
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.
The transaction type (default nil). If nil, the transaction
+type is configuration.defaultTransactionKind, which itself
+defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
+for more information.
+
+
+
+
+
+
+ block
+
+
+
+
+
A block that executes SQL statements and return either
+.commit or .rollback.
letcollation=DatabaseCollation("localized_standard"){(string1,string2)in
+ return(string1asNSString).localizedStandardCompare(string2)
+}
+snapshot.add(collation:collation)
+letfiles=trysnapshot.read{dbin
+ tryFile.fetchAll(db,"SELECT * FROM file ORDER BY name COLLATE localized_standard")
+}
+
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.
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.
+
letcontroller=FetchedRecordsController<Wine>(
+ dbQueue,
+ sql:"SELECT * FROM wine WHERE color = ? ORDER BY name",
+ arguments:[Color.red],
+ isSameRecord:{(wine1,wine2)inwine1.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.
+
letcontroller=FetchedRecordsController<Wine>(
+ dbQueue,
+ sql:"SELECT * FROM wine WHERE color = ? ORDER BY name",
+ arguments:[Color.red])
+
+
+
The records are compared by primary key (single-column primary key,
+compound primary key, or implicit rowid). For a database table which
+has an id primary key, this initializer is equivalent to:
+
// Assuming the wine table has an `id` primary key:
+letcontroller=FetchedRecordsController<Wine>(
+ dbQueue,
+ sql:"SELECT * FROM wine WHERE color = ? ORDER BY name",
+ arguments:[Color.red],
+ isSameRecord:{(wine1,wine2)inwine1.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 wine table has an `id` primary key:
+letcontroller=FetchedRecordsController<Wine>(
+ dbQueue,
+ request:request,
+ isSameRecord:{(wine1,wine2)inwine1.id==wine2.id})
+
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.
A boolean that indicates whether the record has changes that have not
+been saved.
+
+
This flag is purely informative, and does not prevent insert(),
+update(), and save() from performing their database queries.
+
+
A record is edited if has been changed since last database
+synchronization (fetch, update, insert). Comparison
+is performed between values (values stored in the encode(to:)
+method, and values loaded from the database). Property setters do not
+trigger this flag.
+
+
You can rely on the Record base class to compute this flag for you, or
+you may set it to true or false when you know better. Setting it to
+false does not prevent it from turning true on subsequent modifications
+of the record.
On success, this method sets the hasDatabaseChanges flag to false.
+
+
This method is guaranteed to have inserted a row in the database if it
+returns without error.
+
+
Records whose primary key is declared as INTEGER PRIMARY KEY have
+their id automatically set after successful insertion, if it was nil
+before the insertion.
+
+
Throws
+ A DatabaseError whenever an SQLite error occurs.
+
+
On success, this method sets the hasDatabaseChanges flag to false.
+
+
This method is guaranteed to have updated a row in the database if it
+returns without error.
+
+
Throws
+ A DatabaseError is thrown whenever an SQLite error occurs.
+PersistenceError.recordNotFound is thrown if the primary key does not
+match any row in the database and record could not be updated.
+
+
If the record has been changed, executes an UPDATE statement so that
+those changes and only those changes are saved in the database.
+
+
On success, this method sets the hasDatabaseChanges flag to false.
+
+
This method is guaranteed to have saved the eventual changes in the
+database if it returns without error.
+
+
Throws
+ A DatabaseError is thrown whenever an SQLite error occurs.
+PersistenceError.recordNotFound is thrown if the primary key does not
+match any row in the database and record could not be updated.
+
+
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 true if and only if one column contains a non-null value, or if
+the row was fetched with a row adapter that defines a scoped row that
+contains a non-null value.
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 the record encoded in the given scope, if and only if the scope
+has been defined by a row adapter, and the scoped row contains a
+non-null value. Otherwise, return nil.
+
+
This subscript is designed to handle left joined records.
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.
+
letrows=tryRow.fetchCursor(db,"SELECT id, name FROM player")// RowCursor
+whileletrow=tryrows.next(){// Row
+ letid:Int64=row[0]
+ letname:String=row[1]
+}
+
+
+
Fetched rows are reused during the cursor iteration: don’t turn a row
+cursor into an array with Array(rows) or rows.filter { ... } since
+you would not get the distinct rows you expect. Use Row.fetchAll(...)
+instead.
+
+
For the same reason, make sure you make a copy whenever you extract a
+row for later use: row.copy().
+
+
If the database is modified during the cursor iteration, the remaining
+elements are undefined.
+
+
The cursor must be iterated in a protected dispath queue.
+
+
Throws
+ A DatabaseError is thrown whenever an SQLite error occurs.
+
+
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 the row associated with the given scope, by performing a
+breadth-first search in this row’s scopes and the scopes of its
+scoped rows, recursively.
The auto-incremented primary key is an integer primary key that
+automatically generates unused values when you do not explicitly
+provide one, and prevents the reuse of ids over the lifetime of
+the database.
+
+
It is the preferred way to define a numeric primary key.
+
+
The fact that an auto-incremented primary key prevents the reuse of
+ids is an excellent guard against data races that could happen when your
+application processes ids in an asynchronous way. The auto-incremented
+primary key provides the guarantee that a given id can’t reference a row
+that is different from the one it used to be at the beginning of the
+asynchronous process, even if this row gets deleted and a new one is
+inserted in between.
trydb.create(table:"player"){tin
+ t.column("personalPhone",.text)
+ t.column("workPhone",.text)
+ t.check(sql:"personalPhone IS NOT NULL OR workPhone IS NOT NULL")
+}
+
If the database value does not contain a suitable value, the function
+must return nil (GRDB will interpret this nil result as a conversion
+error, and react accordingly).
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.
Swift’s Optional comes with built-in methods that allow to fetch cursors
+and arrays of optional DatabaseValueConvertible:
+
tryOptional<String>.fetchCursor(db,"SELECT name FROM ...",arguments:...)// Cursor of String?
+tryOptional<String>.fetchAll(db,"SELECT name FROM ...",arguments:...)// [String?]
+
+letstatement=trydb.makeSelectStatement("SELECT name FROM ...")
+tryOptional<String>.fetchCursor(statement,arguments:...)// Cursor of String?
+tryOptional<String>.fetchAll(statement,arguments:...)// [String?]
+
+
+
DatabaseValueConvertible is adopted by Bool, Int, String, etc.
trydb.makeFTS5Pattern(rawPattern:"and",forTable:"document")// OK
+trydb.makeFTS5Pattern(rawPattern:"AND",forTable:"document")// malformed MATCH expression: [AND]
+
Returns a date initialized from dbValue, if possible.
+
+
If database value contains a number, that number is interpreted as a
+timeinterval since 00:00:00 UTC on 1 January 1970.
+
+
If database value contains a string, that string is interpreted as a
+SQLite date in the UTC time
+zone. Nil is returned if the date string does not contain at least the
+year, month and day components. Other components (minutes, etc.)
+are set to zero if missing.
Returns a date initialized from dbValue, if possible.
+
+
If database value contains a number, that number is interpreted as a
+timeinterval since 00:00:00 UTC on 1 January 1970.
+
+
If database value contains a string, that string is interpreted as a
+SQLite date in the UTC time
+zone. Nil is returned if the date string does not contain at least the
+year, month and day components. Other components (minutes, etc.)
+are set to zero if missing.
Swift’s Optional comes with built-in methods that allow to fetch cursors
+and arrays of optional DatabaseValueConvertible:
+
tryOptional<String>.fetchCursor(db,"SELECT name FROM ...",arguments:...)// Cursor of String?
+tryOptional<String>.fetchAll(db,"SELECT name FROM ...",arguments:...)// [String?]
+
+letstatement=trydb.makeSelectStatement("SELECT name FROM ...")
+tryOptional<String>.fetchCursor(statement,arguments:...)// Cursor of String?
+tryOptional<String>.fetchAll(statement,arguments:...)// [String?]
+
+
+
DatabaseValueConvertible is adopted by Bool, Int, String, etc.
Returns a cursor over optional values fetched from a prepared statement.
+
letstatement=trydb.makeSelectStatement("SELECT name FROM ...")
+letnames=tryOptional<String>.fetchCursor(statement)// Cursor of String?
+whileletname=trynames.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.
+
+
Returns a cursor over optional values fetched from a prepared statement.
+
letstatement=trydb.makeSelectStatement("SELECT name FROM ...")
+letnames=tryOptional<String>.fetchCursor(statement)// Cursor of String?
+whileletname=trynames.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.
+
+
Creates a request with a full-text predicate added to the eventual
+set of already applied predicates.
+
// SELECT * FROM book WHERE book MATCH '...'
+varrequest=Book.all()
+request=request.matching(pattern)
+
+
+
If the search pattern is nil, the request does not match any
+database row.
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
Returns an expression by joining all elements with an SQL
+logical operator.
+
+
For example:
+
// SELECT * FROM player
+// WHERE (registered
+// AND (score >= 1000)
+// AND (name IS NOT NULL))
+letconditions=[
+ Column("registered"),
+ Column("score")>=1000,
+ Column("name")!=nil]
+Player.filter(conditions.joined(operator:.and))
+
+
+
When the sequence is empty, joined(operator: .and) returns true,
+and joined(operator: .or) returns false:
+
// SELECT * FROM player WHERE 1
+Player.filter([].joined(operator:.and))
+
+// SELECT * FROM player WHERE 0
+Player.filter([].joined(operator:.or))
+
Relationship with standard Sequence and IteratorProtocol
+
+
Cursors share traits with lazy sequences and iterators from the Swift
+standard library. Differences are:
+
+
+
Cursor types are classes, and have a lifetime.
+
Cursor iteration may throw errors.
+
A cursor can not be repeated.
+
+
+
The protocol comes with default implementations for many operations similar
+to those defined by Swift’s Sequence protocol: contains, dropFirst,
+dropLast, drop(while:), enumerated, filter, first, flatMap,
+forEach, joined, joined(separator:), max, max(by:), min,
+min(by:), map, prefix, prefix(while:), reduce, reduce(into:),
+suffix.
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.
Types that adopt DatabaseValueConvertible can be initialized from
+database values.
+
+
The protocol comes with built-in methods that allow to fetch cursors,
+arrays, or single values:
+
tryString.fetchCursor(db,"SELECT name FROM ...",arguments:...)// Cursor of String
+tryString.fetchAll(db,"SELECT name FROM ...",arguments:...)// [String]
+tryString.fetchOne(db,"SELECT name FROM ...",arguments:...)// String?
+
+letstatement=trydb.makeSelectStatement("SELECT name FROM ...")
+tryString.fetchCursor(statement,arguments:...)// Cursor of String
+tryString.fetchAll(statement,arguments:...)// [String]
+tryString.fetchOne(statement,arguments:...)// String?
+
+
+
DatabaseValueConvertible is adopted by Bool, Int, String, etc.
The protocol for all requests that run from a single select statement, and
+tell how fetched rows should be interpreted.
+
structPlayer:FetchableRecord{...}
+letrequest:...// Some FetchRequest that fetches Player
+tryrequest.fetchCursor(db)// Cursor of Player
+tryrequest.fetchAll(db)// [Player]
+tryrequest.fetchOne(db)// Player?
+
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.
The StatementColumnConvertible protocol grants access to the low-level C
+interface that extracts values from query results:
+https://www.sqlite.org/c3ref/column_blob.html. It can bring performance
+improvements.
+
+
To use it, have a value type adopt both StatementColumnConvertible and
+DatabaseValueConvertible. GRDB will then automatically apply the
+optimization whenever direct access to SQLite is possible:
+
letrows=Row.fetchCursor(db,"SELECT ...")
+whileletrow=tryrows.next(){
+ letint:Int=row[0]// there
+}
+letints=Int.fetchAll(db,"SELECT ...")// there
+structPlayer{
+ init(row:Row){
+ name=row["name"]// there
+ score=row["score"]// there
+ }
+}
+
+
+
StatementColumnConvertible is already adopted by all Swift integer types,
+Float, Double, String, and Bool.
The association key defines how rows fetched from this association
+should be consumed.
+
+
For example:
+
structPlayer:TableRecord{
+ // The default key of this association is the name of the
+ // database table for teams, let's say "team":
+ staticletteam=belongsTo(Team.self)
+}
+print(Player.team.key)// Prints "team"
+
+// Consume rows:
+letrequest=Player.including(required:Player.team)
+forrowinRow.fetchAll(db,request){
+ letteam:Team=row["team"]// the association key
+}
+
Creates an association with the provided predicate promise added to
+the eventual set of already applied predicates.
+
structPlayer:TableRecord{
+ staticletteam=belongsTo(Team.self)
+}
+
+// SELECT player.*, team.*
+// FROM player
+// JOIN team ON team.id = player.teamId AND 1
+letassociation=Player.team.filter{dbintrue}
+varrequest=Player.including(required:association)
+
Creates an association with the provided orderings promise.
+
structPlayer:TableRecord{
+ staticletteam=belongsTo(Team.self)
+}
+
+// SELECT player.*, team.*
+// FROM player
+// JOIN team ON team.id = player.teamId
+// ORDER BY team.name
+letassociation=Player.team.order{_in[Column("name")]}
+varrequest=Player.including(required:association)
+
+
+
Any previous ordering is replaced:
+
// SELECT player.*, team.*
+// FROM player
+// JOIN team ON team.id = player.teamId
+// ORDER BY team.name
+letassociation=Player.team
+ .order{_in[Column("color")]}
+ .reversed()
+ .order{_in[Column("name")]}
+varrequest=Player.including(required:association)
+
Creates an association that reverses applied orderings.
+
structPlayer:TableRecord{
+ staticletteam=belongsTo(Team.self)
+}
+
+// SELECT player.*, team.*
+// FROM player
+// JOIN team ON team.id = player.teamId
+// ORDER BY team.name DESC
+letassociation=Player.team.order(Column("name")).reversed()
+varrequest=Player.including(required:association)
+
+
+
If no ordering was applied, the returned association is identical.
+
// SELECT player.*, team.*
+// FROM player
+// JOIN team ON team.id = player.teamId
+letassociation=Player.team.reversed()
+varrequest=Player.including(required:association)
+
Creates an association that includes another one. The columns of the
+associated record are selected. The returned association does not
+require that the associated database table contains a matching row.
Creates an association that includes another one. The columns of the
+associated record are selected. The returned association requires
+that the associated database table contains a matching row.
Creates an association that joins another one. The columns of the
+associated record are not selected. The returned association does not
+require that the associated database table contains a matching row.
Creates an association that joins another one. The columns of the
+associated record are not selected. The returned association requires
+that the associated database table contains a matching row.
Relationship with standard Sequence and IteratorProtocol
+
+
Cursors share traits with lazy sequences and iterators from the Swift
+standard library. Differences are:
+
+
+
Cursor types are classes, and have a lifetime.
+
Cursor iteration may throw errors.
+
A cursor can not be repeated.
+
+
+
The protocol comes with default implementations for many operations similar
+to those defined by Swift’s Sequence protocol: contains, dropFirst,
+dropLast, drop(while:), enumerated, filter, first, flatMap,
+forEach, joined, joined(separator:), max, max(by:), min,
+min(by:), map, prefix, prefix(while:), reduce, reduce(into:),
+suffix.
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.
A closure that takes an element of the cursir as
+its argument and returns true if the element should be skipped or
+false otherwise. Once predicate returns false it will not be
+called again.
A closure that takes an element of the cursor as
+its argument and returns true if the element should be included or
+false otherwise. Once predicate returns false it will not be
+called again.
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:
+
tryreader.read{dbin
+ // Those two values are guaranteed to be equal, even if the
+ // `wine` table is modified between the two requests:
+ letcount1=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+ letcount2=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+}
+
+tryreader.read{dbin
+ // Now this value may be different:
+ letcount=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+}
+
+
+
Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds
+and SQLCipher, attempts to write in the database throw a DatabaseError
+whose resultCode is SQLITE_READONLY.
+
+
Throws
+ The error thrown by the block, or any DatabaseError that would
+happen while establishing the read access to the database.
+
+
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:
+
tryreader.unsafeRead{dbin
+ // Those two values may be different because some other thread
+ // may have inserted or deleted a wine between the two requests:
+ letcount1=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+ letcount2=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+}
+
+
+
Cursor iterations are isolated, though:
+
tryreader.unsafeRead{dbin
+ // No concurrent update can mess with this iteration:
+ letrows=tryRow.fetchCursor(db,"SELECT ...")
+ whileletrow=tryrows.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.
+
+
Synchronously executes a block that takes a database connection, and
+returns its result.
+
+
The two guarantees of the safe read method are lifted:
+
+
The block argument is not isolated: eventual concurrent database updates
+are visible inside the block:
+
tryreader.unsafeReentrantRead{dbin
+ // Those two values may be different because some other thread
+ // may have inserted or deleted a wine between the two requests:
+ letcount1=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+ letcount2=tryInt.fetchOne(db,"SELECT COUNT(*) FROM wine")!
+}
+
+
+
Cursor iterations are isolated, though:
+
tryreader.unsafeReentrantRead{dbin
+ // No concurrent update can mess with this iteration:
+ letrows=tryRow.fetchCursor(db,"SELECT ...")
+ whileletrow=tryrows.next(){...}
+}
+
+
+
The block argument is not prevented from writing (DatabaseQueue, in
+particular, will accept database modifications in unsafeReentrantRead).
+
+
Throws
+ The error thrown by the block, or any DatabaseError that would
+happen while establishing the read access to the database.
+
+
+
+
This method is reentrant. It should be avoided because it fosters
+dangerous concurrency practices.
letcollation=DatabaseCollation("localized_standard"){(string1,string2)in
+ return(string1asNSString).localizedStandardCompare(string2)
+}
+reader.add(collation:collation)
+tryreader.execute("SELECT * FROM file 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.
Types that adopt DatabaseValueConvertible can be initialized from
+database values.
+
+
The protocol comes with built-in methods that allow to fetch cursors,
+arrays, or single values:
+
tryString.fetchCursor(db,"SELECT name FROM ...",arguments:...)// Cursor of String
+tryString.fetchAll(db,"SELECT name FROM ...",arguments:...)// [String]
+tryString.fetchOne(db,"SELECT name FROM ...",arguments:...)// String?
+
+letstatement=trydb.makeSelectStatement("SELECT name FROM ...")
+tryString.fetchCursor(statement,arguments:...)// Cursor of String
+tryString.fetchAll(statement,arguments:...)// [String]
+tryString.fetchOne(statement,arguments:...)// String?
+
+
+
DatabaseValueConvertible is adopted by Bool, Int, String, etc.
Returns a cursor over values fetched from a prepared statement.
+
letstatement=trydb.makeSelectStatement("SELECT name FROM ...")
+letnames=tryString.fetchCursor(statement)// Cursor of String
+whileletname=trynames.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.
+
+
Returns a cursor over values fetched from a prepared statement.
+
letstatement=trydb.makeSelectStatement("SELECT name FROM ...")
+letnames=tryString.fetchCursor(statement)// Cursor of String
+whileletname=trynames.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 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.
This method is deprecated. Use concurrentRead instead.
+
+
Synchronously or asynchronously executes a read-only block that takes a
+database connection.
+
+
This method must be called from a writing dispatch queue, outside of any
+transaction. You’ll get a fatal error otherwise.
+
+
The block argument is guaranteed to see the database in the last
+committed state at the moment this method is called. Eventual concurrent
+database updates are not visible inside the block.
+
+
For example:
+
trywriter.writeWithoutTransaction{dbin
+ trydb.execute("DELETE FROM player")
+ trywriter.readFromCurrentState{dbin
+ // Guaranteed to be zero
+ tryInt.fetchOne(db,"SELECT COUNT(*) FROM player")!
+ }
+ trydb.execute("INSERT INTO player ...")
+}
+
Concurrently executes a read-only block that takes a
+database connection.
+
+
This method must be called from a writing dispatch queue, outside of any
+transaction. You’ll get a fatal error otherwise.
+
+
The block argument is guaranteed to see the database in the last
+committed state at the moment this method is called. Eventual concurrent
+database updates are not visible inside the block.
+
+
This method returns as soon as the isolation guarantees described above
+are established. To access the fetched results, you call the wait()
+method of the returned future, on any dispatch queue.
+
+
In the example below, the number of players is fetched concurrently with
+the player insertion. Yet the future is guaranteed to return zero:
+
trywriter.writeWithoutTransaction{dbin
+ // Delete all players
+ tryPlayer.deleteAll()
+
+ // Count players concurrently
+ letfuture=writer.concurrentRead{dbin
+ returntryPlayer.fetchCount()
+ }
+
+ // Insert a player
+ tryPlayer(...).insert(db)
+
+ // Guaranteed to be zero
+ letcount=tryfuture.wait()
+}
+
The arguments parameter is an array of String built from the CREATE
+VIRTUAL TABLE statement. In the example below, the arguments will
+be ["arg1", "arg2"].
When implementing the accept method, there are a two rules
+to observe:
+
+
+
Errors thrown by the tokenCallback function must not be caught.
+
The input flags should be given unmodified to the tokenCallback
+function, unless you union it with the .colocated flag when the
+tokenizer produces synonyms (see
+https://www.sqlite.org/fts5.html#synonym_support).
The protocol for all requests that run from a single select statement, and
+tell how fetched rows should be interpreted.
+
structPlayer:FetchableRecord{...}
+letrequest:...// Some FetchRequest that fetches Player
+tryrequest.fetchCursor(db)// Cursor of Player
+tryrequest.fetchAll(db)// [Player]
+tryrequest.fetchOne(db)// Player?
+
letrequest:...// Some TypedRequest that fetches Row
+letrows=tryrequest.fetchCursor(db)// RowCursor
+whileletrow=tryrows.next(){// Row
+ letid:Int64=row[0]
+ letname:String=row[1]
+}
+
+
+
Fetched rows are reused during the cursor iteration: don’t turn a row
+cursor into an array with Array(rows) or rows.filter { ... } since
+you would not get the distinct rows you expect. Use Row.fetchAll(...)
+instead.
+
+
For the same reason, make sure you make a copy whenever you extract a
+row for later use: row.copy().
+
+
If the database is modified during the cursor iteration, the remaining
+elements are undefined.
+
+
The cursor must be iterated in a protected dispath queue.
+
+
Throws
+ A DatabaseError is thrown whenever an SQLite error occurs.
+
+
letrequest:...// Some TypedRequest that fetches Player
+letplayers=tryrequest.fetchCursor(db)// Cursor of Player
+whileletplayer=tryplayers.next(){// Player
+ ...
+}
+
+
+
If the database is modified during the cursor iteration, the remaining
+elements are undefined.
+
+
The cursor must be iterated in a protected dispath queue.
+
+
Throws
+ A DatabaseError is thrown whenever an SQLite error occurs.
+
+
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().
When the FetchableRecord type also adopts the standard Decodable
+protocol, you can use this dictionary to customize the decoding process
+from database rows.
+
+
For example:
+
// A key that holds a decoder's name
+letdecoderName=CodingUserInfoKey(rawValue:"decoderName")!
+
+// A FetchableRecord + Decodable record
+structPlayer:FetchableRecord,Decodable{
+ // Customize the decoder name when decoding a database row
+ staticletdatabaseDecodingUserInfo:[CodingUserInfoKey:Any]=[decoderName:"Database"]
+
+ init(fromdecoder:Decoder)throws{
+ // Print the decoder name
+ print(decoder.userInfo[decoderName])
+ ...
+ }
+}
+
+// prints "Database"
+letplayer=tryPlayer.fetchOne(db,...)
+
+// prints "JSON"
+letdecoder=JSONDecoder()
+decoder.userInfo=[decoderName:"JSON"]
+letplayer=trydecoder.decode(Player.self,from:...)
+
When the FetchableRecord type also adopts the standard Decodable
+protocol, this method controls the decoding process of nested properties
+from JSON database columns.
+
+
The default implementation returns a JSONDecoder with the
+following properties:
A cursor over all records fetched from the database.
+
// SELECT * FROM player
+letplayers=tryPlayer.fetchCursor(db)// Cursor of Player
+whileletplayer=tryplayers.next(){// Player
+ ...
+}
+
+
+
Records are iterated in the natural ordering of the table.
+
+
If the database is modified during the cursor iteration, the remaining
+elements are undefined.
+
+
The cursor must be iterated in a protected dispath queue.
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
+
+
Throws
+ A DatabaseError is thrown whenever an SQLite error occurs.
+
+
An array of all records fetched from the database.
+
// SELECT * FROM player
+letplayers=tryPlayer.fetchAll(db)// [Player]
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
+
+
Throws
+ A DatabaseError is thrown whenever an SQLite error occurs.
+
+
// SELECT * FROM player
+letplayer=tryPlayer.fetchOne(db)// Player?
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
+
+
Throws
+ A DatabaseError is thrown whenever an SQLite error occurs.
+
+
Returns a cursor over records identified by the provided unique keys
+(primary key or any key with a unique index on it).
+
letplayers=tryPlayer.fetchCursor(db,keys:[["email":"a@example.com"],["email":"b@example.com"]])// Cursor of Player
+whileletplayer=tryplayers.next(){// Player
+ ...
+}
+
+
+
Records are iterated in unspecified order.
+
+
Throws
+ A DatabaseError is thrown whenever an SQLite error occurs.
+
+
A cursor over records fetched from a prepared statement.
+
letstatement=trydb.makeSelectStatement("SELECT * FROM player")
+letplayers=tryPlayer.fetchCursor(statement)// Cursor of Player
+whileletplayer=tryplayers.next(){// Player
+ ...
+}
+
+
+
If the database is modified during the cursor iteration, the remaining
+elements are undefined.
+
+
The cursor must be iterated in a protected dispath queue.
+
+
Throws
+ A DatabaseError is thrown whenever an SQLite error occurs.
+
+
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.
It is undefined behavior to set different values for the same column.
+Column names are case insensitive, so defining both name and NAME
+is considered undefined behavior.
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.
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().
When the PersistableRecord type also adopts the standard Encodable
+protocol, you can use this dictionary to customize the encoding process
+into database rows.
+
+
For example:
+
// A key that holds a encoder's name
+letencoderName=CodingUserInfoKey(rawValue:"encoderName")!
+
+// A PersistableRecord + Encodable record
+structPlayer:PersistableRecord,Encodable{
+ // Customize the encoder name when encoding a database row
+ staticletdatabaseEncodingUserInfo:[CodingUserInfoKey:Any]=[encoderName:"Database"]
+
+ funcencode(toencoder:Encoder)throws{
+ // Print the encoder name
+ print(encoder.userInfo[encoderName])
+ ...
+ }
+}
+
+letplayer=Player(...)
+
+// prints "Database"
+tryplayer.insert(db)
+
+// prints "JSON"
+letencoder=JSONEncoder()
+encoder.userInfo=[encoderName:"JSON"]
+letdata=tryencoder.encode(player)
+
When the PersistableRecord type also adopts the standard Encodable
+protocol, this method controls the encoding process of nested properties
+into JSON database columns.
+
+
The default implementation returns a JSONEncoder with the
+following properties:
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.
+
+
If the record has differences from the other record, executes an UPDATE
+statement so that those changes and only those changes are saved in
+the database.
+
+
This method is guaranteed to have saved the eventual changes in the
+database if it returns without error.
+
+
Throws
+ A DatabaseError is thrown whenever an SQLite error occurs.
+PersistenceError.recordNotFound is thrown if the primary key does not
+match any row in the database and record could not be updated.
+
+
A dictionary of values changed from the other record.
+
+
Its keys are column names. Its values come from the other record.
+
+
Note that this method is not symmetrical, not only in terms of values,
+but also in terms of columns. When the two records don’t define the
+same set of columns in their encode(to:) method, only the columns
+defined by the receiver record are considered.
Don’t invoke this method directly: it is an internal method for types
+that adopt MutablePersistableRecord.
+
+
performInsert() provides the default implementation for insert(). Types
+that adopt MutablePersistableRecord can invoke performInsert() in their
+implementation of insert(). They should not provide their own
+implementation of performInsert().
Don’t invoke this method directly: it is an internal method for types
+that adopt MutablePersistableRecord.
+
+
performUpdate() provides the default implementation for update(). Types
+that adopt MutablePersistableRecord can invoke performUpdate() in their
+implementation of update(). They should not provide their own
+implementation of performUpdate().
+
+
Throws
+ A DatabaseError is thrown whenever an SQLite error occurs.
+PersistenceError.recordNotFound is thrown if the primary key does not
+match any row in the database.
+
+
Don’t invoke this method directly: it is an internal method for types
+that adopt MutablePersistableRecord.
+
+
performSave() provides the default implementation for save(). Types
+that adopt MutablePersistableRecord can invoke performSave() in their
+implementation of save(). They should not provide their own
+implementation of performSave().
+
+
This default implementation forwards the job to update or insert.
Don’t invoke this method directly: it is an internal method for types
+that adopt MutablePersistableRecord.
+
+
performDelete() provides the default implementation for deelte(). Types
+that adopt MutablePersistableRecord can invoke performDelete() in
+their implementation of delete(). They should not provide their own
+implementation of performDelete().
Don’t invoke this method directly: it is an internal method for types
+that adopt MutablePersistableRecord.
+
+
performExists() provides the default implementation for exists(). Types
+that adopt MutablePersistableRecord can invoke performExists() in
+their implementation of exists(). They should not provide their own
+implementation of performExists().
Delete records identified by their primary keys; returns the number of
+deleted rows.
+
// DELETE FROM player WHERE id IN (1, 2, 3)
+tryPlayer.deleteAll(db,keys:[1,2,3])
+
+// DELETE FROM country WHERE code IN ('FR', 'US', 'DE')
+tryCountry.deleteAll(db,keys:["FR","US","DE"])
+
+
+
When the table has no explicit primary key, GRDB uses the hidden
+rowid column:
+
// DELETE FROM document WHERE rowid IN (1, 2, 3)
+tryDocument.deleteAll(db,keys:[1,2,3])
+
Notifies the record that it was succesfully inserted.
+
+
Do not call this method directly: it is called for you, in a protected
+dispatch queue, with the inserted RowID and the eventual
+INTEGER PRIMARY KEY column name.
+
+
This method is optional: the default implementation does nothing.
+
+
If you need a mutating variant of this method, adopt the
+MutablePersistableRecord protocol instead.
+
+
+
Default Implementation
+
+
Notifies the record that it was succesfully inserted.
+
+
The default implementation does nothing.
+
+
+
+
Declaration
+
+
Swift
+
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 PersistableRecord.
+
+
performInsert() provides the default implementation for insert(). Types
+that adopt PersistableRecord can invoke performInsert() in their
+implementation of insert(). They should not provide their own
+implementation of performInsert().
Don’t invoke this method directly: it is an internal method for types
+that adopt PersistableRecord.
+
+
performSave() provides the default implementation for save(). Types
+that adopt PersistableRecord can invoke performSave() in their
+implementation of save(). They should not provide their own
+implementation of performSave().
+
+
This default implementation forwards the job to update or insert.
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.
+structFirstColumnAdapter:RowAdapter{
+ funclayoutedAdapter(fromlayout:RowLayout)throws->LayoutedRowAdapter{
+ returnLayoutedColumnMapping(layoutColumns:[(0,"foo")])
+ }
+}
+
+// [foo:1]
+tryRow.fetchOne(db,"SELECT 1, 2, 3",adapter:FirstColumnAdapter())
+
The StatementColumnConvertible protocol grants access to the low-level C
+interface that extracts values from query results:
+https://www.sqlite.org/c3ref/column_blob.html. It can bring performance
+improvements.
+
+
To use it, have a value type adopt both StatementColumnConvertible and
+DatabaseValueConvertible. GRDB will then automatically apply the
+optimization whenever direct access to SQLite is possible:
+
letrows=Row.fetchCursor(db,"SELECT ...")
+whileletrow=tryrows.next(){
+ letint:Int=row[0]// there
+}
+letints=Int.fetchAll(db,"SELECT ...")// there
+structPlayer{
+ init(row:Row){
+ name=row["name"]// there
+ score=row["score"]// there
+ }
+}
+
+
+
StatementColumnConvertible is already adopted by all Swift integer types,
+Float, Double, String, and Bool.
Unless said otherwise, requests select all columns:
+
// SELECT * FROM player
+tryPlayer.fetchAll(db)
+
+
+
You can provide a custom implementation and provide an explicit list
+of columns:
+
structRestrictedPlayer:TableRecord{
+ staticvardatabaseTableName="player"
+ staticvardatabaseSelection=[Column("id"),Column("name")]
+}
+
+// SELECT id, name FROM player
+tryRestrictedPlayer.fetchAll(db)
+
+
+
You can also add extra columns such as the rowid column:
+
structExtendedPlayer:TableRecord{
+ staticvardatabaseTableName="player"
+ staticletdatabaseSelection:[SQLSelectable]=[AllColumns(),Column.rowID]
+}
+
+// SELECT *, rowid FROM player
+tryExtendedPlayer.fetchAll(db)
+
The record type at the other side of the association.
+
+
+
+
+
+
+ key
+
+
+
+
+
An eventual decoding key for the association. By default, it
+is destination.databaseTableName.
+
+
+
+
+
+
+ foreignKey
+
+
+
+
+
An eventual foreign key. You need to provide an
+explicit foreign key when GRDB can’t infer one from the database
+schema. This happens when the schema does not define any foreign
+key to the destination table, or when the schema defines several
+foreign keys to the destination table.
The record type at the other side of the association.
+
+
+
+
+
+
+ key
+
+
+
+
+
An eventual decoding key for the association. By default, it
+is destination.databaseTableName.
+
+
+
+
+
+
+ foreignKey
+
+
+
+
+
An eventual foreign key. You need to provide an
+explicit foreign key when GRDB can’t infer one from the database
+schema. This happens when the schema does not define any foreign
+key from the destination table, or when the schema defines several
+foreign keys from the destination table.
The record type at the other side of the association.
+
+
+
+
+
+
+ key
+
+
+
+
+
An eventual decoding key for the association. By default, it
+is destination.databaseTableName.
+
+
+
+
+
+
+ foreignKey
+
+
+
+
+
An eventual foreign key. You need to provide an
+explicit foreign key when GRDB can’t infer one from the database
+schema. This happens when the schema does not define any foreign
+key from the destination table, or when the schema defines several
+foreign keys from the destination table.
Returns a QueryInterfaceRequest with a matching predicate.
+
// SELECT * FROM book WHERE book MATCH '...'
+varrequest=Book.matching(pattern)
+
+
+
If the search pattern is nil, the request does not match any
+database row.
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
Creates a request that includes an association. The columns of the
+associated record are selected. The returned association does not
+require that the associated database table contains a matching row.
Creates a request that includes an association. The columns of the
+associated record are selected. The returned association requires
+that the associated database table contains a matching row.
Creates a request that includes an association. The columns of the
+associated record are not selected. The returned association does not
+require that the associated database table contains a matching row.
Creates a request that includes an association. The columns of the
+associated record are not selected. The returned association requires
+that the associated database table contains a matching row.
Creates a request with aggregates appended to the selection.
+
// SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
+// FROM player LEFT JOIN book ...
+varrequest=Player.annotated(with:[Player.books.count])
+
Creates a request with the provided aggregate predicate.
+
// SELECT player.*
+// FROM player LEFT JOIN book ...
+// HAVING COUNT(DISTINCT book.rowid) = 0
+varrequest=Player.all()
+request=request.having(Player.books.isEmpty)
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
// SELECT * FROM player
+letrequest=Player.all()
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
// SELECT * FROM player WHERE email = 'arthur@example.com'
+letrequest=Player.filter(Column("email")=="arthur@example.com")
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
Creates a request with the provided primary key predicate.
+
// SELECT * FROM player WHERE id = 1
+letrequest=Player.filter(key:1)
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
Creates a request with the provided primary key predicate.
+
// SELECT * FROM player WHERE id IN (1, 2, 3)
+letrequest=Player.filter(keys:[1,2,3])
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
Creates a request with the provided primary key predicate.
+
// SELECT * FROM passport WHERE personId = 1 AND countryCode = 'FR'
+letrequest=Passport.filter(key:["personId":1,"countryCode":"FR"])
+
+
+
When executed, this request raises a fatal error if there is no unique
+index on the key columns.
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
Creates a request with the provided primary key predicate.
+
// SELECT * FROM passport WHERE (personId = 1 AND countryCode = 'FR') OR ...
+letrequest=Passport.filter(keys:[["personId":1,"countryCode":"FR"],...])
+
+
+
When executed, this request raises a fatal error if there is no unique
+index on the key columns.
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
// SELECT * FROM player WHERE email = 'arthur@example.com'
+letrequest=Player.filter(sql:"email = ?",arguments:["arthur@example.com"])
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
Creates a request sorted according to the
+provided orderings.
+
// SELECT * FROM player ORDER BY name
+letrequest=Player.order(Column("name"))
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
Creates a request sorted according to the
+provided orderings.
+
// SELECT * FROM player ORDER BY name
+letrequest=Player.order([Column("name")])
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
// SELECT * FROM player ORDER BY id
+letrequest=Player.orderByPrimaryKey()
+
+// SELECT * FROM country ORDER BY code
+letrequest=Country.orderByPrimaryKey()
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
// SELECT * FROM player ORDER BY name
+letrequest=Player.order(sql:"name")
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
Creates a request which fetches limit rows, starting at
+offset.
+
// SELECT * FROM player LIMIT 1
+letrequest=Player.limit(1)
+
+
+
The selection defaults to all columns. This default can be changed for
+all requests by the TableRecord.databaseSelection property, or
+for individual requests with the TableRecord.select method.
structPlayer:TableRecord{
+ staticletdatabaseTableName="player"
+}
+
+// SELECT "player".* FROM player
+letsql="SELECT \(Player.selectionSQL()) FROM player"
+
+// SELECT "p".* FROM player AS p
+letsql="SELECT \(Player.selectionSQL(alias:"p")) FROM player p"
+
Notifies a database change (insert, update, or delete).
+
+
The change is pending until the current transaction ends. See
+databaseWillCommit, databaseDidCommit and databaseDidRollback.
+
+
This method is called in a protected dispatch queue, serialized will all
+database updates.
+
+
The event is only valid for the duration of this method call. If you
+need to keep it longer, store a copy: event.copy()
+
+
The observer has an opportunity to stop receiving further change events
+from the current transaction by calling the
+stopObservingDatabaseChangesUntilNextTransaction() method.
Notifies before a database change (insert, update, or delete)
+with change information (initial / final values for the row’s
+columns). (Called before databaseDidChangeWithEvent.)
+
+
The change is pending until the end of the current transaction,
+and you always get a second chance to get basic event information in
+the databaseDidChangeWithEvent callback.
+
+
This callback is mostly useful for calculating detailed change
+information for a row, and provides the initial / final values.
+
+
This method is called in a protected dispatch queue, serialized will all
+database updates.
+
+
The event is only valid for the duration of this method call. If you
+need to keep it longer, store a copy: event.copy()
+
+
Warning
+ this method must not change the database.
+
+
+
+
Availability Info
+
+
Requires SQLite 3.13.0 +
+Compiled with option SQLITE_ENABLE_PREUPDATE_HOOK
The databaseDidChangeWithEvent callback is always available,
+and may provide most/all of what you need.
+(For example, FetchedRecordsController is built without databaseWillChange)
DatabaseRegion defines a region in the database. DatabaseRegion is dedicated
+to help transaction observers recognize impactful database changes in their
+observes(eventsOfKind:) and databaseDidChange(with:) methods.
+
+
A database region is the union of any number of table regions, which can
+cover a full table, or the combination of columns and rows (identified by
+their rowids):
let request = Player.filter(key: 1)
+try print(request.databaseRegion(db))
+// prints player(*)[1]
+
+
+
Database regions returned by requests can be more precise than regions
+returned by select statements. Especially, regions returned by statements
+don’t know about rowids:
+
// A plain statement
+letstatement=db.makeSelectStatement("SELECT * FROM player WHERE id = 1")
+statement.databaseRegion// "player(*)"
+
+// A query interface request that executes the same statement:
+letrequest=Player.filter(key:1)
+tryrequest.databaseRegion(db)// "player(*)[1]"
+
ColumnMapping is a row adapter that maps column names.
+
letadapter=ColumnMapping(["foo":"bar"])
+letsql="SELECT 'foo' AS foo, 'bar' AS bar, 'baz' AS baz"
+
+// [foo:"bar"]
+tryRow.fetchOne(db,sql,adapter:adapter)
+
RangeRowAdapter is a row adapter that only exposes a range of columns.
+
letadapter=RangeRowAdapter(1..<3)
+letsql="SELECT 1 AS foo, 2 AS bar, 3 AS baz, 4 as qux"
+
+// [bar:2 baz:3]
+tryRow.fetchOne(db,sql,adapter:adapter)
+
+ and += operators consider that overriding named arguments is a
+programmer error:
+
vararguments:StatementArguments=["name":"Arthur"]
+arguments+=["name":"Barbara"]
+// fatal error: already defined statement argument: name
+
+
+
&+ and append(contentsOf:) allow overriding named arguments:
+
vararguments:StatementArguments=["name":"Arthur"]
+arguments=arguments&+["name":"Barbara"]
+print(arguments)
+// Prints ["name": "Barbara"]
+
+
Mixed Arguments
+
+
It is possible to mix named and positional arguments. Yet this is usually
+confusing, and it is best to avoid this practice:
+
letsql="SELECT ?2 AS two, :foo AS foo, ?1 AS one, :foo AS foo2, :bar AS bar"
+vararguments:StatementArguments=[1,2,"bar"]+["foo":"foo"]
+letrow=tryRow.fetchOne(db,sql,arguments:arguments)!
+print(row)
+// Prints [two:2 foo:"foo" one:1 foo2:"foo" bar:"bar"]
+
+
+
Mixed arguments exist as a support for requests like the following:
The BelongsTo association sets up a one-to-one connection from a record
+type to another record type, such as each instance of the declaring record
+belongs to an instance of the other record.
+
+
For example, if your application includes authors and books, and each book
+is assigned its author, you’d declare the association this way:
A BelongsTo associations should be supported by an SQLite foreign key.
+
+
Foreign keys are the recommended way to declare relationships between
+database tables because not only will SQLite guarantee the integrity of your
+data, but GRDB will be able to use those foreign keys to automatically
+configure your association.
+
+
You define the foreign key when you create database tables. For example:
The book.authorId column is used to link a book to the author it
+belongs to.
+
Make the book.authorId column not null if you want SQLite to guarantee
+that all books have an author.
+
Create an index on the book.authorId column in order to ease the
+selection of an author’s books.
+
Create a foreign key from book.authorId column to authors.id, so that
+SQLite guarantees that no book refers to a missing author. The
+onDelete: .cascade option has SQLite automatically delete all of an
+author’s books when that author is deleted.
+See https://sqlite.org/foreignkeys.html#fk_actions for more information.
+
+
+
The example above uses auto-incremented primary keys. But generally
+speaking, all primary keys are supported.
+
+
If the database schema does not define foreign keys between tables, you can
+still use BelongsTo associations. But your help is needed to define the
+missing foreign key:
A ForeignKey helps building associations when GRDB can’t infer a foreign
+key from the database schema.
+
+
Sometimes the database schema does not define any foreign key between two
+tables. And sometimes, there are several foreign keys from a table
+to another:
When this happens, associations can’t be automatically inferred from the
+database schema. GRDB will complain with a fatal error such as Ambiguous
+foreign key from book to person, or Could not infer foreign key from book
+to person.
+
+
Your help is needed. You have to instruct GRDB which foreign key to use:
Foreign keys are always defined from the table that contains the columns at
+the origin of the foreign key. Person’s symmetric HasMany associations reuse
+Book’s foreign keys:
The HasMany association indicates a one-to-many connection between two
+record types, such as each instance of the declaring record has many
+instances of the other record.
+
+
For example, if your application includes authors and books, and each author
+is assigned zero or more books, you’d declare the association this way:
HasMany associations should be supported by an SQLite foreign key.
+
+
Foreign keys are the recommended way to declare relationships between
+database tables because not only will SQLite guarantee the integrity of your
+data, but GRDB will be able to use those foreign keys to automatically
+configure your association.
+
+
You define the foreign key when you create database tables. For example:
The book.authorId column is used to link a book to the author it
+belongs to.
+
Make the book.authorId column not null if you want SQLite to guarantee
+that all books have an author.
+
Create an index on the book.authorId column in order to ease the
+selection of an author’s books.
+
Create a foreign key from book.authorId column to authors.id, so that
+SQLite guarantees that no book refers to a missing author. The
+onDelete: .cascade option has SQLite automatically delete all of an
+author’s books when that author is deleted.
+See https://sqlite.org/foreignkeys.html#fk_actions for more information.
+
+
+
The example above uses auto-incremented primary keys. But generally
+speaking, all primary keys are supported.
+
+
If the database schema does not define foreign keys between tables, you can
+still use HasMany associations. But your help is needed to define the
+missing foreign key:
The HasOne association indicates a one-to-one connection between two
+record types, such as each instance of the declaring record has one
+instances of the other record.
+
+
For example, if your application has one database table for countries, and
+another for their demographic profiles, you’d declare the association
+this way:
HasOne associations should be supported by an SQLite foreign key.
+
+
Foreign keys are the recommended way to declare relationships between
+database tables because not only will SQLite guarantee the integrity of your
+data, but GRDB will be able to use those foreign keys to automatically
+configure your association.
+
+
You define the foreign key when you create database tables. For example:
The demographics.countryCode column is used to link a demographic
+profile to the country it belongs to.
+
Make the demographics.countryCode column not null if you want SQLite to
+guarantee that all profiles are linked to a country.
+
Create a unique index on the demographics.countryCode column in order to
+guarantee the unicity of any country’s profile.
+
Create a foreign key from demographics.countryCode column to
+country.code, so that SQLite guarantees that no profile refers to a
+missing country. The onDelete: .cascade option has SQLite automatically
+delete a profile when its country is deleted.
+See https://sqlite.org/foreignkeys.html#fk_actions for more information.
+
+
+
The example above uses a string primary for the country table. But generally
+speaking, all primary keys are supported.
+
+
If the database schema does not follow this convention, and does not define
+foreign keys between tables, you can still use HasOne associations. But
+your help is needed to define the missing foreign key:
The BelongsTo association sets up a one-to-one connection from a record
+type to another record type, such as each instance of the declaring record
+belongs to an instance of the other record.
+
+
For example, if your application includes authors and books, and each book
+is assigned its author, you’d declare the association this way:
A BelongsTo associations should be supported by an SQLite foreign key.
+
+
Foreign keys are the recommended way to declare relationships between
+database tables because not only will SQLite guarantee the integrity of your
+data, but GRDB will be able to use those foreign keys to automatically
+configure your association.
+
+
You define the foreign key when you create database tables. For example:
The book.authorId column is used to link a book to the author it
+belongs to.
+
Make the book.authorId column not null if you want SQLite to guarantee
+that all books have an author.
+
Create an index on the book.authorId column in order to ease the
+selection of an author’s books.
+
Create a foreign key from book.authorId column to authors.id, so that
+SQLite guarantees that no book refers to a missing author. The
+onDelete: .cascade option has SQLite automatically delete all of an
+author’s books when that author is deleted.
+See https://sqlite.org/foreignkeys.html#fk_actions for more information.
+
+
+
The example above uses auto-incremented primary keys. But generally
+speaking, all primary keys are supported.
+
+
If the database schema does not define foreign keys between tables, you can
+still use BelongsTo associations. But your help is needed to define the
+missing foreign key:
The SQL snippet that defines the default value, if any.
+
+
When nil, the column has no default value.
+
+
When not nil, it contains an SQL string that defines an expression. That
+expression may be a literal, as 1, or 'foo'. It may also contain a
+non-constant expression such as CURRENT_TIMESTAMP.
+
+
For example:
+
trydb.execute("""
+ CREATE TABLE player(
+ id INTEGER PRIMARY KEY,
+ name TEXT DEFAULT 'Anonymous',
+ score INT DEFAULT 0,
+ creationDate DATE DEFAULT CURRENT_TIMESTAMP
+ )
+ """)
+letcolumnInfos=trydb.columns(in:"player")
+columnInfos[0].defaultValueSQL// nil
+columnInfos[1].defaultValueSQL// "'Anoynymous'"
+columnInfos[2].defaultValueSQL// "0"
+columnInfos[3].defaultValueSQL// "CURRENT_TIMESTAMP"
+
ColumnMapping is a row adapter that maps column names.
+
letadapter=ColumnMapping(["foo":"bar"])
+letsql="SELECT 'foo' AS foo, 'bar' AS bar, 'baz' AS baz"
+
+// [foo:"bar"]
+tryRow.fetchOne(db,sql,adapter:adapter)
+
The database label is also used to name the various dispatch queues
+created by GRDB, visible in debugging sessions and crash logs. However
+those dispatch queue labels are intended for debugging only. Their
+format may change between GRDB releases. Applications should not depend
+on the GRDB dispatch queue labels.
+
+
If the database label is nil, the current GRDB implementation uses the
+following dispatch queue labels:
+
+
+
GRDB.DatabaseQueue: the (unique) dispatch queue of a DatabaseQueue
+
GRDB.DatabasePool.writer: the (unique) writer dispatch queue of
+a DatabasePool
+
GRDB.DatabasePool.reader.N, where N is 1, 2, …: one of the reader
+dispatch queue(s) of a DatabasePool. N grows with the number of SQLite
+connections: it may get bigger than the maximum number of concurrent
+readers, as SQLite connections get closed and new ones are opened.
+
GRDB.DatabasePool.snapshot.N: the dispatch queue of a
+DatabaseSnapshot. N grows with the number of snapshots.
+
+
+
If the database label is not nil, for example MyDatabase, the current
+GRDB implementation uses the following dispatch queue labels:
+
+
+
MyDatabase: the (unique) dispatch queue of a DatabaseQueue
+
MyDatabase.writer: the (unique) writer dispatch queue of
+a DatabasePool
+
MyDatabase.reader.N, where N is 1, 2, …: one of the reader
+dispatch queue(s) of a DatabasePool. N grows with the number of SQLite
+connections: it may get bigger than the maximum number of concurrent
+readers, as SQLite connections get closed and new ones are opened.
+
MyDatabase.snapshot.N: the dispatch queue of a
+DatabaseSnapshot. N grows with the number of snapshots.
If false, it is a programmer error to leave a transaction opened at the
+end of a database access block.
+
+
For example:
+
letdbQueue=DatabaseQueue()
+
+// fatal error: A transaction has been left opened at the end of a database access
+trydbQueue.inDatabase{dbin
+ trydb.beginTransaction()
+}
+
+
+
If true, one can leave opened transaction at the end of database access
+blocks:
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.
When the eraseDatabaseOnSchemaChange flag is true, the migrator will
+automatically wipe out the full database content, and recreate the whole
+database from scratch, if it detects that a migration has changed its
+definition.
+
+
This flag can destroy your precious users’ data!
+
+
But it may be useful in two situations:
+
+
+
During application development, as you are still designing
+migrations, and the schema changes often.
+
+
In this case, it is recommended that you make sure this flag does
+not ship in the distributed application, in order to avoid undesired
+data loss:
+
varmigrator=DatabaseMigrator()
+#if DEBUG
+// Speed up development by nuking the database when migrations change
+migrator.eraseDatabaseOnSchemaChange=true
+#endif
+
+
When the database content can easily be recreated, such as a cache
+for some downloaded data.
Iterate migrations in the same order as they were registered, up to the
+provided target. If a migration has not yet been applied, its block is
+executed in a transaction.
+
targetIdentifier: The identifier of a registered migration.
+
+
Throws
+ An eventual error thrown by the registered migration blocks.
+
+
DatabaseRegion defines a region in the database. DatabaseRegion is dedicated
+to help transaction observers recognize impactful database changes in their
+observes(eventsOfKind:) and databaseDidChange(with:) methods.
+
+
A database region is the union of any number of table regions, which can
+cover a full table, or the combination of columns and rows (identified by
+their rowids):
let request = Player.filter(key: 1)
+try print(request.databaseRegion(db))
+// prints player(*)[1]
+
+
+
Database regions returned by requests can be more precise than regions
+returned by select statements. Especially, regions returned by statements
+don’t know about rowids:
+
// A plain statement
+letstatement=db.makeSelectStatement("SELECT * FROM player WHERE id = 1")
+statement.databaseRegion// "player(*)"
+
+// A query interface request that executes the same statement:
+letrequest=Player.filter(key:1)
+tryrequest.databaseRegion(db)// "player(*)[1]"
+
Returns whether the content in the region is impacted by this event.
+
+
Precondition
+ event has been filtered by the same region
+in the TransactionObserver.observes(eventsOfKind:) method, by calling
+region.isModified(byEventsOfKind:)
+
+
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.
A ForeignKey helps building associations when GRDB can’t infer a foreign
+key from the database schema.
+
+
Sometimes the database schema does not define any foreign key between two
+tables. And sometimes, there are several foreign keys from a table
+to another:
When this happens, associations can’t be automatically inferred from the
+database schema. GRDB will complain with a fatal error such as Ambiguous
+foreign key from book to person, or Could not infer foreign key from book
+to person.
+
+
Your help is needed. You have to instruct GRDB which foreign key to use:
Foreign keys are always defined from the table that contains the columns at
+the origin of the foreign key. Person’s symmetric HasMany associations reuse
+Book’s foreign keys:
The HasMany association indicates a one-to-many connection between two
+record types, such as each instance of the declaring record has many
+instances of the other record.
+
+
For example, if your application includes authors and books, and each author
+is assigned zero or more books, you’d declare the association this way:
HasMany associations should be supported by an SQLite foreign key.
+
+
Foreign keys are the recommended way to declare relationships between
+database tables because not only will SQLite guarantee the integrity of your
+data, but GRDB will be able to use those foreign keys to automatically
+configure your association.
+
+
You define the foreign key when you create database tables. For example:
The book.authorId column is used to link a book to the author it
+belongs to.
+
Make the book.authorId column not null if you want SQLite to guarantee
+that all books have an author.
+
Create an index on the book.authorId column in order to ease the
+selection of an author’s books.
+
Create a foreign key from book.authorId column to authors.id, so that
+SQLite guarantees that no book refers to a missing author. The
+onDelete: .cascade option has SQLite automatically delete all of an
+author’s books when that author is deleted.
+See https://sqlite.org/foreignkeys.html#fk_actions for more information.
+
+
+
The example above uses auto-incremented primary keys. But generally
+speaking, all primary keys are supported.
+
+
If the database schema does not define foreign keys between tables, you can
+still use HasMany associations. But your help is needed to define the
+missing foreign key:
The HasOne association indicates a one-to-one connection between two
+record types, such as each instance of the declaring record has one
+instances of the other record.
+
+
For example, if your application has one database table for countries, and
+another for their demographic profiles, you’d declare the association
+this way:
HasOne associations should be supported by an SQLite foreign key.
+
+
Foreign keys are the recommended way to declare relationships between
+database tables because not only will SQLite guarantee the integrity of your
+data, but GRDB will be able to use those foreign keys to automatically
+configure your association.
+
+
You define the foreign key when you create database tables. For example:
The demographics.countryCode column is used to link a demographic
+profile to the country it belongs to.
+
Make the demographics.countryCode column not null if you want SQLite to
+guarantee that all profiles are linked to a country.
+
Create a unique index on the demographics.countryCode column in order to
+guarantee the unicity of any country’s profile.
+
Create a foreign key from demographics.countryCode column to
+country.code, so that SQLite guarantees that no profile refers to a
+missing country. The onDelete: .cascade option has SQLite automatically
+delete a profile when its country is deleted.
+See https://sqlite.org/foreignkeys.html#fk_actions for more information.
+
+
+
The example above uses a string primary for the country table. But generally
+speaking, all primary keys are supported.
+
+
If the database schema does not follow this convention, and does not define
+foreign keys between tables, you can still use HasOne associations. But
+your help is needed to define the missing foreign key:
Accesses the value associated with the given column.
+
+
It is undefined behavior to set different values for the same column.
+Column names are case insensitive, so defining both name and NAME
+is considered undefined behavior.
Accesses the value associated with the given column.
+
+
It is undefined behavior to set different values for the same column.
+Column names are case insensitive, so defining both name and NAME
+is considered undefined behavior.
Creates a request that includes an association. The columns of the
+associated record are selected. The returned association does not
+require that the associated database table contains a matching row.
Creates a request that includes an association. The columns of the
+associated record are selected. The returned association requires
+that the associated database table contains a matching row.
Creates a request that includes an association. The columns of the
+associated record are not selected. The returned association does not
+require that the associated database table contains a matching row.
Creates a request that includes an association. The columns of the
+associated record are not selected. The returned association requires
+that the associated database table contains a matching row.
Creates a request which appends aggregates to the current selection.
+
// SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
+// FROM player LEFT JOIN book ...
+varrequest=Player.all()
+request=request.annotated(with:Player.books.count)
+
Creates a request which appends aggregates to the current selection.
+
// SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
+// FROM player LEFT JOIN book ...
+varrequest=Player.all()
+request=request.annotated(with:[Player.books.count])
+
Creates a request which appends the provided aggregate predicate to
+the eventual set of already applied predicates.
+
// SELECT player.*
+// FROM player LEFT JOIN book ...
+// HAVING COUNT(DISTINCT book.rowid) = 0
+varrequest=Player.all()
+request=request.having(Player.books.isEmpty)
+
// SELECT id, email, name FROM player
+varrequest=Player.all()
+request=request
+ .select([Column("id"),Column("email")])
+ .annotated(with:[Column("name")])
+
// SELECT DISTINCT * FROM player
+varrequest=Player.all()
+request=request.distinct()
+
+// SELECT DISTINCT name FROM player
+varrequest=Player.select(Column("name"))
+request=request.distinct()
+
RangeRowAdapter is a row adapter that only exposes a range of columns.
+
letadapter=RangeRowAdapter(1..<3)
+letsql="SELECT 1 AS foo, 2 AS bar, 3 AS baz, 4 as qux"
+
+// [bar:2 baz:3]
+tryRow.fetchOne(db,sql,adapter:adapter)
+
Returns true if the code on the left matches the code on the right.
+
+
Primary result codes match themselves and their extended result codes,
+while extended result codes match only themselves:
+
switcherror.extendedResultCode{
+case.SQLITE_CONSTRAINT_FOREIGNKEY:// foreign key constraint error
+case.SQLITE_CONSTRAINT:// any other constraint error
+default:// any other database error
+}
+
+ and += operators consider that overriding named arguments is a
+programmer error:
+
vararguments:StatementArguments=["name":"Arthur"]
+arguments+=["name":"Barbara"]
+// fatal error: already defined statement argument: name
+
+
+
&+ and append(contentsOf:) allow overriding named arguments:
+
vararguments:StatementArguments=["name":"Arthur"]
+arguments=arguments&+["name":"Barbara"]
+print(arguments)
+// Prints ["name": "Barbara"]
+
+
Mixed Arguments
+
+
It is possible to mix named and positional arguments. Yet this is usually
+confusing, and it is best to avoid this practice:
+
letsql="SELECT ?2 AS two, :foo AS foo, ?1 AS one, :foo AS foo2, :bar AS bar"
+vararguments:StatementArguments=[1,2,"bar"]+["foo":"foo"]
+letrow=tryRow.fetchOne(db,sql,arguments:arguments)!
+print(row)
+// Prints [two:2 foo:"foo" one:1 foo2:"foo" bar:"bar"]
+
+
+
Mixed arguments exist as a support for requests like the following:
A question? Looking for advice? Do you wonder how to contribute? Fancy a chat? Go to the GRDB forums, or open a Github issue.
+
+
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.
Carthage can build GRDB frameworks, but it can also inexplicably fail. This installation method is thus unsupported.
+
+
If you decide to use Carthage despite this warning, and get any Carthage-related error, please open an issue in the Carthage repo, ask Stack Overflow, summon your local Xcode guru, or submit a pull request that has the make test_CarthageBuild command succeed 100% of the time (one time is not enough). See #262 for more information.
+
Manually
+
+
+
Download a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the git checkout v3.4.0 command.
+
Embed the GRDB.xcodeproj project in your own project.
+
Add the GRDBOSX, GRDBiOS, or GRDBWatchOS target in the Target Dependencies section of the Build Phases tab of your application target (extension target for WatchOS).
+
Add the GRDB.framework from the targetted platform to the Embedded Binaries section of the General tab of your application target (extension target for WatchOS).
SQLite creates the database file if it does not already exist. The connection is closed when the database queue gets deallocated.
+
+
A database queue can be used from any thread. The write and read methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue:
A database queue serializes accesses to the database, which means that there is never more than one thread that uses the database.
+
+
+
When you don’t need to modify the database, prefer the read method. It prevents any modification to the database.
+
The write method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, all changes are reverted, the whole transaction is rollbacked, and the error is rethrown.
SQLite creates the database file if it does not already exist. The connection is closed when the database pool gets deallocated.
+
+
+
:point_up: Note: unless read-only, a database pool opens your database in the SQLite WAL mode. The WAL mode does not fit all situations. Please have a look at https://www.sqlite.org/wal.html.
+
+
+
A database pool can be used from any thread. The write and read methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue:
Database pools allow several threads to access the database at the same time:
+
+
+
When you don’t need to modify the database, prefer the read method, because several threads can perform reads in parallel.
+
+
Reads are generally non-blocking, unless the maximum number of concurrent reads has been reached. In this case, a read has to wait for another read to complete. That maximum number can be configured.
+
Reads are guaranteed an immutable view of the last committed state of the database, regardless of concurrent writes. This kind of isolation is called snapshot isolation.
+
Unlike reads, writes are serialized. There is never more than a single thread that is writing into the database.
+
The write method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, all changes are reverted, the whole transaction is rollbacked, and the error is rethrown.
Database pools can take snapshots of the database.
+
+
+
A database pool needs your application to follow rules in order to deliver its safety guarantees. See the Concurrency chapter for more details about database pools, how they differ from database queues, and advanced use cases.
+
+
See the Demo Application for a sample code that sets up a database queue on iOS, and just 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.label="MyDatabase"// Useful when your app opens multiple databases
+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:
+
trydbQueue.write{dbin
+ trydb.execute("""
+ CREATE TABLE player (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NOT NULL,
+ score INT)
+ """)
+
+ trydb.execute(
+ "INSERT INTO player (name, score) VALUES (?, ?)",
+ arguments:["Barbara",1000])
+
+ trydb.execute(
+ "UPDATE player SET score = :score WHERE id = :id",
+ arguments:["score":1000,"id":1])
+ }
+}
+
+
+
The ? and colon-prefixed keys like :score in the SQL query are the statements arguments. You pass arguments with arrays or dictionaries, as in the example above. See Values for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and StatementArguments for a detailed documentation of SQLite arguments.
+
+
Never ever embed values directly in your SQL strings, and always use arguments instead. See Avoiding SQL Injection for more information:
+
// WRONG
+letid=123
+letname=textField.text
+trydb.execute("UPDATE player SET name = '\(name)' WHERE id = \(id)")
+
+// CORRECT
+trydb.execute(
+ "UPDATE player SET name = :name WHERE id = :id",
+ arguments:["name":name,"id":id])
+
+
+
Join multiple statements with a semicolon:
+
trydb.execute("""
+ INSERT INTO player (name, score) VALUES (?, ?);
+ INSERT INTO player (name, score) VALUES (?, ?)
+ """,arguments:["Arthur",750,"Barbara",1000])
+
+
+
When you want to make sure that a single statement is executed, use Prepared Statements.
+
+
After an INSERT statement, you can get the row ID of the inserted row:
+
trydb.execute(
+ "INSERT INTO player (name, score) VALUES (?, ?)",
+ arguments:["Arthur",1000])
+letplayerId=db.lastInsertedRowID
+
+
+
Don’t miss Records, that provide classic persistence methods:
Whenever you consume several rows from the database, you can fetch an Array, or a Cursor.
+
+
The fetchAll() method returns a regular Swift array, that you iterate like all other arrays:
+
trydbQueue.read{dbin
+ // [Player]
+ letplayers=tryPlayer.fetchAll(db,"SELECT ...")
+ forplayerinplayers{
+ // use player
+ }
+}
+
+
+
Unlike arrays, cursors returned by fetchCursor() load their results step after step:
+
trydbQueue.read{dbin
+ // Cursor of Player
+ letplayers=tryPlayer.fetchCursor(db,"SELECT ...")
+ whileletplayer=tryplayers.next(){
+ // use player
+ }
+}
+
+
+
Both arrays and cursors can iterate over database results. How do you choose one or the other? Look at the differences:
+
+
+
Cursors can not be used on any thread: you must consume a cursor on the dispatch queue it was created in. Particularly, don’t extract a cursor out of a database access method:
// OK
+letarray=trydbQueue.read{dbin
+ tryPlayer.fetchAll(db,...)
+}
+forplayerinarray{...}
+
+
Cursors can be iterated only one time. Arrays can be iterated many times.
+
Cursors iterate database results in a lazy fashion, and don’t consume much memory. Arrays contain copies of database values, and may take a lot of memory when there are many fetched results.
+
Cursors are granted with direct access to SQLite, unlike arrays that have to take the time to copy database values. If you look after extra performance, you may prefer cursors over arrays.
+
Cursors adopt the Cursor protocol, which looks a lot like standard lazy sequences of Swift. As such, cursors come with many convenience methods: compactMap, contains, dropFirst, dropLast, drop(while:), enumerated, filter, first, flatMap, forEach, joined, joined(separator:), max, max(by:), min, min(by:), map, prefix, prefix(while:), reduce, reduce(into:), suffix:
+
// Prints all Github links
+tryURL
+ .fetchCursor(db,"SELECT url FROM link")
+ .filter{urlinurl.host=="github.com"}
+ .forEach{urlinprint(url)}
+
+// An efficient cursor of coordinates:
+letlocations=tryRow.
+ .fetchCursor(db,"SELECT latitude, longitude FROM place")
+ .map{rowin
+ CLLocationCoordinate2D(latitude:row[0],longitude:row[1])
+ }
+
+// Turn cursors into arrays or sets:
+letarray=tryArray(cursor)
+letset=trySet(cursor)
+
+
Cursors are not Swift sequences. That’s because Swift sequences can’t handle iteration errors, when reading SQLite results may fail at any time. SQL functions may throw errors. On iOS, data protection may block access to the database file in the background. On macOS, your application users may mess with the file system.
+
Cursors require a little care:
+
+
+
Don’t modify the results during a cursor iteration:
Don’t turn a cursor of Row into an array. You would not get the distinct rows you expect. To get a array of rows, use Row.fetchAll(...). Generally speaking, make sure you copy a row whenever you extract it from a cursor for later use: row.copy().
+
+
+
+
If you don’t see, or don’t care about the difference, use arrays. If you care about memory and performance, use cursors when appropriate.
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 player WHERE name = ?",
+ arguments:["Arthur"])
+
+letrows=tryRow.fetchAll(db,
+ "SELECT * FROM player WHERE name = :name",
+ arguments:["name":"Arthur"])
+
+
+
See Values for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and StatementArguments for a detailed documentation of SQLite arguments.
+
+
Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care:
+
+
+
:point_up: Don’t turn a cursor of Row into an array. You would not get the distinct rows you expect. To get a array of rows, use Row.fetchAll(...). Generally speaking, make sure you copy a row whenever you extract it from a cursor for later use: row.copy().
+
+
Column Values
+
+
Read column values by index or column name:
+
letname:String=row[0]// 0 is the leftmost column
+letname:String=row["name"]// Leftmost matching column - lookup is case-insensitive
+letname:String=row[Column("name")]// Using query interface's Column
+
+
+
Make sure to ask for an optional when the value may be NULL:
+
letname:String?=row["name"]
+
+
+
The row[] subscript returns the type you ask for. See Values for more information on supported value types:
+
letbookCount:Int=row["bookCount"]
+letbookCount64:Int64=row["bookCount"]
+lethasBooks:Bool=row["bookCount"]// false when 0
+
+letstring:String=row["date"]// "2015-09-11 18:14:15.123"
+letdate:Date=row["date"]// Date
+self.date=row["date"]// Depends on the type of the property.
+
+
+
You can also use the as type casting operator:
+
row[...]asInt
+row[...]asInt?
+
+
+
+
:warning: Warning: avoid the as! and as? operators:
+
ifletint=row[...]as?Int{...}// BAD - doesn't work
+ifletint=row[...]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[0]asInt?// nil
+row[0]asInt// fatal error: could not convert NULL to Int.
+
+
+
There is one exception, though: the DatabaseValue type:
+
row[0]asDatabaseValue// DatabaseValue.null
+
+
Missing columns return nil.
+
letrow=tryRow.fetchOne(db,"SELECT 'foo' AS foo")!
+row["missing"]asString?// nil
+row["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[0]asString// "Mom’s birthday"
+row[0]asDate?// fatal error: could not convert "Mom’s birthday" to Date.
+row[0]asDate// fatal error: could not convert "Mom’s birthday" to Date.
+
+letrow=tryRow.fetchOne(db,"SELECT 256")!
+row[0]asInt// 256
+row[0]asUInt8?// fatal error: could not convert 256 to UInt8.
+row[0]asUInt8// fatal error: could not convert 256 to UInt8.
+
+
+
Those conversion fatal errors can be avoided with the DatabaseValue type:
This extra verbosity is the consequence of having to deal with an untrusted database: you may consider fixing the content of your database instead. See Fatal Errors for more information.
+
SQLite has a weak type system, and provides convenience conversions that can turn String to Int, Double to Blob, etc.
+
+
GRDB will sometimes let those conversions go through:
+
letrows=tryRow.fetchCursor(db,"SELECT '20 small cigars'")
+whileletrow=tryrows.next(){
+ row[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:
+
letdbValue:DatabaseValue=row[0]
+letdbValue:DatabaseValue?=row["name"]// nil if and only if column does not exist
+
+// Check for NULL:
+dbValue.isNull// Bool
+
+// The stored value:
+dbValue.storage.value// Int64, Double, String, Data, or nil
+
+// All the five storage classes supported by SQLite:
+switchdbValue.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)")
+}
+
A [String: AnyObject] dictionary which keeps rightmost value in case of duplicated column name. This dictionary is identical to FMResultSet’s resultDictionary from FMDB. It contains NSNull values for null columns, and can be shared with Objective-C:
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:
+
trydbQueue.read{dbin
+ tryInt.fetchCursor(db,"SELECT ...",arguments:...)// A Cursor of Int
+ tryInt.fetchAll(db,"SELECT ...",arguments:...)// [Int]
+ tryInt.fetchOne(db,"SELECT ...",arguments:...)// Int?
+
+ // When database may contain NULL:
+ tryOptional<Int>.fetchCursor(db,"SELECT ...",arguments:...)// A Cursor of Int?
+ tryOptional<Int>.fetchAll(db,"SELECT ...",arguments:...)// [Int?]
+}
+
+letplayerCount=trydbQueue.read{dbin
+ tryInt.fetchOne(db,"SELECT COUNT(*) FROM player")!
+}
+
+
+
fetchOne returns an optional value which is nil in two cases: either the SELECT statement yielded no row, or one row with a NULL value.
+
+
There are many supported value types (Bool, Int, String, Date, Swift enums, etc.). See Values for more information:
+
letcount=tryInt.fetchOne(db,"SELECT COUNT(*) FROM player")!// Int
+leturls=tryURL.fetchAll(db,"SELECT url FROM link")// [URL]
+
+
Values
+
+
GRDB ships with built-in support for the following value types:
+
+
+
Swift Standard Library: Bool, Double, Float, all signed and unsigned integer types, String, Swift enums.
At each step of the request iteration, the row[] subscript creates two copies of the database bytes: one fetched by SQLite, and another, stored in the Swift Data value.
+
+
You have the opportunity to save memory by not copying the data fetched by SQLite:
Here is how GRDB supports the various date formats supported by SQLite:
+
+
+
+
SQLite format
+
Date
+
DateComponents
+
+
+
+
YYYY-MM-DD
+
Read ¹
+
Read/Write
+
+
+
YYYY-MM-DD HH:MM
+
Read ¹
+
Read/Write
+
+
+
YYYY-MM-DD HH:MM:SS
+
Read ¹
+
Read/Write
+
+
+
YYYY-MM-DD HH:MM:SS.SSS
+
Read/Write ¹
+
Read/Write
+
+
+
YYYY-MM-DD*T*HH:MM
+
Read ¹
+
Read
+
+
+
YYYY-MM-DD*T*HH:MM:SS
+
Read ¹
+
Read
+
+
+
YYYY-MM-DD*T*HH:MM:SS.SSS
+
Read ¹
+
Read
+
+
+
HH:MM
+
+
Read/Write
+
+
+
HH:MM:SS
+
+
Read/Write
+
+
+
HH:MM:SS.SSS
+
+
Read/Write
+
+
+
Timestamps since unix epoch
+
Read ²
+
+
+
+
now
+
+
+
+
+
+
¹ Dates are stored and read in the UTC time zone. Missing components are assumed to be zero.
+
+
² GRDB 2+ interprets numerical values as timestamps that fuel Date(timeIntervalSince1970:). Previous GRDB versions used to interpret numbers as julian days. Julian days are still supported, with the Date(julianDay:) initializer.
+
Date
+
+
Date can be stored and fetched from the database just like other values:
+
trydb.execute(
+ "INSERT INTO player (creationDate, ...) VALUES (?, ...)",
+ arguments:[Date(),...])
+
+letrow=tryRow.fetchOne(db,...)!
+letcreationDate:Date=row["creationDate"]
+
+
+
Dates are stored using the format YYYY-MM-DD HH:MM:SS.SSS in the UTC time zone. It is precise to the millisecond.
+
+
+
:point_up: Note: this format was chosen because it is the only format that is:
+
+
+
Comparable (ORDER BY date works)
+
Comparable with the SQLite keyword CURRENT_TIMESTAMP (WHERE date > CURRENT_TIMESTAMP works)
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 player (birthDate, ...) VALUES (?, ...)",
+ arguments:[dbComponents,...])
+
+// Read "1973-09-18"
+letrow=tryRow.fetchOne(db,"SELECT birthDate ...")!
+letdbComponents:DatabaseDateComponents=row["birthDate"]
+dbComponents.format// .YMD (the actual format found in the database)
+dbComponents.dateComponents// DateComponents
+
+
NSNumber and NSDecimalNumber
+
+
NSNumber can be stored and fetched from the database just like other values. Floating point NSNumbers are stored as Double. Integer and boolean, as Int64. Integers that don’t fit Int64 won’t be stored: you’ll get a fatal error instead. Be cautious when an NSNumber contains an UInt64, for example.
+
+
NSDecimalNumber deserves a longer discussion:
+
+
SQLite has no support for decimal numbers. Given the table below, SQLite will actually store integers or doubles:
+
CREATETABLEtransfer(
+ amountDECIMAL(10,5)-- will store integer or double, actually
+)
+
+
+
This means that computations will not be exact:
+
trydb.execute("INSERT INTO transfer (amount) VALUES (0.1)")
+trydb.execute("INSERT INTO transfer (amount) VALUES (0.2)")
+letsum=tryNSDecimalNumber.fetchOne(db,"SELECT SUM(amount) FROM transfer")!
+
+// Yikes! 0.3000000000000000512
+print(sum)
+
+
+
Don’t blame SQLite or GRDB, and instead store your decimal numbers differently.
+
+
A classic technique is to store integers instead, since SQLite performs exact computations of integers. For example, don’t store Euros, but store cents instead:
+
// Write
+letamount=NSDecimalNumber(string:"0.10")
+letintegerAmount=amount.multiplying(byPowerOf10:2).int64Value
+trydb.execute("INSERT INTO transfer (amount) VALUES (?)",arguments:[integerAmount])
+
+// Read
+letintegerAmount=tryInt64.fetchOne(db,"SELECT SUM(amount) FROM transfer")!
+letamount=NSDecimalNumber(value:integerAmount).multiplying(byPowerOf10:-2)// 0.10
+
+
UUID
+
+
UUID can be stored and fetched from the database just like other values.
+
+
GRDB stores uuids as 16-bytes data blobs, and decodes them from both 16-bytes data blobs and strings such as E621E1F8-C36C-495A-93FC-0C247A3E6E5F.
+
Swift Enums
+
+
Swift enums and generally all types that adopt the RawRepresentable protocol can be stored and fetched from the database just like their raw values:
protocolDatabaseValueConvertible{
+ /// Returns a value that can be stored in the database.
+ vardatabaseValue:DatabaseValue{get}
+
+ /// Returns a value initialized from dbValue, if possible.
+ staticfuncfromDatabaseValue(_dbValue:DatabaseValue)->Self?
+}
+
+
+
All types that adopt this protocol can be used like all other values (Bool, Int, String, Date, Swift enums, etc.)
+
+
The databaseValue property returns DatabaseValue, a type that wraps the five values supported by SQLite: NULL, Int64, Double, String and Data. Since DatabaseValue has no public initializer, use DatabaseValue.null, or another type that already adopts the protocol: 1.databaseValue, "foo".databaseValue, etc. Conversion to DatabaseValue must not fail.
+
+
The fromDatabaseValue() factory method returns an instance of your custom type if the database value contains a suitable value. If the database value does not contain a suitable value, such as foo for Date, fromDatabaseValuemust return nil (GRDB will interpret this nil result as a conversion error, and react accordingly).
A transaction is a fundamental tool of SQLite that guarantees data consistency as well as proper isolation between application threads and database connections.
+
+
GRDB generally opens transactions for you, as a way to enforce its concurrency guarantees, and provide maximal security for both your application data and application logic:
+
// BEGIN TRANSACTION
+// INSERT INTO credit ...
+// INSERT INTO debit ...
+// COMMIT
+trydbQueue.write{dbin
+ tryCredit(destinationAccout,amount).insert(db)
+ tryDebit(sourceAccount,amount).insert(db)
+}
+
+// BEGIN TRANSACTION
+// INSERT INTO credit ...
+// INSERT INTO debit ...
+// COMMIT
+trydbPool.write{dbin
+ tryCredit(destinationAccout,amount).insert(db)
+ tryDebit(sourceAccount,amount).insert(db)
+}
+
+
+
Yet you may need to exactly control when transactions take place:
+
Explicit Transactions
+
+
DatabaseQueue.inDatabase() and DatabasePool.writeWithoutTransaction() execute your database statements outside of any transaction:
+
// INSERT INTO credit ...
+// INSERT INTO debit ...
+trydbQueue.inDatabase{dbin
+ tryCredit(destinationAccout,amount).insert(db)
+ tryDebit(sourceAccount,amount).insert(db)
+}
+
+// INSERT INTO credit ...
+// INSERT INTO debit ...
+trydbPool.writeWithoutTransaction{dbin
+ tryCredit(destinationAccout,amount).insert(db)
+ tryDebit(sourceAccount,amount).insert(db)
+}
+
+
+
Writing outside of any transaction is dangerous, for two reasons:
+
+
+
In our credit/debit example, you may successfully insert a credit, but fail inserting the debit, and end up with unbalanced accounts (oops).
+
// UNSAFE DATABASE INTEGRITY
+trydbQueue.inDatabase{dbin// or dbPool.writeWithoutTransaction
+ tryCredit(destinationAccout,amount).insert(db)// may succeed
+ tryDebit(sourceAccount,amount).insert(db)// may fail
+}
+
+
+
Transactions avoid this kind of bug.
+
Database pool concurrent reads can see an inconsistent state of the database:
+
// UNSAFE CONCURRENCY
+trydbPool.writeWithoutTransaction{dbin
+ tryCredit(destinationAccout,amount).insert(db)
+ // <- Concurrent dbPool.read sees a partial db update here
+ tryDebit(sourceAccount,amount).insert(db)
+}
+
+
+
Transactions avoid this kind of bug, too.
+
+
+
To open explicit transactions, use one of the Database.inTransaction, DatabaseQueue.inTransaction, or DatabasePool.writeInTransaction methods:
+
// BEGIN TRANSACTION
+// INSERT INTO credit ...
+// INSERT INTO debit ...
+// COMMIT
+trydbQueue.inDatabase{dbin// or dbPool.writeWithoutTransaction
+ trydb.inTransaction{
+ tryCredit(destinationAccout,amount).insert(db)
+ tryDebit(sourceAccount,amount).insert(db)
+ return.commit
+ }
+}
+
+// BEGIN TRANSACTION
+// INSERT INTO credit ...
+// INSERT INTO debit ...
+// COMMIT
+trydbQueue.inTransaction{dbin// or dbPool.writeInTransaction
+ tryCredit(destinationAccout,amount).insert(db)
+ tryDebit(sourceAccount,amount).insert(db)
+ return.commit
+}
+
+
+
If an error is thrown from the transaction block, the transaction is rollbacked and the error is rethrown by the inTransaction method. If you return .rollback instead of .commit, the transaction is also rollbacked, but no error is thrown.
+
+
You can also perform manual transaction management:
Transactions can’t be left opened unless you set the allowsUnsafeTransactions configuration flag:
+
// fatal error: A transaction has been left opened at the end of a database access
+trydbQueue.inDatabase{dbin
+ trydb.execute("BEGIN TRANSACTION")
+ // <- no commit or rollback
+}
+
Yet, you have a better option than checking for transactions: critical database sections 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.write{dbin
+ // Makes sure both inserts succeed, or none:
+ trydb.inSavepoint{
+ tryCredit(destinationAccout,amount).insert(db)
+ tryDebit(sourceAccount,amount).insert(db)
+ return.commit
+ }
+
+ // Other savepoints, etc...
+}
+
+
+
If an error is thrown from the savepoint block, the savepoint is rollbacked and the error is rethrown by the inSavepoint method. If you return .rollback instead of .commit, the savepoint is also rollbacked, but no error is thrown.
+
+
Unlike transactions, savepoints can be nested. They implicitly open a transaction if no one was opened when the savepoint begins. As such, they behave just like nested transactions. Yet the database changes are only written to disk when the outermost transaction is committed:
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.write{dbin
+ letupdateSQL="INSERT INTO player (name, score) VALUES (:name, :score)"
+ letupdateStatement=trydb.makeUpdateStatement(updateSQL)
+
+ letselectSQL="SELECT * FROM player 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).
After arguments are set, you can execute the prepared statement:
+
tryupdateStatement.execute()
+
+
+
Select statements can be used wherever a raw SQL query string would fit (see fetch queries):
+
letrows=tryRow.fetchCursor(selectStatement)// A Cursor of Row
+letplayers=tryPlayer.fetchAll(selectStatement)// [Player]
+letplayer=tryPlayer.fetchOne(selectStatement)// Player?
+
+
+
You can set the arguments at the moment of the statement execution:
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:
// SELECT reverseString("name") FROM player
+Player.select(reverseString.apply(nameColumn))
+
+
+
GRDB ships with built-in SQL functions that perform unicode-aware string transformations. See Unicode.
+
Custom Aggregates
+
+
Before registering a custom aggregate, you need to define a type that adopts the DatabaseAggregate protocol:
+
protocolDatabaseAggregate{
+ // Initializes an aggregate
+ init()
+
+ // Called at each step of the aggregation
+ mutatingfuncstep(_dbValues:[DatabaseValue])throws
+
+ // Returns the final result
+ funcfinalize()throws->DatabaseValueConvertible?
+}
+
+
+
For example:
+
structMaxLength:DatabaseAggregate{
+ varmaxLength:Int=0
+
+ mutatingfuncstep(_dbValues:[DatabaseValue]){
+ // At each step, extract string value, if any...
+ guardletstring=String.fromDatabaseValue(dbValues[0])else{
+ return
+ }
+ // ... and update the result
+ letlength=string.count
+ iflength>maxLength{
+ maxLength=length
+ }
+ }
+
+ funcfinalize()->DatabaseValueConvertible?{
+ returnmaxLength
+ }
+}
+
+letmaxLength=DatabaseFunction(
+ "maxLength",
+ argumentCount:1,
+ pure:true,
+ aggregate:MaxLength.self)
+
+dbQueue.add(function:maxLength)// Or dbPool.add(function: ...)
+
+trydbQueue.read{dbin
+ // Some Int
+ tryInt.fetchOne(db,"SELECT maxLength(name) FROM player")!
+}
+
+
+
The step method of the aggregate takes an array of DatabaseValue. This array contains as many values as the argumentCount parameter (or any number of values, when argumentCount is omitted).
+
+
The finalize method of the aggregate returns the final aggregated value (Bool, Int, String, Date, Swift enums, etc.).
+
+
SQLite has the opportunity to perform additional optimizations when aggregates are pure, which means that their result only depends on their inputs. So make sure to set the pure argument to true when possible.
// SELECT maxLength("name") FROM player
+letrequest=Player.select(maxLength.apply(nameColumn))
+tryInt.fetchOne(db,request)// Int?
+
+
Database Schema Introspection
+
+
GRDB comes with a set of schema introspection methods:
+
trydbQueue.read{dbin
+ // Bool, true if the table exists
+ trydb.tableExists("player")
+
+ // [ColumnInfo], the columns in the table
+ trydb.columns(in:"player")
+
+ // PrimaryKeyInfo
+ trydb.primaryKey("player")
+
+ // [ForeignKeyInfo], the foreign keys defined on the table
+ trydb.foreignKeys(on:"player")
+
+ // [IndexInfo], the indexes defined on the table
+ trydb.indexes(on:"player")
+
+ // Bool, true if column(s) is a unique key (primary key or unique index)
+ trydb.table("player",hasUniqueKey:["email"])
+}
+
+// Bool, true if argument is the name of an internal SQLite table
+Database.isSQLiteInternalTable(...)
+
+// Bool, true if argument is the name of an internal GRDB table
+Database.isGRDBInternalTable(...)
+
+
Row Adapters
+
+
Row adapters let you present database rows in the way expected by the row consumers.
+
+
They basically help two incompatible row interfaces to work together. For example, a row consumer expects a column named consumed, but the produced row has a column named produced.
+
+
In this case, the ColumnMapping row adapter comes in handy:
+
// Fetch a 'produced' column, and consume a 'consumed' column:
+letadapter=ColumnMapping(["consumed":"produced"])
+letrow=tryRow.fetchOne(db,"SELECT 'Hello' AS produced",adapter:adapter)!
+row["consumed"]// "Hello"
+row["produced"]// nil
+
+
+
Row adapters are values that adopt the RowAdapter protocol. You can implement your own custom adapters (:fire: EXPERIMENTAL), or use one of the four built-in adapters, described below.
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 through the Row.scopes property:
letadapter=ScopeAdapter([
+ "left":ScopeAdapter([
+ "left":RangeRowAdapter(0..<1),
+ "right":RangeRowAdapter(1..<2)]),
+ "right":ScopeAdapter([
+ "left":RangeRowAdapter(2..<3),
+ "right":RangeRowAdapter(3..<4)])
+ ])
+letrow=tryRow.fetchOne(db,"SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d",adapter:adapter)!
+
+letleftRow=row.scopes["left"]!
+leftRow.scopes["left"]// [a:0]
+leftRow.scopes["right"]// [b:1]
+
+letrightRow=row.scopes["right"]!
+rightRow.scopes["left"]// [c:2]
+rightRow.scopes["right"]// [d:3]
+
+
+
Any adapter can be extended with scopes:
+
letbaseAdapter=RangeRowAdapter(0..<2)
+letadapter=ScopeAdapter(base:baseAdapter,scopes:[
+ "remainder":SuffixRowAdapter(fromIndex:2)])
+letrow=tryRow.fetchOne(db,"SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d",adapter:adapter)!
+
+row// [a:0 b:1]
+row.scopes["remainder"]// [c:2 d:3]
+
Those functions are embedded right into the GRDBCustom and GRCBCipher modules. For the regular GRDB framework: you’ll need to import SQLite3, or CSQLite, depending on whether you use the Swift Package Manager or not:
+
#if SWIFT_PACKAGE
+ importCSQLite// For Swift Package Manager
+#else
+ importSQLite3// Otherwise
+#endif
+
+letsqliteVersion=String(cString:sqlite3_libversion())
+
trydbQueue.read{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.
+
GRDB opens SQLite connections in the [multi-thread mode](https://www.sqlite.org/threadsafe.html), which (oddly) means that they are not thread-safe. Make sure you touch raw databases and statements inside their dedicated dispatch queues.
+
Use the raw SQLite C Interface at your own risk. GRDB won’t prevent you from shooting yourself in the foot.
+
+
+
+
Before jumping in the low-level wagon, here is the list of all SQLite APIs used by GRDB:
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 record comparison. See the list of record methods for an overview.
+
+
+
:point_up: Note: if you are familiar with Core Data’s NSManagedObject or Realm’s Object, you may experience a cultural shock: GRDB records are not uniqued, do not auto-update, and do not lazy-load. This is both a purpose, and a consequence of protocol-oriented programming. You should read How to build an iOS application with SQLite and GRDB.swift for a general introduction.
GRDB ships with three record protocols. Your own types will adopt one or several of them, according to the abilities you want to extend your types with.
See column values for more information about the row[] subscript.
+
+
When your record type adopts the standard Decodable protocol, you don’t have to provide the implementation for init(row:). See Codable Records for more information:
FetchableRecord allows adopting types to be fetched from SQL queries:
+
tryPlace.fetchCursor(db,"SELECT ...",arguments:...)// A Cursor of Place
+tryPlace.fetchAll(db,"SELECT ...",arguments:...)// [Place]
+tryPlace.fetchOne(db,"SELECT ...",arguments:...)// Place?
+
+
+
See fetching methods for information about the fetchCursor, fetchAll and fetchOne methods. See StatementArguments for more information about the query arguments.
+
+
+
:point_up: Note: for performance reasons, the same row argument to init(row:) is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: self.row = row.copy().
+
+
:point_up: Note: The FetchableRecord.init(row:) initializer fits the needs of most applications. But some application are more demanding than others. When FetchableRecord does not exactly provide the support you need, have a look at the Beyond FetchableRecord chapter.
+
+
TableRecord Protocol
+
+
The TableRecord protocol generates SQL for you. To use TableRecord, subclass the Record class, or adopt it explicitly:
When the table has no explicit primary key, GRDB uses the hidden rowid column:
+
// SELECT * FROM document 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 citizenship WHERE citizenId = 1 AND countryCode = 'FR'
+tryCitizenship.fetchOne(db,key:["citizenId":1,"countryCode":"FR"])// Citizenship?
+
+
PersistableRecord Protocol
+
+
GRDB provides two protocols that let adopting types create, update, and delete rows in the database:
+
protocolMutablePersistableRecord:TableRecord{
+ /// Defines the values persisted in the database
+ funcencode(tocontainer:inoutPersistenceContainer)
+
+ /// 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?)
+}
+
+
protocolPersistableRecord:MutablePersistableRecord{
+ /// 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 class, choose PersistableRecord. On top of that, implement didInsert(with:for:) if the database table has an auto-incremented primary key.
+
If your type is a struct, and the database table has an auto-incremented primary key, choose MutablePersistableRecord, and implement didInsert(with:for:).
+
Otherwise, choose PersistableRecord, and ignore didInsert(with:for:).
+
+
+
The encode(to:) method defines which values (Bool, Int, String, Date, Swift enums, etc.) are assigned to database columns.
+
+
The optional didInsert method lets the adopting type store its rowID after successful insertion, and is only useful for tables that have an auto-incremented primary key. It is called from a protected dispatch queue, and serialized with all database updates.
+
+
To use the persistable protocols, subclass the Record class, or adopt one of them explicitly. For example:
+
extensionPlace:MutablePersistableRecord{
+ /// The values persisted in the database
+ funcencode(tocontainer:inoutPersistenceContainer){
+ container["id"]=id
+ container["title"]=title
+ container["latitude"]=coordinate.latitude
+ container["longitude"]=coordinate.longitude
+ }
+
+ // Update id upon successful insertion:
+ mutatingfuncdidInsert(withrowID:Int64,forcolumn:String?){
+ id=rowID
+ }
+}
+
+varparis=Place(
+ id:nil,
+ title:"Paris",
+ coordinate:CLLocationCoordinate2D(latitude:48.8534100,longitude:2.3488000))
+
+tryparis.insert(db)
+paris.id// some value
+
When your record type adopts the standard Encodable protocol, you don’t have to provide the implementation for encode(to:). See Codable Records for more information:
insert, update, save and delete can throw a DatabaseError.
+
update and updateChanges can also throw a PersistenceError, should the update fail because there is no matching row in the database.
+
+
When saving an object that may or may not already exist in the database, prefer the save method:
+
save makes sure your values are stored in the database.
+
+
It performs an UPDATE if the record has a non-null primary key, and then, if no row was modified, an INSERT. It directly perfoms an INSERT if the record has no primary key, or a null primary key.
+
+
Despite the fact that it may execute two SQL statements, save behaves as an atomic operation: GRDB won’t allow any concurrent thread to sneak in (see concurrency).
+
delete returns whether a database row was deleted or not.
+
+
+
All primary keys are supported, including composite primary keys that span several columns, and the implicit rowid primary key.
+
Customizing the Persistence Methods
+
+
Your custom type may want to perform extra work when the persistence methods are invoked.
+
+
For example, it may want to have its UUID automatically set before inserting. Or it may want to validate its values before saving.
+
+
When you subclass Record, you simply have to override the customized method, and call super:
If you use the raw PersistableRecord protocol, use one of the special methodsperformInsert, performUpdate, performSave, performDelete, or performExists:
: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.
// Declare a record...
+structPlayer:Codable,FetchableRecord,PersistableRecord{
+ varname:String
+ varscore:Int
+}
+
+// ...and there you go:
+trydbQueue.write{dbin
+ tryPlayer(name:"Arthur",score:100).insert(db)
+ letplayers=tryPlayer.fetchAll(db)
+}
+
+
+
Codable records encode and decode their properties according to their own implementation of the Encodable and Decodable protocols. Yet databases have specific requirements:
+
+
+
Properties are always coded according to their preferred database representation, when they have one (all values that adopt the DatabaseValueConvertible protocol).
+
You can customize the encoding and decoding of dates and uuids.
+
Complex properties (arrays, dictionaries, nested structs, etc.) are stored as JSON.
When a Codable record contains a property that is not a simple value (Bool, Int, String, Date, Swift enums, etc.), that value is encoded and decoded as a JSON string. For example:
GRDB uses the standard JSONDecoder and JSONEncoder from Foundation. By default, Data values are handled with the .base64 strategy, Date with the .millisecondsSince1970 strategy, and non conforming floats with the .throw strategy.
+
+
You can customize the JSON format by implementing those methods:
:bulb: Tip: Make sure you set the JSONEncoder sortedKeys option, available from iOS 11.0+, macOS 10.13+, and watchOS 4.0+. This option makes sure that the JSON output is stable. This stability is required for Record Comparison to work as expected, and database observation tools such as FetchedRecordsController or RxGRDB to accurately recognize changed records.
To sum up: dates encode themselves in the YYYY-MM-DD HH:MM:SS.SSS format, in the UTC time zone, and decode a variety of date formats and timestamps. UUIDs encode themselves as 16-bytes data blobs, and decode both 16-bytes data blobs and strings such as E621E1F8-C36C-495A-93FC-0C247A3E6E5F.
:point_up: Note: there is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs, and uuid strings).
+
+
The userInfo Dictionary
+
+
Your Codable Records can be stored in the database, but they may also have other purposes. In this case, you may need to customize their implementations of Decodable.init(from:) and Encodable.encode(to:), depending on the context.
+
+
The standard way to provide such context is the userInfo dictionary. Implement those properties:
For example, here is a Player type that customizes its decoding:
+
// A key that holds a decoder's name
+letdecoderName=CodingUserInfoKey(rawValue:"decoderName")!
+
+structPlayer:FetchableRecord,Decodable{
+ init(fromdecoder:Decoder)throws{
+ // Print the decoder name
+ letdecoderName=decoder.userInfo[decoderName]as?String
+ print("Decoded from \(decoderName??"unknown decoder")")
+ ...
+ }
+}
+
+
+
You can have a specific decoding from JSON…
+
// prints "Decoded from JSON"
+letdecoder=JSONDecoder()
+decoder.userInfo=[decoderName:"JSON"]
+letplayer=trydecoder.decode(Player.self,from:jsonData)
+
+
+
… and another one from database rows:
+
extensionPlayer:FetchableRecord{
+ staticletdatabaseDecodingUserInfo:[CodingUserInfoKey:Any]=[decoderName:"database row"]
+}
+
+// prints "Decoded from database row"
+letplayer=tryPlayer.fetchOne(db,...)
+
+
+
+
:point_up: Note: make sure the databaseDecodingUserInfo and databaseEncodingUserInfo properties are explicitly declared as [CodingUserInfoKey: Any]. If they are not, the Swift compiler may silently miss the protocol requirement, resulting in sticky empty userInfo.
+
+
Tip: Use Coding Keys as Columns
+
+
If you declare an explicit CodingKeys enum (what is this?), you can instruct GRDB to use those coding keys as database columns:
// Fetch values
+trydbQueue.read{dbin
+ // SELECT * FROM player WHERE name = 'Arthur'
+ letarthur=tryPlayer.filter(name:"Arthur").fetchOne(db)// Player?
+
+ // SELECT MAX(score) FROM player
+ letmaxScore=tryPlayer.maximumScore.fetchOne(db)// Int?
+}
+
+
+
… and feed database observation tools such as RxGRDB:
+
// Observe changes
+Player.maximumScore.rx
+ .fetchOne(in:dbQueue)
+ .subscribe(onNext:{maxScore:Int?in
+ print("The maximum score has changed")
+ })
+
Record subclasses define their custom database relationship by overriding database methods. For example:
+
classPlace:Record{
+ varid:Int64?
+ vartitle:String
+ varisFavorite:Bool
+ varcoordinate:CLLocationCoordinate2D
+
+ init(id:Int64?,title:String,isFavorite:Bool,coordinate:CLLocationCoordinate2D){
+ self.id=id
+ self.title=title
+ self.isFavorite=isFavorite
+ self.coordinate=coordinate
+ super.init()
+ }
+
+ /// The table name
+ overrideclassvardatabaseTableName:String{
+ return"place"
+ }
+
+ /// The table columns
+ enumColumns:String,ColumnExpression{
+ caseid,title,favorite,latitude,longitude
+ }
+
+ /// Creates a record from a database row
+ requiredinit(row:Row){
+ id=row[Columns.id]
+ title=row[Columns.title]
+ isFavorite=row[Columns.favorite]
+ coordinate=CLLocationCoordinate2D(
+ latitude:row[Columns.latitude],
+ longitude:row[Columns.longitude])
+ super.init(row:row)
+ }
+
+ /// The values persisted in the database
+ overridefuncencode(tocontainer:inoutPersistenceContainer){
+ container[Columns.id]=id
+ container[Columns.title]=title
+ container[Columns.favorite]=isFavorite
+ container[Columns.latitude]=coordinate.latitude
+ container[Columns.longitude]=coordinate.longitude
+ }
+
+ /// Update record ID after a successful insertion
+ overridefuncdidInsert(withrowID:Int64,forcolumn:String?){
+ id=rowID
+ }
+}
+
+
Record Comparison
+
+
Records can compare against other records, or against previous versions of themselves.
+
+
This helps avoiding costly UPDATE statements when a record has not been edited.
+
+
You can use the updateChanges method, available on the PersistableRecord protocol, which performs an update of the changed columns only (and does nothing if record has no change):
+
letoldPlayer=tryPlayer.fetchOne(db,...)
+varnewPlayer=oldPlayer
+newPlayer.score=100
+iftrynewPlayer.updateChanges(db,from:oldPlayer){
+ print("player was modified, and updated in the database")
+}else{
+ print("player was not modified")
+}
+
+
+
+
:point_up: Note: The comparison is performed on the database representation of records. As long as your record type adopts a PersistableRecord protocol, you don’t need to care about Equatable.
+
+
+
The Record class is able to compare against itself, and knows if it has changes that have not been saved since it was last fetched or persisted:
+
// Record class only
+letplayer=tryPlayer.fetchOne(db,...)
+player.score=100
+iftryplayer.updateChanges(db){
+ print("player was modified, and updated in the database")
+}else{
+ print("player was not modified")
+}
+
+
+
You can also use the databaseEquals method, which returns whether two records have the same database representation:
Again, Record instances can compare against themselves, with the hasDatabaseChanges property:
+
// Record class only
+player.score=100
+ifplayer.hasDatabaseChanges{
+ tryplayer.save(db)
+}
+
+
+
Record.hasDatabaseChanges is false after a Record instance has been fetched or saved into the database. Subsequent modifications may set it, or not: hasDatabaseChanges is based on value comparison. Setting a property to the same value does not set the changed flag:
For an efficient algorithm which synchronizes the content of a database table with a JSON payload, check JSONSynchronization.playground.
+
Record Customization Options
+
+
GRDB records come with many default behaviors, that are designed to fit most situations. Many of those defaults can be customized for your specific needs:
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:
+
+
+
In the definition of the database table:
+
// CREATE TABLE player (
+// id INTEGER PRIMARY KEY AUTOINCREMENT,
+// email TEXT UNIQUE ON CONFLICT REPLACE
+// )
+trydb.create(table:"player"){tin
+ t.autoIncrementedPrimaryKey("id")
+ t.column("email",.text).unique(onConflict:.replace)// <--
+}
+
+// Despite the unique index on email, both inserts succeed.
+// The second insert replaces the first row:
+trydb.execute("INSERT INTO player (email) VALUES (?)",arguments:["arthur@example.com"])
+trydb.execute("INSERT INTO player (email) VALUES (?)",arguments:["arthur@example.com"])
+
+
In each modification query:
+
// CREATE TABLE player (
+// id INTEGER PRIMARY KEY AUTOINCREMENT,
+// email TEXT UNIQUE
+// )
+trydb.create(table:"player"){tin
+ t.autoIncrementedPrimaryKey("id")
+ t.column("email",.text).unique()
+}
+
+// Again, despite the unique index on email, both inserts succeed.
+trydb.execute("INSERT OR REPLACE INTO player (email) VALUES (?)",arguments:["arthur@example.com"])
+trydb.execute("INSERT OR REPLACE INTO player (email) VALUES (?)",arguments:["arthur@example.com"])
+
+
+
+
When you want to handle conflicts at the query level, specify a custom persistenceConflictPolicy in your type that adopts the PersistableRecord protocol. It will alter the INSERT and UPDATE queries run by the insert, update and savepersistence methods:
+
protocolMutablePersistableRecord{
+ /// The policy that handles SQLite conflicts when records are
+ /// inserted or updated.
+ ///
+ /// This property is optional: its default value uses the ABORT
+ /// policy for both insertions and updates, so that GRDB generate
+ /// regular INSERT and UPDATE queries.
+ staticvarpersistenceConflictPolicy:PersistenceConflictPolicy{get}
+}
+
+structPlayer:MutablePersistableRecord{
+ staticletpersistenceConflictPolicy=PersistenceConflictPolicy(
+ insert:.replace,
+ update:.replace)
+}
+
+// INSERT OR REPLACE INTO player (...) VALUES (...)
+tryplayer.insert(db)
+
+
+
+
:point_up: Note: the ignore policy does not play well at all with the didInsert method which notifies the rowID of inserted records. Choose your poison:
+
+
+
if you specify the ignore policy in the database table definition, don’t implement the didInsert method: it will be called with some random id in case of failed insert.
+
if you specify the ignore policy at the query level, the didInsert method is never called.
+
+
+
:point_up: Note: The replace policy may have to delete rows so that inserts and updates can succeed. Those deletions are not reported to transaction observers (this might change in a future release of SQLite).
+
+
The Implicit RowID Primary Key
+
+
All SQLite tables have a primary key. Even when the primary key is not explicit:
+
// No explicit primary key
+trydb.create(table:"event"){tin
+ t.column("message",.text)
+ t.column("date",.datetime)
+}
+
+// No way to define an explicit primary key
+trydb.create(virtualTable:"book",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 event WHERE rowid = 1
+letevent=tryEvent.fetchOne(db,key:1)
+
+// DELETE FROM book 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 databaseSelection static property (from the TableRecord protocol) return the hidden rowid column:
+
structEvent:TableRecord{
+ staticletdatabaseSelection:[SQLSelectable]=[AllColumns(),Column.rowID]
+}
+
+// When you subclass Record, you need an override:
+classBook:Record{
+ overrideclassvardatabaseSelection:[SQLSelectable]{
+ return[AllColums(),Column.rowID]
+ }
+}
+
+
+
GRDB will then select the rowid column by default:
+
// SELECT *, rowid FROM event
+letevents=tryEvent.fetchAll(db)
+
+
Have init(row:) from the FetchableRecord protocol consume the rowid column:
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
+
+
+
Beyond FetchableRecord
+
+
Some GRDB users eventually discover that the FetchableRecord protocol does not fit all situations. Use cases that are not well handled by FetchableRecord include:
+
+
+
Your application needs polymorphic row decoding: it decodes some type or another, depending on the values contained in a database row.
+
Your application needs to decode rows with a context: each decoded value should be initialized with some extra value that does not come from the database.
+
Your application needs a record type that supports untrusted databases, and may fail at decoding database rows (throw an error when a row contains invalid values).
+
+
+
Since those use cases are not well handled by FetchableRecord, don’t try to implement them on top of this protocol: you’ll just fight the framework.
+
+
Instead, please have a look at the CustomizedDecodingOfDatabaseRows playground. You’ll run some sample code, and learn how to escape FetchableRecord when you need. And remember that leaving FetchableRecord will not deprive you of query interface requests and generally all SQL generation features of the TableRecord and PersistableRecord protocols.
+
Examples of Record Definitions
+
+
We will show below how to declare a record type for the following database table:
Each one of the three examples below is correct. You will pick one or the other depending on your personal preferences and the requirements of your application:
+
+
+ Define a Codable struct, and adopt the record protocols you need
+
+This is the shortest way to define a record type.
+
+See the [Record Protocols Overview](#record-protocols-overview), and [Codable Records] for more information.
+
+”`swift
+struct Place: Codable {
+ var id: Int64?
+ var title: String
+ var favorite: Bool
+ var latitude: CLLocationDegrees
+ var longitude: CLLocationDegrees
+
+ var coordinate: CLLocationCoordinate2D {
+ get {
+ return CLLocationCoordinate2D(
+ latitude: latitude,
+ longitude: longitude)
+ }
+ set {
+ latitude = newValue.latitude
+ longitude = newValue.longitude
+ }
+ }
+}
+
+// SQL generation
+extension Place: TableRecord { }
+
+// Fetching methods
+extension Place: FetchableRecord { }
+
+// Persistence methods
+extension Place: MutablePersistableRecord {
+ /// Update record ID after a successful insertion
+ mutating func didInsert(with rowID: Int64, for column: String?) {
+ id = rowID
+ }
+}
+“`
+
+
+
+
+ Define a plain struct, and adopt the record protocols you need
+
+See the [Record Protocols Overview](#record-protocols-overview) for more information.
+
+”`swift
+struct Place {
+ var id: Int64?
+ var title: String
+ var isFavorite: Bool
+ var coordinate: CLLocationCoordinate2D
+}
+
+// SQL generation
+extension Place: TableRecord {
+ /// The table columns
+ enum Columns: String, ColumnExpression {
+ case id, title, favorite, latitude, longitude
+ }
+}
+
+// Fetching methods
+extension Place: FetchableRecord {
+ /// Creates a record from a database row
+ init(row: Row) {
+ id = row[Columns.id]
+ title = row[Columns.title]
+ isFavorite = row[Columns.favorite]
+ coordinate = CLLocationCoordinate2D(
+ latitude: row[Columns.latitude],
+ longitude: row[Columns.longitude])
+ }
+}
+
+// Persistence methods
+extension Place: MutablePersistableRecord {
+ /// The values persisted in the database
+ func encode(to container: inout PersistenceContainer) {
+ container[Columns.id] = id
+ container[Columns.title] = title
+ container[Columns.favorite] = isFavorite
+ container[Columns.latitude] = coordinate.latitude
+ container[Columns.longitude] = coordinate.longitude
+ }
+
+ /// Update record ID after a successful insertion
+ mutating func didInsert(with rowID: Int64, for column: String?) {
+ id = rowID
+ }
+}
+“`
+
+
+
+
+ Subclass the Record class
+
+See the [Record class](#record-class) for more information.
+
+”`swift
+class Place: Record {
+ var id: Int64?
+ var title: String
+ var isFavorite: Bool
+ var coordinate: CLLocationCoordinate2D
+
+ init(id: Int64?, title: String, isFavorite: Bool, coordinate: CLLocationCoordinate2D) {
+ self.id = id
+ self.title = title
+ self.isFavorite = isFavorite
+ self.coordinate = coordinate
+ super.init()
+ }
+
+ /// The table name
+ override class var databaseTableName: String {
+ return “place”
+ }
+
+ /// The table columns
+ enum Columns: String, ColumnExpression {
+ case id, title, favorite, latitude, longitude
+ }
+
+ /// Creates a record from a database row
+ required init(row: Row) {
+ id = row[Columns.id]
+ title = row[Columns.title]
+ isFavorite = row[Columns.favorite]
+ coordinate = CLLocationCoordinate2D(
+ latitude: row[Columns.latitude],
+ longitude: row[Columns.longitude])
+ super.init(row: row)
+ }
+
+ /// The values persisted in the database
+ override func encode(to container: inout PersistenceContainer) {
+ container[Columns.id] = id
+ container[Columns.title] = title
+ container[Columns.favorite] = isFavorite
+ container[Columns.latitude] = coordinate.latitude
+ container[Columns.longitude] = coordinate.longitude
+ }
+
+ /// Update record ID after a successful insertion
+ override func didInsert(with rowID: Int64, for column: String?) {
+ id = rowID
+ }
+}
+“`
+
+
+
List of Record Methods
+
+
This is the list of record methods, along with their required protocols. The Record class adopts all these protocols, and adds a few extra methods.
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:
+
trydbQueue.write{dbin
+ // Update database schema (with SQL)
+ trydb.execute("CREATE TABLE wine (...)")
+
+ // Fetch records (with SQL)
+ letwines=tryWine.fetchAll(db,
+ "SELECT * FROM wine WHERE origin = ? ORDER BY price",
+ arguments:["Burgundy"])
+
+ // Count (with an SQL snippet)
+ letcount=tryWine
+ .filter(sql:"color = ?",arguments:[Color.red])
+ .fetchCount(db)
+
+ // Delete (with SQL)
+ trydb.execute("DELETE FROM wine 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
+
+
+
+
:bulb: Tip: database table names should be singular, and camel-cased. Make them look like Swift identifiers: place, country, postalAddress, ‘httpRequest’.
+
+
This will help you using Associations when you need them. Database table names that follow another naming convention are totally OK, but you will need to perform extra configuration.
+
+
+
Add regular columns with their name and eventual type (text, integer, double, numeric, boolean, blob, date and datetime) - see SQLite data types:
+
// CREATE TABLE example (
+// a,
+// name TEXT,
+// creationDate DATETIME,
+trydb.create(table:"example"){tin
+ t.column("a")
+ t.column("name",.text)
+ t.column("creationDate",.datetime)
+
+
+
Define not null columns, and set default values:
+
// email TEXT NOT NULL,
+ t.column("email",.text).notNull()
+
+ // name TEXT NOT NULL DEFAULT 'Anonymous',
+ t.column("name",.text).notNull().defaults(to:"Anonymous")
+
+
+
Use an individual column as primary, unique, or foreign key. When defining a foreign key, the referenced column is the primary key of the referenced table (unless you specify otherwise):
+
// id INTEGER PRIMARY KEY AUTOINCREMENT,
+ t.autoIncrementedPrimaryKey("id")
+
+ // uuid TEXT PRIMARY KEY,
+ t.column("uuid",.text).primaryKey()
+
+ // email TEXT UNIQUE,
+ t.column("email",.text).unique()
+
+ // countryCode TEXT REFERENCES country(code) ON DELETE CASCADE,
+ t.column("countryCode",.text).references("country",onDelete:.cascade)
+
+
+
+
:bulb: Tip: when you need an integer primary key that automatically generates unique values, it is highly recommended that you use the autoIncrementedPrimaryKey method:
The reason for this recommendation is that auto-incremented primary keys prevent the reuse of ids. This prevents your app or database observation tools to think that a row was updated, when it was actually deleted, then replaced. Depending on your application needs, this may be OK. Or not.
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.
Other table constraints can involve several columns:
+
// PRIMARY KEY (a, b),
+ t.primaryKey(["a","b"])
+
+ // UNIQUE (a, b) ON CONFLICT REPLACE,
+ t.uniqueKey(["a","b"],onConfict:.replace)
+
+ // FOREIGN KEY (a, b) REFERENCES parents(c, d),
+ t.foreignKey(["a","b"],references:"parents")
+
+ // CHECK (a + b < 10),
+ t.check(Column("a")+Column("b")<10)
+
+ // CHECK (a + b < 10)
+ t.check(sql:"a + b < 10")
+}
+
+
Modify Tables
+
+
SQLite lets you rename tables, and add columns to existing tables:
+
// ALTER TABLE referer RENAME TO referrer
+trydb.rename(table:"referer",to:"referrer")
+
+// ALTER TABLE player ADD COLUMN url TEXT
+trydb.alter(table:"player"){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)
+
// Columns.id and Columns.name can be used just as
+// idColumn and nameColumn declared above.
+enumColumns:String,ColumnExpression{
+ caseid
+ casename
+}
+
+
+
You can now build requests with the following methods: all, none, select, distinct, filter, matching, group, having, order, reversed, limit. All those methods return another request, which you can further refine by applying another method: Player.select(...).filter(...).order(...).
+
+
+
all(), none(): the requests for all rows, or no row.
+
// SELECT * FROM player
+Player.all()
+
+
+
The hidden rowid column can be selected as well when you need it.
// SELECT name FROM player
+Player.select(nameColumn,as:String.self)
+
+
distinct() performs uniquing.
+
// SELECT DISTINCT name FROM player
+Player.select(nameColumn,as:String.self).distinct()
+
+
filter(expression) applies conditions.
+
// SELECT * FROM player WHERE id IN (1, 2, 3)
+Player.filter([1,2,3].contains(idColumn))
+
+// SELECT * FROM player WHERE (name IS NOT NULL) AND (height > 1.75)
+Player.filter(nameColumn!=nil&&heightColumn>1.75)
+
+
filter(key:) and filter(keys:) apply conditions on primary keys and unique keys:
+
// SELECT * FROM player WHERE id = 1
+Player.filter(key:1)
+
+// SELECT * FROM country WHERE isoCode IN ('FR', 'US')
+Country.filter(keys:["FR","US"])
+
+// SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR'
+Citizenship.filter(key:["citizenId":1,"countryCode":"FR"])
+
+// SELECT * FROM player WHERE email = 'arthur@example.com'
+Player.filter(key:["email":"arthur@example.com"])
+
// SELECT * FROM document WHERE document 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(score) FROM player GROUP BY name
+Player
+ .select(nameColumn,max(scoreColumn))
+ .group(nameColumn)
+
+
having(expression) applies conditions on grouped rows.
+
// SELECT team, MAX(score) FROM player GROUP BY team HAVING MIN(score) >= 1000
+Player
+ .select(teamColumn,max(scoreColumn))
+ .group(teamColumn)
+ .having(min(scoreColumn)>=1000)
+
+
order(ordering, ...) sorts.
+
// SELECT * FROM player ORDER BY name
+Player.order(nameColumn)
+
+// SELECT * FROM player ORDER BY score DESC, name
+Player.order(scoreColumn.desc,nameColumn)
+
+
+
Each order call clears any previous ordering:
+
// SELECT * FROM player ORDER BY name
+Player.order(scoreColumn).order(nameColumn)
+
+
+
orderByPrimaryKey() sorts by primary key:
+
// SELECT * FROM player ORDER BY id
+Player.orderByPrimaryKey()
+
+// SELECT * FROM country ORDER BY code
+Country.orderByPrimaryKey()
+
+// SELECT * FROM citizenship ORDER BY citizenId, countryCode
+Citizenship.orderByPrimaryKey()
+
+
reversed() reverses the eventual orderings.
+
// SELECT * FROM player ORDER BY score ASC, name DESC
+Player.order(scoreColumn.desc,nameColumn).reversed()
+
+
+
If no ordering was already specified, this method has no effect:
+
// SELECT * FROM player
+Player.all().reversed()
+
+
limit(limit, offset: offset) limits and pages results.
+
// SELECT * FROM player LIMIT 5
+Player.limit(5)
+
+// SELECT * FROM player LIMIT 5 OFFSET 10
+Player.limit(5,offset:10)
+
+
+
+
You can refine requests by chaining those methods:
+
// SELECT * FROM player WHERE (email IS NOT NULL) ORDER BY name
+Player.order(nameColumn).filter(emailColumn!=nil)
+
+
+
The select, order, group, and limit methods ignore and replace previously applied selection, orderings, grouping, and limits. On the opposite, filter, matching, and having methods extend the query:
+
Player// SELECT * FROM player
+ .filter(nameColumn!=nil)// WHERE (name IS NOT NULL)
+ .filter(emailColumn!=nil)// AND (email IS NOT NULL)
+ .order(nameColumn)// - ignored -
+ .reversed()// - ignored -
+ .order(scoreColumn)// ORDER BY score
+ .limit(20,offset:40)// - ignored -
+ .limit(10)// LIMIT 10
+
+
+
Raw SQL snippets are also accepted, with eventual arguments:
+
// SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate)
+Player
+ .select(sql:"DATE(creationDate), COUNT(*)")
+ .filter(sql:"name = ?",arguments:["Arthur"])
+ .group(sql:"DATE(creationDate)")
+
+
Columns Selected by a Request
+
+
By default, query interface requests select all columns:
+
// SELECT * FROM player
+letrequest=Player.all()
+
+
+
The selection can be changed for each individual requests, or for all requests built from a given type.
+
+
The select(...) and select(..., as:) methods change the selection of a single request (see Fetching from Requests for detailed information):
The default selection for a record type is controlled by the databaseSelection property:
+
structRestrictedPlayer:TableRecord{
+ staticletdatabaseTableName="player"
+ staticletdatabaseSelection:[SQLSelectable]=[Column("id"),Column("name")]
+}
+
+structExtendedPlayer:TableRecord{
+ staticletdatabaseTableName="player"
+ staticletdatabaseSelection:[SQLSelectable]=[AllColumns(),Column.rowID]
+}
+
+// SELECT id, name FROM player
+letrequest=RestrictedPlayer.all()
+
+// SELECT *, rowid FROM player
+letrequest=ExtendedPlayer.all()
+
+
+
+
:point_up: Note: make sure the databaseSelection property is explicitly declared as [SQLSelectable]. If it is not, the Swift compiler may silently miss the protocol requirement, resulting in sticky SELECT * requests. To verify your setup, see the How do I print a request as SQL? FAQ.
+
+
Expressions
+
+
Feed requests with SQL expressions built from your Swift code:
+
SQL Operators
+
+
+
=, <>, <, <=, >, >=, IS, IS NOT
+
+
Comparison operators are based on the Swift operators ==, !=, ===, !==, <, <=, >, >=:
+
// SELECT * FROM player WHERE (name = 'Arthur')
+Player.filter(nameColumn=="Arthur")
+
+// SELECT * FROM player WHERE (name IS NULL)
+Player.filter(nameColumn==nil)
+
+// SELECT * FROM player WHERE (score IS 1000)
+Player.filter(scoreColumn===1000)
+
+// SELECT * FROM rectangle WHERE width < height
+Rectangle.filter(widthColumn<heightColumn)
+
+
+
+
:point_up: Note: SQLite string comparison, by default, is case-sensitive and not Unicode-aware. See string comparison if you need more control.
+
+
*, /, +, -
+
+
SQLite arithmetic operators are derived from their Swift equivalent:
+
// SELECT ((temperature * 1.8) + 32) AS farenheit FROM planet
+Planet.select((temperatureColumn*1.8+32).aliased("farenheit"))
+
+
+
+
:point_up: Note: an expression like nameColumn + "rrr" will be interpreted by SQLite as a numerical addition (with funny results), not as a string concatenation.
+
+
AND, OR, NOT
+
+
The SQL logical operators are derived from the Swift &&, || and !:
+
// SELECT * FROM player WHERE ((NOT verified) OR (score < 1000))
+Player.filter(!verifiedColumn||scoreColumn<1000)
+
+
+
When you want to join a sequence of expressions with AND or OR operators, use joined(operator:):
+
// SELECT * FROM player WHERE (verified AND (score >= 1000) AND (name IS NOT NULL))
+letconditions=[
+ verifiedColumn,
+ scoreColumn>=1000,
+ nameColumn!=nil]
+Player.filter(conditions.joined(operator:.and))
+
+
+
When the sequence is empty, joined(operator: .and) returns true, and joined(operator: .or) returns false:
+
// SELECT * FROM player WHERE 1
+Player.filter([].joined(operator:.and))
+
+// SELECT * FROM player WHERE 0
+Player.filter([].joined(operator:.or))
+
+
BETWEEN, IN, NOT IN
+
+
To check inclusion in a Swift sequence (array, set, range…), call the contains method:
+
// SELECT * FROM player WHERE id IN (1, 2, 3)
+Player.filter([1,2,3].contains(idColumn))
+
+// SELECT * FROM player WHERE id NOT IN (1, 2, 3)
+Player.filter(![1,2,3].contains(idColumn))
+
+// SELECT * FROM player WHERE score BETWEEN 0 AND 1000
+Player.filter((0...1000).contains(scoreColumn))
+
+// SELECT * FROM player WHERE (score >= 0) AND (score < 1000)
+Player.filter((0..<1000).contains(scoreColumn))
+
+// SELECT * FROM player WHERE initial BETWEEN 'A' AND 'N'
+Player.filter(("A"..."N").contains(initialColumn))
+
+// SELECT * FROM player WHERE (initial >= 'A') AND (initial < 'N')
+Player.filter(("A"..<"N").contains(initialColumn))
+
+
+
+
:point_up: Note: SQLite string comparison, by default, is case-sensitive and not Unicode-aware. See string comparison if you need more control.
+
+
LIKE
+
+
The SQLite LIKE operator is available as the like method:
+
// SELECT * FROM player WHERE (email LIKE '%@example.com')
+Player.filter(emailColumn.like("%@example.com"))
+
+
+
+
:point_up: Note: the SQLite LIKE operator is case-insensitive but not Unicode-aware. For example, the expression 'a' LIKE 'A' is true but 'æ' LIKE 'Æ' is false.
+
+
MATCH
+
+
The full-text MATCH operator is available through FTS3Pattern (for FTS3 and FTS4 tables) and FTS5Pattern (for FTS5):
+
+
FTS3 and FTS4:
+
letpattern=FTS3Pattern(matchingAllTokensIn:"SQLite database")
+
+// SELECT * FROM document WHERE document MATCH 'sqlite database'
+Document.matching(pattern)
+
+// SELECT * FROM document WHERE content MATCH 'sqlite database'
+Document.filter(contentColumn.match(pattern))
+
+
+
FTS5:
+
letpattern=FTS5Pattern(matchingAllTokensIn:"SQLite database")
+
+// SELECT * FROM document WHERE document MATCH 'sqlite database'
+Document.matching(pattern)
+
+
+
SQL Functions
+
+
+
ABS, AVG, COUNT, LENGTH, MAX, MIN, SUM:
+
+
Those are based on the abs, average, count, length, max, min and sum Swift functions:
+
// SELECT MIN(score), MAX(score) FROM player
+Player.select(min(scoreColumn),max(scoreColumn))
+
+// SELECT COUNT(name) FROM player
+Player.select(count(nameColumn))
+
+// SELECT COUNT(DISTINCT name) FROM player
+Player.select(count(distinct:nameColumn))
+
+
IFNULL
+
+
Use the Swift ?? operator:
+
// SELECT IFNULL(name, 'Anonymous') FROM player
+Player.select(nameColumn??"Anonymous")
+
+// SELECT IFNULL(name, email) FROM player
+Player.select(nameColumn??emailColumn)
+
+
LOWER, UPPER
+
+
The query interface does not give access to those SQLite functions. Nothing against them, but they are not unicode aware.
+
+
Instead, GRDB extends SQLite with SQL functions that call the Swift built-in string functions capitalized, lowercased, uppercased, localizedCapitalized, localizedLowercased and localizedUppercased:
+
Player.select(nameColumn.uppercased())
+
+
+
+
:point_up: Note: When comparing strings, you’d rather use a collation:
letf=DatabaseFunction("f",...)
+
+// SELECT f(name) FROM player
+Player.select(f.apply(nameColumn))
+
+
+
Fetching from Requests
+
+
Once you have a request, you can fetch the records at the origin of the request:
+
// Some request based on `Player`
+letrequest=Player.filter(...)...// QueryInterfaceRequest<Player>
+
+// Fetch players:
+tryrequest.fetchCursor(db)// A Cursor of Player
+tryrequest.fetchAll(db)// [Player]
+tryrequest.fetchOne(db)// Player?
+
See fetching methods for information about the fetchCursor, fetchAll and fetchOne methods.
+
+
You sometimes want to fetch other values.
+
+
The simplest way is to use the request as an argument to a fetching method of the desired type:
+
// Fetch an Int
+letrequest=Player.select(max(scoreColumn))
+letmaxScore=tryInt.fetchOne(db,request)// Int?
+
+// Fetch a Row
+letrequest=Player.select(min(scoreColumn),max(scoreColumn))
+letrow=tryRow.fetchOne(db,request)!// Row
+letminScore=row[0]asInt?
+letmaxScore=row[1]asInt?
+
+
+
When you also want to use database observation tools such as FetchedRecordsController or RxGRDB, you have to go one step further, and change the type of the request:
+
+
+
When you change the selection, prefer the select(..., as:) method:
+
// A request of Int
+letrequest=Player.select(max(scoreColumn),as:Int.self)
+
+// Simple fetch
+letmaxScore=trydbQueue.read{dbin
+ tryrequest.fetchOne(db)// Int?
+}
+
+// Observe with RxGRDB
+request.rx
+ .fetchOne(in:dbQueue)
+ .subscribe(onNext:{maxScore:Int?in
+ print("The maximum score has changed")
+ })
+
+
Otherwise, use asRequest(of:). Here is an example that uses Associations:
Fetching records according to their primary key is a very common task. It has a shortcut which accepts any single-column primary key:
+
// SELECT * FROM player WHERE id = 1
+tryPlayer.fetchOne(db,key:1)// Player?
+
+// SELECT * FROM player WHERE id IN (1, 2, 3)
+tryPlayer.fetchAll(db,keys:[1,2,3])// [Player]
+
+// SELECT * FROM country WHERE isoCode = 'FR'
+tryCountry.fetchOne(db,key:"FR")// Country?
+
+// SELECT * FROM country 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 document 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 citizenship WHERE citizenId = 1 AND countryCode = 'FR'
+tryCitizenship.fetchOne(db,key:["citizenId":1,"countryCode":"FR"])// Citizenship?
+
+// SELECT * FROM player WHERE email = 'arthur@example.com'
+tryPlayer.fetchOne(db,key:["email":"arthur@example.com"])// Player?
+
+
+
When you want to build a request and plan to fetch from it later, use the filter(key:) and filter(keys:) methods:
+
// SELECT * FROM player WHERE id = 1
+letrequest=Player.filter(key:1)
+letplayer=tryrequest.fetchOne(db)// Player?
+
+// SELECT * FROM player WHERE id IN (1, 2, 3)
+letrequest=Player.filter(keys:[1,2,3])
+letplayers=tryrequest.fetchAll(db)// [Player]
+
+// SELECT * FROM country WHERE isoCode = 'FR'
+letrequest=Country.filter(key:"FR")
+letcountry=tryrequest.fetchOne(db)// Country?
+
+// SELECT * FROM country WHERE isoCode IN ('FR', 'US')
+letrequest=Country.filter(keys:["FR","US"])
+letcountries=tryrequest.fetchAll(db)// [Country]
+
+// SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR'
+letrequest=Citizenship.filter(key:["citizenId":1,"countryCode":"FR"])
+letcitizenship=request.fetchOne(db)// Citizenship?
+
+// SELECT * FROM player WHERE email = 'arthur@example.com'
+letrequest=Player.filter(key:["email":"arthur@example.com"])
+letplayer=tryrequest.fetchOne(db)// Player?
+
Requests can count. The fetchCount() method returns the number of rows that would be returned by a fetch request:
+
// SELECT COUNT(*) FROM player
+letcount=tryPlayer.fetchCount(db)// Int
+
+// SELECT COUNT(*) FROM player WHERE email IS NOT NULL
+letcount=tryPlayer.filter(emailColumn!=nil).fetchCount(db)
+
+// SELECT COUNT(DISTINCT name) FROM player
+letcount=tryPlayer.select(nameColumn).distinct().fetchCount(db)
+
+// SELECT COUNT(*) FROM (SELECT DISTINCT name, score FROM player)
+letcount=tryPlayer.select(nameColumn,scoreColumn).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 player WHERE email IS NULL
+letrequest=Player.filter(emailColumn==nil)
+tryrequest.deleteAll(db)
+
+
+
+
:point_up: Note Deletion methods are only available for records that adopts the PersistableRecord protocol.
+
+
+
Deleting records according to their primary key is also quite common. It has a shortcut which accepts any single-column primary key:
+
// DELETE FROM player WHERE id = 1
+tryPlayer.deleteOne(db,key:1)
+
+// DELETE FROM player WHERE id IN (1, 2, 3)
+tryPlayer.deleteAll(db,keys:[1,2,3])
+
+// DELETE FROM country WHERE isoCode = 'FR'
+tryCountry.deleteOne(db,key:"FR")
+
+// DELETE FROM country 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 document 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 citizenship WHERE citizenId = 1 AND countryCode = 'FR'
+tryCitizenship.deleteOne(db,key:["citizenId":1,"countryCode":"FR"])
+
+// DELETE FROM player WHERE email = 'arthur@example.com'
+Player.deleteOne(db,key:["email":"arthur@example.com"])
+
+
Custom Requests
+
+
Until now, we have seen requests created from any type that adopts the TableRecord protocol:
tryrequest.fetchCursor(db)// A Cursor of Player
+tryrequest.fetchAll(db)// [Player]
+tryrequest.fetchOne(db)// Player?
+tryrequest.fetchCount(db)// Int
+
+
+
When the query interface can not generate the SQL you need, you can still fallback to raw SQL:
+
// Custom SQL is always welcome
+tryPlayer.fetchAll(db,"SELECT ...")// [Player]
+
+
+
But you may prefer to bring some elegance back in, and build custom requests:
+
// No custom SQL in sight
+tryPlayer.customRequest().fetchAll(db)// [Player]
+
FetchRequest is the protocol for all requests that run from a single select statement, and know how fetched rows should be interpreted:
+
protocolFetchRequest{
+ /// The type that tells how fetched rows should be decoded
+ associatedtypeRowDecoder
+
+ /// A tuple that contains a prepared statement, 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 database region that the request looks into.
+ funcdatabaseRegion(_db:Database)throws->DatabaseRegion
+}
+
The prepare method returns a prepared statement and an optional row adapter. The prepared statement tells which SQL query should be executed. The row adapter helps presenting the fetched rows in the way expected by the row decoders (see row adapter).
+
+
The fetchCount method has a default implementation that builds a correct but naive SQL query from the statement returned by prepare: SELECT COUNT(*) FROM (...). Adopting types can refine the counting SQL by customizing their fetchCount implementation.
+
+
The databaseRegion method is involved in database observation. It is given a default implementation, based on the statement returned by prepare. For more information, see DatabaseRegion, and RxGRDB.
// A FetchRequest whose RowDecoder associated type is Player:
+letrequest=Player.all()
+
+
Building Custom Requests
+
+
To build custom requests, you can use one of the built-in requests, derive requests from other requests, or create your own request type that adopts the FetchRequest protocol.
+
+
+
SQLRequest is a fetch request built from raw SQL. For example:
+
extensionPlayer{
+ staticfuncfilter(color:Color)->SQLRequest<Player>{
+ returnSQLRequest<Player>(
+ "SELECT * FROM player WHERE color = ?"
+ arguments:[color])
+ }
+}
+
+// [Player]
+tryPlayer.filter(color:.red).fetchAll(db)
+
+
The asRequest(of:) method changes the type fetched by the request. It is useful, for example, when you use Associations:
A type adopting FetchRequest knows exactly what it has to do when its RowDecoder associated type can decode database rows (Row itself, values, or FetchableRecord):
+
letrowRequest=...// Some FetchRequest that fetches Row
+tryrequest.fetchCursor(db)// A cursor of rows
+
+letplayerRequest=...// Some FetchRequest that fetches Player
+tryrequest.fetchAll(db)// [Player]
+
+letintRequest=...// Some FetchRequest that fetches Int
+tryrequest.fetchOne(db)// Int?
+
+
+
For example:
+
letplayerRequest=SQLRequest<Player>(
+ "SELECT * FROM player WHERE color = ?"
+ arguments:[color])
+tryrequest.fetchAll(db)// [Player]
+
+
+
See fetching methods for information about the fetchCursor, fetchAll and fetchOne methods.
+
+
The RowDecoder type associated with the FetchRequest does not have to be Row, DatabaseValueConvertible, or FetchableRecord. See the Beyond FetchableRecord chapter for more information.
+
Migrations
+
+
Migrations are a convenient way to alter your database schema over time in a consistent and easy way.
+
+
Migrations run in order, once and only once. When a user upgrades your application, only non-applied migrations are run.
varmigrator=DatabaseMigrator()
+
+// 1st migration
+migrator.registerMigration("v1"){dbin
+ trydb.create(table:"author"){tin...}
+ trydb.create(table:"book"){tin...}
+ trydb.create(index:...)
+}
+
+// 2nd migration
+migrator.registerMigration("v2"){dbin
+ trydb.alter(table:"author"){tin...}
+}
+
+// Migrations for future versions will be inserted here:
+//
+// // 3rd migration
+// migrator.registerMigration("...") { db in
+// ...
+// }
+
+
+
Each migration runs in a separate transaction. Should one throw an error, its transaction is rollbacked, subsequent migrations do not run, and the error is eventually thrown by migrator.migrate(dbQueue).
+
+
The memory of applied migrations is stored in the database itself (in a reserved table).
+
+
You migrate the database up to the latest version with the migrate(_:) method:
+
trymigrator.migrate(dbQueue)// or migrator.migrate(dbPool)
+
+
+
To migrate a database up to a specific version, use migrate(_:upTo:):
letappliedMigrations=trymigrator.appliedMigrations(in:dbQueue)
+ifappliedMigrations.contains("v2"){
+ // "v2" migration has been applied
+}
+
+
The eraseDatabaseOnSchemaChange Option
+
+
A DatabaseMigrator can automatically wipe out the full database content, and recreate the whole database from scratch, if it detects that a migration has changed its definition:
Beware! This flag can destroy your precious users’ data!
+
+
Yet it may be useful in those two situations:
+
+
+
During application development, as you are still designing migrations, and the schema changes often.
+
+
In this case, it is recommended that this flag does not ship in the distributed application:
+
varmigrator=DatabaseMigrator()
+#if DEBUG
+// Speed up development by nuking the database when migrations change
+migrator.eraseDatabaseOnSchemaChange=true
+#endif
+
+
When the database content can easily be recreated, such as a cache for some downloaded data.
+
+
+
The eraseDatabaseOnSchemaChange option triggers a recreation of the database if the migrator detects a schema change. A schema change is any difference in the sqlite_master table, which contains the SQL used to create database tables, indexes, triggers, and views.
+
Advanced Database Schema Changes
+
+
SQLite does not support many schema changes, and won’t let you drop a table column with ALTER TABLE … DROP COLUMN …, for example.
+
+
Yet any kind of schema change is still possible. The SQLite documentation explains in detail how to do so: https://www.sqlite.org/lang_altertable.html#otheralter. This technique requires the temporary disabling of foreign key checks, and is supported by the registerMigrationWithDeferredForeignKeyCheck function:
+
// Add a NOT NULL constraint on player.name:
+migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName"){dbin
+ trydb.create(table:"new_player"){tin
+ t.autoIncrementedPrimaryKey("id")
+ t.column("name",.text).notNull()
+ }
+ trydb.execute("INSERT INTO new_player SELECT * FROM player")
+ trydb.drop(table:"player")
+ trydb.rename(table:"new_player",to:"player")
+}
+
+
+
While your migration code runs with disabled foreign key checks, those are re-enabled and checked at the end of the migration, regardless of eventual errors.
+
Full-Text Search
+
+
Full-Text Search is an efficient way to search a corpus of textual documents.
+
// Create full-text tables
+trydb.create(virtualTable:"book",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 book (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 book WHERE book 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 supports FTS3 and FTS4 out of the box, but not always FTS5. To use FTS5, see Enabling FTS5 Support.
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)
+
+
Enabling FTS5 Support
+
+
When the FTS3 and FTS4 full-text engines don’t suit your needs, you may want to use FTS5. See Choosing the Full-Text Engine to help you make a decision.
+
+
The version of SQLite that ships with iOS, macOS and watchOS does not always support the FTS5 engine. To enable FTS5 support, you’ll need to install GRDB with one of those installation techniques:
+
+
+
Use the GRDBPlus CocoaPod. It uses the system SQLite, and requires iOS 11.4+ / macOS 10.13+ / watchOS 4.3+:
+
pod'GRDBPlus'
+
+
Use the GRDBCipher CocoaPod. It uses SQLCipher (see encryption), and requires iOS 8.0+ / macOS 10.9+ / watchOS 2.0+:
+
pod'GRDBCipher'
+
+
Use a custom SQLite build and activate the SQLITE_ENABLE_FTS5 compilation option.
+
+
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:"book")
+// DatabaseError: syntax error near \"AND\"
+trydb.makeFTS5Pattern(rawPattern:"AND",forTable:"book")
+// DatabaseError: no such column: missing
+trydb.makeFTS5Pattern(rawPattern:"missing: sqlite",forTable:"book")
+
+
+
The FTS5Pattern initializers don’t throw. They build a valid pattern from any string, including strings provided by users of your application. They let you find documents that match all given words, any given word, or a full phrase, depending on the needs of your application:
+
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)
+// Matches documents that start with "SQLite database"
+letpattern=FTS5Pattern(matchingPrefixPhrase: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 document WHERE document 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:"book"){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:"book_ft",using:FTS4()){tin// or FTS5()
+ t.synchronize(withTable:"book")
+ t.column("author")
+ t.column("title")
+ t.column("content")
+}
+
+
+
The eventual content already present in the regular table is indexed, and every insert, update or delete that happens in the regular table is automatically applied to the full-text index.
+
+
For more information, see the SQLite documentation about external content tables: FTS4, FTS5.
+
+
See also WWDC Companion, a sample app that uses external content tables to store, display, and let the user search the WWDC sessions.
+
Deleting Synchronized Full-Text Tables
+
+
Synchronization of full-text tables with their content table happens by the mean of SQL triggers.
+
+
SQLite automatically deletes those triggers when the content (not full-text) table is dropped.
+
+
However, those triggers remain after the full-text table has been dropped. Unless they are dropped too, they will prevent future insertion, updates, and deletions in the content table, and the creation of a new full-text table.
+
+
To drop those triggers, use the dropFTS4SynchronizationTriggers or dropFTS5SynchronizationTriggers methods:
:warning: Warning: there was a bug in GRDB up to version 2.3.1 included, which created triggers with a wrong name. If it is possible that the full-text table was created by an old version of GRDB, then delete the synchronization triggers twice: once with the name of the deleted full-text table, and once with the name of the content table:
+
// Drop full-text table
+trydb.drop(table:"book_ft")
+trydb.dropFTS4SynchronizationTriggers(forTable:"book_ft")
+trydb.dropFTS4SynchronizationTriggers(forTable:"book")// Support for GRDB <= 2.3.1
+
+
+
Querying External Content Full-Text Tables
+
+
When you need to perform a full-text search, and the external content table contains all the data you need, you can simply query the full-text table.
+
+
But if you need to load columns from the regular table, and in the same time perform a full-text search, then you will need to query both tables at the same time.
+
+
That is because SQLite will throw an error when you try to perform a full-text search on a regular table:
+
// SQLite error 1: unable to use function MATCH in the requested context
+// SELECT * FROM book WHERE book MATCH '...'
+letbooks=Book.matching(pattern).fetchAll(db)
+
+
+
The solution is to perform a joined request, using raw SQL:
+
letsql="""
+ SELECT book.*
+ FROM book
+ JOIN book_ft
+ ON book_ft.rowid = book.rowid
+ AND book_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!
+
Joined Queries Support
+
+
GRDB helps consuming joined queries with complex selection.
+
+
In this chapter, we will focus on the extraction of information from complex rows, such as the ones fetched by the query below:
+
-- How to consume the left, middle, and right parts of those rows?
+SELECTplayer.*,team.*,MAX(round.score)ASmaxScore
+FROMplayer
+LEFTJOINteamON...
+LEFTJOINroundON...
+GROUPBY...
+
+
+
We will not talk about the generation of joined queries, which is covered in Associations.
+
+
So what are we talking about?
+
+
It is difficult to consume rows fetched from complex joined queries, because they often contain several columns with the same name: id from table player, id from table team, etc.
+
+
When such ambiguity happens, GRDB row accessors always favor the leftmost matching column. This means that row["id"] would give a player id, whithout any obvious way to access the team id.
+
+
A classical technique to avoid this ambiguity is to give each column a unique name. For example:
+
-- A classical technique
+SELECTplayer.idASplayer_id,player.nameASplayer_name,team.idASteam_id,team.nameASteam_name,team.colorASteam_color,MAX(round.score)ASmaxScore
+FROMplayer
+LEFTJOINteamON...
+LEFTJOINroundON...
+GROUPBY...
+
+
+
This technique works pretty well, but it has three drawbacks:
+
+
+
The selection becomes hard to read and understand.
+
Such queries are difficult to write by hand.
+
The mangled names are a very bad fit for FetchableRecord types that expect specific column names. After all, if the Team record type can read SELECT * FROM team ..., it should be able to read SELECT ..., team.*, ... as well.
+
+
+
We thus need another technique. Below we’ll see how to split rows into slices, and preserve column names.
+
+
SELECT player.*, team.*, MAX(round.score) AS maxScore FROM ... will be splitted into three slices: one that contains player’s columns, one that contains team’s columns, and a remaining slice that contains remaining column(s). The Player record type will be able to read the first slice, which contains the colums expected by the Player.init(row:) initializer. In the same way, the Team record type could read the second slice.
+
+
Unlike the name-mangling technique, splitting rows keeps SQL legible, accepts your hand-crafted SQL queries, and plays as nicely as possible with your existing record types.
Let’s first write some introductory code, hoping that this chapter will make you understand how pieces fall together. We’ll see later how records will help us streamline the initial approach, how to track changes in joined requests, and how we can use the standard Decodable protocol.
+
+
To split rows, we will use row adapters. Row adapters adapt rows so that row consumers see exactly the columns they want. Among other things, row adapters can define several row scopes that give access to as many row slices. Sounds like a perfect match.
+
+
At the very beginning, there is an SQL query:
+
trydbQueue.read{dbin
+ letsql="""
+ SELECT player.*, team.*, MAX(round.score) AS maxScore
+ FROM player
+ LEFT JOIN team ON ...
+ LEFT JOIN round ON ...
+ GROUP BY ...
+ """
+
+
+
We need an adapter that extracts player columns, in a slice that has as many columns as there are columns in the player table. That’s RangeRowAdapter:
In the SQL query, the team is joined with the LEFT JOIN operator. This means that the team may be missing: its slice may contain team values, or it may only contain NULLs. When this happens, we don’t want to build a Team record, and we thus load an optional Team:
+
letteam:Team?=row[teamScope]
+
+
+
And finally, we can load the maximum score, assuming that the maxScore column is not ambiguous:
how to use RangeRowAdapter to extract a specific table’s columns into a row slice.
+
how to use ScopeAdapter to gives access to several row slices through named scopes.
+
how to use Row subscripting to extract records from rows, or optional records in order to deal with left joins.
+
+
+
Splitting Rows, the Record Way
+
+
Our introduction above has introduced important techniques. It uses row adapters in order to split rows. It uses Row subscripting in order to extract records from row slices.
+
+
But we may want to make it more usable and robust:
+
+
+
It’s generally easier to consume records than raw rows.
To address the first bullet, let’s define a record that holds our player, optional team, and maximum score. Since it can decode database rows, it adopts the FetchableRecord protocol:
To acknowledge that both Player and Team records may customize their selection of the player and team columns, we’ll write our SQL in a slightly different way:
+
// Let Player and Team customize their selection:
+ letsql="""
+ SELECT
+ \(Player.selectionSQL()), -- instead of player.*
+ \(Team.selectionSQL()), -- instead of team.*
+ MAX(round.score) AS maxScore
+ FROM player
+ LEFT JOIN team ON ...
+ LEFT JOIN round ON ...
+ GROUP BY ...
+ """
+
+
+
Player.selectionSQL() will output player.*, unless Player defines a customized selection.
+
+
+
:point_up: Note: you may also use SQL table aliases:
+
letsql="""
+ SELECT
+ \(Player.selectionSQL(alias:"p")),
+ \(Team.selectionSQL(alias:"t")),
+ MAX(r.score) AS maxScore
+ FROM player p
+ LEFT JOIN team t ON ...
+ LEFT JOIN round r ON ...
+ GROUP BY ...
+ """
+
+
+
+
Now is the time to build adapters (taking in account the customized selection of both player and team). We use the splittingRowAdapters global function, which builds row adapters of desired widths:
:point_up: Note: splittingRowAdapters returns as many adapters as necessary to fully split a row. In the example above, it returns three adapters: one for player, one for team, and one for the remaining columns.
Now we write a method that returns a request, and build the fetching method on top of that request:
+
extensionPlayerInfo{
+ /// The request for all player infos
+ staticfuncall()->AdaptedFetchRequest<SQLRequest<PlayerInfo>>{
+ letsql="""
+ SELECT
+ \(Player.selectionSQL()),
+ \(Team.selectionSQL()),
+ MAX(round.score) AS maxScore
+ FROM player
+ LEFT JOIN team ON ...
+ LEFT JOIN round ON ...
+ GROUP BY ...
+ """
+ returnSQLRequest<PlayerInfo>(sql).adapted{dbin
+ letadapters=trysplittingRowAdapters(columnCounts:[
+ Player.numberOfSelectedColumns(db),
+ Team.numberOfSelectedColumns(db)])
+ returnScopeAdapter([
+ Scopes.player:adapters[0],
+ Scopes.team:adapters[1]])
+ }
+ }
+
+ /// Fetches all player infos
+ staticfuncfetchAll(_db:Database)throws->[PlayerInfo]{
+ returntryall().fetchAll(db)
+ }
+}
+
+
+
It is now time to use our request:
+
// Fetch player infos
+letplayerInfos=trydbQueue.read{dbin
+ tryPlayerInfo.fetchAll(db)
+}
+
+// Track player infos with RxRGDB:
+PlayerInfo.all()
+ .rx.fetchAll(in:dbQueue)
+ .subscribe(onNext:{playerInfos:[PlayerInfo]in
+ print("Player infos have changed")
+ })
+
+
+
+
:bulb: In this chapter, we have learned how to define a custom request that can both fetch records from joined queries, and feed database observation tools.
+
+
Splitting Rows, the Codable Way
+
+
Codable Records build on top of the standard Decodable protocol in order to decode database rows.
+
+
You can consume complex joined queries with Codable records as well. As a demonstration, we’ll rewrite the above sample code:
+
structPlayer:Decodable,FetchableRecord,TableRecord{
+ varid:Int64
+ varname:String
+}
+structTeam:Decodable,FetchableRecord,TableRecord{
+ varid:Int64
+ varname:String
+ varcolor:Color
+}
+structPlayerInfo:Decodable,FetchableRecord{
+ varplayer:Player
+ varteam:Team?
+ varmaxScore:Int
+}
+
+extensionPlayerInfo{
+ /// The request for all player infos
+ staticfuncall()->AdaptedFetchRequest<SQLRequest<PlayerInfo>>{
+ letsql="""
+ SELECT
+ \(Player.selectionSQL()),
+ \(Team.selectionSQL()),
+ MAX(round.score) AS maxScore
+ FROM player
+ LEFT JOIN team ON ...
+ LEFT JOIN round ON ...
+ GROUP BY ...
+ """
+ returnSQLRequest<PlayerInfo>(sql).adapted{dbin
+ letadapters=trysplittingRowAdapters(columnCounts:[
+ Player.numberOfSelectedColumns(db),
+ Team.numberOfSelectedColumns(db)])
+ returnScopeAdapter([
+ CodingKeys.player.stringValue:adapters[0],
+ CodingKeys.team.stringValue:adapters[1]])
+ }
+ }
+
+ /// Fetches all player infos
+ staticfuncfetchAll(_db:Database)throws->[PlayerInfo]{
+ returntryall().fetchAll(db)
+ }
+}
+
+// Fetch player infos
+letplayerInfos=trydbQueue.read{dbin
+ tryPlayerInfo.fetchAll(db)
+}
+
+// Track player infos with RxRGDB:
+PlayerInfo.all()
+ .rx.fetchAll(in:dbQueue)
+ .subscribe(onNext:{playerInfos:[PlayerInfo]in
+ print("Player infos have changed")
+ })
+
+
+
+
:bulb: In this chapter, we have learned how to use the Decodable protocol and its associated CodingKeys enum in order to dry up our code.
+
+
Database Changes Observation
+
+
SQLite notifies its host application of changes performed to the database, as well of transaction commits and rollbacks.
+
+
GRDB puts this SQLite feature to some good use, and lets you observe the database in various ways:
+
+
+
After Commit Hook: The simplest way to handle successful transactions.
FetchedRecordsController: Automated tracking of changes in a query results, plus UITableView animations
+
RxGRDB: Automated tracking of changes in a query results, based on RxSwift
+
+
+
Database observation requires that a single database queue or pool is kept open for all the duration of the database usage.
+
After Commit Hook
+
+
When your application needs to make sure a specific database transaction has been successfully committed before it executes some work, use the Database.afterNextTransactionCommit(_:) method.
+
+
Its closure argument is called right after database changes have been successfully written to disk:
The closure runs in a protected dispatch queue, serialized with all database updates.
+
+
This after commit hook helps synchronizing the database with other resources, such as files, or system sensors.
+
+
In the example below, a location manager starts monitoring a CLRegion if and only if it has successfully been stored in the database:
+
/// Inserts a region in the database, and start monitoring upon
+/// successful insertion.
+funcstartMonitoring(_db:Database,region:CLRegion)throws{
+ // Make sure database is inside a transaction
+ trydb.inSavepoint{
+
+ // Save the region in the database
+ tryinsert(...)
+
+ // Start monitoring if and only if the insertion is
+ // eventually committed
+ db.afterNextTransactionCommit{_in
+ // locationManager prefers the main queue:
+ DispatchQueue.main.async{
+ locationManager.startMonitoring(for:region)
+ }
+ }
+
+ return.commit
+ }
+}
+
+
+
The method above won’t trigger the location manager if the transaction is eventually rollbacked (explicitly, or because of an error), as in the sample code below:
+
trydbQueue.write{dbin
+ // success
+ trystartMonitoring(db,region)
+
+ // On error, the transaction is rollbacked, the region is not inserted, and
+ // the location manager is not invoked.
+ tryfailableMethod(db)
+}
+
+
TransactionObserver Protocol
+
+
The TransactionObserver protocol lets you observe database changes and transactions:
+
protocolTransactionObserver:class{
+ /// Notifies a database change:
+ /// - event.kind (insert, update, or delete)
+ /// - event.tableName
+ /// - event.rowID
+ ///
+ /// For performance reasons, the event is only valid for the duration of
+ /// this method call. If you need to keep it longer, store a copy:
+ /// event.copy().
+ funcdatabaseDidChange(withevent:DatabaseEvent)
+
+ /// Filters the database changes that should be notified to the
+ /// `databaseDidChange(with:)` method.
+ funcobserves(eventsOfKindeventKind:DatabaseEventKind)->Bool
+
+ /// 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)
+}
+
By default, database holds weak references to its transaction observers: they are not retained, and stop getting notifications after they are deallocated. See Observation Extent for more options.
+
Database Changes And Transactions
+
+
A transaction observer is notified of all database changes: inserts, updates and deletes. This includes indirect changes triggered by ON DELETE and ON UPDATE actions associated to foreign keys, and SQL triggers.
+
+
+
:point_up: Note: the changes that are not notified are changes to internal system tables (such as sqlite_master), changes to WITHOUT ROWID tables, and the deletion of duplicate rows triggered by ON CONFLICT REPLACE clauses (this last exception might change in a future release of SQLite).
+
+
+
Notified changes are not actually written to disk until the transaction commits, and the databaseDidCommit callback is called. On the other side, databaseDidRollback confirms their invalidation:
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 database changes they are not interested in.
+
+
The filtering happens in the observes(eventsOfKind:) method, which tells whether the observer wants notification of specific kinds of changes, or not. For example, here is how an observer can focus on the changes that happen on the player database table:
+
classPlayerObserver:TransactionObserver{
+ funcobserves(eventsOfKindeventKind:DatabaseEventKind)->Bool{
+ // Only observe changes to the "player" table.
+ returneventKind.tableName=="player"
+ }
+
+ funcdatabaseDidChange(withevent:DatabaseEvent){
+ // This method is only called for changes that happen to
+ // the "player" table.
+ }
+}
+
+
+
Generally speaking, the observes(eventsOfKind:) method can distinguish insertions from deletions and updates, and is also able to inspect the columns that are about to be changed:
+
classPlayerScoreObserver:TransactionObserver{
+ funcobserves(eventsOfKindeventKind:DatabaseEventKind)->Bool{
+ // Only observe changes to the "score" column of the "player" table.
+ switcheventKind{
+ case.insert(lettableName):
+ returntableName=="player"
+ case.delete(lettableName):
+ returntableName=="player"
+ case.update(lettableName,letcolumnNames):
+ returntableName=="player"&&columnNames.contains("score")
+ }
+ }
+}
+
+
+
When the observes(eventsOfKind:) method returns false for all event kinds, the observer is still notified of commits and rollbacks:
+
classPureTransactionObserver:TransactionObserver{
+ funcobserves(eventsOfKindeventKind:DatabaseEventKind)->Bool{
+ // Ignore all individual changes
+ returnfalse
+ }
+
+ funcdatabaseDidChange(withevent:DatabaseEvent){/* Never called */}
+ funcdatabaseWillCommit()throws{/* Called before commit */}
+ funcdatabaseDidRollback(_db:Database){/* Called on rollback */}
+ funcdatabaseDidCommit(_db:Database){/* Called on commit */}
+}
+
+
+
For more information about event filtering, see DatabaseRegion.
+
Observation Extent
+
+
You can specify how long an observer is notified of database changes and transactions.
+
+
The remove(transactionObserver:) method explicitly stops notifications, at any time:
+
// From a database queue or pool:
+dbQueue.remove(transactionObserver:observer)
+
+// From a database connection:
+dbQueue.inDatabase{dbin
+ db.remove(transactionObserver:observer)
+}
+
+
+
Alternatively, use the extent parameter of the add(transactionObserver:extent:) method:
+
letobserver=MyObserver()
+
+// On a database queue or pool:
+dbQueue.add(transactionObserver:observer)// default extent
+dbQueue.add(transactionObserver:observer,extent:.observerLifetime)
+dbQueue.add(transactionObserver:observer,extent:.nextTransaction)
+dbQueue.add(transactionObserver:observer,extent:.databaseLifetime)
+
+// On a database connection:
+dbQueue.inDatabase{dbin
+ db.add(transactionObserver:...)
+}
+
+
+
+
The default extent is .observerLifetime: the database holds a weak reference to the observer, and the observation automatically ends when the observer is deallocated. Meanwhile, observer is notified of all changes and transactions.
+
.nextTransaction activates the observer until the current or next transaction completes. The database keeps a strong reference to the observer until its databaseDidCommit or databaseDidRollback method is eventually called. Hereafter the observer won’t get any further notification.
+
.databaseLifetime has the database retain and notify the observer until the database connection is closed.
+
+
+
Finally, an observer may ignore all database changes until the end of the current transaction:
+
classPlayerObserver:TransactionObserver{
+ varplayerTableWasModified=false
+
+ funcobserves(eventsOfKindeventKind:DatabaseEventKind)->Bool{
+ returneventKind.tableName=="player"
+ }
+
+ funcdatabaseDidChange(withevent:DatabaseEvent){
+ playerTableWasModified=true
+
+ // It is pointless to keep on tracking further changes:
+ stopObservingDatabaseChangesUntilNextTransaction()
+ }
+}
+
+
+
After stopObservingDatabaseChangesUntilNextTransaction(), the databaseDidChange(with:) method will not be notified of any change for the remaining duration of the current transaction. This helps GRDB optimize database observation.
+
DatabaseRegion
+
+
DatabaseRegion is a type that helps observing changes in the results of a database request.
+
+
A request knows which database modifications can impact its results. It can communicate this information to a transaction observer by the way of a database region.
Beware that a region notifies potential changes, not actual changes in the results of a request. A change is notified if and only if a statement has actually modified the tracked tables and columns by inserting, updating, or deleting a row.
+
+
For example, if you observe the region of Player.select(max(Column("score"))), then you’ll get be notified of all changes performed on the score column of the player table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table.
+
+
Similarly, observing the region of Country.filter(key: "FR") will notify all changes that happen to the whole country table. That is because SQLite only notifies the numerical rowid of changed rows, and we can’t check if it is the row FR that has been changed, or another. This limitation does not apply to tables whose primary key is the rowid: Player.filter(key: 42) will only notify of changes performed on the row with id 42.
+
Support for SQLite Pre-Update Hooks
+
+
A custom SQLite build can activate SQLite preupdate hooks. In this case, TransactionObserverType gets an extra callback which lets you observe individual column values in the rows modified by a transaction:
+
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 FetchableRecord protocol, such as a subclass of the Record class, a FetchedRecordsController is able to track changes in the results of the fetch request, notify of those changes, and return the results of the request in a form that is suitable for a table view or a collection view, with one cell per fetched record.
+
+
See the Demo Application for an sample app that uses FetchedRecordsController.
+
+
See also RxGRDB, an RxSwift extension, for a reactive way to track request changes.
The type of the fetched records. It must be a type that adopts the FetchableRecord protocol, such as a subclass of the Record class
+
A fetch request
+
+
classPlayer:Record{...}
+letdbQueue=DatabaseQueue(...)// or DatabasePool
+
+// Using a Request from the Query Interface:
+letcontroller=FetchedRecordsController(
+ dbQueue,
+ request:Player.order(Column("name")))
+
+// Using SQL, and eventual arguments:
+letcontroller=FetchedRecordsController<Player>(
+ dbQueue,
+ sql:"SELECT * FROM player ORDER BY name WHERE countryCode = ?",
+ arguments:["FR"])
+
+
+
The fetch request can involve several database tables. The fetched records controller will only track changes in the columns and tables used by the fetch request.
+
letcontroller=FetchedRecordsController<Author>(
+ dbQueue,
+ sql:"""
+ SELECT author.name, COUNT(book.id) AS bookCount
+ FROM author
+ LEFT JOIN book ON book.authorId = author.id
+ GROUP BY author.id
+ ORDER BY author.name
+ """)
+
+
+
After creating an instance, you invoke performFetch() to actually execute
+the fetch.
+
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:
+
// One transaction
+trydbQueue.write{dbin// or dbPool.write
+ tryplayer1.insert(db)
+ tryplayer2.insert(db)
+}
+
+// One transaction
+trydbQueue.inTransaction{dbin// or dbPool.writeInTransaction
+ tryplayer1.insert(db)
+ tryplayer2.insert(db)
+ return.commit
+}
+
+// Two transactions
+trydbQueue.inDatabase{dbin// or dbPool.writeWithoutTransaction
+ tryplayer1.insert(db)
+ tryplayer2.insert(db)
+}
+
+
+
When you apply several changes to the database, you should group them in a single explicit transaction. The controller will then notify of all changes together.
+
The Changes Notifications
+
+
An instance of FetchedRecordsController notifies that the controller’s fetched records have been changed by the mean of callbacks:
+
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()
+
:warning: Warning: notification of individual record changes (the onChange callback) has FetchedRecordsController use a diffing algorithm that has a high complexity, a high memory consumption, and is thus not suited for large result sets. One hundred rows is probably OK, but one thousand is probably not. If your application experiences problems with large lists, see Issue 263 for more information.
+
+
+
Callbacks have the fetched record controller itself as an argument: use it in order to avoid memory leaks:
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:
+ returntryPlayer.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(Player.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 TableRecord 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()
+ })
+
+
+
+
:warning: Warning: notification of individual record changes (the onChange callback) has FetchedRecordsController use a diffing algorithm that has a high complexity, a high memory consumption, and is thus not suited for large result sets. One hundred rows is probably OK, but one thousand is probably not. If your application experiences problems with large lists, see Issue 263 for more information.
+
+
+
See the Demo Application for an sample app that uses FetchedRecordsController to animate a table view.
+
+
+
:point_up: Note: our sample code above uses unowned references to the table view controller. This is a safe pattern as long as the table view controller owns the fetched records controller, and is deallocated from the main thread (this is usually the case). In other situations, prefer weak references.
+
+
FetchedRecordsController Concurrency
+
+
A fetched records controller can not be used from any thread.
+
+
When the database itself can be read and modified from any thread, fetched records controllers must be used from the main thread. Record changes are also notified on the main thread.
+
+
Change callbacks are invoked asynchronously. This means that changes made from the main thread are not immediately notified. When you need to take immediate action, force the controller to refresh immediately with its performFetch method. In this case, changes callbacks are not called:
+
// Change database on the main thread:
+trydbQueue.write{dbin
+ tryPlayer(...).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.
+
Avoiding SQL Injection
+
+
SQL injection is a technique that lets an attacker nuke your database.
Here is an example of code that is vulnerable to SQL injection:
+
// BAD BAD BAD
+letid=1
+letname=textField.text
+trydbQueue.write{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 raw SQL queries:
+
letname=textField.text
+trydbQueue.write{dbin
+ // Good
+ trydb.execute(
+ "UPDATE students SET name = ? WHERE id = ?",
+ arguments:[name,id])
+
+ // Just as good
+ trydb.execute(
+ "UPDATE students SET name = :name WHERE id = :id",
+ arguments:["name":name,"id":id])
+}
+
+
+
When you use records and the query interface, GRDB always prevents SQL injection for you:
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.
do{
+ trydb.execute(
+ "INSERT INTO pet (masterId, name) VALUES (?, ?)",
+ arguments:[1,"Bobby"])
+}catchleterrorasDatabaseError{
+ // The SQLite error code: 19 (SQLITE_CONSTRAINT)
+ error.resultCode
+
+ // The extended error code: 787 (SQLITE_CONSTRAINT_FOREIGNKEY)
+ error.extendedResultCode
+
+ // The eventual SQLite message: FOREIGN KEY constraint failed
+ error.message
+
+ // The eventual erroneous SQL query
+ // "INSERT INTO pet (masterId, name) VALUES (?, ?)"
+ error.sql
+
+ // Full error description:
+ // "SQLite error 19 with statement `INSERT INTO pet (masterId, name)
+ // VALUES (?, ?)` arguments [1, "Bobby"]: FOREIGN KEY constraint failed""
+ error.description
+}
+
+
+
SQLite uses codes to distinguish between various errors:
+
do{
+ try...
+}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 PersistableRecord protocol, in a single case: when the update method could not find any row to update:
+
do{
+ tryplayer.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["name"]
+
+
+
Solution: fix the contents of the database, use NOT NULL constraints, or load an optional:
+
letname:String?=row["name"]
+
+
Conversion from database value to Swift type fails:
+
// fatal error: could not convert "Mom’s birthday" to Date.
+letdate:Date=row["date"]
+
+// fatal error: could not convert "" to URL.
+leturl:URL=row["url"]
+
+
+
Solution: fix the contents of the database, or use DatabaseValue to handle all possible cases:
+
letdbValue:DatabaseValue=row["date"]
+ifdbValue.isNull{
+ // Handle NULL
+}elseifletdate=Date.fromDatabaseValue(dbValue){
+ // Handle valid date
+}else{
+ // Handle invalid date
+}
+
+
The database can’t guarantee that the code does what it says:
+
// fatal error: table player has no unique index on column email
+tryPlayer.deleteOne(db,key:["email":"arthur@example.com"])
+
+
+
Solution: add a unique index to the player.email column, or use the deleteAll method to make it clear that you may delete more than one row:
// fatal error: Database methods are not reentrant.
+dbQueue.write{dbin
+ dbQueue.write{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[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:
:warning: Warning: Database.logError must be set before any database connection is opened. This includes the connections that your application opens with GRDB, but also connections opened by other tools, such as third-party libraries. Setting it after a connection has been opened is an SQLite misuse, and has no effect.
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:
+
Player.select(nameColumn.uppercased)
+
+
String Comparison
+
+
SQLite compares strings in many occasions: when you sort rows according to a string column, or when you use a comparison operator such as = and <=.
+
+
The comparison result comes from a collating function, or collation. SQLite comes with three built-in collations that do not support Unicode: binary, nocase, and rtrim.
+
+
GRDB comes with five extra collations that leverage unicode-aware comparisons based on the standard Swift String comparison functions and operators:
+
+
+
unicodeCompare (uses the built-in <= and == Swift operators)
+
caseInsensitiveCompare
+
localizedCaseInsensitiveCompare
+
localizedCompare
+
localizedStandardCompare
+
+
+
A collation can be applied to a table column. All comparisons involving this column will then automatically trigger the comparison function:
+
trydb.create(table:"player"){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)
+}
+
+// Players are sorted in a localized case insensitive way:
+letplayers=tryPlayer.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
+letplayers=tryPlayer.fetchAll(db,
+ "SELECT * FROM player ORDER BY name COLLATE \(collation.name))")
+letplayers=tryPlayer.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.shared)
+
+
Data Protection
+
+
Data Protection lets you protect files so that they are encrypted and unavailable until the device is unlocked.
+
+
Data protection can be enabled globally for all files created by an application.
+
+
You can also explicitly protect a database, by configuring its enclosing directory. This will not only protect the database file, but also all temporary files created by SQLite (including the persistent .shm and .wal files created by database pools).
+
+
For example, to explicitly use complete protection:
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.
+
DatabaseSnapshot opens a single read-only database connection on an unchanging database content, and (currently) serializes all database accesses
+
+
+
All foster application safety: regardless of the concurrency mode you choose, GRDB provides you with the same guarantees, as long as you follow three rules.
+
+
+
:bowtie: Guarantee 1: writes are always serialized. At every moment, there is no more than a single thread that is writing into the database.
+
+
+
Database writes always happen in a unique serial dispatch queue, named the writer protected dispatch queue.
+
+
:bowtie: Guarantee 2: reads are always isolated. This means that they are guaranteed an immutable view of the last committed state of the database, and that you can perform subsequent fetches without fearing eventual concurrent writes to mess with your application logic:
+
trydbPool.read{dbin// or dbQueue.read
+ // Guaranteed to be equal
+ letcount1=tryPlayer.fetchCount(db)
+ letcount2=tryPlayer.fetchCount(db)
+}
+
+
+
+
In database queues, reads happen in the same protected dispatch queue as writes: isolation is just a consequence of the serialization of database accesses
: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 a bad idea. Do share a single connection instead.
+
+
See the Demo Application for an sample app that sets up a single database queue that is available throughout the application.
+
+
If there are several instances of database queues or pools that write in the same database, a multi-threaded application will eventually face database is locked errors. See Dealing with External Connections.
+
// SAFE CONCURRENCY
+funcfetchCurrentUser(_db:Database)throws->User?{
+ returntryUser.fetchOne(db)
+}
+// dbQueue is a singleton defined somewhere in your app
+letuser=trydbQueue.read{dbin// or dbPool.read
+ tryfetchCurrentUser(db)
+}
+
+// UNSAFE CONCURRENCY
+// This method fails when some other thread is currently writing into
+// the database.
+funccurrentUser()throws->User?{
+ letdbQueue=tryDatabaseQueue(...)
+ returntrydbQueue.read{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 (or use snapshots).
+
+
Database access methods isolate your groups of related statements against eventual database updates performed by other threads, and guarantee a consistent view of the database. This isolation is only guaranteed inside the closure argument of those methods. Two consecutive calls do not guarantee isolation:
+
// SAFE CONCURRENCY
+trydbPool.read{dbin// or dbQueue.read
+ // Guaranteed to be equal:
+ letcount1=tryPlace.fetchCount(db)
+ letcount2=tryPlace.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{dbintryPlace.fetchCount(db)}
+letcount2=trydbPool.read{dbintryPlace.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
+ tryPlace(...).insert(db)
+ letcount=tryPlace.fetchCount(db)
+}
+
+// UNSAFE CONCURRENCY
+// The count may be zero because some other thread may have performed
+// a deletion between the two blocks:
+trydbPool.write{dbintryPlace(...).insert(db)}
+letcount=trydbPool.read{dbintryPlace.fetchCount(db)}
+
+
+
On that last example, see Advanced DatabasePool if you look after extra performance.
+
:point_up: Rule 3: When you perform several modifications of the database that temporarily put the database in an inconsistent state, make sure those modifications are grouped within a transaction.
+
// SAFE CONCURRENCY
+trydbPool.write{dbin// or dbQueue.write
+ tryCredit(destinationAccout,amount).insert(db)
+ tryDebit(sourceAccount,amount).insert(db)
+}
+
+// SAFE CONCURRENCY
+trydbPool.writeInTransaction{dbin// or dbQueue.inTransaction
+ tryCredit(destinationAccout,amount).insert(db)
+ tryDebit(sourceAccount,amount).insert(db)
+ return.commit
+}
+
+// UNSAFE CONCURRENCY
+trydbPool.writeWithoutTransaction{dbin
+ tryCredit(destinationAccout,amount).insert(db)
+ // <- Concurrent dbPool.read sees a partial db update here
+ tryDebit(sourceAccount,amount).insert(db)
+}
+
+
+
Without transaction, DatabasePool.read { ... } may see the first statement, but not the second, and access a database where the balance of accounts is not zero. A highly bug-prone situation.
+
+
So do use transactions in order to guarantee database consistency accross your application threads: that’s what they are made for.
Database queues serialize all database accesses, reads, and writes. There is never more than one thread that uses the database. In the image below, we see how three threads can see the database as time passes:
+
+
+
+
Database pools also serialize all writes. But they allow concurrent reads and writes, and isolate reads so that they don’t see changes performed by other threads. This gives a very different picture:
+
+
+
+
See how, with database pools, two reads can see different database states at the same time.
+
+
For more information about database pools, grab information about SQLite WAL mode and snapshot isolation. See Database Observation when you look after automatic notifications of database changes.
+
Advanced DatabasePool
+
+
Database pools are very concurrent, since all reads can run in parallel, and can even run during write operations. But writes are still serialized: at any given point in time, there is no more than a single thread that is writing into the database.
+
+
When your application modifies the database, and then reads some value that depends on those modifications, you may want to avoid locking the writer queue longer than necessary:
+
trydbPool.write{dbin
+ // Increment the number of players
+ tryPlayer(...).insert(db)
+
+ // Read the number of players. The writer queue is still locked :-(
+ letcount=tryPlayer.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 players
+ tryPlayer(...).insert(db)
+}
+// <- other threads can write in the database here
+trydbPool.read{dbin
+ // Read some random value :-(
+ letcount=tryPlayer.fetchCount(db)
+}
+
+
+
The correct solution is the concurrentRead method, which must be called from within a write block, outside of any transaction.
+
+
concurrentRead returns a future value which you consume on any dispatch queue, with the wait() method:
+
// CORRECT
+letfutureCount:Future<Int>=trydbPool.writeWithoutTransaction{dbin
+ // increment the number of players
+ tryPlayer(...).insert(db)
+
+ // <- not in a transaction here
+ letfutureCount=dbPool.concurrentRead{db
+ returntryPlayer.fetchCount(db)
+ }
+ returnfutureCount
+}
+// <- The writer queue has been unlocked :-)
+
+// Wait for the player count
+letcount:Int=tryfutureCount.wait()
+
+
+
concurrentRead 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.
+
+
The closure can run concurrently with eventual updates performed after concurrentRead: those updates won’t be visible from within the closure. In the example below, the number of players is guaranteed to be non-zero, even though it is fetched concurrently with the player deletion:
+
trydbPool.writeWithoutTransaction{dbin
+ // Increment the number of players
+ tryPlayer(...).insert(db)
+
+ letfutureCount=dbPool.concurrentRead{db
+ // Guaranteed to be non-zero
+ returntryPlayer.fetchCount(db)
+ }
+
+ tryPlayer.deleteAll(db)
+}
+
+
+
Transaction Observers can also use concurrentRead in their databaseDidCommit method in order to process database changes without blocking other threads that want to write into the database.
+
Database Snapshots
+
+
A database snapshot sees an unchanging database content, as it existed at the moment it was created.
+
+
Unchanging means that a snapshot never sees any database modifications during all its lifetime. And yet it doesn’t prevent database updates. This magic is made possible by SQLite’s WAL mode (see Isolation In SQLite).
You can create as many snapshots as you need, regardless of the maximum number of readers in the pool. A snapshot database connection is closed when the snapshot gets deallocated.
+
+
A snapshot can be used from any thread. Its read methods is synchronous, and blocks the current thread until your database statements are executed:
+
// Read values:
+trysnapshot.read{dbin
+ letplayers=tryPlayer.fetchAll(db)
+ letplayerCount=tryPlayer.fetchCount(db)
+}
+
+// Extract a value from the database:
+letplayerCount=trysnapshot.read{dbin
+ tryPlayer.fetchCount(db)
+}
+
+
+
When you want to control the latest committed changes seen by a snapshot, create it from the pool’s writer protected dispatch queue, outside of any transaction:
+
letsnapshot1=trydbPool.writeWithoutTransaction{db->DatabaseSnapshotin
+ trydb.inTransaction{
+ // delete all players
+ tryPlayer.deleteAll()
+ return.commit
+ }
+
+ // <- not in a transaction here
+ returndbPool.makeSnapshot()
+}
+// <- Other threads may modify the database here
+letsnapshot2=trydbPool.makeSnapshot()
+
+trysnapshot1.read{dbin
+ // Guaranteed to be zero
+ tryPlayer.fetchCount(db)
+}
+
+trysnapshot2.read{dbin
+ // Could be anything
+ tryPlayer.fetchCount(db)
+}
+
+
+
+
:point_up: Note: snapshots currently serialize all database accesses. In the future, snapshots may allow concurrent reads.
+
+
DatabaseWriter and DatabaseReader Protocols
+
+
Both DatabaseQueue and DatabasePool adopt the DatabaseReader and DatabaseWriter protocols. DatabaseSnapshot adopts DatabaseReader only.
+
+
These protocols provide a unified API that let you write generic code that targets all concurrency modes. They fuel, for example:
Caution: DatabaseReader and DatabaseWriter only provide the smallest common guarantees. They don’t erase the differences between queues, pools, and snapshots. See for example Differences between Database Queues and Pools.
+
Unsafe Concurrency APIs
+
+
Database queues, pools, snapshots, as well as their common protocols DatabaseReader and DatabaseWriter provide unsafe APIs. Unsafe APIs lift concurrency guarantees, and allow advanced yet unsafe patterns.
+
+
+
unsafeRead
+
+
The unsafeRead method is synchronous, and blocks the current thread until your database statements are executed in a protected dispatch queue. GRDB does just the bare minimum to provide a database connection that can read.
+
+
When used on a database pool, reads are no longer isolated:
+
dbPool.unsafeRead{dbin
+ // Those two values may be different because some other thread
+ // may have inserted or deleted a player between the two requests:
+ letcount1=tryPlayer.fetchCount(db)
+ letcount2=tryPlayer.fetchCount(db)
+}
+
+
+
When used on a database queue, the closure argument is allowed to write in the database.
+
unsafeReentrantRead
+
+
The unsafeReentrantRead behaves just as unsafeRead (see above), and allows reentrant calls:
+
dbPool.read{db1in
+ // No "Database methods are not reentrant" fatal error:
+ dbPool.unsafeReentrantRead{db2in
+ dbPool.unsafeReentrantRead{db3in
+ ...
+ }
+ }
+}
+
+
+
Reentrant database accesses make it very easy to break the second safety rule, which says: group related statements within a single call to a DatabaseQueue or DatabasePool database access method.. Using a reentrant method is pretty much likely the sign of a wrong application architecture that needs refactoring.
+
+
There is a single valid use case for reentrant methods, which is when you are unable to control database access scheduling.
+
unsafeReentrantWrite
+
+
The unsafeReentrantWrite method is synchronous, and blocks the current thread until your database statements are executed in a protected dispatch queue. Writes are serialized: eventual concurrent database updates are postponed until the block has executed.
+
+
Reentrant calls are allowed:
+
dbQueue.write{db1in
+ // No "Database methods are not reentrant" fatal error:
+ dbQueue.unsafeReentrantWrite{db2in
+ dbQueue.unsafeReentrantWrite{db3in
+ ...
+ }
+ }
+}
+
+
+
Reentrant database accesses make it very easy to break the second safety rule, which says: group related statements within a single call to a DatabaseQueue or DatabasePool database access method.. Using a reentrant method is pretty much likely the sign of a wrong application architecture that needs refactoring.
+
+
There is a single valid use case for reentrant methods, which is when you are unable to control database access scheduling.
+
+
Dealing with External Connections
+
+
The first rule of GRDB is:
+
+
+
Rule 1: Have a unique instance of DatabaseQueue or DatabasePool connected to any database file.
+
+
+
This means that dealing with external connections is not a focus of GRDB. Guarantees of GRDB may or may not hold as soon as some external connection modifies a database.
+
+
If you absolutely need multiple connections, then:
You’ll find below general advice when you do look after performance:
+
+
+
Focus
+
Know your platform
+
Use transactions
+
Don’t do useless work
+
Learn about SQL strengths and weaknesses
+
Avoid strings & dictionaries
+
+
Performance tip: focus
+
+
You don’t know which part of your program needs improvement until you have run a benchmarking tool.
+
+
Don’t make any assumption, avoid optimizing code too early, and use Instruments.
+
Performance tip: know your platform
+
+
If your application processes a huge JSON file and inserts thousands of rows in the database right from the main thread, it will quite likely become unresponsive, and provide a sub-quality user experience.
+
+
If not done yet, read the Concurrency Programming Guide and learn how to perform heavy computations without blocking your application.
+
+
Most GRBD APIs are synchronous. Spawning them into parallel queues is as easy as:
+
DispatchQueue.global().async{
+ dbQueue.write{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:
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
+letplayers=tryPlayer.order(scoreColumn.desc).fetchAll(db)
+lethallOfFame=players.prefix(5)
+
+// Better way
+lethallOfFame=tryPlayer.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 author
+letauthors=tryAuthor.fetchAll(db)
+forauthorinauthors{
+ // SELECT COUNT(*) FROM book WHERE authorId = ...
+ author.bookCount=tryBook.filter(authorIdColumn==author.id).fetchCount(db)
+}
+
+
+
Instead, perform a single query:
+
letsql="""
+ SELECT author.*, COUNT(book.id) AS bookCount
+ FROM author
+ LEFT JOIN book ON book.authorId = author.id
+ GROUP BY author.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
+forplayerinplayers{
+ tryplayer.insert(db)
+}
+
+// Prepared statement
+letinsertStatement=db.prepareStatement("INSERT INTO player (name, email) VALUES (?, ?)")
+forplayerinplayers{
+ // Only use the unsafe arguments setter if you are sure that you provide
+ // all statement arguments. A mistake can store unexpected values in
+ // the database.
+ insertStatement.unsafeSetArguments([player.name,player.email])
+ tryinsertStatement.execute()
+}
+
This question assumes that your application has to create a new database from scratch. If your app has to open an existing database that is embedded inside your application as a resource, see How do I open a database stored as a resource of my application? instead.
+
+
The database has to be stored in a valid place where it can be created and modified. For example, in the Application Support directory:
If the application should modify the database, you need to copy it to a place where it can be modified. For example, in the Application Support directory. Only then, open a connection:
Database connections are managed by database queues and pools. A connection is closed when its database queue or pool is deallocated, and all usages of this connection are completed.
+
+
Database accesses that run in background threads postpone the closing of connections.
+
How do I print a request as SQL?
+
+
When you want to debug a request that does not deliver the expected results, you may want to print the SQL that is actually executed.
+
+
You can turn your request into a SQLRequest instance:
+
trydbQueue.read{dbin
+ letrequest=Wine
+ .filter(Column("origin")=="Burgundy")
+ .order(Column("price")
+
+ letsqlRequest=trySQLRequest(db,request:request)
+ print(sqlRequest.sql)
+ // Prints SELECT * FROM wine WHERE origin = ? ORDER BY price
+ print(sqlRequest.arguments)
+ // Prints ["Burgundy"]
+}
+
+
+
Another option is to setup a tracing function that will print out all SQL requests executed by your application. You provide the trace function when you connect to the database:
+
varconfig=Configuration()
+config.trace={print($0)}// Prints all SQL statements
+letdbQueue=tryDatabaseQueue(path:dbPath,configuration:config)
+
+trydbQueue.read{dbin
+ letwines=Wine
+ .filter(Column("origin")=="Burgundy")
+ .order(Column("price")
+ .fetchAll(db)
+ // Prints SELECT * FROM wine WHERE origin = 'Burgundy' ORDER BY price
+}
+
+
Generic parameter ‘T’ could not be inferred
+
+
You may get this error when using the read and write methods of database queues and pools:
+
// Generic parameter 'T' could not be inferred
+letx=trydbQueue.read{dbin
+ letresult=tryString.fetchOne(db,...)
+ returnresult
+}
+
This error can also be prevented altogether by using a more relaxed file protection.
+
What Are Experimental Features?
+
+
Since GRDB 1.0, all backwards compatibility guarantees of semantic versioning apply: no breaking change will happen until the next major version of the library.
+
+
There is an exception, though: experimental features, marked with the **:fire: EXPERIMENTAL** badge. Those are advanced features that are too young, or lack user feedback. They are not stabilized yet.
+
+
Those experimental features are not protected by semantic versioning, and may break between two minor releases of the library. To help them becoming stable, your feedback is greatly appreciated.
Creates a request with a full-text predicate added to the eventual","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB21QueryInterfaceRequestVA2A11TableRecordRzlE9including8optionalACyxGqd___t16OriginRowDecoderQyd__RszAA11AssociationRd__lF":{"name":"including(optional:)","abstract":"
Creates a request that includes an association. The columns of the","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB21QueryInterfaceRequestVA2A11TableRecordRzlE9including8requiredACyxGqd___t16OriginRowDecoderQyd__RszAA11AssociationRd__lF":{"name":"including(required:)","abstract":"
Creates a request that includes an association. The columns of the","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB21QueryInterfaceRequestVA2A11TableRecordRzlE7joining8optionalACyxGqd___t16OriginRowDecoderQyd__RszAA11AssociationRd__lF":{"name":"joining(optional:)","abstract":"
Creates a request that includes an association. The columns of the","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB21QueryInterfaceRequestVA2A11TableRecordRzlE7joining8requiredACyxGqd___t16OriginRowDecoderQyd__RszAA11AssociationRd__lF":{"name":"joining(required:)","abstract":"
Creates a request that includes an association. The columns of the","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB21QueryInterfaceRequestVA2A11TableRecordRzlE9annotated4withACyxGAA20AssociationAggregateVyxGd_tF":{"name":"annotated(with:)","abstract":"
Creates a request which appends aggregates to the current selection.
Creates a request which appends the provided aggregate predicate to","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB12FetchRequestP10RowDecoderQa":{"name":"RowDecoder","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB21QueryInterfaceRequestV6selectyACyxGSayAA13SQLSelectable_pGF":{"name":"select(_:)","abstract":"
Creates a request which selects selection, and fetches values of","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB21QueryInterfaceRequestV6select_2asACyqd__GAA13SQLSelectable_pd_qd__mtlF":{"name":"select(_:as:)","abstract":"
Creates a request which selects selection, and fetches values of","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB21QueryInterfaceRequestV6select3sql9arguments2asACyqd__GSS_AA18StatementArgumentsVSgqd__mtlF":{"name":"select(sql:arguments:as:)","abstract":"
Creates a request which selects sql, and fetches values of","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB21QueryInterfaceRequestV9annotated4withACyxGSayAA13SQLSelectable_pG_tF":{"name":"annotated(with:)","abstract":"
Creates a request with the provided predicate promise added to the","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB21QueryInterfaceRequestV5groupyACyxGSayAA14SQLExpressible_pGAA8DatabaseCKcF":{"name":"group(_:)","abstract":"
Creates a request grouped according to expressions promise.
Creates a request with the provided predicate added to the","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB21QueryInterfaceRequestV5orderyACyxGSayAA15SQLOrderingTerm_pGAA8DatabaseCKcF":{"name":"order(_:)","abstract":"
Creates a request with the provided orderings promise.
Creates a request that allows you to define expressions that target","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB21QueryInterfaceRequestV02asD02ofACyqd__Gqd__m_tlF":{"name":"asRequest(of:)","abstract":"
Returns an aggregate that is selected in a column named like the given","parent_name":"AssociationAggregate"},"Structs/DatabaseMigrator.html#/s:4GRDB16DatabaseMigratorV05eraseB14OnSchemaChangeSbvp":{"name":"eraseDatabaseOnSchemaChange","abstract":"
When the eraseDatabaseOnSchemaChange flag is true, the migrator will","parent_name":"DatabaseMigrator"},"Structs/DatabaseMigrator.html#/s:4GRDB16DatabaseMigratorVACycfc":{"name":"init()","abstract":"
Iterate migrations in the same order as they were registered. If a","parent_name":"DatabaseMigrator"},"Structs/DatabaseMigrator.html#/s:4GRDB16DatabaseMigratorV7migrate_4upToyAA0B6Writer_p_SStKF":{"name":"migrate(_:upTo:)","abstract":"
Iterate migrations in the same order as they were registered, up to the","parent_name":"DatabaseMigrator"},"Structs/DatabaseMigrator.html#/s:4GRDB16DatabaseMigratorV17appliedMigrations2inShySSGAA0B6Reader_p_tKF":{"name":"appliedMigrations(in:)","abstract":"
Creates a pattern that matches any token found in the input string;","parent_name":"FTS5Pattern"},"Structs/FTS5Pattern.html#/init(matchingAllTokensIn:)":{"name":"init(matchingAllTokensIn:)","abstract":"
Creates a pattern that matches all tokens found in the input string;","parent_name":"FTS5Pattern"},"Structs/FTS5Pattern.html#/init(matchingPhrase:)":{"name":"init(matchingPhrase:)","abstract":"
Creates a pattern that matches a contiguous string; returns nil if no","parent_name":"FTS5Pattern"},"Structs/FTS5Pattern.html#/init(matchingPrefixPhrase:)":{"name":"init(matchingPrefixPhrase:)","abstract":"
Creates a pattern that matches a contiguous string prefix; returns","parent_name":"FTS5Pattern"},"Structs/FTS5Pattern.html#/databaseValue":{"name":"databaseValue","abstract":"
Returns a value that can be stored in the database.
Creates a FTS4 module suitable for the Database","parent_name":"FTS4"},"Structs/FTS4.html#/s:4GRDB4FTS4V10moduleNameSSvp":{"name":"moduleName","abstract":"
Creates a pattern from a raw pattern string; throws DatabaseError on","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/init(matchingAnyTokenIn:)":{"name":"init(matchingAnyTokenIn:)","abstract":"
Creates a pattern that matches any token found in the input string;","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/init(matchingAllTokensIn:)":{"name":"init(matchingAllTokensIn:)","abstract":"
Creates a pattern that matches all tokens found in the input string;","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/init(matchingPhrase:)":{"name":"init(matchingPhrase:)","abstract":"
Creates a pattern that matches a contiguous string; returns nil if no","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/s:4GRDB11FTS3PatternV18matchingAnyTokenInACSgSS_tcfc":{"name":"init(matchingAnyTokenIn:)","abstract":"
Creates a pattern that matches any token found in the input string;","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/s:4GRDB11FTS3PatternV19matchingAllTokensInACSgSS_tcfc":{"name":"init(matchingAllTokensIn:)","abstract":"
Creates a pattern that matches all tokens found in the input string;","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/s:4GRDB11FTS3PatternV14matchingPhraseACSgSS_tcfc":{"name":"init(matchingPhrase:)","abstract":"
Creates a pattern that matches a contiguous string; returns nil if no","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/s:4GRDB11FTS3PatternV13databaseValueAA08DatabaseE0Vvp":{"name":"databaseValue","abstract":"
Returns a value that can be stored in the database.
Returns an FTS3Pattern initialized from dbValue, if it contains","parent_name":"FTS3Pattern"},"Structs/FTS3.html#/s:4GRDB4FTS3VACycfc":{"name":"init()","abstract":"
Creates a FTS3 module suitable for the Database","parent_name":"FTS3"},"Structs/FTS3.html#/s:4GRDB4FTS3V10moduleNameSSvp":{"name":"moduleName","abstract":"
1 for inserts, updates, or deletes invoked by top-level triggers;","parent_name":"DatabasePreUpdateEvent"},"Structs/DatabasePreUpdateEvent.html#/initialRowID":{"name":"initialRowID","abstract":"
The initial rowID of the row being changed for .Update and .Delete changes,","parent_name":"DatabasePreUpdateEvent"},"Structs/DatabasePreUpdateEvent.html#/finalRowID":{"name":"finalRowID","abstract":"
The final rowID of the row being changed for .Update and .Insert changes,","parent_name":"DatabasePreUpdateEvent"},"Structs/DatabasePreUpdateEvent.html#/initialDatabaseValues":{"name":"initialDatabaseValues","abstract":"
Returns a DatabaseDateComponents if dbValue contains a","parent_name":"DatabaseDateComponents"},"Structs/StatementArguments.html#/s:4GRDB18StatementArgumentsV7isEmptySbvp":{"name":"isEmpty","abstract":"
Creates statement arguments from any array. The result is nil unless all","parent_name":"StatementArguments"},"Structs/StatementArguments.html#/s:4GRDB18StatementArgumentsVyACSDySSAA24DatabaseValueConvertible_pSgGcfc":{"name":"init(_:)","abstract":"
Creates statement arguments from a sequence of (key, value) dictionary,","parent_name":"StatementArguments"},"Structs/StatementArguments.html#/s:4GRDB18StatementArgumentsVyACxcSTRzSS_AA24DatabaseValueConvertible_pSgt7ElementRtzlufc":{"name":"init(_:)","abstract":"
Creates statement arguments from a sequence of (key, value) pairs, such","parent_name":"StatementArguments"},"Structs/StatementArguments.html#/s:4GRDB18StatementArgumentsVyACSgSDys11AnyHashableVypGcfc":{"name":"init(_:)","abstract":"
Creates statement arguments from [AnyHashable: Any].
Creates a new StatementArguments by extending the left-hand size","parent_name":"StatementArguments"},"Structs/StatementArguments.html#/s:4GRDB18StatementArgumentsV2apoiyA2C_ACtFZ":{"name":"&+(_:_:)","abstract":"
Creates a new StatementArguments by extending the left-hand size","parent_name":"StatementArguments"},"Structs/StatementArguments.html#/s:4GRDB18StatementArgumentsV2peoiyyACz_ACtFZ":{"name":"+=(_:_:)","abstract":"
Extends the left-hand size arguments with the right-hand side arguments.
Creates a SuffixRowAdapter that hides all columns before the","parent_name":"SuffixRowAdapter"},"Structs/ColumnMapping.html#/s:4GRDB13ColumnMappingVyACSDyS2SGcfc":{"name":"init(_:)","abstract":"
Creates a ColumnMapping with a dictionary from mapped column names to","parent_name":"ColumnMapping"},"Structs/EmptyRowAdapter.html#/s:4GRDB15EmptyRowAdapterVACycfc":{"name":"init()","abstract":"
Creates a request from an SQL string, optional arguments, and","parent_name":"SQLRequest"},"Structs/SQLRequest.html#/s:4GRDB10SQLRequestV_7request6cachedACyxGAA8DatabaseC_qd__SbtKc10RowDecoderQyd__RszAA12FetchRequestRd__lufc":{"name":"init(_:request:cached:)","abstract":"
Creates an SQL request from any other fetch request.
Creates a request whose prepare() method wraps and forwards","parent_name":"AnyFetchRequest"},"Structs/AdaptedFetchRequest.html#/s:4GRDB12FetchRequestP10RowDecoderQa":{"name":"RowDecoder","parent_name":"AdaptedFetchRequest"},"Structs/DatabaseValue/Storage.html#/s:4GRDB13DatabaseValueV7StorageO4nullyA2EmF":{"name":"null","abstract":"
The region that covers the full database: all columns and all rows","parent_name":"DatabaseRegion"},"Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionVACycfc":{"name":"init()","abstract":"
Returns whether the content in the region would be impacted if the","parent_name":"DatabaseRegion"},"Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF":{"name":"isModified(by:)","abstract":"
Returns whether the content in the region is impacted by this event.
The SQLite error code (see","parent_name":"DatabaseError"},"Structs/DatabaseError.html#/s:4GRDB13DatabaseErrorV18extendedResultCodeAA0eF0Vvp":{"name":"extendedResultCode","abstract":"
The SQLite extended error code (see","parent_name":"DatabaseError"},"Structs/DatabaseError.html#/s:4GRDB13DatabaseErrorV7messageSSSgvp":{"name":"message","abstract":"
A result code limited to the least significant 8 bits of the receiver.","parent_name":"ResultCode"},"Structs/ResultCode.html#/s:4GRDB10ResultCodeV2teoiySbAC_ACtFZ":{"name":"~=(_:_:)","abstract":"
Returns true if the code on the left matches the code on the right.
If false, it is a programmer error to leave a transaction opened at the","parent_name":"Configuration"},"Structs/Configuration.html#/s:4GRDB13ConfigurationV8busyModeAA8DatabaseC04BusyD0Ovp":{"name":"busyMode","abstract":"
The maximum number of concurrent readers (applies to database","parent_name":"Configuration"},"Structs/Configuration.html#/s:4GRDB13ConfigurationVACycfc":{"name":"init()","abstract":"
StatementArguments provide values to argument placeholders in raw"},"Structs/DatabaseDateComponents.html":{"name":"DatabaseDateComponents","abstract":"
DatabaseDateComponents reads and stores DateComponents in the database.
Use persistence containers in the encode(to:) method of your"},"Structs/PersistenceConflictPolicy.html":{"name":"PersistenceConflictPolicy","abstract":"
The MutablePersistableRecord protocol uses this type in order to handle SQLite"},"Protocols/PersistableRecord.html#/s:4GRDB17PersistableRecordP9didInsert4with3forys5Int64V_SSSgtF":{"name":"didInsert(with:for:)","abstract":"
Notifies the record that it was succesfully inserted.
Executes an INSERT or an UPDATE statement so that self is saved in","parent_name":"PersistableRecord"},"Protocols/PersistableRecord.html#/s:4GRDB17PersistableRecordPAAE13performInsertyyAA8DatabaseCKF":{"name":"performInsert(_:)","abstract":"
Don’t invoke this method directly: it is an internal method for types","parent_name":"PersistableRecord"},"Protocols/PersistableRecord.html#/s:4GRDB17PersistableRecordPAAE11performSaveyyAA8DatabaseCKF":{"name":"performSave(_:)","abstract":"
Don’t invoke this method directly: it is an internal method for types","parent_name":"PersistableRecord"},"Protocols/FetchableRecord.html#/s:4GRDB15FetchableRecordP3rowxAA3RowC_tcfc":{"name":"init(row:)","abstract":"
When the FetchableRecord type also adopts the standard Decodable","parent_name":"FetchableRecord"},"Protocols/FetchableRecord.html#/s:4GRDB15FetchableRecordP19databaseJSONDecoder3for10Foundation0E0CSS_tFZ":{"name":"databaseJSONDecoder(for:)","abstract":"
When the FetchableRecord type also adopts the standard Decodable","parent_name":"FetchableRecord"},"Protocols/FetchableRecord.html#/s:4GRDB15FetchableRecordP28databaseDateDecodingStrategyAA08DatabaseefG0OvpZ":{"name":"databaseDateDecodingStrategy","abstract":"
When the FetchableRecord type also adopts the standard Decodable","parent_name":"FetchableRecord"},"Protocols/FetchableRecord.html#/s:4GRDB15FetchableRecordPA2A05TableC0RzrlE11fetchCursoryAA0cF0CyxGAA8DatabaseCKFZ":{"name":"fetchCursor(_:)","abstract":"
A cursor over all records fetched from the database.
Returns a cursor over records identified by the provided unique keys","parent_name":"FetchableRecord"},"Protocols/FetchableRecord.html#/s:4GRDB15FetchableRecordPA2A05TableC0RzrlE8fetchAll_4keysSayxGAA8DatabaseC_SaySDySSAA0H16ValueConvertible_pSgGGtKFZ":{"name":"fetchAll(_:keys:)","abstract":"
Returns an array of records identified by the provided unique keys","parent_name":"FetchableRecord"},"Protocols/FetchableRecord.html#/s:4GRDB15FetchableRecordPA2A05TableC0RzrlE8fetchOne_3keyxSgAA8DatabaseC_SDySSAA0H16ValueConvertible_pSgGSgtKFZ":{"name":"fetchOne(_:key:)","abstract":"
Returns a single record identified by a unique key (the primary key or","parent_name":"FetchableRecord"},"Protocols/FetchableRecord.html#/s:4GRDB15FetchableRecordPAAE11fetchCursor_9arguments7adapterAA0cE0CyxGAA15SelectStatementC_AA0I9ArgumentsVSgAA10RowAdapter_pSgtKFZ":{"name":"fetchCursor(_:arguments:adapter:)","abstract":"
A cursor over records fetched from a prepared statement.
The type of the closure argument in the","parent_name":"VirtualTableModule"},"Protocols/VirtualTableModule.html#/s:4GRDB18VirtualTableModuleP10moduleNameSSvp":{"name":"moduleName","abstract":"
Returns a table definition that is passed as the closure argument in the","parent_name":"VirtualTableModule"},"Protocols/VirtualTableModule.html#/s:4GRDB18VirtualTableModuleP15moduleArguments3for2inSaySSG0C10DefinitionQz_AA8DatabaseCtKF":{"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/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordP25persistenceConflictPolicyAA011PersistencefG0VvpZ":{"name":"persistenceConflictPolicy","abstract":"
The policy that handles SQLite conflicts when records are inserted","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordP6encode2toyAA20PersistenceContainerVz_tF":{"name":"encode(to:)","abstract":"
Executes an INSERT or an UPDATE statement so that self is saved in","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordP6deleteySbAA8DatabaseCKF":{"name":"delete(_:)","abstract":"
Returns true if and only if the primary key matches a row in","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordP24databaseEncodingUserInfoSDys06CodinggH3KeyVypGvpZ":{"name":"databaseEncodingUserInfo","abstract":"
When the PersistableRecord type also adopts the standard Encodable","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordP19databaseJSONEncoder3for10Foundation0F0CSS_tFZ":{"name":"databaseJSONEncoder(for:)","abstract":"
When the PersistableRecord type also adopts the standard Encodable","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordP28databaseDateEncodingStrategyAA08DatabasefgH0OvpZ":{"name":"databaseDateEncodingStrategy","abstract":"
When the PersistableRecord type also adopts the standard Encodable","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordP28databaseUUIDEncodingStrategyAA08DatabasefG0OvpZ":{"name":"databaseUUIDEncodingStrategy","abstract":"
When the PersistableRecord type also adopts the standard Encodable","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordPAAE7request3forAA21QueryInterfaceRequestVy10RowDecoderQyd__Gqd___t06OriginjK0Qyd__RszAA11AssociationRd__lF":{"name":"request(for:)","abstract":"
Creates a request that fetches the associated record(s).
If the record has differences from the other record, executes an UPDATE","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordPAAE14databaseEqualsySbxF":{"name":"databaseEquals(_:)","abstract":"
Returns a boolean indicating whether this record and the other record","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordPAAE15databaseChanges4fromSDySSAA13DatabaseValueVGAaB_p_tF":{"name":"databaseChanges(from:)","abstract":"
A dictionary of values changed from the other record.
Don’t invoke this method directly: it is an internal method for types","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordPAAE13performUpdate_7columnsyAA8DatabaseC_ShySSGtKF":{"name":"performUpdate(_:columns:)","abstract":"
Don’t invoke this method directly: it is an internal method for types","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordPAAE11performSaveyyAA8DatabaseCKF":{"name":"performSave(_:)","abstract":"
Don’t invoke this method directly: it is an internal method for types","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordPAAE13performDeleteySbAA8DatabaseCKF":{"name":"performDelete(_:)","abstract":"
Don’t invoke this method directly: it is an internal method for types","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordPAAE13performExistsySbAA8DatabaseCKF":{"name":"performExists(_:)","abstract":"
Don’t invoke this method directly: it is an internal method for types","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordPAAE9deleteAllySiAA8DatabaseCKFZ":{"name":"deleteAll(_:)","abstract":"
Deletes all records; returns the number of deleted rows.
Delete records identified by their primary keys; returns the number of","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordPAAE9deleteOne_3keySbAA8DatabaseC_qd__SgtKAA0H16ValueConvertibleRd__lFZ":{"name":"deleteOne(_:key:)","abstract":"
Delete a record, identified by its primary key; returns whether a","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordPAAE9deleteAll_4keysSiAA8DatabaseC_SaySDySSAA0H16ValueConvertible_pSgGGtKFZ":{"name":"deleteAll(_:keys:)","abstract":"
Delete records identified by the provided unique keys (primary key or","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordPAAE9deleteOne_3keySbAA8DatabaseC_SDySSAA0H16ValueConvertible_pSgGtKFZ":{"name":"deleteOne(_:key:)","abstract":"
Delete a record, identified by a unique key (the primary key or any key","parent_name":"MutablePersistableRecord"},"Protocols/ColumnExpression.html#/s:4GRDB16ColumnExpressionP4nameSSvp":{"name":"name","abstract":"
Creates a Belongs To association between Self and the","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE7hasMany_3key5usingAA03HasE11AssociationVyxqd__Gqd__m_SSSgAA10ForeignKeyVSgtAaBRd__lFZ":{"name":"hasMany(_:key:using:)","abstract":"
Creates a Has many association between Self and the","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE6hasOne_3key5usingAA03HasE11AssociationVyxqd__Gqd__m_SSSgAA10ForeignKeyVSgtAaBRd__lFZ":{"name":"hasOne(_:key:using:)","abstract":"
Creates a Has one association between Self and the","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE8matchingyAA21QueryInterfaceRequestVyxGAA11FTS3PatternVSgFZ":{"name":"matching(_:)","abstract":"
Returns a QueryInterfaceRequest with a matching predicate.
Creates a request that includes an association. The columns of the","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE9including8requiredAA21QueryInterfaceRequestVyxGqd___t16OriginRowDecoderQyd__RszAA11AssociationRd__lFZ":{"name":"including(required:)","abstract":"
Creates a request that includes an association. The columns of the","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE7joining8optionalAA21QueryInterfaceRequestVyxGqd___t16OriginRowDecoderQyd__RszAA11AssociationRd__lFZ":{"name":"joining(optional:)","abstract":"
Creates a request that includes an association. The columns of the","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE7joining8requiredAA21QueryInterfaceRequestVyxGqd___t16OriginRowDecoderQyd__RszAA11AssociationRd__lFZ":{"name":"joining(required:)","abstract":"
Creates a request that includes an association. The columns of the","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE9annotated4withAA21QueryInterfaceRequestVyxGAA20AssociationAggregateVyxGd_tFZ":{"name":"annotated(with:)","abstract":"
Creates a request with aggregates appended to the selection.
Creates a request which selects selection, and fetches values of","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE6select_2asAA21QueryInterfaceRequestVyqd__GAA13SQLSelectable_pd_qd__mtlFZ":{"name":"select(_:as:)","abstract":"
Creates a request which selects selection, and fetches values of","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE6select3sql9arguments2asAA21QueryInterfaceRequestVyqd__GSS_AA18StatementArgumentsVSgqd__mtlFZ":{"name":"select(sql:arguments:as:)","abstract":"
Creates a request which selects sql, and fetches values of","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE6filteryAA21QueryInterfaceRequestVyxGAA14SQLExpressible_pFZ":{"name":"filter(_:)","abstract":"
Creates a request sorted according to the","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE5orderyAA21QueryInterfaceRequestVyxGSayAA15SQLOrderingTerm_pGFZ":{"name":"order(_:)","abstract":"
Creates a request sorted according to the","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE17orderByPrimaryKeyAA21QueryInterfaceRequestVyxGyFZ":{"name":"orderByPrimaryKey()","abstract":"
Creates a request which fetches limit rows, starting at","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE7aliasedyAA21QueryInterfaceRequestVyxGAA0B5AliasCFZ":{"name":"aliased(_:)","abstract":"
Creates a request that allows you to define expressions that target","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE10fetchCountySiAA8DatabaseCKFZ":{"name":"fetchCount(_:)","abstract":"
The association key defines how rows fetched from this association","parent_name":"Association"},"Protocols/Association.html#/s:4GRDB11AssociationP6forKeyyxSSF":{"name":"forKey(_:)","abstract":"
Creates an association with the provided predicate promise added to","parent_name":"Association"},"Protocols/Association.html#/s:4GRDB11AssociationPAAE5orderyxSayAA15SQLOrderingTerm_pGAA8DatabaseCKcF":{"name":"order(_:)","abstract":"
Creates an association with the provided orderings promise.
Creates an association that allows you to define expressions that target","parent_name":"Association"},"Protocols/Association.html#/s:4GRDB11AssociationPAAE9including8optionalxqd___tAaBRd__16OriginRowDecoderQyd__0fG0RtzlF":{"name":"including(optional:)","abstract":"
Creates an association that includes another one. The columns of the","parent_name":"Association"},"Protocols/Association.html#/s:4GRDB11AssociationPAAE9including8requiredxqd___tAaBRd__16OriginRowDecoderQyd__0fG0RtzlF":{"name":"including(required:)","abstract":"
Creates an association that includes another one. The columns of the","parent_name":"Association"},"Protocols/Association.html#/s:4GRDB11AssociationPAAE7joining8optionalxqd___tAaBRd__16OriginRowDecoderQyd__0fG0RtzlF":{"name":"joining(optional:)","abstract":"
Creates an association that joins another one. The columns of the","parent_name":"Association"},"Protocols/Association.html#/s:4GRDB11AssociationPAAE7joining8requiredxqd___tAaBRd__16OriginRowDecoderQyd__0fG0RtzlF":{"name":"joining(required:)","abstract":"
Creates an association that joins another one. The columns of the","parent_name":"Association"},"Protocols/FTS5WrapperTokenizer.html#/wrappedTokenizer":{"name":"wrappedTokenizer","abstract":"
Given a token produced by the wrapped tokenizer, notifies customized","parent_name":"FTS5WrapperTokenizer"},"Protocols/FTS5WrapperTokenizer.html#/tokenize(context:tokenization:pText:nText:tokenCallback:)":{"name":"tokenize(context:tokenization:pText:nText:tokenCallback:)","abstract":"
Tokenizes the text described by pText and nText, and","parent_name":"FTS5Tokenizer"},"Protocols/FTS5CustomTokenizer.html#/name":{"name":"name","abstract":"
The name of the tokenizer; should uniquely identify your custom","parent_name":"FTS5CustomTokenizer"},"Protocols/FTS5CustomTokenizer.html#/init(db:arguments:)":{"name":"init(db:arguments:)","abstract":"
Filters database changes that should be notified the the","parent_name":"TransactionObserver"},"Protocols/TransactionObserver.html#/s:4GRDB19TransactionObserverP17databaseDidChange4withyAA13DatabaseEventV_tF":{"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:4GRDB19TransactionObserverP17databaseDidCommityyAA8DatabaseCF":{"name":"databaseDidCommit(_:)","abstract":"
Notifies before a database change (insert, update, or delete)","parent_name":"TransactionObserver"},"Protocols/TransactionObserver.html#/s:4GRDB19TransactionObserverPAAE037stopObservingDatabaseChangesUntilNextB0yyF":{"name":"stopObservingDatabaseChangesUntilNextTransaction()","abstract":"
After this method has been called, the databaseDidChange(with:)","parent_name":"TransactionObserver"},"Protocols/StatementColumnConvertible.html#/s:4GRDB26StatementColumnConvertibleP06sqliteB05indexxs13OpaquePointerV_s5Int32Vtcfc":{"name":"init(sqliteStatement:index:)","abstract":"
Initializes a value from a raw SQLite statement pointer.
Synchronously executes a block that takes a database connection, and","parent_name":"DatabaseWriter"},"Protocols/DatabaseWriter.html#/s:4GRDB14DatabaseWriterP23writeWithoutTransactionyqd__qd__AA0B0CKXEKlF":{"name":"writeWithoutTransaction(_:)","abstract":"
Synchronously executes a block that takes a database connection, and","parent_name":"DatabaseWriter"},"Protocols/DatabaseWriter.html#/s:4GRDB14DatabaseWriterP20unsafeReentrantWriteyqd__qd__AA0B0CKXEKlF":{"name":"unsafeReentrantWrite(_:)","abstract":"
Synchronously executes a block that takes a database connection, and","parent_name":"DatabaseWriter"},"Protocols/DatabaseWriter.html#/s:4GRDB14DatabaseWriterP20readFromCurrentStateyyyAA0B0CcKF":{"name":"readFromCurrentState(_:)","abstract":"
This method is deprecated. Use concurrentRead instead.
Concurrently executes a read-only block that takes a","parent_name":"DatabaseWriter"},"Protocols/DatabaseWriter.html#/s:4GRDB14DatabaseWriterPAAE3add19transactionObserver6extentyAA011TransactionF0_p_AA0B0C0H17ObservationExtentOtF":{"name":"add(transactionObserver:extent:)","abstract":"
Add a transaction observer, so that it gets notified of","parent_name":"DatabaseWriter"},"Protocols/DatabaseWriter.html#/s:4GRDB14DatabaseWriterPAAE6remove19transactionObserveryAA011TransactionF0_p_tF":{"name":"remove(transactionObserver:)","abstract":"
Rebuilds the database file, repacking it into a minimal amount of","parent_name":"DatabaseWriter"},"Protocols/FetchRequest.html#/s:4GRDB12FetchRequestP10RowDecoderQa":{"name":"RowDecoder","abstract":"
The type that tells how fetched database rows should be interpreted.
Returns a tuple that contains a prepared statement that is ready to be","parent_name":"FetchRequest"},"Protocols/FetchRequest.html#/s:4GRDB12FetchRequestP10fetchCountySiAA8DatabaseCKF":{"name":"fetchCount(_:)","abstract":"
Returns the number of rows fetched by the request.
Synchronously executes a read-only block that takes a database","parent_name":"DatabaseReader"},"Protocols/DatabaseReader.html#/s:4GRDB14DatabaseReaderP10unsafeReadyqd__qd__AA0B0CKXEKlF":{"name":"unsafeRead(_:)","abstract":"
Synchronously executes a read-only block that takes a database","parent_name":"DatabaseReader"},"Protocols/DatabaseReader.html#/s:4GRDB14DatabaseReaderP19unsafeReentrantReadyqd__qd__AA0B0CKXEKlF":{"name":"unsafeReentrantRead(_:)","abstract":"
Synchronously executes a block that takes a database connection, and","parent_name":"DatabaseReader"},"Protocols/DatabaseReader.html#/s:4GRDB14DatabaseReaderP3add8functionyAA0B8FunctionC_tF":{"name":"add(function:)","abstract":"
Advances to the next element and returns it, or nil if no next element","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE7isEmptySbyKF":{"name":"isEmpty()","abstract":"
Returns a Boolean value indicating whether the cursor contains","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE8contains5whereS2b7ElementQzKXE_tKF":{"name":"contains(where:)","abstract":"
Returns a Boolean value indicating whether the cursor contains an","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE10enumeratedAA010EnumeratedB0CyxGyF":{"name":"enumerated()","abstract":"
Returns a cursor of pairs (n, x), where n represents a consecutive","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE6filteryAA06FilterB0CyxGSb7ElementQzKcF":{"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:4GRDB6CursorPAAE10compactMapyAA0dB0CyAA06FilterB0CyAFyxqd__SgGGqd__GAI7ElementQzKclF":{"name":"compactMap(_:)","abstract":"
Returns a cursor over the concatenated non-nil results of mapping","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE7flatMapyAA0dB0CyAA06FilterB0CyAFyxqd__SgGGqd__GAI7ElementQzKclF":{"name":"flatMap(_:)","abstract":"
Returns a cursor that skips any initial elements that satisfy","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE9dropFirstyAA04DropdB0CyxGSiF":{"name":"dropFirst(_:)","abstract":"
Returns a cursor containing all but the given number of initial","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE9dropFirstAA04DropdB0CyxGyF":{"name":"dropFirst()","abstract":"
Returns a cursor containing all but the first element of the cursor.
Returns an array containing all but the given number of final","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE8dropLastSay7ElementQzGyKF":{"name":"dropLast()","abstract":"
Returns an array containing all but the last element of the cursor.
Returns a cursor over the concatenated results of mapping transform","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE7flatMapyAA07FlattenB0CyAA0dB0Cyxqd__GGqd__7ElementQzKcAaBRd__lF":{"name":"flatMap(_:)","abstract":"
Returns a cursor over the concatenated results of mapping transform","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE7forEachyyy7ElementQzKXEKF":{"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:4GRDB6CursorPAAE3max2by7ElementQzSgSbAG_AGtKXE_tKF":{"name":"max(by:)","abstract":"
Returns the maximum element in the cursor, using the given predicate as","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE3min2by7ElementQzSgSbAG_AGtKXE_tKF":{"name":"min(by:)","abstract":"
Returns the minimum element in the cursor, using the given predicate as","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE6prefixyAA06PrefixB0CyxGSiF":{"name":"prefix(_:)","abstract":"
Returns a cursor, up to the specified maximum length, containing the","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE6prefix5whileAA011PrefixWhileB0CyxGSb7ElementQzKc_tF":{"name":"prefix(while:)","abstract":"
Returns a cursor of the initial consecutive elements that satisfy","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE6reduceyqd__qd___qd__qd___7ElementQztKXEtKlF":{"name":"reduce(_:_:)","abstract":"
Returns the result of calling the given combining closure with each","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE6reduce4into_qd__qd___yqd__z_7ElementQztKXEtKlF":{"name":"reduce(into:_:)","abstract":"
Returns the result of calling the given combining closure with each","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE6suffixySay7ElementQzGSiKF":{"name":"suffix(_:)","abstract":"
Returns an array, up to the given maximum length, containing the","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAASQ7ElementRpzrlE8containsySbAEKF":{"name":"contains(_:)","abstract":"
Returns a Boolean value indicating whether the cursor contains the","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAASL7ElementRpzrlE3maxAESgyKF":{"name":"max()","abstract":"
RowAdapter is a protocol that helps two incompatible row interfaces working"},"Protocols/StatementColumnConvertible.html":{"name":"StatementColumnConvertible","abstract":"
The StatementColumnConvertible protocol grants access to the low-level C"},"Protocols/TransactionObserver.html":{"name":"TransactionObserver","abstract":"
A transaction observer is notified of all changes and transactions committed"},"Protocols/FTS5CustomTokenizer.html":{"name":"FTS5CustomTokenizer","abstract":"
Returns an array of row adapters that split a row according to the input"},"Functions.html#/s:4GRDB3absyAA13SQLExpression_pAA22SQLSpecificExpressible_pF":{"name":"abs(_:)","abstract":"
Returns an expression that evaluates the ABS SQL function.
Creates a request with a full-text predicate added to the eventual","parent_name":"QueryInterfaceRequest"},"Extensions/Database.html#/dropFTS5SynchronizationTriggers(forTable:)":{"name":"dropFTS5SynchronizationTriggers(forTable:)","abstract":"
Deletes the synchronization triggers for a synchronized FTS5 table
Creates a pattern from a raw pattern string; throws DatabaseError on","parent_name":"Database"},"Extensions/Database.html#/makeTokenizer(_:)":{"name":"makeTokenizer(_:)","abstract":"
Returns the receiver, quoted for safe insertion as an identifier in an","parent_name":"String"},"Extensions/Float.html#/s:Sf4GRDBE15sqliteStatement5indexSfs13OpaquePointerV_s5Int32Vtcfc":{"name":"init(sqliteStatement:index:)","abstract":"
Returns a value initialized from a raw SQLite statement pointer.
Returns a value that can be stored in the database.","parent_name":"NSURL"},"Extensions/NSURL.html#/s:So5NSURLC4GRDBE17fromDatabaseValueyABXDSgAC0dE0VFZ":{"name":"fromDatabaseValue(_:)","abstract":"
Returns an NSURL initialized from dbValue, if possible.
Returns an NSData initialized from dbValue, if it contains","parent_name":"NSData"},"Extensions/Date.html#/s:10Foundation4DateV4GRDBE13databaseValueAD08DatabaseE0Vvp":{"name":"databaseValue","abstract":"
Returns a database value that contains the date encoded as","parent_name":"Date"},"Extensions/Date.html#/s:10Foundation4DateV4GRDBE17fromDatabaseValueyACSgAD0eF0VFZ":{"name":"fromDatabaseValue(_:)","abstract":"
Returns a date initialized from dbValue, if possible.
Returns a database value that contains the date encoded as","parent_name":"NSDate"},"Extensions/NSDate.html#/s:So6NSDateC4GRDBE17fromDatabaseValueyABXDSgAC0dE0VFZ":{"name":"fromDatabaseValue(_:)","abstract":"
Returns a date initialized from dbValue, if possible.
Returns a Data initialized from dbValue, if it contains","parent_name":"Data"},"Extensions/CGFloat.html#/s:12CoreGraphics7CGFloatV4GRDBE13databaseValueAD08DatabaseF0Vvp":{"name":"databaseValue","abstract":"
Returns a value that can be stored in the database.
Returns a cursor over the concatenated results of mapping transform","parent_name":"Sequence"},"Extensions/Sequence.html#/s:ST4GRDBAA14SQLExpressible7ElementRpzrlE8containsyAA13SQLExpression_pAA22SQLSpecificExpressible_pF":{"name":"contains(_:)","abstract":"
An SQL expression that checks the inclusion of an expression in","parent_name":"Sequence"},"Extensions/Sequence.html#/s:ST4GRDBAA14SQLExpressible7ElementRpzrlE8containsyAA13SQLExpression_pAA21SQLCollatedExpressionVF":{"name":"contains(_:)","abstract":"
An SQL expression that checks the inclusion of an expression in","parent_name":"Sequence"},"Extensions/Sequence.html#/s:ST4GRDBAA13SQLExpression_p7ElementRtzrlE6joined8operatorAaB_pAA24SQLLogicalBinaryOperatorO_tF":{"name":"joined(operator:)","abstract":"
Returns an expression by joining all elements with an SQL","parent_name":"Sequence"},"Extensions/Array.html#/s:Sa4GRDBEySayxGqd__Kc7ElementQyd__RszAA6CursorRd__lufc":{"name":"init(_:)","abstract":"
Creates an array containing the elements of a cursor.
Encodes a Double: the number of seconds between the date and","parent_name":"DatabaseDateEncodingStrategy"},"Enums/DatabaseDateEncodingStrategy.html#/s:4GRDB28DatabaseDateEncodingStrategyO21timeIntervalSince1970yA2CmF":{"name":"timeIntervalSince1970","abstract":"
Encodes a Double: the number of seconds between the date and","parent_name":"DatabaseDateEncodingStrategy"},"Enums/DatabaseDateEncodingStrategy.html#/s:4GRDB28DatabaseDateEncodingStrategyO16secondsSince1970yA2CmF":{"name":"secondsSince1970","abstract":"
Encodes an Int64: the number of seconds between the date and","parent_name":"DatabaseDateEncodingStrategy"},"Enums/DatabaseDateEncodingStrategy.html#/s:4GRDB28DatabaseDateEncodingStrategyO21millisecondsSince1970yA2CmF":{"name":"millisecondsSince1970","abstract":"
Encodes an Int64: the number of milliseconds between the date and","parent_name":"DatabaseDateEncodingStrategy"},"Enums/DatabaseDateEncodingStrategy.html#/s:4GRDB28DatabaseDateEncodingStrategyO7iso8601yA2CmF":{"name":"iso8601","abstract":"
Encodes dates according to the ISO 8601 and RFC 3339 standards
Thrown by MutablePersistableRecord.update() when no matching row could be","parent_name":"PersistenceError"},"Enums/FetchedRecordChange.html#/s:4GRDB19FetchedRecordChangeO9insertionyAC10Foundation9IndexPathV_tcACmF":{"name":"insertion(indexPath:)","abstract":"
A move event, from indexPath to newIndexPath. The changes are a","parent_name":"FetchedRecordChange"},"Enums/FetchedRecordChange.html#/s:4GRDB19FetchedRecordChangeO6updateyAC10Foundation9IndexPathV_SDySSAA13DatabaseValueVGtcACmF":{"name":"update(indexPath:changes:)","abstract":"
An update event, at given indexPath. The changes are a dictionary","parent_name":"FetchedRecordChange"},"Enums/FetchedRecordChange.html#/s:s23CustomStringConvertibleP11descriptionSSvp":{"name":"description","parent_name":"FetchedRecordChange"},"Enums/DatabaseDateDecodingStrategy.html#/s:4GRDB28DatabaseDateDecodingStrategyO010deferredToC0yA2CmF":{"name":"deferredToDate","abstract":"
The strategy that uses formatting from the Date structure.
Decodes numeric values as a number of seconds between the date and","parent_name":"DatabaseDateDecodingStrategy"},"Enums/DatabaseDateDecodingStrategy.html#/s:4GRDB28DatabaseDateDecodingStrategyO21timeIntervalSince1970yA2CmF":{"name":"timeIntervalSince1970","abstract":"
Decodes numeric values as a number of seconds between the date and","parent_name":"DatabaseDateDecodingStrategy"},"Enums/DatabaseDateDecodingStrategy.html#/s:4GRDB28DatabaseDateDecodingStrategyO21millisecondsSince1970yA2CmF":{"name":"millisecondsSince1970","abstract":"
Decodes numeric values as a number of milliseconds between the date and","parent_name":"DatabaseDateDecodingStrategy"},"Enums/DatabaseDateDecodingStrategy.html#/s:4GRDB28DatabaseDateDecodingStrategyO7iso8601yA2CmF":{"name":"iso8601","abstract":"
A kind of database event. See the TransactionObserver protocol for"},"Enums/SQLLogicalBinaryOperator.html":{"name":"SQLLogicalBinaryOperator","abstract":"
DatabaseDateDecodingStrategy specifies how FetchableRecord types that also"},"Enums/FetchedRecordChange.html":{"name":"FetchedRecordChange","abstract":"
A record change, given by a FetchedRecordsController to its change callback.
DatabaseDateEncodingStrategy specifies how PersistableRecord types that also"},"Enums/DatabaseUUIDEncodingStrategy.html":{"name":"DatabaseUUIDEncodingStrategy","abstract":"
DatabaseUUIDEncodingStrategy specifies how FetchableRecord types that also"},"Classes/Record.html#/s:4GRDB6RecordCACycfc":{"name":"init()","abstract":"
The policy that handles SQLite conflicts when records are inserted","parent_name":"Record"},"Classes/Record.html#/s:4GRDB6RecordC17databaseSelectionSayAA13SQLSelectable_pGvpZ":{"name":"databaseSelection","abstract":"
Returns a copy of self, initialized from all values encoded in the","parent_name":"Record"},"Classes/Record.html#/s:4GRDB6RecordC18hasDatabaseChangesSbvp":{"name":"hasDatabaseChanges","abstract":"
A boolean that indicates whether the record has changes that have not","parent_name":"Record"},"Classes/Record.html#/s:4GRDB6RecordC15databaseChangesSDySSAA13DatabaseValueVSgGvp":{"name":"databaseChanges","abstract":"
If the record has been changed, executes an UPDATE statement so that","parent_name":"Record"},"Classes/Record.html#/s:4GRDB6RecordC4saveyyAA8DatabaseCKF":{"name":"save(_:)","abstract":"
Executes an INSERT or an UPDATE statement so that self is saved in","parent_name":"Record"},"Classes/Record.html#/s:4GRDB6RecordC6deleteySbAA8DatabaseCKF":{"name":"delete(_:)","abstract":"
Creates a fetched records controller initialized from a SQL query and","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:4GRDB24FetchedRecordsControllerC_7request5queue12isSameRecordACyxGAA14DatabaseWriter_p_qd__So012OS_dispatch_F0CSbx_xtcSgtKc10RowDecoderQyd__RszAA12FetchRequestRd__lufc":{"name":"init(_:request:queue:isSameRecord:)","abstract":"
Creates a fetched records controller initialized from a fetch request","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:4GRDB24FetchedRecordsControllerC12performFetchyyKF":{"name":"performFetch()","abstract":"
Updates the fetch request, and eventually notifies the tracking","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:4GRDB24FetchedRecordsControllerC10setRequest3sql9arguments7adapterySS_AA18StatementArgumentsVSgAA10RowAdapter_pSgtKF":{"name":"setRequest(sql:arguments:adapter:)","abstract":"
Updates the fetch request, and eventually notifies the tracking","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:4GRDB24FetchedRecordsControllerC12trackChanges10willChange02onH003didH0yyACyxGcSg_yAH_xAA0b6RecordH0OtcSgAItF":{"name":"trackChanges(willChange:onChange:didChange:)","abstract":"
Call this method when changes performed while the application is","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:4GRDB24FetchedRecordsControllerC07fetchedC0SayxGvp":{"name":"fetchedRecords","abstract":"
Creates a fetched records controller initialized from a SQL query and","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:4GRDB24FetchedRecordsControllerCA2A11TableRecordRzrlE_7request5queueACyxGAA14DatabaseWriter_p_qd__So012OS_dispatch_H0CtKc10RowDecoderQyd__RszAA12FetchRequestRd__lufc":{"name":"init(_:request:queue:)","abstract":"
Creates a fetched records controller initialized from a fetch request","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:4GRDB24FetchedRecordsControllerC6record2atx10Foundation9IndexPathV_tF":{"name":"record(at:)","abstract":"
Returns a qualified value that is able to resolve ambiguities in","parent_name":"TableAlias"},"Classes/TableAlias.html#/s:4GRDB10TableAliasCyAA13SQLExpression_pAaD_pcip":{"name":"subscript(_:)","abstract":"
Returns a qualified expression that is able to resolve ambiguities in","parent_name":"TableAlias"},"Classes/FTS5ColumnDefinition.html#/notIndexed()":{"name":"notIndexed()","abstract":"
Synchronizes the full-text table with the content of an external","parent_name":"FTS5TableDefinition"},"Classes/FTS4ColumnDefinition.html#/s:4GRDB20FTS4ColumnDefinitionC10notIndexedACXDyF":{"name":"notIndexed()","abstract":"
Synchronizes the full-text table with the content of an external","parent_name":"FTS4TableDefinition"},"Classes/FTS3TableDefinition.html#/s:4GRDB19FTS3TableDefinitionC9tokenizerAA0B19TokenizerDescriptorVSgvp":{"name":"tokenizer","abstract":"
Returns the index of the leftmost column named name, in a","parent_name":"SelectStatement"},"Classes/Statement.html#/s:4GRDB9StatementC06sqliteB0s13OpaquePointerVvp":{"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:4GRDB9StatementC18unsafeSetArgumentsyyAA0bE0VF":{"name":"unsafeSetArguments(_:)","abstract":"
Set arguments without any validation. Trades safety for performance.
Returns the row associated with the given scope, by performing a","parent_name":"ScopesTreeView"},"Classes/Row/ScopesView.html#/s:Sl5IndexQa":{"name":"Index","parent_name":"ScopesView"},"Classes/Row/ScopesView.html#/s:4GRDB3RowC10ScopesViewV5namesSD4KeysVySSAA08LayoutedB7Adapter_p_Gvp":{"name":"names","abstract":"
Returns the row associated with the given scope, or nil if the","parent_name":"ScopesView"},"Classes/Row.html#/s:4GRDB3RowC5countSivp":{"name":"count","abstract":"
Returns true if and only if one column contains a non-null value, or if","parent_name":"Row"},"Classes/Row.html#/s:4GRDB3RowC7hasNull7atIndexSbSi_tF":{"name":"hasNull(atIndex:)","abstract":"
Returns true if the row contains null at given index.
Returns Int64, Double, String, Data or nil, depending on the value","parent_name":"Row"},"Classes/Row.html#/s:4GRDB3RowCyxSgSicAA24DatabaseValueConvertibleRzluip":{"name":"subscript(_:)","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:4GRDB3RowCyxSgSScAA24DatabaseValueConvertibleRzluip":{"name":"subscript(_:)","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:4GRDB3RowCyxSgAA16ColumnExpression_pcAA24DatabaseValueConvertibleRzluip":{"name":"subscript(_:)","abstract":"
Returns the value at given column, converted to the requested type.
Returns the record encoded in the given scope, if and only if the scope","parent_name":"Row"},"Classes/Row.html#/s:4GRDB3RowC6scopesAC10ScopesViewVvp":{"name":"scopes","abstract":"
Returns a view on the scopes defined by row adapters.
Creates a row initialized with elements. Column order is preserved, and","parent_name":"Row"},"Classes/Row.html#/s:4GRDB3RowCySS_AA13DatabaseValueVtAA0B5IndexVcip":{"name":"subscript(_:)","abstract":"
Accesses the (ColumnName, DatabaseValue) pair at given index.
A view of the scopes defined by row adapters. It is a collection of","parent_name":"Row"},"Classes/Row/ScopesTreeView.html":{"name":"ScopesTreeView","abstract":"
A view on the scopes tree defined by row adapters.
Synchronously executes a read-only block that takes a database","parent_name":"DatabaseSnapshot"},"Classes/DatabaseSnapshot.html#/s:4GRDB16DatabaseSnapshotC3add8functionyAA0B8FunctionC_tF":{"name":"add(function:)","abstract":"
Listens to UIApplicationDidEnterBackgroundNotification and","parent_name":"DatabaseQueue"},"Classes/DatabaseQueue.html#/s:4GRDB13DatabaseQueueC4readyxxAA0B0CKXEKlF":{"name":"read(_:)","abstract":"
Synchronously executes a read-only block in a protected dispatch queue,","parent_name":"DatabaseQueue"},"Classes/DatabaseQueue.html#/s:4GRDB13DatabaseQueueC20readFromCurrentStateyyyAA0B0CcF":{"name":"readFromCurrentState(_:)","abstract":"
This method is deprecated. Use concurrentRead instead.
Synchronously executes a block in a protected dispatch queue, wrapped","parent_name":"DatabaseQueue"},"Classes/DatabaseQueue.html#/s:4GRDB13DatabaseQueueC13inTransactionyyAA0B0C0E4KindOSg_AF0E10CompletionOAFKXEtKF":{"name":"inTransaction(_:_:)","abstract":"
Synchronously executes a block in a protected dispatch queue, wrapped","parent_name":"DatabaseQueue"},"Classes/DatabaseQueue.html#/s:4GRDB13DatabaseQueueC02inB0yxxAA0B0CKXEKlF":{"name":"inDatabase(_:)","abstract":"
Synchronously executes a block in a protected dispatch queue, and","parent_name":"DatabaseQueue"},"Classes/DatabaseQueue.html#/s:4GRDB13DatabaseQueueC20unsafeReentrantWriteyxxAA0B0CKXEKlF":{"name":"unsafeReentrantWrite(_:)","abstract":"
Synchronously executes a block in a protected dispatch queue, and","parent_name":"DatabaseQueue"},"Classes/DatabaseQueue.html#/s:4GRDB13DatabaseQueueC3add8functionyAA0B8FunctionC_tF":{"name":"add(function:)","abstract":"
Listens to UIApplicationDidEnterBackgroundNotification and","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:4GRDB12DatabasePoolC4readyxxAA0B0CKXEKlF":{"name":"read(_:)","abstract":"
Synchronously executes a read-only block in a protected dispatch queue,","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:4GRDB12DatabasePoolC10unsafeReadyxxAA0B0CKXEKlF":{"name":"unsafeRead(_:)","abstract":"
Synchronously executes a read-only block in a protected dispatch queue,","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:4GRDB12DatabasePoolC19unsafeReentrantReadyxxAA0B0CKXEKlF":{"name":"unsafeReentrantRead(_:)","abstract":"
Synchronously executes a read-only block in a protected dispatch queue,","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:4GRDB12DatabasePoolC20readFromCurrentStateyyyAA0B0CcKF":{"name":"readFromCurrentState(_:)","abstract":"
This method is deprecated. Use concurrentRead instead.
Synchronously executes an update block in a protected dispatch queue,","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:4GRDB12DatabasePoolC23writeWithoutTransactionyxxAA0B0CKXEKlF":{"name":"writeWithoutTransaction(_:)","abstract":"
Synchronously executes a block that takes a database connection, and","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:4GRDB12DatabasePoolC18writeInTransactionyyAA0B0C0F4KindOSg_AF0F10CompletionOAFKXEtKF":{"name":"writeInTransaction(_:_:)","abstract":"
Synchronously executes a block in a protected dispatch queue, wrapped","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:4GRDB12DatabasePoolC20unsafeReentrantWriteyxxAA0B0CKXEKlF":{"name":"unsafeReentrantWrite(_:)","abstract":"
Synchronously executes an update block in a protected dispatch queue,","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:4GRDB12DatabasePoolC3add8functionyAA0B8FunctionC_tF":{"name":"add(function:)","abstract":"
An SQL function that returns the Swift built-in capitalized","parent_name":"DatabaseFunction"},"Classes/DatabaseFunction.html#/s:4GRDB16DatabaseFunctionC9lowercaseACvpZ":{"name":"lowercase","abstract":"
An SQL function that returns the Swift built-in lowercased","parent_name":"DatabaseFunction"},"Classes/DatabaseFunction.html#/s:4GRDB16DatabaseFunctionC9uppercaseACvpZ":{"name":"uppercase","abstract":"
An SQL function that returns the Swift built-in uppercased","parent_name":"DatabaseFunction"},"Classes/DatabaseFunction.html#/s:4GRDB16DatabaseFunctionC19localizedCapitalizeACvpZ":{"name":"localizedCapitalize","abstract":"
An SQL function that returns the Swift built-in","parent_name":"DatabaseFunction"},"Classes/DatabaseFunction.html#/s:4GRDB16DatabaseFunctionC18localizedLowercaseACvpZ":{"name":"localizedLowercase","abstract":"
An SQL function that returns the Swift built-in","parent_name":"DatabaseFunction"},"Classes/DatabaseFunction.html#/s:4GRDB16DatabaseFunctionC18localizedUppercaseACvpZ":{"name":"localizedUppercase","abstract":"
An SQL function that returns the Swift built-in","parent_name":"DatabaseFunction"},"Classes/DatabaseFunction.html#/s:4GRDB16DatabaseFunctionC5applyyAA13SQLExpression_pAA14SQLExpressible_pd_tF":{"name":"apply(_:)","abstract":"
Returns an SQL expression that applies the function.
A collation, or SQL string comparison function, that compares strings","parent_name":"DatabaseCollation"},"Classes/DatabaseCollation.html#/s:4GRDB17DatabaseCollationC22caseInsensitiveCompareACvpZ":{"name":"caseInsensitiveCompare","abstract":"
A collation, or SQL string comparison function, that compares strings","parent_name":"DatabaseCollation"},"Classes/DatabaseCollation.html#/s:4GRDB17DatabaseCollationC31localizedCaseInsensitiveCompareACvpZ":{"name":"localizedCaseInsensitiveCompare","abstract":"
A collation, or SQL string comparison function, that compares strings","parent_name":"DatabaseCollation"},"Classes/DatabaseCollation.html#/s:4GRDB17DatabaseCollationC16localizedCompareACvpZ":{"name":"localizedCompare","abstract":"
A collation, or SQL string comparison function, that compares strings","parent_name":"DatabaseCollation"},"Classes/DatabaseCollation.html#/s:4GRDB17DatabaseCollationC24localizedStandardCompareACvpZ":{"name":"localizedStandardCompare","abstract":"
A collation, or SQL string comparison function, that compares strings","parent_name":"DatabaseCollation"},"Classes/Database/TransactionObservationExtent.html#/s:4GRDB8DatabaseC28TransactionObservationExtentO16observerLifetimeyA2EmF":{"name":"observerLifetime","abstract":"
The SQLITE_BUSY error is immediately returned to the connection that","parent_name":"BusyMode"},"Classes/Database/BusyMode.html#/s:4GRDB8DatabaseC8BusyModeO7timeoutyAESdcAEmF":{"name":"timeout(_:)","abstract":"
The SQLITE_BUSY error will be returned only if the database remains","parent_name":"BusyMode"},"Classes/Database/BusyMode.html#/s:4GRDB8DatabaseC8BusyModeO8callbackyAESbSiccAEmF":{"name":"callback(_:)","abstract":"
A custom callback that is called when a database is locked.","parent_name":"BusyMode"},"Classes/Database.html#/s:4GRDB8DatabaseC16sqliteConnections13OpaquePointerVvp":{"name":"sqliteConnection","abstract":"
The raw SQLite connection, suitable for the SQLite C API.
The number of rows modified, inserted or deleted by the most recent","parent_name":"Database"},"Classes/Database.html#/s:4GRDB8DatabaseC17totalChangesCountSivp":{"name":"totalChangesCount","abstract":"
The total number of rows modified, inserted or deleted by all successful","parent_name":"Database"},"Classes/Database.html#/s:4GRDB8DatabaseC19isInsideTransactionSbvp":{"name":"isInsideTransaction","abstract":"
True if the database connection is currently in a transaction.
The indexes on table named tableName; returns the empty array if the","parent_name":"Database"},"Classes/Database.html#/s:4GRDB8DatabaseC5table_12hasUniqueKeySbSS_xtKSTRzSS7ElementRtzlF":{"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:4GRDB8DatabaseC11foreignKeys2onSayAA14ForeignKeyInfoVGSS_tKF":{"name":"foreignKeys(on:)","abstract":"
The foreign keys defined on table named tableName.
When there are several connections to a database, a connection may try","parent_name":"Database"},"Classes/Database/CheckpointMode.html":{"name":"CheckpointMode","abstract":"
Add a transaction observer, so that it gets notified of","parent_name":"Database"},"Classes/Database.html#/s:4GRDB8DatabaseC6remove19transactionObserveryAA011TransactionE0_p_tF":{"name":"remove(transactionObserver:)","abstract":"
Registers a closure to be executed after the next or current","parent_name":"Database"},"Classes/Database/TransactionObservationExtent.html":{"name":"TransactionObservationExtent","abstract":"
Creates a cursor that wraps a base cursor but whose type depends only on","parent_name":"AnyCursor"},"Classes/AnyCursor.html#/s:4GRDB9AnyCursorC8iteratorACyxGqd___tc7ElementQyd__RszStRd__lufc":{"name":"init(iterator:)","abstract":"
Creates a cursor that wraps a base iterator but whose type depends only","parent_name":"AnyCursor"},"Classes/AnyCursor.html#/s:4GRDB9AnyCursorCyACyxGqd__c7ElementQyd__RszSTRd__lufc":{"name":"init(_:)","abstract":"
Creates a cursor that wraps a base sequence but whose type depends only","parent_name":"AnyCursor"},"Classes/AnyCursor.html#/s:4GRDB9AnyCursorCyACyxGxSgyKccfc":{"name":"init(_:)","abstract":"
Creates a cursor that wraps the given closure in its next() method
A DatabaseSnapshot sees an unchanging database content, as it existed at the"},"Classes.html#/s:4GRDB19DatabaseValueCursorC":{"name":"DatabaseValueCursor","abstract":"
A cursor of database values extracted from a single column."},"Classes.html#/s:4GRDB27NullableDatabaseValueCursorC":{"name":"NullableDatabaseValueCursor","abstract":"
A cursor of optional database values extracted from a single column."},"Classes/Future.html":{"name":"Future","abstract":"
A cursor of database values extracted from a single column."},"Classes.html#/s:4GRDB31FastNullableDatabaseValueCursorC":{"name":"FastNullableDatabaseValueCursor","abstract":"
A cursor of optional database values extracted from a single column."},"Classes/FTS3TableDefinition.html":{"name":"FTS3TableDefinition","abstract":"
The FTS3TableDefinition class lets you define columns of a FTS3 virtual table.
A question? Looking for advice? Do you wonder how to contribute? Fancy a chat? Go to the GRDB forums, or open a Github issue.
+
+
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.
Carthage can build GRDB frameworks, but it can also inexplicably fail. This installation method is thus unsupported.
+
+
If you decide to use Carthage despite this warning, and get any Carthage-related error, please open an issue in the Carthage repo, ask Stack Overflow, summon your local Xcode guru, or submit a pull request that has the make test_CarthageBuild command succeed 100% of the time (one time is not enough). See #262 for more information.
+
Manually
+
+
+
Download a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the git checkout v3.4.0 command.
+
Embed the GRDB.xcodeproj project in your own project.
+
Add the GRDBOSX, GRDBiOS, or GRDBWatchOS target in the Target Dependencies section of the Build Phases tab of your application target (extension target for WatchOS).
+
Add the GRDB.framework from the targetted platform to the Embedded Binaries section of the General tab of your application target (extension target for WatchOS).
SQLite creates the database file if it does not already exist. The connection is closed when the database queue gets deallocated.
+
+
A database queue can be used from any thread. The write and read methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue:
A database queue serializes accesses to the database, which means that there is never more than one thread that uses the database.
+
+
+
When you don’t need to modify the database, prefer the read method. It prevents any modification to the database.
+
The write method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, all changes are reverted, the whole transaction is rollbacked, and the error is rethrown.
SQLite creates the database file if it does not already exist. The connection is closed when the database pool gets deallocated.
+
+
+
:point_up: Note: unless read-only, a database pool opens your database in the SQLite WAL mode. The WAL mode does not fit all situations. Please have a look at https://www.sqlite.org/wal.html.
+
+
+
A database pool can be used from any thread. The write and read methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue:
Database pools allow several threads to access the database at the same time:
+
+
+
When you don’t need to modify the database, prefer the read method, because several threads can perform reads in parallel.
+
+
Reads are generally non-blocking, unless the maximum number of concurrent reads has been reached. In this case, a read has to wait for another read to complete. That maximum number can be configured.
+
Reads are guaranteed an immutable view of the last committed state of the database, regardless of concurrent writes. This kind of isolation is called snapshot isolation.
+
Unlike reads, writes are serialized. There is never more than a single thread that is writing into the database.
+
The write method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, all changes are reverted, the whole transaction is rollbacked, and the error is rethrown.
Database pools can take snapshots of the database.
+
+
+
A database pool needs your application to follow rules in order to deliver its safety guarantees. See the Concurrency chapter for more details about database pools, how they differ from database queues, and advanced use cases.
+
+
See the Demo Application for a sample code that sets up a database queue on iOS, and just 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.label="MyDatabase"// Useful when your app opens multiple databases
+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:
+
trydbQueue.write{dbin
+ trydb.execute("""
+ CREATE TABLE player (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NOT NULL,
+ score INT)
+ """)
+
+ trydb.execute(
+ "INSERT INTO player (name, score) VALUES (?, ?)",
+ arguments:["Barbara",1000])
+
+ trydb.execute(
+ "UPDATE player SET score = :score WHERE id = :id",
+ arguments:["score":1000,"id":1])
+ }
+}
+
+
+
The ? and colon-prefixed keys like :score in the SQL query are the statements arguments. You pass arguments with arrays or dictionaries, as in the example above. See Values for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and StatementArguments for a detailed documentation of SQLite arguments.
+
+
Never ever embed values directly in your SQL strings, and always use arguments instead. See Avoiding SQL Injection for more information:
+
// WRONG
+letid=123
+letname=textField.text
+trydb.execute("UPDATE player SET name = '\(name)' WHERE id = \(id)")
+
+// CORRECT
+trydb.execute(
+ "UPDATE player SET name = :name WHERE id = :id",
+ arguments:["name":name,"id":id])
+
+
+
Join multiple statements with a semicolon:
+
trydb.execute("""
+ INSERT INTO player (name, score) VALUES (?, ?);
+ INSERT INTO player (name, score) VALUES (?, ?)
+ """,arguments:["Arthur",750,"Barbara",1000])
+
+
+
When you want to make sure that a single statement is executed, use Prepared Statements.
+
+
After an INSERT statement, you can get the row ID of the inserted row:
+
trydb.execute(
+ "INSERT INTO player (name, score) VALUES (?, ?)",
+ arguments:["Arthur",1000])
+letplayerId=db.lastInsertedRowID
+
+
+
Don’t miss Records, that provide classic persistence methods:
Whenever you consume several rows from the database, you can fetch an Array, or a Cursor.
+
+
The fetchAll() method returns a regular Swift array, that you iterate like all other arrays:
+
trydbQueue.read{dbin
+ // [Player]
+ letplayers=tryPlayer.fetchAll(db,"SELECT ...")
+ forplayerinplayers{
+ // use player
+ }
+}
+
+
+
Unlike arrays, cursors returned by fetchCursor() load their results step after step:
+
trydbQueue.read{dbin
+ // Cursor of Player
+ letplayers=tryPlayer.fetchCursor(db,"SELECT ...")
+ whileletplayer=tryplayers.next(){
+ // use player
+ }
+}
+
+
+
Both arrays and cursors can iterate over database results. How do you choose one or the other? Look at the differences:
+
+
+
Cursors can not be used on any thread: you must consume a cursor on the dispatch queue it was created in. Particularly, don’t extract a cursor out of a database access method:
// OK
+letarray=trydbQueue.read{dbin
+ tryPlayer.fetchAll(db,...)
+}
+forplayerinarray{...}
+
+
Cursors can be iterated only one time. Arrays can be iterated many times.
+
Cursors iterate database results in a lazy fashion, and don’t consume much memory. Arrays contain copies of database values, and may take a lot of memory when there are many fetched results.
+
Cursors are granted with direct access to SQLite, unlike arrays that have to take the time to copy database values. If you look after extra performance, you may prefer cursors over arrays.
+
Cursors adopt the Cursor protocol, which looks a lot like standard lazy sequences of Swift. As such, cursors come with many convenience methods: compactMap, contains, dropFirst, dropLast, drop(while:), enumerated, filter, first, flatMap, forEach, joined, joined(separator:), max, max(by:), min, min(by:), map, prefix, prefix(while:), reduce, reduce(into:), suffix:
+
// Prints all Github links
+tryURL
+ .fetchCursor(db,"SELECT url FROM link")
+ .filter{urlinurl.host=="github.com"}
+ .forEach{urlinprint(url)}
+
+// An efficient cursor of coordinates:
+letlocations=tryRow.
+ .fetchCursor(db,"SELECT latitude, longitude FROM place")
+ .map{rowin
+ CLLocationCoordinate2D(latitude:row[0],longitude:row[1])
+ }
+
+// Turn cursors into arrays or sets:
+letarray=tryArray(cursor)
+letset=trySet(cursor)
+
+
Cursors are not Swift sequences. That’s because Swift sequences can’t handle iteration errors, when reading SQLite results may fail at any time. SQL functions may throw errors. On iOS, data protection may block access to the database file in the background. On macOS, your application users may mess with the file system.
+
Cursors require a little care:
+
+
+
Don’t modify the results during a cursor iteration:
Don’t turn a cursor of Row into an array. You would not get the distinct rows you expect. To get a array of rows, use Row.fetchAll(...). Generally speaking, make sure you copy a row whenever you extract it from a cursor for later use: row.copy().
+
+
+
+
If you don’t see, or don’t care about the difference, use arrays. If you care about memory and performance, use cursors when appropriate.
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 player WHERE name = ?",
+ arguments:["Arthur"])
+
+letrows=tryRow.fetchAll(db,
+ "SELECT * FROM player WHERE name = :name",
+ arguments:["name":"Arthur"])
+
+
+
See Values for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and StatementArguments for a detailed documentation of SQLite arguments.
+
+
Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care:
+
+
+
:point_up: Don’t turn a cursor of Row into an array. You would not get the distinct rows you expect. To get a array of rows, use Row.fetchAll(...). Generally speaking, make sure you copy a row whenever you extract it from a cursor for later use: row.copy().
+
+
Column Values
+
+
Read column values by index or column name:
+
letname:String=row[0]// 0 is the leftmost column
+letname:String=row["name"]// Leftmost matching column - lookup is case-insensitive
+letname:String=row[Column("name")]// Using query interface's Column
+
+
+
Make sure to ask for an optional when the value may be NULL:
+
letname:String?=row["name"]
+
+
+
The row[] subscript returns the type you ask for. See Values for more information on supported value types:
+
letbookCount:Int=row["bookCount"]
+letbookCount64:Int64=row["bookCount"]
+lethasBooks:Bool=row["bookCount"]// false when 0
+
+letstring:String=row["date"]// "2015-09-11 18:14:15.123"
+letdate:Date=row["date"]// Date
+self.date=row["date"]// Depends on the type of the property.
+
+
+
You can also use the as type casting operator:
+
row[...]asInt
+row[...]asInt?
+
+
+
+
:warning: Warning: avoid the as! and as? operators:
+
ifletint=row[...]as?Int{...}// BAD - doesn't work
+ifletint=row[...]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[0]asInt?// nil
+row[0]asInt// fatal error: could not convert NULL to Int.
+
+
+
There is one exception, though: the DatabaseValue type:
+
row[0]asDatabaseValue// DatabaseValue.null
+
+
Missing columns return nil.
+
letrow=tryRow.fetchOne(db,"SELECT 'foo' AS foo")!
+row["missing"]asString?// nil
+row["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[0]asString// "Mom’s birthday"
+row[0]asDate?// fatal error: could not convert "Mom’s birthday" to Date.
+row[0]asDate// fatal error: could not convert "Mom’s birthday" to Date.
+
+letrow=tryRow.fetchOne(db,"SELECT 256")!
+row[0]asInt// 256
+row[0]asUInt8?// fatal error: could not convert 256 to UInt8.
+row[0]asUInt8// fatal error: could not convert 256 to UInt8.
+
+
+
Those conversion fatal errors can be avoided with the DatabaseValue type:
This extra verbosity is the consequence of having to deal with an untrusted database: you may consider fixing the content of your database instead. See Fatal Errors for more information.
+
SQLite has a weak type system, and provides convenience conversions that can turn String to Int, Double to Blob, etc.
+
+
GRDB will sometimes let those conversions go through:
+
letrows=tryRow.fetchCursor(db,"SELECT '20 small cigars'")
+whileletrow=tryrows.next(){
+ row[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:
+
letdbValue:DatabaseValue=row[0]
+letdbValue:DatabaseValue?=row["name"]// nil if and only if column does not exist
+
+// Check for NULL:
+dbValue.isNull// Bool
+
+// The stored value:
+dbValue.storage.value// Int64, Double, String, Data, or nil
+
+// All the five storage classes supported by SQLite:
+switchdbValue.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)")
+}
+
A [String: AnyObject] dictionary which keeps rightmost value in case of duplicated column name. This dictionary is identical to FMResultSet’s resultDictionary from FMDB. It contains NSNull values for null columns, and can be shared with Objective-C:
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:
+
trydbQueue.read{dbin
+ tryInt.fetchCursor(db,"SELECT ...",arguments:...)// A Cursor of Int
+ tryInt.fetchAll(db,"SELECT ...",arguments:...)// [Int]
+ tryInt.fetchOne(db,"SELECT ...",arguments:...)// Int?
+
+ // When database may contain NULL:
+ tryOptional<Int>.fetchCursor(db,"SELECT ...",arguments:...)// A Cursor of Int?
+ tryOptional<Int>.fetchAll(db,"SELECT ...",arguments:...)// [Int?]
+}
+
+letplayerCount=trydbQueue.read{dbin
+ tryInt.fetchOne(db,"SELECT COUNT(*) FROM player")!
+}
+
+
+
fetchOne returns an optional value which is nil in two cases: either the SELECT statement yielded no row, or one row with a NULL value.
+
+
There are many supported value types (Bool, Int, String, Date, Swift enums, etc.). See Values for more information:
+
letcount=tryInt.fetchOne(db,"SELECT COUNT(*) FROM player")!// Int
+leturls=tryURL.fetchAll(db,"SELECT url FROM link")// [URL]
+
+
Values
+
+
GRDB ships with built-in support for the following value types:
+
+
+
Swift Standard Library: Bool, Double, Float, all signed and unsigned integer types, String, Swift enums.
At each step of the request iteration, the row[] subscript creates two copies of the database bytes: one fetched by SQLite, and another, stored in the Swift Data value.
+
+
You have the opportunity to save memory by not copying the data fetched by SQLite:
Here is how GRDB supports the various date formats supported by SQLite:
+
+
+
+
SQLite format
+
Date
+
DateComponents
+
+
+
+
YYYY-MM-DD
+
Read ¹
+
Read/Write
+
+
+
YYYY-MM-DD HH:MM
+
Read ¹
+
Read/Write
+
+
+
YYYY-MM-DD HH:MM:SS
+
Read ¹
+
Read/Write
+
+
+
YYYY-MM-DD HH:MM:SS.SSS
+
Read/Write ¹
+
Read/Write
+
+
+
YYYY-MM-DD*T*HH:MM
+
Read ¹
+
Read
+
+
+
YYYY-MM-DD*T*HH:MM:SS
+
Read ¹
+
Read
+
+
+
YYYY-MM-DD*T*HH:MM:SS.SSS
+
Read ¹
+
Read
+
+
+
HH:MM
+
+
Read/Write
+
+
+
HH:MM:SS
+
+
Read/Write
+
+
+
HH:MM:SS.SSS
+
+
Read/Write
+
+
+
Timestamps since unix epoch
+
Read ²
+
+
+
+
now
+
+
+
+
+
+
¹ Dates are stored and read in the UTC time zone. Missing components are assumed to be zero.
+
+
² GRDB 2+ interprets numerical values as timestamps that fuel Date(timeIntervalSince1970:). Previous GRDB versions used to interpret numbers as julian days. Julian days are still supported, with the Date(julianDay:) initializer.
+
Date
+
+
Date can be stored and fetched from the database just like other values:
+
trydb.execute(
+ "INSERT INTO player (creationDate, ...) VALUES (?, ...)",
+ arguments:[Date(),...])
+
+letrow=tryRow.fetchOne(db,...)!
+letcreationDate:Date=row["creationDate"]
+
+
+
Dates are stored using the format YYYY-MM-DD HH:MM:SS.SSS in the UTC time zone. It is precise to the millisecond.
+
+
+
:point_up: Note: this format was chosen because it is the only format that is:
+
+
+
Comparable (ORDER BY date works)
+
Comparable with the SQLite keyword CURRENT_TIMESTAMP (WHERE date > CURRENT_TIMESTAMP works)
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 player (birthDate, ...) VALUES (?, ...)",
+ arguments:[dbComponents,...])
+
+// Read "1973-09-18"
+letrow=tryRow.fetchOne(db,"SELECT birthDate ...")!
+letdbComponents:DatabaseDateComponents=row["birthDate"]
+dbComponents.format// .YMD (the actual format found in the database)
+dbComponents.dateComponents// DateComponents
+
+
NSNumber and NSDecimalNumber
+
+
NSNumber can be stored and fetched from the database just like other values. Floating point NSNumbers are stored as Double. Integer and boolean, as Int64. Integers that don’t fit Int64 won’t be stored: you’ll get a fatal error instead. Be cautious when an NSNumber contains an UInt64, for example.
+
+
NSDecimalNumber deserves a longer discussion:
+
+
SQLite has no support for decimal numbers. Given the table below, SQLite will actually store integers or doubles:
+
CREATETABLEtransfer(
+ amountDECIMAL(10,5)-- will store integer or double, actually
+)
+
+
+
This means that computations will not be exact:
+
trydb.execute("INSERT INTO transfer (amount) VALUES (0.1)")
+trydb.execute("INSERT INTO transfer (amount) VALUES (0.2)")
+letsum=tryNSDecimalNumber.fetchOne(db,"SELECT SUM(amount) FROM transfer")!
+
+// Yikes! 0.3000000000000000512
+print(sum)
+
+
+
Don’t blame SQLite or GRDB, and instead store your decimal numbers differently.
+
+
A classic technique is to store integers instead, since SQLite performs exact computations of integers. For example, don’t store Euros, but store cents instead:
+
// Write
+letamount=NSDecimalNumber(string:"0.10")
+letintegerAmount=amount.multiplying(byPowerOf10:2).int64Value
+trydb.execute("INSERT INTO transfer (amount) VALUES (?)",arguments:[integerAmount])
+
+// Read
+letintegerAmount=tryInt64.fetchOne(db,"SELECT SUM(amount) FROM transfer")!
+letamount=NSDecimalNumber(value:integerAmount).multiplying(byPowerOf10:-2)// 0.10
+
+
UUID
+
+
UUID can be stored and fetched from the database just like other values.
+
+
GRDB stores uuids as 16-bytes data blobs, and decodes them from both 16-bytes data blobs and strings such as E621E1F8-C36C-495A-93FC-0C247A3E6E5F.
+
Swift Enums
+
+
Swift enums and generally all types that adopt the RawRepresentable protocol can be stored and fetched from the database just like their raw values:
protocolDatabaseValueConvertible{
+ /// Returns a value that can be stored in the database.
+ vardatabaseValue:DatabaseValue{get}
+
+ /// Returns a value initialized from dbValue, if possible.
+ staticfuncfromDatabaseValue(_dbValue:DatabaseValue)->Self?
+}
+
+
+
All types that adopt this protocol can be used like all other values (Bool, Int, String, Date, Swift enums, etc.)
+
+
The databaseValue property returns DatabaseValue, a type that wraps the five values supported by SQLite: NULL, Int64, Double, String and Data. Since DatabaseValue has no public initializer, use DatabaseValue.null, or another type that already adopts the protocol: 1.databaseValue, "foo".databaseValue, etc. Conversion to DatabaseValue must not fail.
+
+
The fromDatabaseValue() factory method returns an instance of your custom type if the database value contains a suitable value. If the database value does not contain a suitable value, such as foo for Date, fromDatabaseValuemust return nil (GRDB will interpret this nil result as a conversion error, and react accordingly).
A transaction is a fundamental tool of SQLite that guarantees data consistency as well as proper isolation between application threads and database connections.
+
+
GRDB generally opens transactions for you, as a way to enforce its concurrency guarantees, and provide maximal security for both your application data and application logic:
+
// BEGIN TRANSACTION
+// INSERT INTO credit ...
+// INSERT INTO debit ...
+// COMMIT
+trydbQueue.write{dbin
+ tryCredit(destinationAccout,amount).insert(db)
+ tryDebit(sourceAccount,amount).insert(db)
+}
+
+// BEGIN TRANSACTION
+// INSERT INTO credit ...
+// INSERT INTO debit ...
+// COMMIT
+trydbPool.write{dbin
+ tryCredit(destinationAccout,amount).insert(db)
+ tryDebit(sourceAccount,amount).insert(db)
+}
+
+
+
Yet you may need to exactly control when transactions take place:
+
Explicit Transactions
+
+
DatabaseQueue.inDatabase() and DatabasePool.writeWithoutTransaction() execute your database statements outside of any transaction:
+
// INSERT INTO credit ...
+// INSERT INTO debit ...
+trydbQueue.inDatabase{dbin
+ tryCredit(destinationAccout,amount).insert(db)
+ tryDebit(sourceAccount,amount).insert(db)
+}
+
+// INSERT INTO credit ...
+// INSERT INTO debit ...
+trydbPool.writeWithoutTransaction{dbin
+ tryCredit(destinationAccout,amount).insert(db)
+ tryDebit(sourceAccount,amount).insert(db)
+}
+
+
+
Writing outside of any transaction is dangerous, for two reasons:
+
+
+
In our credit/debit example, you may successfully insert a credit, but fail inserting the debit, and end up with unbalanced accounts (oops).
+
// UNSAFE DATABASE INTEGRITY
+trydbQueue.inDatabase{dbin// or dbPool.writeWithoutTransaction
+ tryCredit(destinationAccout,amount).insert(db)// may succeed
+ tryDebit(sourceAccount,amount).insert(db)// may fail
+}
+
+
+
Transactions avoid this kind of bug.
+
Database pool concurrent reads can see an inconsistent state of the database:
+
// UNSAFE CONCURRENCY
+trydbPool.writeWithoutTransaction{dbin
+ tryCredit(destinationAccout,amount).insert(db)
+ // <- Concurrent dbPool.read sees a partial db update here
+ tryDebit(sourceAccount,amount).insert(db)
+}
+
+
+
Transactions avoid this kind of bug, too.
+
+
+
To open explicit transactions, use one of the Database.inTransaction, DatabaseQueue.inTransaction, or DatabasePool.writeInTransaction methods:
+
// BEGIN TRANSACTION
+// INSERT INTO credit ...
+// INSERT INTO debit ...
+// COMMIT
+trydbQueue.inDatabase{dbin// or dbPool.writeWithoutTransaction
+ trydb.inTransaction{
+ tryCredit(destinationAccout,amount).insert(db)
+ tryDebit(sourceAccount,amount).insert(db)
+ return.commit
+ }
+}
+
+// BEGIN TRANSACTION
+// INSERT INTO credit ...
+// INSERT INTO debit ...
+// COMMIT
+trydbQueue.inTransaction{dbin// or dbPool.writeInTransaction
+ tryCredit(destinationAccout,amount).insert(db)
+ tryDebit(sourceAccount,amount).insert(db)
+ return.commit
+}
+
+
+
If an error is thrown from the transaction block, the transaction is rollbacked and the error is rethrown by the inTransaction method. If you return .rollback instead of .commit, the transaction is also rollbacked, but no error is thrown.
+
+
You can also perform manual transaction management:
Transactions can’t be left opened unless you set the allowsUnsafeTransactions configuration flag:
+
// fatal error: A transaction has been left opened at the end of a database access
+trydbQueue.inDatabase{dbin
+ trydb.execute("BEGIN TRANSACTION")
+ // <- no commit or rollback
+}
+
Yet, you have a better option than checking for transactions: critical database sections 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.write{dbin
+ // Makes sure both inserts succeed, or none:
+ trydb.inSavepoint{
+ tryCredit(destinationAccout,amount).insert(db)
+ tryDebit(sourceAccount,amount).insert(db)
+ return.commit
+ }
+
+ // Other savepoints, etc...
+}
+
+
+
If an error is thrown from the savepoint block, the savepoint is rollbacked and the error is rethrown by the inSavepoint method. If you return .rollback instead of .commit, the savepoint is also rollbacked, but no error is thrown.
+
+
Unlike transactions, savepoints can be nested. They implicitly open a transaction if no one was opened when the savepoint begins. As such, they behave just like nested transactions. Yet the database changes are only written to disk when the outermost transaction is committed:
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.write{dbin
+ letupdateSQL="INSERT INTO player (name, score) VALUES (:name, :score)"
+ letupdateStatement=trydb.makeUpdateStatement(updateSQL)
+
+ letselectSQL="SELECT * FROM player 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).
After arguments are set, you can execute the prepared statement:
+
tryupdateStatement.execute()
+
+
+
Select statements can be used wherever a raw SQL query string would fit (see fetch queries):
+
letrows=tryRow.fetchCursor(selectStatement)// A Cursor of Row
+letplayers=tryPlayer.fetchAll(selectStatement)// [Player]
+letplayer=tryPlayer.fetchOne(selectStatement)// Player?
+
+
+
You can set the arguments at the moment of the statement execution:
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:
// SELECT reverseString("name") FROM player
+Player.select(reverseString.apply(nameColumn))
+
+
+
GRDB ships with built-in SQL functions that perform unicode-aware string transformations. See Unicode.
+
Custom Aggregates
+
+
Before registering a custom aggregate, you need to define a type that adopts the DatabaseAggregate protocol:
+
protocolDatabaseAggregate{
+ // Initializes an aggregate
+ init()
+
+ // Called at each step of the aggregation
+ mutatingfuncstep(_dbValues:[DatabaseValue])throws
+
+ // Returns the final result
+ funcfinalize()throws->DatabaseValueConvertible?
+}
+
+
+
For example:
+
structMaxLength:DatabaseAggregate{
+ varmaxLength:Int=0
+
+ mutatingfuncstep(_dbValues:[DatabaseValue]){
+ // At each step, extract string value, if any...
+ guardletstring=String.fromDatabaseValue(dbValues[0])else{
+ return
+ }
+ // ... and update the result
+ letlength=string.count
+ iflength>maxLength{
+ maxLength=length
+ }
+ }
+
+ funcfinalize()->DatabaseValueConvertible?{
+ returnmaxLength
+ }
+}
+
+letmaxLength=DatabaseFunction(
+ "maxLength",
+ argumentCount:1,
+ pure:true,
+ aggregate:MaxLength.self)
+
+dbQueue.add(function:maxLength)// Or dbPool.add(function: ...)
+
+trydbQueue.read{dbin
+ // Some Int
+ tryInt.fetchOne(db,"SELECT maxLength(name) FROM player")!
+}
+
+
+
The step method of the aggregate takes an array of DatabaseValue. This array contains as many values as the argumentCount parameter (or any number of values, when argumentCount is omitted).
+
+
The finalize method of the aggregate returns the final aggregated value (Bool, Int, String, Date, Swift enums, etc.).
+
+
SQLite has the opportunity to perform additional optimizations when aggregates are pure, which means that their result only depends on their inputs. So make sure to set the pure argument to true when possible.
// SELECT maxLength("name") FROM player
+letrequest=Player.select(maxLength.apply(nameColumn))
+tryInt.fetchOne(db,request)// Int?
+
+
Database Schema Introspection
+
+
GRDB comes with a set of schema introspection methods:
+
trydbQueue.read{dbin
+ // Bool, true if the table exists
+ trydb.tableExists("player")
+
+ // [ColumnInfo], the columns in the table
+ trydb.columns(in:"player")
+
+ // PrimaryKeyInfo
+ trydb.primaryKey("player")
+
+ // [ForeignKeyInfo], the foreign keys defined on the table
+ trydb.foreignKeys(on:"player")
+
+ // [IndexInfo], the indexes defined on the table
+ trydb.indexes(on:"player")
+
+ // Bool, true if column(s) is a unique key (primary key or unique index)
+ trydb.table("player",hasUniqueKey:["email"])
+}
+
+// Bool, true if argument is the name of an internal SQLite table
+Database.isSQLiteInternalTable(...)
+
+// Bool, true if argument is the name of an internal GRDB table
+Database.isGRDBInternalTable(...)
+
+
Row Adapters
+
+
Row adapters let you present database rows in the way expected by the row consumers.
+
+
They basically help two incompatible row interfaces to work together. For example, a row consumer expects a column named consumed, but the produced row has a column named produced.
+
+
In this case, the ColumnMapping row adapter comes in handy:
+
// Fetch a 'produced' column, and consume a 'consumed' column:
+letadapter=ColumnMapping(["consumed":"produced"])
+letrow=tryRow.fetchOne(db,"SELECT 'Hello' AS produced",adapter:adapter)!
+row["consumed"]// "Hello"
+row["produced"]// nil
+
+
+
Row adapters are values that adopt the RowAdapter protocol. You can implement your own custom adapters (:fire: EXPERIMENTAL), or use one of the four built-in adapters, described below.
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 through the Row.scopes property:
letadapter=ScopeAdapter([
+ "left":ScopeAdapter([
+ "left":RangeRowAdapter(0..<1),
+ "right":RangeRowAdapter(1..<2)]),
+ "right":ScopeAdapter([
+ "left":RangeRowAdapter(2..<3),
+ "right":RangeRowAdapter(3..<4)])
+ ])
+letrow=tryRow.fetchOne(db,"SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d",adapter:adapter)!
+
+letleftRow=row.scopes["left"]!
+leftRow.scopes["left"]// [a:0]
+leftRow.scopes["right"]// [b:1]
+
+letrightRow=row.scopes["right"]!
+rightRow.scopes["left"]// [c:2]
+rightRow.scopes["right"]// [d:3]
+
+
+
Any adapter can be extended with scopes:
+
letbaseAdapter=RangeRowAdapter(0..<2)
+letadapter=ScopeAdapter(base:baseAdapter,scopes:[
+ "remainder":SuffixRowAdapter(fromIndex:2)])
+letrow=tryRow.fetchOne(db,"SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d",adapter:adapter)!
+
+row// [a:0 b:1]
+row.scopes["remainder"]// [c:2 d:3]
+
Those functions are embedded right into the GRDBCustom and GRCBCipher modules. For the regular GRDB framework: you’ll need to import SQLite3, or CSQLite, depending on whether you use the Swift Package Manager or not:
+
#if SWIFT_PACKAGE
+ importCSQLite// For Swift Package Manager
+#else
+ importSQLite3// Otherwise
+#endif
+
+letsqliteVersion=String(cString:sqlite3_libversion())
+
trydbQueue.read{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.
+
GRDB opens SQLite connections in the [multi-thread mode](https://www.sqlite.org/threadsafe.html), which (oddly) means that they are not thread-safe. Make sure you touch raw databases and statements inside their dedicated dispatch queues.
+
Use the raw SQLite C Interface at your own risk. GRDB won’t prevent you from shooting yourself in the foot.
+
+
+
+
Before jumping in the low-level wagon, here is the list of all SQLite APIs used by GRDB:
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 record comparison. See the list of record methods for an overview.
+
+
+
:point_up: Note: if you are familiar with Core Data’s NSManagedObject or Realm’s Object, you may experience a cultural shock: GRDB records are not uniqued, do not auto-update, and do not lazy-load. This is both a purpose, and a consequence of protocol-oriented programming. You should read How to build an iOS application with SQLite and GRDB.swift for a general introduction.
GRDB ships with three record protocols. Your own types will adopt one or several of them, according to the abilities you want to extend your types with.
See column values for more information about the row[] subscript.
+
+
When your record type adopts the standard Decodable protocol, you don’t have to provide the implementation for init(row:). See Codable Records for more information:
FetchableRecord allows adopting types to be fetched from SQL queries:
+
tryPlace.fetchCursor(db,"SELECT ...",arguments:...)// A Cursor of Place
+tryPlace.fetchAll(db,"SELECT ...",arguments:...)// [Place]
+tryPlace.fetchOne(db,"SELECT ...",arguments:...)// Place?
+
+
+
See fetching methods for information about the fetchCursor, fetchAll and fetchOne methods. See StatementArguments for more information about the query arguments.
+
+
+
:point_up: Note: for performance reasons, the same row argument to init(row:) is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: self.row = row.copy().
+
+
:point_up: Note: The FetchableRecord.init(row:) initializer fits the needs of most applications. But some application are more demanding than others. When FetchableRecord does not exactly provide the support you need, have a look at the Beyond FetchableRecord chapter.
+
+
TableRecord Protocol
+
+
The TableRecord protocol generates SQL for you. To use TableRecord, subclass the Record class, or adopt it explicitly:
When the table has no explicit primary key, GRDB uses the hidden rowid column:
+
// SELECT * FROM document 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 citizenship WHERE citizenId = 1 AND countryCode = 'FR'
+tryCitizenship.fetchOne(db,key:["citizenId":1,"countryCode":"FR"])// Citizenship?
+
+
PersistableRecord Protocol
+
+
GRDB provides two protocols that let adopting types create, update, and delete rows in the database:
+
protocolMutablePersistableRecord:TableRecord{
+ /// Defines the values persisted in the database
+ funcencode(tocontainer:inoutPersistenceContainer)
+
+ /// 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?)
+}
+
+
protocolPersistableRecord:MutablePersistableRecord{
+ /// 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 class, choose PersistableRecord. On top of that, implement didInsert(with:for:) if the database table has an auto-incremented primary key.
+
If your type is a struct, and the database table has an auto-incremented primary key, choose MutablePersistableRecord, and implement didInsert(with:for:).
+
Otherwise, choose PersistableRecord, and ignore didInsert(with:for:).
+
+
+
The encode(to:) method defines which values (Bool, Int, String, Date, Swift enums, etc.) are assigned to database columns.
+
+
The optional didInsert method lets the adopting type store its rowID after successful insertion, and is only useful for tables that have an auto-incremented primary key. It is called from a protected dispatch queue, and serialized with all database updates.
+
+
To use the persistable protocols, subclass the Record class, or adopt one of them explicitly. For example:
+
extensionPlace:MutablePersistableRecord{
+ /// The values persisted in the database
+ funcencode(tocontainer:inoutPersistenceContainer){
+ container["id"]=id
+ container["title"]=title
+ container["latitude"]=coordinate.latitude
+ container["longitude"]=coordinate.longitude
+ }
+
+ // Update id upon successful insertion:
+ mutatingfuncdidInsert(withrowID:Int64,forcolumn:String?){
+ id=rowID
+ }
+}
+
+varparis=Place(
+ id:nil,
+ title:"Paris",
+ coordinate:CLLocationCoordinate2D(latitude:48.8534100,longitude:2.3488000))
+
+tryparis.insert(db)
+paris.id// some value
+
When your record type adopts the standard Encodable protocol, you don’t have to provide the implementation for encode(to:). See Codable Records for more information:
insert, update, save and delete can throw a DatabaseError.
+
update and updateChanges can also throw a PersistenceError, should the update fail because there is no matching row in the database.
+
+
When saving an object that may or may not already exist in the database, prefer the save method:
+
save makes sure your values are stored in the database.
+
+
It performs an UPDATE if the record has a non-null primary key, and then, if no row was modified, an INSERT. It directly perfoms an INSERT if the record has no primary key, or a null primary key.
+
+
Despite the fact that it may execute two SQL statements, save behaves as an atomic operation: GRDB won’t allow any concurrent thread to sneak in (see concurrency).
+
delete returns whether a database row was deleted or not.
+
+
+
All primary keys are supported, including composite primary keys that span several columns, and the implicit rowid primary key.
+
Customizing the Persistence Methods
+
+
Your custom type may want to perform extra work when the persistence methods are invoked.
+
+
For example, it may want to have its UUID automatically set before inserting. Or it may want to validate its values before saving.
+
+
When you subclass Record, you simply have to override the customized method, and call super:
If you use the raw PersistableRecord protocol, use one of the special methodsperformInsert, performUpdate, performSave, performDelete, or performExists:
: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.
// Declare a record...
+structPlayer:Codable,FetchableRecord,PersistableRecord{
+ varname:String
+ varscore:Int
+}
+
+// ...and there you go:
+trydbQueue.write{dbin
+ tryPlayer(name:"Arthur",score:100).insert(db)
+ letplayers=tryPlayer.fetchAll(db)
+}
+
+
+
Codable records encode and decode their properties according to their own implementation of the Encodable and Decodable protocols. Yet databases have specific requirements:
+
+
+
Properties are always coded according to their preferred database representation, when they have one (all values that adopt the DatabaseValueConvertible protocol).
+
You can customize the encoding and decoding of dates and uuids.
+
Complex properties (arrays, dictionaries, nested structs, etc.) are stored as JSON.
When a Codable record contains a property that is not a simple value (Bool, Int, String, Date, Swift enums, etc.), that value is encoded and decoded as a JSON string. For example:
GRDB uses the standard JSONDecoder and JSONEncoder from Foundation. By default, Data values are handled with the .base64 strategy, Date with the .millisecondsSince1970 strategy, and non conforming floats with the .throw strategy.
+
+
You can customize the JSON format by implementing those methods:
:bulb: Tip: Make sure you set the JSONEncoder sortedKeys option, available from iOS 11.0+, macOS 10.13+, and watchOS 4.0+. This option makes sure that the JSON output is stable. This stability is required for Record Comparison to work as expected, and database observation tools such as FetchedRecordsController or RxGRDB to accurately recognize changed records.
To sum up: dates encode themselves in the YYYY-MM-DD HH:MM:SS.SSS format, in the UTC time zone, and decode a variety of date formats and timestamps. UUIDs encode themselves as 16-bytes data blobs, and decode both 16-bytes data blobs and strings such as E621E1F8-C36C-495A-93FC-0C247A3E6E5F.
:point_up: Note: there is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs, and uuid strings).
+
+
The userInfo Dictionary
+
+
Your Codable Records can be stored in the database, but they may also have other purposes. In this case, you may need to customize their implementations of Decodable.init(from:) and Encodable.encode(to:), depending on the context.
+
+
The standard way to provide such context is the userInfo dictionary. Implement those properties:
For example, here is a Player type that customizes its decoding:
+
// A key that holds a decoder's name
+letdecoderName=CodingUserInfoKey(rawValue:"decoderName")!
+
+structPlayer:FetchableRecord,Decodable{
+ init(fromdecoder:Decoder)throws{
+ // Print the decoder name
+ letdecoderName=decoder.userInfo[decoderName]as?String
+ print("Decoded from \(decoderName??"unknown decoder")")
+ ...
+ }
+}
+
+
+
You can have a specific decoding from JSON…
+
// prints "Decoded from JSON"
+letdecoder=JSONDecoder()
+decoder.userInfo=[decoderName:"JSON"]
+letplayer=trydecoder.decode(Player.self,from:jsonData)
+
+
+
… and another one from database rows:
+
extensionPlayer:FetchableRecord{
+ staticletdatabaseDecodingUserInfo:[CodingUserInfoKey:Any]=[decoderName:"database row"]
+}
+
+// prints "Decoded from database row"
+letplayer=tryPlayer.fetchOne(db,...)
+
+
+
+
:point_up: Note: make sure the databaseDecodingUserInfo and databaseEncodingUserInfo properties are explicitly declared as [CodingUserInfoKey: Any]. If they are not, the Swift compiler may silently miss the protocol requirement, resulting in sticky empty userInfo.
+
+
Tip: Use Coding Keys as Columns
+
+
If you declare an explicit CodingKeys enum (what is this?), you can instruct GRDB to use those coding keys as database columns:
// Fetch values
+trydbQueue.read{dbin
+ // SELECT * FROM player WHERE name = 'Arthur'
+ letarthur=tryPlayer.filter(name:"Arthur").fetchOne(db)// Player?
+
+ // SELECT MAX(score) FROM player
+ letmaxScore=tryPlayer.maximumScore.fetchOne(db)// Int?
+}
+
+
+
… and feed database observation tools such as RxGRDB:
+
// Observe changes
+Player.maximumScore.rx
+ .fetchOne(in:dbQueue)
+ .subscribe(onNext:{maxScore:Int?in
+ print("The maximum score has changed")
+ })
+
Record subclasses define their custom database relationship by overriding database methods. For example:
+
classPlace:Record{
+ varid:Int64?
+ vartitle:String
+ varisFavorite:Bool
+ varcoordinate:CLLocationCoordinate2D
+
+ init(id:Int64?,title:String,isFavorite:Bool,coordinate:CLLocationCoordinate2D){
+ self.id=id
+ self.title=title
+ self.isFavorite=isFavorite
+ self.coordinate=coordinate
+ super.init()
+ }
+
+ /// The table name
+ overrideclassvardatabaseTableName:String{
+ return"place"
+ }
+
+ /// The table columns
+ enumColumns:String,ColumnExpression{
+ caseid,title,favorite,latitude,longitude
+ }
+
+ /// Creates a record from a database row
+ requiredinit(row:Row){
+ id=row[Columns.id]
+ title=row[Columns.title]
+ isFavorite=row[Columns.favorite]
+ coordinate=CLLocationCoordinate2D(
+ latitude:row[Columns.latitude],
+ longitude:row[Columns.longitude])
+ super.init(row:row)
+ }
+
+ /// The values persisted in the database
+ overridefuncencode(tocontainer:inoutPersistenceContainer){
+ container[Columns.id]=id
+ container[Columns.title]=title
+ container[Columns.favorite]=isFavorite
+ container[Columns.latitude]=coordinate.latitude
+ container[Columns.longitude]=coordinate.longitude
+ }
+
+ /// Update record ID after a successful insertion
+ overridefuncdidInsert(withrowID:Int64,forcolumn:String?){
+ id=rowID
+ }
+}
+
+
Record Comparison
+
+
Records can compare against other records, or against previous versions of themselves.
+
+
This helps avoiding costly UPDATE statements when a record has not been edited.
+
+
You can use the updateChanges method, available on the PersistableRecord protocol, which performs an update of the changed columns only (and does nothing if record has no change):
+
letoldPlayer=tryPlayer.fetchOne(db,...)
+varnewPlayer=oldPlayer
+newPlayer.score=100
+iftrynewPlayer.updateChanges(db,from:oldPlayer){
+ print("player was modified, and updated in the database")
+}else{
+ print("player was not modified")
+}
+
+
+
+
:point_up: Note: The comparison is performed on the database representation of records. As long as your record type adopts a PersistableRecord protocol, you don’t need to care about Equatable.
+
+
+
The Record class is able to compare against itself, and knows if it has changes that have not been saved since it was last fetched or persisted:
+
// Record class only
+letplayer=tryPlayer.fetchOne(db,...)
+player.score=100
+iftryplayer.updateChanges(db){
+ print("player was modified, and updated in the database")
+}else{
+ print("player was not modified")
+}
+
+
+
You can also use the databaseEquals method, which returns whether two records have the same database representation:
Again, Record instances can compare against themselves, with the hasDatabaseChanges property:
+
// Record class only
+player.score=100
+ifplayer.hasDatabaseChanges{
+ tryplayer.save(db)
+}
+
+
+
Record.hasDatabaseChanges is false after a Record instance has been fetched or saved into the database. Subsequent modifications may set it, or not: hasDatabaseChanges is based on value comparison. Setting a property to the same value does not set the changed flag:
For an efficient algorithm which synchronizes the content of a database table with a JSON payload, check JSONSynchronization.playground.
+
Record Customization Options
+
+
GRDB records come with many default behaviors, that are designed to fit most situations. Many of those defaults can be customized for your specific needs:
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:
+
+
+
In the definition of the database table:
+
// CREATE TABLE player (
+// id INTEGER PRIMARY KEY AUTOINCREMENT,
+// email TEXT UNIQUE ON CONFLICT REPLACE
+// )
+trydb.create(table:"player"){tin
+ t.autoIncrementedPrimaryKey("id")
+ t.column("email",.text).unique(onConflict:.replace)// <--
+}
+
+// Despite the unique index on email, both inserts succeed.
+// The second insert replaces the first row:
+trydb.execute("INSERT INTO player (email) VALUES (?)",arguments:["arthur@example.com"])
+trydb.execute("INSERT INTO player (email) VALUES (?)",arguments:["arthur@example.com"])
+
+
In each modification query:
+
// CREATE TABLE player (
+// id INTEGER PRIMARY KEY AUTOINCREMENT,
+// email TEXT UNIQUE
+// )
+trydb.create(table:"player"){tin
+ t.autoIncrementedPrimaryKey("id")
+ t.column("email",.text).unique()
+}
+
+// Again, despite the unique index on email, both inserts succeed.
+trydb.execute("INSERT OR REPLACE INTO player (email) VALUES (?)",arguments:["arthur@example.com"])
+trydb.execute("INSERT OR REPLACE INTO player (email) VALUES (?)",arguments:["arthur@example.com"])
+
+
+
+
When you want to handle conflicts at the query level, specify a custom persistenceConflictPolicy in your type that adopts the PersistableRecord protocol. It will alter the INSERT and UPDATE queries run by the insert, update and savepersistence methods:
+
protocolMutablePersistableRecord{
+ /// The policy that handles SQLite conflicts when records are
+ /// inserted or updated.
+ ///
+ /// This property is optional: its default value uses the ABORT
+ /// policy for both insertions and updates, so that GRDB generate
+ /// regular INSERT and UPDATE queries.
+ staticvarpersistenceConflictPolicy:PersistenceConflictPolicy{get}
+}
+
+structPlayer:MutablePersistableRecord{
+ staticletpersistenceConflictPolicy=PersistenceConflictPolicy(
+ insert:.replace,
+ update:.replace)
+}
+
+// INSERT OR REPLACE INTO player (...) VALUES (...)
+tryplayer.insert(db)
+
+
+
+
:point_up: Note: the ignore policy does not play well at all with the didInsert method which notifies the rowID of inserted records. Choose your poison:
+
+
+
if you specify the ignore policy in the database table definition, don’t implement the didInsert method: it will be called with some random id in case of failed insert.
+
if you specify the ignore policy at the query level, the didInsert method is never called.
+
+
+
:point_up: Note: The replace policy may have to delete rows so that inserts and updates can succeed. Those deletions are not reported to transaction observers (this might change in a future release of SQLite).
+
+
The Implicit RowID Primary Key
+
+
All SQLite tables have a primary key. Even when the primary key is not explicit:
+
// No explicit primary key
+trydb.create(table:"event"){tin
+ t.column("message",.text)
+ t.column("date",.datetime)
+}
+
+// No way to define an explicit primary key
+trydb.create(virtualTable:"book",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 event WHERE rowid = 1
+letevent=tryEvent.fetchOne(db,key:1)
+
+// DELETE FROM book 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 databaseSelection static property (from the TableRecord protocol) return the hidden rowid column:
+
structEvent:TableRecord{
+ staticletdatabaseSelection:[SQLSelectable]=[AllColumns(),Column.rowID]
+}
+
+// When you subclass Record, you need an override:
+classBook:Record{
+ overrideclassvardatabaseSelection:[SQLSelectable]{
+ return[AllColums(),Column.rowID]
+ }
+}
+
+
+
GRDB will then select the rowid column by default:
+
// SELECT *, rowid FROM event
+letevents=tryEvent.fetchAll(db)
+
+
Have init(row:) from the FetchableRecord protocol consume the rowid column:
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
+
+
+
Beyond FetchableRecord
+
+
Some GRDB users eventually discover that the FetchableRecord protocol does not fit all situations. Use cases that are not well handled by FetchableRecord include:
+
+
+
Your application needs polymorphic row decoding: it decodes some type or another, depending on the values contained in a database row.
+
Your application needs to decode rows with a context: each decoded value should be initialized with some extra value that does not come from the database.
+
Your application needs a record type that supports untrusted databases, and may fail at decoding database rows (throw an error when a row contains invalid values).
+
+
+
Since those use cases are not well handled by FetchableRecord, don’t try to implement them on top of this protocol: you’ll just fight the framework.
+
+
Instead, please have a look at the CustomizedDecodingOfDatabaseRows playground. You’ll run some sample code, and learn how to escape FetchableRecord when you need. And remember that leaving FetchableRecord will not deprive you of query interface requests and generally all SQL generation features of the TableRecord and PersistableRecord protocols.
+
Examples of Record Definitions
+
+
We will show below how to declare a record type for the following database table:
Each one of the three examples below is correct. You will pick one or the other depending on your personal preferences and the requirements of your application:
+
+
+ Define a Codable struct, and adopt the record protocols you need
+
+This is the shortest way to define a record type.
+
+See the [Record Protocols Overview](#record-protocols-overview), and [Codable Records] for more information.
+
+”`swift
+struct Place: Codable {
+ var id: Int64?
+ var title: String
+ var favorite: Bool
+ var latitude: CLLocationDegrees
+ var longitude: CLLocationDegrees
+
+ var coordinate: CLLocationCoordinate2D {
+ get {
+ return CLLocationCoordinate2D(
+ latitude: latitude,
+ longitude: longitude)
+ }
+ set {
+ latitude = newValue.latitude
+ longitude = newValue.longitude
+ }
+ }
+}
+
+// SQL generation
+extension Place: TableRecord { }
+
+// Fetching methods
+extension Place: FetchableRecord { }
+
+// Persistence methods
+extension Place: MutablePersistableRecord {
+ /// Update record ID after a successful insertion
+ mutating func didInsert(with rowID: Int64, for column: String?) {
+ id = rowID
+ }
+}
+“`
+
+
+
+
+ Define a plain struct, and adopt the record protocols you need
+
+See the [Record Protocols Overview](#record-protocols-overview) for more information.
+
+”`swift
+struct Place {
+ var id: Int64?
+ var title: String
+ var isFavorite: Bool
+ var coordinate: CLLocationCoordinate2D
+}
+
+// SQL generation
+extension Place: TableRecord {
+ /// The table columns
+ enum Columns: String, ColumnExpression {
+ case id, title, favorite, latitude, longitude
+ }
+}
+
+// Fetching methods
+extension Place: FetchableRecord {
+ /// Creates a record from a database row
+ init(row: Row) {
+ id = row[Columns.id]
+ title = row[Columns.title]
+ isFavorite = row[Columns.favorite]
+ coordinate = CLLocationCoordinate2D(
+ latitude: row[Columns.latitude],
+ longitude: row[Columns.longitude])
+ }
+}
+
+// Persistence methods
+extension Place: MutablePersistableRecord {
+ /// The values persisted in the database
+ func encode(to container: inout PersistenceContainer) {
+ container[Columns.id] = id
+ container[Columns.title] = title
+ container[Columns.favorite] = isFavorite
+ container[Columns.latitude] = coordinate.latitude
+ container[Columns.longitude] = coordinate.longitude
+ }
+
+ /// Update record ID after a successful insertion
+ mutating func didInsert(with rowID: Int64, for column: String?) {
+ id = rowID
+ }
+}
+“`
+
+
+
+
+ Subclass the Record class
+
+See the [Record class](#record-class) for more information.
+
+”`swift
+class Place: Record {
+ var id: Int64?
+ var title: String
+ var isFavorite: Bool
+ var coordinate: CLLocationCoordinate2D
+
+ init(id: Int64?, title: String, isFavorite: Bool, coordinate: CLLocationCoordinate2D) {
+ self.id = id
+ self.title = title
+ self.isFavorite = isFavorite
+ self.coordinate = coordinate
+ super.init()
+ }
+
+ /// The table name
+ override class var databaseTableName: String {
+ return “place”
+ }
+
+ /// The table columns
+ enum Columns: String, ColumnExpression {
+ case id, title, favorite, latitude, longitude
+ }
+
+ /// Creates a record from a database row
+ required init(row: Row) {
+ id = row[Columns.id]
+ title = row[Columns.title]
+ isFavorite = row[Columns.favorite]
+ coordinate = CLLocationCoordinate2D(
+ latitude: row[Columns.latitude],
+ longitude: row[Columns.longitude])
+ super.init(row: row)
+ }
+
+ /// The values persisted in the database
+ override func encode(to container: inout PersistenceContainer) {
+ container[Columns.id] = id
+ container[Columns.title] = title
+ container[Columns.favorite] = isFavorite
+ container[Columns.latitude] = coordinate.latitude
+ container[Columns.longitude] = coordinate.longitude
+ }
+
+ /// Update record ID after a successful insertion
+ override func didInsert(with rowID: Int64, for column: String?) {
+ id = rowID
+ }
+}
+“`
+
+
+
List of Record Methods
+
+
This is the list of record methods, along with their required protocols. The Record class adopts all these protocols, and adds a few extra methods.
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:
+
trydbQueue.write{dbin
+ // Update database schema (with SQL)
+ trydb.execute("CREATE TABLE wine (...)")
+
+ // Fetch records (with SQL)
+ letwines=tryWine.fetchAll(db,
+ "SELECT * FROM wine WHERE origin = ? ORDER BY price",
+ arguments:["Burgundy"])
+
+ // Count (with an SQL snippet)
+ letcount=tryWine
+ .filter(sql:"color = ?",arguments:[Color.red])
+ .fetchCount(db)
+
+ // Delete (with SQL)
+ trydb.execute("DELETE FROM wine 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
+
+
+
+
:bulb: Tip: database table names should be singular, and camel-cased. Make them look like Swift identifiers: place, country, postalAddress, ‘httpRequest’.
+
+
This will help you using Associations when you need them. Database table names that follow another naming convention are totally OK, but you will need to perform extra configuration.
+
+
+
Add regular columns with their name and eventual type (text, integer, double, numeric, boolean, blob, date and datetime) - see SQLite data types:
+
// CREATE TABLE example (
+// a,
+// name TEXT,
+// creationDate DATETIME,
+trydb.create(table:"example"){tin
+ t.column("a")
+ t.column("name",.text)
+ t.column("creationDate",.datetime)
+
+
+
Define not null columns, and set default values:
+
// email TEXT NOT NULL,
+ t.column("email",.text).notNull()
+
+ // name TEXT NOT NULL DEFAULT 'Anonymous',
+ t.column("name",.text).notNull().defaults(to:"Anonymous")
+
+
+
Use an individual column as primary, unique, or foreign key. When defining a foreign key, the referenced column is the primary key of the referenced table (unless you specify otherwise):
+
// id INTEGER PRIMARY KEY AUTOINCREMENT,
+ t.autoIncrementedPrimaryKey("id")
+
+ // uuid TEXT PRIMARY KEY,
+ t.column("uuid",.text).primaryKey()
+
+ // email TEXT UNIQUE,
+ t.column("email",.text).unique()
+
+ // countryCode TEXT REFERENCES country(code) ON DELETE CASCADE,
+ t.column("countryCode",.text).references("country",onDelete:.cascade)
+
+
+
+
:bulb: Tip: when you need an integer primary key that automatically generates unique values, it is highly recommended that you use the autoIncrementedPrimaryKey method:
The reason for this recommendation is that auto-incremented primary keys prevent the reuse of ids. This prevents your app or database observation tools to think that a row was updated, when it was actually deleted, then replaced. Depending on your application needs, this may be OK. Or not.
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.
Other table constraints can involve several columns:
+
// PRIMARY KEY (a, b),
+ t.primaryKey(["a","b"])
+
+ // UNIQUE (a, b) ON CONFLICT REPLACE,
+ t.uniqueKey(["a","b"],onConfict:.replace)
+
+ // FOREIGN KEY (a, b) REFERENCES parents(c, d),
+ t.foreignKey(["a","b"],references:"parents")
+
+ // CHECK (a + b < 10),
+ t.check(Column("a")+Column("b")<10)
+
+ // CHECK (a + b < 10)
+ t.check(sql:"a + b < 10")
+}
+
+
Modify Tables
+
+
SQLite lets you rename tables, and add columns to existing tables:
+
// ALTER TABLE referer RENAME TO referrer
+trydb.rename(table:"referer",to:"referrer")
+
+// ALTER TABLE player ADD COLUMN url TEXT
+trydb.alter(table:"player"){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)
+
// Columns.id and Columns.name can be used just as
+// idColumn and nameColumn declared above.
+enumColumns:String,ColumnExpression{
+ caseid
+ casename
+}
+
+
+
You can now build requests with the following methods: all, none, select, distinct, filter, matching, group, having, order, reversed, limit. All those methods return another request, which you can further refine by applying another method: Player.select(...).filter(...).order(...).
+
+
+
all(), none(): the requests for all rows, or no row.
+
// SELECT * FROM player
+Player.all()
+
+
+
The hidden rowid column can be selected as well when you need it.
// SELECT name FROM player
+Player.select(nameColumn,as:String.self)
+
+
distinct() performs uniquing.
+
// SELECT DISTINCT name FROM player
+Player.select(nameColumn,as:String.self).distinct()
+
+
filter(expression) applies conditions.
+
// SELECT * FROM player WHERE id IN (1, 2, 3)
+Player.filter([1,2,3].contains(idColumn))
+
+// SELECT * FROM player WHERE (name IS NOT NULL) AND (height > 1.75)
+Player.filter(nameColumn!=nil&&heightColumn>1.75)
+
+
filter(key:) and filter(keys:) apply conditions on primary keys and unique keys:
+
// SELECT * FROM player WHERE id = 1
+Player.filter(key:1)
+
+// SELECT * FROM country WHERE isoCode IN ('FR', 'US')
+Country.filter(keys:["FR","US"])
+
+// SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR'
+Citizenship.filter(key:["citizenId":1,"countryCode":"FR"])
+
+// SELECT * FROM player WHERE email = 'arthur@example.com'
+Player.filter(key:["email":"arthur@example.com"])
+
// SELECT * FROM document WHERE document 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(score) FROM player GROUP BY name
+Player
+ .select(nameColumn,max(scoreColumn))
+ .group(nameColumn)
+
+
having(expression) applies conditions on grouped rows.
+
// SELECT team, MAX(score) FROM player GROUP BY team HAVING MIN(score) >= 1000
+Player
+ .select(teamColumn,max(scoreColumn))
+ .group(teamColumn)
+ .having(min(scoreColumn)>=1000)
+
+
order(ordering, ...) sorts.
+
// SELECT * FROM player ORDER BY name
+Player.order(nameColumn)
+
+// SELECT * FROM player ORDER BY score DESC, name
+Player.order(scoreColumn.desc,nameColumn)
+
+
+
Each order call clears any previous ordering:
+
// SELECT * FROM player ORDER BY name
+Player.order(scoreColumn).order(nameColumn)
+
+
+
orderByPrimaryKey() sorts by primary key:
+
// SELECT * FROM player ORDER BY id
+Player.orderByPrimaryKey()
+
+// SELECT * FROM country ORDER BY code
+Country.orderByPrimaryKey()
+
+// SELECT * FROM citizenship ORDER BY citizenId, countryCode
+Citizenship.orderByPrimaryKey()
+
+
reversed() reverses the eventual orderings.
+
// SELECT * FROM player ORDER BY score ASC, name DESC
+Player.order(scoreColumn.desc,nameColumn).reversed()
+
+
+
If no ordering was already specified, this method has no effect:
+
// SELECT * FROM player
+Player.all().reversed()
+
+
limit(limit, offset: offset) limits and pages results.
+
// SELECT * FROM player LIMIT 5
+Player.limit(5)
+
+// SELECT * FROM player LIMIT 5 OFFSET 10
+Player.limit(5,offset:10)
+
+
+
+
You can refine requests by chaining those methods:
+
// SELECT * FROM player WHERE (email IS NOT NULL) ORDER BY name
+Player.order(nameColumn).filter(emailColumn!=nil)
+
+
+
The select, order, group, and limit methods ignore and replace previously applied selection, orderings, grouping, and limits. On the opposite, filter, matching, and having methods extend the query:
+
Player// SELECT * FROM player
+ .filter(nameColumn!=nil)// WHERE (name IS NOT NULL)
+ .filter(emailColumn!=nil)// AND (email IS NOT NULL)
+ .order(nameColumn)// - ignored -
+ .reversed()// - ignored -
+ .order(scoreColumn)// ORDER BY score
+ .limit(20,offset:40)// - ignored -
+ .limit(10)// LIMIT 10
+
+
+
Raw SQL snippets are also accepted, with eventual arguments:
+
// SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate)
+Player
+ .select(sql:"DATE(creationDate), COUNT(*)")
+ .filter(sql:"name = ?",arguments:["Arthur"])
+ .group(sql:"DATE(creationDate)")
+
+
Columns Selected by a Request
+
+
By default, query interface requests select all columns:
+
// SELECT * FROM player
+letrequest=Player.all()
+
+
+
The selection can be changed for each individual requests, or for all requests built from a given type.
+
+
The select(...) and select(..., as:) methods change the selection of a single request (see Fetching from Requests for detailed information):
The default selection for a record type is controlled by the databaseSelection property:
+
structRestrictedPlayer:TableRecord{
+ staticletdatabaseTableName="player"
+ staticletdatabaseSelection:[SQLSelectable]=[Column("id"),Column("name")]
+}
+
+structExtendedPlayer:TableRecord{
+ staticletdatabaseTableName="player"
+ staticletdatabaseSelection:[SQLSelectable]=[AllColumns(),Column.rowID]
+}
+
+// SELECT id, name FROM player
+letrequest=RestrictedPlayer.all()
+
+// SELECT *, rowid FROM player
+letrequest=ExtendedPlayer.all()
+
+
+
+
:point_up: Note: make sure the databaseSelection property is explicitly declared as [SQLSelectable]. If it is not, the Swift compiler may silently miss the protocol requirement, resulting in sticky SELECT * requests. To verify your setup, see the How do I print a request as SQL? FAQ.
+
+
Expressions
+
+
Feed requests with SQL expressions built from your Swift code:
+
SQL Operators
+
+
+
=, <>, <, <=, >, >=, IS, IS NOT
+
+
Comparison operators are based on the Swift operators ==, !=, ===, !==, <, <=, >, >=:
+
// SELECT * FROM player WHERE (name = 'Arthur')
+Player.filter(nameColumn=="Arthur")
+
+// SELECT * FROM player WHERE (name IS NULL)
+Player.filter(nameColumn==nil)
+
+// SELECT * FROM player WHERE (score IS 1000)
+Player.filter(scoreColumn===1000)
+
+// SELECT * FROM rectangle WHERE width < height
+Rectangle.filter(widthColumn<heightColumn)
+
+
+
+
:point_up: Note: SQLite string comparison, by default, is case-sensitive and not Unicode-aware. See string comparison if you need more control.
+
+
*, /, +, -
+
+
SQLite arithmetic operators are derived from their Swift equivalent:
+
// SELECT ((temperature * 1.8) + 32) AS farenheit FROM planet
+Planet.select((temperatureColumn*1.8+32).aliased("farenheit"))
+
+
+
+
:point_up: Note: an expression like nameColumn + "rrr" will be interpreted by SQLite as a numerical addition (with funny results), not as a string concatenation.
+
+
AND, OR, NOT
+
+
The SQL logical operators are derived from the Swift &&, || and !:
+
// SELECT * FROM player WHERE ((NOT verified) OR (score < 1000))
+Player.filter(!verifiedColumn||scoreColumn<1000)
+
+
+
When you want to join a sequence of expressions with AND or OR operators, use joined(operator:):
+
// SELECT * FROM player WHERE (verified AND (score >= 1000) AND (name IS NOT NULL))
+letconditions=[
+ verifiedColumn,
+ scoreColumn>=1000,
+ nameColumn!=nil]
+Player.filter(conditions.joined(operator:.and))
+
+
+
When the sequence is empty, joined(operator: .and) returns true, and joined(operator: .or) returns false:
+
// SELECT * FROM player WHERE 1
+Player.filter([].joined(operator:.and))
+
+// SELECT * FROM player WHERE 0
+Player.filter([].joined(operator:.or))
+
+
BETWEEN, IN, NOT IN
+
+
To check inclusion in a Swift sequence (array, set, range…), call the contains method:
+
// SELECT * FROM player WHERE id IN (1, 2, 3)
+Player.filter([1,2,3].contains(idColumn))
+
+// SELECT * FROM player WHERE id NOT IN (1, 2, 3)
+Player.filter(![1,2,3].contains(idColumn))
+
+// SELECT * FROM player WHERE score BETWEEN 0 AND 1000
+Player.filter((0...1000).contains(scoreColumn))
+
+// SELECT * FROM player WHERE (score >= 0) AND (score < 1000)
+Player.filter((0..<1000).contains(scoreColumn))
+
+// SELECT * FROM player WHERE initial BETWEEN 'A' AND 'N'
+Player.filter(("A"..."N").contains(initialColumn))
+
+// SELECT * FROM player WHERE (initial >= 'A') AND (initial < 'N')
+Player.filter(("A"..<"N").contains(initialColumn))
+
+
+
+
:point_up: Note: SQLite string comparison, by default, is case-sensitive and not Unicode-aware. See string comparison if you need more control.
+
+
LIKE
+
+
The SQLite LIKE operator is available as the like method:
+
// SELECT * FROM player WHERE (email LIKE '%@example.com')
+Player.filter(emailColumn.like("%@example.com"))
+
+
+
+
:point_up: Note: the SQLite LIKE operator is case-insensitive but not Unicode-aware. For example, the expression 'a' LIKE 'A' is true but 'æ' LIKE 'Æ' is false.
+
+
MATCH
+
+
The full-text MATCH operator is available through FTS3Pattern (for FTS3 and FTS4 tables) and FTS5Pattern (for FTS5):
+
+
FTS3 and FTS4:
+
letpattern=FTS3Pattern(matchingAllTokensIn:"SQLite database")
+
+// SELECT * FROM document WHERE document MATCH 'sqlite database'
+Document.matching(pattern)
+
+// SELECT * FROM document WHERE content MATCH 'sqlite database'
+Document.filter(contentColumn.match(pattern))
+
+
+
FTS5:
+
letpattern=FTS5Pattern(matchingAllTokensIn:"SQLite database")
+
+// SELECT * FROM document WHERE document MATCH 'sqlite database'
+Document.matching(pattern)
+
+
+
SQL Functions
+
+
+
ABS, AVG, COUNT, LENGTH, MAX, MIN, SUM:
+
+
Those are based on the abs, average, count, length, max, min and sum Swift functions:
+
// SELECT MIN(score), MAX(score) FROM player
+Player.select(min(scoreColumn),max(scoreColumn))
+
+// SELECT COUNT(name) FROM player
+Player.select(count(nameColumn))
+
+// SELECT COUNT(DISTINCT name) FROM player
+Player.select(count(distinct:nameColumn))
+
+
IFNULL
+
+
Use the Swift ?? operator:
+
// SELECT IFNULL(name, 'Anonymous') FROM player
+Player.select(nameColumn??"Anonymous")
+
+// SELECT IFNULL(name, email) FROM player
+Player.select(nameColumn??emailColumn)
+
+
LOWER, UPPER
+
+
The query interface does not give access to those SQLite functions. Nothing against them, but they are not unicode aware.
+
+
Instead, GRDB extends SQLite with SQL functions that call the Swift built-in string functions capitalized, lowercased, uppercased, localizedCapitalized, localizedLowercased and localizedUppercased:
+
Player.select(nameColumn.uppercased())
+
+
+
+
:point_up: Note: When comparing strings, you’d rather use a collation:
letf=DatabaseFunction("f",...)
+
+// SELECT f(name) FROM player
+Player.select(f.apply(nameColumn))
+
+
+
Fetching from Requests
+
+
Once you have a request, you can fetch the records at the origin of the request:
+
// Some request based on `Player`
+letrequest=Player.filter(...)...// QueryInterfaceRequest<Player>
+
+// Fetch players:
+tryrequest.fetchCursor(db)// A Cursor of Player
+tryrequest.fetchAll(db)// [Player]
+tryrequest.fetchOne(db)// Player?
+
See fetching methods for information about the fetchCursor, fetchAll and fetchOne methods.
+
+
You sometimes want to fetch other values.
+
+
The simplest way is to use the request as an argument to a fetching method of the desired type:
+
// Fetch an Int
+letrequest=Player.select(max(scoreColumn))
+letmaxScore=tryInt.fetchOne(db,request)// Int?
+
+// Fetch a Row
+letrequest=Player.select(min(scoreColumn),max(scoreColumn))
+letrow=tryRow.fetchOne(db,request)!// Row
+letminScore=row[0]asInt?
+letmaxScore=row[1]asInt?
+
+
+
When you also want to use database observation tools such as FetchedRecordsController or RxGRDB, you have to go one step further, and change the type of the request:
+
+
+
When you change the selection, prefer the select(..., as:) method:
+
// A request of Int
+letrequest=Player.select(max(scoreColumn),as:Int.self)
+
+// Simple fetch
+letmaxScore=trydbQueue.read{dbin
+ tryrequest.fetchOne(db)// Int?
+}
+
+// Observe with RxGRDB
+request.rx
+ .fetchOne(in:dbQueue)
+ .subscribe(onNext:{maxScore:Int?in
+ print("The maximum score has changed")
+ })
+
+
Otherwise, use asRequest(of:). Here is an example that uses Associations:
Fetching records according to their primary key is a very common task. It has a shortcut which accepts any single-column primary key:
+
// SELECT * FROM player WHERE id = 1
+tryPlayer.fetchOne(db,key:1)// Player?
+
+// SELECT * FROM player WHERE id IN (1, 2, 3)
+tryPlayer.fetchAll(db,keys:[1,2,3])// [Player]
+
+// SELECT * FROM country WHERE isoCode = 'FR'
+tryCountry.fetchOne(db,key:"FR")// Country?
+
+// SELECT * FROM country 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 document 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 citizenship WHERE citizenId = 1 AND countryCode = 'FR'
+tryCitizenship.fetchOne(db,key:["citizenId":1,"countryCode":"FR"])// Citizenship?
+
+// SELECT * FROM player WHERE email = 'arthur@example.com'
+tryPlayer.fetchOne(db,key:["email":"arthur@example.com"])// Player?
+
+
+
When you want to build a request and plan to fetch from it later, use the filter(key:) and filter(keys:) methods:
+
// SELECT * FROM player WHERE id = 1
+letrequest=Player.filter(key:1)
+letplayer=tryrequest.fetchOne(db)// Player?
+
+// SELECT * FROM player WHERE id IN (1, 2, 3)
+letrequest=Player.filter(keys:[1,2,3])
+letplayers=tryrequest.fetchAll(db)// [Player]
+
+// SELECT * FROM country WHERE isoCode = 'FR'
+letrequest=Country.filter(key:"FR")
+letcountry=tryrequest.fetchOne(db)// Country?
+
+// SELECT * FROM country WHERE isoCode IN ('FR', 'US')
+letrequest=Country.filter(keys:["FR","US"])
+letcountries=tryrequest.fetchAll(db)// [Country]
+
+// SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR'
+letrequest=Citizenship.filter(key:["citizenId":1,"countryCode":"FR"])
+letcitizenship=request.fetchOne(db)// Citizenship?
+
+// SELECT * FROM player WHERE email = 'arthur@example.com'
+letrequest=Player.filter(key:["email":"arthur@example.com"])
+letplayer=tryrequest.fetchOne(db)// Player?
+
Requests can count. The fetchCount() method returns the number of rows that would be returned by a fetch request:
+
// SELECT COUNT(*) FROM player
+letcount=tryPlayer.fetchCount(db)// Int
+
+// SELECT COUNT(*) FROM player WHERE email IS NOT NULL
+letcount=tryPlayer.filter(emailColumn!=nil).fetchCount(db)
+
+// SELECT COUNT(DISTINCT name) FROM player
+letcount=tryPlayer.select(nameColumn).distinct().fetchCount(db)
+
+// SELECT COUNT(*) FROM (SELECT DISTINCT name, score FROM player)
+letcount=tryPlayer.select(nameColumn,scoreColumn).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 player WHERE email IS NULL
+letrequest=Player.filter(emailColumn==nil)
+tryrequest.deleteAll(db)
+
+
+
+
:point_up: Note Deletion methods are only available for records that adopts the PersistableRecord protocol.
+
+
+
Deleting records according to their primary key is also quite common. It has a shortcut which accepts any single-column primary key:
+
// DELETE FROM player WHERE id = 1
+tryPlayer.deleteOne(db,key:1)
+
+// DELETE FROM player WHERE id IN (1, 2, 3)
+tryPlayer.deleteAll(db,keys:[1,2,3])
+
+// DELETE FROM country WHERE isoCode = 'FR'
+tryCountry.deleteOne(db,key:"FR")
+
+// DELETE FROM country 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 document 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 citizenship WHERE citizenId = 1 AND countryCode = 'FR'
+tryCitizenship.deleteOne(db,key:["citizenId":1,"countryCode":"FR"])
+
+// DELETE FROM player WHERE email = 'arthur@example.com'
+Player.deleteOne(db,key:["email":"arthur@example.com"])
+
+
Custom Requests
+
+
Until now, we have seen requests created from any type that adopts the TableRecord protocol:
tryrequest.fetchCursor(db)// A Cursor of Player
+tryrequest.fetchAll(db)// [Player]
+tryrequest.fetchOne(db)// Player?
+tryrequest.fetchCount(db)// Int
+
+
+
When the query interface can not generate the SQL you need, you can still fallback to raw SQL:
+
// Custom SQL is always welcome
+tryPlayer.fetchAll(db,"SELECT ...")// [Player]
+
+
+
But you may prefer to bring some elegance back in, and build custom requests:
+
// No custom SQL in sight
+tryPlayer.customRequest().fetchAll(db)// [Player]
+
FetchRequest is the protocol for all requests that run from a single select statement, and know how fetched rows should be interpreted:
+
protocolFetchRequest{
+ /// The type that tells how fetched rows should be decoded
+ associatedtypeRowDecoder
+
+ /// A tuple that contains a prepared statement, 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 database region that the request looks into.
+ funcdatabaseRegion(_db:Database)throws->DatabaseRegion
+}
+
The prepare method returns a prepared statement and an optional row adapter. The prepared statement tells which SQL query should be executed. The row adapter helps presenting the fetched rows in the way expected by the row decoders (see row adapter).
+
+
The fetchCount method has a default implementation that builds a correct but naive SQL query from the statement returned by prepare: SELECT COUNT(*) FROM (...). Adopting types can refine the counting SQL by customizing their fetchCount implementation.
+
+
The databaseRegion method is involved in database observation. It is given a default implementation, based on the statement returned by prepare. For more information, see DatabaseRegion, and RxGRDB.
// A FetchRequest whose RowDecoder associated type is Player:
+letrequest=Player.all()
+
+
Building Custom Requests
+
+
To build custom requests, you can use one of the built-in requests, derive requests from other requests, or create your own request type that adopts the FetchRequest protocol.
+
+
+
SQLRequest is a fetch request built from raw SQL. For example:
+
extensionPlayer{
+ staticfuncfilter(color:Color)->SQLRequest<Player>{
+ returnSQLRequest<Player>(
+ "SELECT * FROM player WHERE color = ?"
+ arguments:[color])
+ }
+}
+
+// [Player]
+tryPlayer.filter(color:.red).fetchAll(db)
+
+
The asRequest(of:) method changes the type fetched by the request. It is useful, for example, when you use Associations:
A type adopting FetchRequest knows exactly what it has to do when its RowDecoder associated type can decode database rows (Row itself, values, or FetchableRecord):
+
letrowRequest=...// Some FetchRequest that fetches Row
+tryrequest.fetchCursor(db)// A cursor of rows
+
+letplayerRequest=...// Some FetchRequest that fetches Player
+tryrequest.fetchAll(db)// [Player]
+
+letintRequest=...// Some FetchRequest that fetches Int
+tryrequest.fetchOne(db)// Int?
+
+
+
For example:
+
letplayerRequest=SQLRequest<Player>(
+ "SELECT * FROM player WHERE color = ?"
+ arguments:[color])
+tryrequest.fetchAll(db)// [Player]
+
+
+
See fetching methods for information about the fetchCursor, fetchAll and fetchOne methods.
+
+
The RowDecoder type associated with the FetchRequest does not have to be Row, DatabaseValueConvertible, or FetchableRecord. See the Beyond FetchableRecord chapter for more information.
+
Migrations
+
+
Migrations are a convenient way to alter your database schema over time in a consistent and easy way.
+
+
Migrations run in order, once and only once. When a user upgrades your application, only non-applied migrations are run.
varmigrator=DatabaseMigrator()
+
+// 1st migration
+migrator.registerMigration("v1"){dbin
+ trydb.create(table:"author"){tin...}
+ trydb.create(table:"book"){tin...}
+ trydb.create(index:...)
+}
+
+// 2nd migration
+migrator.registerMigration("v2"){dbin
+ trydb.alter(table:"author"){tin...}
+}
+
+// Migrations for future versions will be inserted here:
+//
+// // 3rd migration
+// migrator.registerMigration("...") { db in
+// ...
+// }
+
+
+
Each migration runs in a separate transaction. Should one throw an error, its transaction is rollbacked, subsequent migrations do not run, and the error is eventually thrown by migrator.migrate(dbQueue).
+
+
The memory of applied migrations is stored in the database itself (in a reserved table).
+
+
You migrate the database up to the latest version with the migrate(_:) method:
+
trymigrator.migrate(dbQueue)// or migrator.migrate(dbPool)
+
+
+
To migrate a database up to a specific version, use migrate(_:upTo:):
letappliedMigrations=trymigrator.appliedMigrations(in:dbQueue)
+ifappliedMigrations.contains("v2"){
+ // "v2" migration has been applied
+}
+
+
The eraseDatabaseOnSchemaChange Option
+
+
A DatabaseMigrator can automatically wipe out the full database content, and recreate the whole database from scratch, if it detects that a migration has changed its definition:
Beware! This flag can destroy your precious users’ data!
+
+
Yet it may be useful in those two situations:
+
+
+
During application development, as you are still designing migrations, and the schema changes often.
+
+
In this case, it is recommended that this flag does not ship in the distributed application:
+
varmigrator=DatabaseMigrator()
+#if DEBUG
+// Speed up development by nuking the database when migrations change
+migrator.eraseDatabaseOnSchemaChange=true
+#endif
+
+
When the database content can easily be recreated, such as a cache for some downloaded data.
+
+
+
The eraseDatabaseOnSchemaChange option triggers a recreation of the database if the migrator detects a schema change. A schema change is any difference in the sqlite_master table, which contains the SQL used to create database tables, indexes, triggers, and views.
+
Advanced Database Schema Changes
+
+
SQLite does not support many schema changes, and won’t let you drop a table column with ALTER TABLE … DROP COLUMN …, for example.
+
+
Yet any kind of schema change is still possible. The SQLite documentation explains in detail how to do so: https://www.sqlite.org/lang_altertable.html#otheralter. This technique requires the temporary disabling of foreign key checks, and is supported by the registerMigrationWithDeferredForeignKeyCheck function:
+
// Add a NOT NULL constraint on player.name:
+migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName"){dbin
+ trydb.create(table:"new_player"){tin
+ t.autoIncrementedPrimaryKey("id")
+ t.column("name",.text).notNull()
+ }
+ trydb.execute("INSERT INTO new_player SELECT * FROM player")
+ trydb.drop(table:"player")
+ trydb.rename(table:"new_player",to:"player")
+}
+
+
+
While your migration code runs with disabled foreign key checks, those are re-enabled and checked at the end of the migration, regardless of eventual errors.
+
Full-Text Search
+
+
Full-Text Search is an efficient way to search a corpus of textual documents.
+
// Create full-text tables
+trydb.create(virtualTable:"book",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 book (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 book WHERE book 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 supports FTS3 and FTS4 out of the box, but not always FTS5. To use FTS5, see Enabling FTS5 Support.
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)
+
+
Enabling FTS5 Support
+
+
When the FTS3 and FTS4 full-text engines don’t suit your needs, you may want to use FTS5. See Choosing the Full-Text Engine to help you make a decision.
+
+
The version of SQLite that ships with iOS, macOS and watchOS does not always support the FTS5 engine. To enable FTS5 support, you’ll need to install GRDB with one of those installation techniques:
+
+
+
Use the GRDBPlus CocoaPod. It uses the system SQLite, and requires iOS 11.4+ / macOS 10.13+ / watchOS 4.3+:
+
pod'GRDBPlus'
+
+
Use the GRDBCipher CocoaPod. It uses SQLCipher (see encryption), and requires iOS 8.0+ / macOS 10.9+ / watchOS 2.0+:
+
pod'GRDBCipher'
+
+
Use a custom SQLite build and activate the SQLITE_ENABLE_FTS5 compilation option.
+
+
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:"book")
+// DatabaseError: syntax error near \"AND\"
+trydb.makeFTS5Pattern(rawPattern:"AND",forTable:"book")
+// DatabaseError: no such column: missing
+trydb.makeFTS5Pattern(rawPattern:"missing: sqlite",forTable:"book")
+
+
+
The FTS5Pattern initializers don’t throw. They build a valid pattern from any string, including strings provided by users of your application. They let you find documents that match all given words, any given word, or a full phrase, depending on the needs of your application:
+
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)
+// Matches documents that start with "SQLite database"
+letpattern=FTS5Pattern(matchingPrefixPhrase: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 document WHERE document 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:"book"){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:"book_ft",using:FTS4()){tin// or FTS5()
+ t.synchronize(withTable:"book")
+ t.column("author")
+ t.column("title")
+ t.column("content")
+}
+
+
+
The eventual content already present in the regular table is indexed, and every insert, update or delete that happens in the regular table is automatically applied to the full-text index.
+
+
For more information, see the SQLite documentation about external content tables: FTS4, FTS5.
+
+
See also WWDC Companion, a sample app that uses external content tables to store, display, and let the user search the WWDC sessions.
+
Deleting Synchronized Full-Text Tables
+
+
Synchronization of full-text tables with their content table happens by the mean of SQL triggers.
+
+
SQLite automatically deletes those triggers when the content (not full-text) table is dropped.
+
+
However, those triggers remain after the full-text table has been dropped. Unless they are dropped too, they will prevent future insertion, updates, and deletions in the content table, and the creation of a new full-text table.
+
+
To drop those triggers, use the dropFTS4SynchronizationTriggers or dropFTS5SynchronizationTriggers methods:
:warning: Warning: there was a bug in GRDB up to version 2.3.1 included, which created triggers with a wrong name. If it is possible that the full-text table was created by an old version of GRDB, then delete the synchronization triggers twice: once with the name of the deleted full-text table, and once with the name of the content table:
+
// Drop full-text table
+trydb.drop(table:"book_ft")
+trydb.dropFTS4SynchronizationTriggers(forTable:"book_ft")
+trydb.dropFTS4SynchronizationTriggers(forTable:"book")// Support for GRDB <= 2.3.1
+
+
+
Querying External Content Full-Text Tables
+
+
When you need to perform a full-text search, and the external content table contains all the data you need, you can simply query the full-text table.
+
+
But if you need to load columns from the regular table, and in the same time perform a full-text search, then you will need to query both tables at the same time.
+
+
That is because SQLite will throw an error when you try to perform a full-text search on a regular table:
+
// SQLite error 1: unable to use function MATCH in the requested context
+// SELECT * FROM book WHERE book MATCH '...'
+letbooks=Book.matching(pattern).fetchAll(db)
+
+
+
The solution is to perform a joined request, using raw SQL:
+
letsql="""
+ SELECT book.*
+ FROM book
+ JOIN book_ft
+ ON book_ft.rowid = book.rowid
+ AND book_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!
+
Joined Queries Support
+
+
GRDB helps consuming joined queries with complex selection.
+
+
In this chapter, we will focus on the extraction of information from complex rows, such as the ones fetched by the query below:
+
-- How to consume the left, middle, and right parts of those rows?
+SELECTplayer.*,team.*,MAX(round.score)ASmaxScore
+FROMplayer
+LEFTJOINteamON...
+LEFTJOINroundON...
+GROUPBY...
+
+
+
We will not talk about the generation of joined queries, which is covered in Associations.
+
+
So what are we talking about?
+
+
It is difficult to consume rows fetched from complex joined queries, because they often contain several columns with the same name: id from table player, id from table team, etc.
+
+
When such ambiguity happens, GRDB row accessors always favor the leftmost matching column. This means that row["id"] would give a player id, whithout any obvious way to access the team id.
+
+
A classical technique to avoid this ambiguity is to give each column a unique name. For example:
+
-- A classical technique
+SELECTplayer.idASplayer_id,player.nameASplayer_name,team.idASteam_id,team.nameASteam_name,team.colorASteam_color,MAX(round.score)ASmaxScore
+FROMplayer
+LEFTJOINteamON...
+LEFTJOINroundON...
+GROUPBY...
+
+
+
This technique works pretty well, but it has three drawbacks:
+
+
+
The selection becomes hard to read and understand.
+
Such queries are difficult to write by hand.
+
The mangled names are a very bad fit for FetchableRecord types that expect specific column names. After all, if the Team record type can read SELECT * FROM team ..., it should be able to read SELECT ..., team.*, ... as well.
+
+
+
We thus need another technique. Below we’ll see how to split rows into slices, and preserve column names.
+
+
SELECT player.*, team.*, MAX(round.score) AS maxScore FROM ... will be splitted into three slices: one that contains player’s columns, one that contains team’s columns, and a remaining slice that contains remaining column(s). The Player record type will be able to read the first slice, which contains the colums expected by the Player.init(row:) initializer. In the same way, the Team record type could read the second slice.
+
+
Unlike the name-mangling technique, splitting rows keeps SQL legible, accepts your hand-crafted SQL queries, and plays as nicely as possible with your existing record types.
Let’s first write some introductory code, hoping that this chapter will make you understand how pieces fall together. We’ll see later how records will help us streamline the initial approach, how to track changes in joined requests, and how we can use the standard Decodable protocol.
+
+
To split rows, we will use row adapters. Row adapters adapt rows so that row consumers see exactly the columns they want. Among other things, row adapters can define several row scopes that give access to as many row slices. Sounds like a perfect match.
+
+
At the very beginning, there is an SQL query:
+
trydbQueue.read{dbin
+ letsql="""
+ SELECT player.*, team.*, MAX(round.score) AS maxScore
+ FROM player
+ LEFT JOIN team ON ...
+ LEFT JOIN round ON ...
+ GROUP BY ...
+ """
+
+
+
We need an adapter that extracts player columns, in a slice that has as many columns as there are columns in the player table. That’s RangeRowAdapter:
In the SQL query, the team is joined with the LEFT JOIN operator. This means that the team may be missing: its slice may contain team values, or it may only contain NULLs. When this happens, we don’t want to build a Team record, and we thus load an optional Team:
+
letteam:Team?=row[teamScope]
+
+
+
And finally, we can load the maximum score, assuming that the maxScore column is not ambiguous:
how to use RangeRowAdapter to extract a specific table’s columns into a row slice.
+
how to use ScopeAdapter to gives access to several row slices through named scopes.
+
how to use Row subscripting to extract records from rows, or optional records in order to deal with left joins.
+
+
+
Splitting Rows, the Record Way
+
+
Our introduction above has introduced important techniques. It uses row adapters in order to split rows. It uses Row subscripting in order to extract records from row slices.
+
+
But we may want to make it more usable and robust:
+
+
+
It’s generally easier to consume records than raw rows.
To address the first bullet, let’s define a record that holds our player, optional team, and maximum score. Since it can decode database rows, it adopts the FetchableRecord protocol:
To acknowledge that both Player and Team records may customize their selection of the player and team columns, we’ll write our SQL in a slightly different way:
+
// Let Player and Team customize their selection:
+ letsql="""
+ SELECT
+ \(Player.selectionSQL()), -- instead of player.*
+ \(Team.selectionSQL()), -- instead of team.*
+ MAX(round.score) AS maxScore
+ FROM player
+ LEFT JOIN team ON ...
+ LEFT JOIN round ON ...
+ GROUP BY ...
+ """
+
+
+
Player.selectionSQL() will output player.*, unless Player defines a customized selection.
+
+
+
:point_up: Note: you may also use SQL table aliases:
+
letsql="""
+ SELECT
+ \(Player.selectionSQL(alias:"p")),
+ \(Team.selectionSQL(alias:"t")),
+ MAX(r.score) AS maxScore
+ FROM player p
+ LEFT JOIN team t ON ...
+ LEFT JOIN round r ON ...
+ GROUP BY ...
+ """
+
+
+
+
Now is the time to build adapters (taking in account the customized selection of both player and team). We use the splittingRowAdapters global function, which builds row adapters of desired widths:
:point_up: Note: splittingRowAdapters returns as many adapters as necessary to fully split a row. In the example above, it returns three adapters: one for player, one for team, and one for the remaining columns.
Now we write a method that returns a request, and build the fetching method on top of that request:
+
extensionPlayerInfo{
+ /// The request for all player infos
+ staticfuncall()->AdaptedFetchRequest<SQLRequest<PlayerInfo>>{
+ letsql="""
+ SELECT
+ \(Player.selectionSQL()),
+ \(Team.selectionSQL()),
+ MAX(round.score) AS maxScore
+ FROM player
+ LEFT JOIN team ON ...
+ LEFT JOIN round ON ...
+ GROUP BY ...
+ """
+ returnSQLRequest<PlayerInfo>(sql).adapted{dbin
+ letadapters=trysplittingRowAdapters(columnCounts:[
+ Player.numberOfSelectedColumns(db),
+ Team.numberOfSelectedColumns(db)])
+ returnScopeAdapter([
+ Scopes.player:adapters[0],
+ Scopes.team:adapters[1]])
+ }
+ }
+
+ /// Fetches all player infos
+ staticfuncfetchAll(_db:Database)throws->[PlayerInfo]{
+ returntryall().fetchAll(db)
+ }
+}
+
+
+
It is now time to use our request:
+
// Fetch player infos
+letplayerInfos=trydbQueue.read{dbin
+ tryPlayerInfo.fetchAll(db)
+}
+
+// Track player infos with RxRGDB:
+PlayerInfo.all()
+ .rx.fetchAll(in:dbQueue)
+ .subscribe(onNext:{playerInfos:[PlayerInfo]in
+ print("Player infos have changed")
+ })
+
+
+
+
:bulb: In this chapter, we have learned how to define a custom request that can both fetch records from joined queries, and feed database observation tools.
+
+
Splitting Rows, the Codable Way
+
+
Codable Records build on top of the standard Decodable protocol in order to decode database rows.
+
+
You can consume complex joined queries with Codable records as well. As a demonstration, we’ll rewrite the above sample code:
+
structPlayer:Decodable,FetchableRecord,TableRecord{
+ varid:Int64
+ varname:String
+}
+structTeam:Decodable,FetchableRecord,TableRecord{
+ varid:Int64
+ varname:String
+ varcolor:Color
+}
+structPlayerInfo:Decodable,FetchableRecord{
+ varplayer:Player
+ varteam:Team?
+ varmaxScore:Int
+}
+
+extensionPlayerInfo{
+ /// The request for all player infos
+ staticfuncall()->AdaptedFetchRequest<SQLRequest<PlayerInfo>>{
+ letsql="""
+ SELECT
+ \(Player.selectionSQL()),
+ \(Team.selectionSQL()),
+ MAX(round.score) AS maxScore
+ FROM player
+ LEFT JOIN team ON ...
+ LEFT JOIN round ON ...
+ GROUP BY ...
+ """
+ returnSQLRequest<PlayerInfo>(sql).adapted{dbin
+ letadapters=trysplittingRowAdapters(columnCounts:[
+ Player.numberOfSelectedColumns(db),
+ Team.numberOfSelectedColumns(db)])
+ returnScopeAdapter([
+ CodingKeys.player.stringValue:adapters[0],
+ CodingKeys.team.stringValue:adapters[1]])
+ }
+ }
+
+ /// Fetches all player infos
+ staticfuncfetchAll(_db:Database)throws->[PlayerInfo]{
+ returntryall().fetchAll(db)
+ }
+}
+
+// Fetch player infos
+letplayerInfos=trydbQueue.read{dbin
+ tryPlayerInfo.fetchAll(db)
+}
+
+// Track player infos with RxRGDB:
+PlayerInfo.all()
+ .rx.fetchAll(in:dbQueue)
+ .subscribe(onNext:{playerInfos:[PlayerInfo]in
+ print("Player infos have changed")
+ })
+
+
+
+
:bulb: In this chapter, we have learned how to use the Decodable protocol and its associated CodingKeys enum in order to dry up our code.
+
+
Database Changes Observation
+
+
SQLite notifies its host application of changes performed to the database, as well of transaction commits and rollbacks.
+
+
GRDB puts this SQLite feature to some good use, and lets you observe the database in various ways:
+
+
+
After Commit Hook: The simplest way to handle successful transactions.
FetchedRecordsController: Automated tracking of changes in a query results, plus UITableView animations
+
RxGRDB: Automated tracking of changes in a query results, based on RxSwift
+
+
+
Database observation requires that a single database queue or pool is kept open for all the duration of the database usage.
+
After Commit Hook
+
+
When your application needs to make sure a specific database transaction has been successfully committed before it executes some work, use the Database.afterNextTransactionCommit(_:) method.
+
+
Its closure argument is called right after database changes have been successfully written to disk:
The closure runs in a protected dispatch queue, serialized with all database updates.
+
+
This after commit hook helps synchronizing the database with other resources, such as files, or system sensors.
+
+
In the example below, a location manager starts monitoring a CLRegion if and only if it has successfully been stored in the database:
+
/// Inserts a region in the database, and start monitoring upon
+/// successful insertion.
+funcstartMonitoring(_db:Database,region:CLRegion)throws{
+ // Make sure database is inside a transaction
+ trydb.inSavepoint{
+
+ // Save the region in the database
+ tryinsert(...)
+
+ // Start monitoring if and only if the insertion is
+ // eventually committed
+ db.afterNextTransactionCommit{_in
+ // locationManager prefers the main queue:
+ DispatchQueue.main.async{
+ locationManager.startMonitoring(for:region)
+ }
+ }
+
+ return.commit
+ }
+}
+
+
+
The method above won’t trigger the location manager if the transaction is eventually rollbacked (explicitly, or because of an error), as in the sample code below:
+
trydbQueue.write{dbin
+ // success
+ trystartMonitoring(db,region)
+
+ // On error, the transaction is rollbacked, the region is not inserted, and
+ // the location manager is not invoked.
+ tryfailableMethod(db)
+}
+
+
TransactionObserver Protocol
+
+
The TransactionObserver protocol lets you observe database changes and transactions:
+
protocolTransactionObserver:class{
+ /// Notifies a database change:
+ /// - event.kind (insert, update, or delete)
+ /// - event.tableName
+ /// - event.rowID
+ ///
+ /// For performance reasons, the event is only valid for the duration of
+ /// this method call. If you need to keep it longer, store a copy:
+ /// event.copy().
+ funcdatabaseDidChange(withevent:DatabaseEvent)
+
+ /// Filters the database changes that should be notified to the
+ /// `databaseDidChange(with:)` method.
+ funcobserves(eventsOfKindeventKind:DatabaseEventKind)->Bool
+
+ /// 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)
+}
+
By default, database holds weak references to its transaction observers: they are not retained, and stop getting notifications after they are deallocated. See Observation Extent for more options.
+
Database Changes And Transactions
+
+
A transaction observer is notified of all database changes: inserts, updates and deletes. This includes indirect changes triggered by ON DELETE and ON UPDATE actions associated to foreign keys, and SQL triggers.
+
+
+
:point_up: Note: the changes that are not notified are changes to internal system tables (such as sqlite_master), changes to WITHOUT ROWID tables, and the deletion of duplicate rows triggered by ON CONFLICT REPLACE clauses (this last exception might change in a future release of SQLite).
+
+
+
Notified changes are not actually written to disk until the transaction commits, and the databaseDidCommit callback is called. On the other side, databaseDidRollback confirms their invalidation:
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 database changes they are not interested in.
+
+
The filtering happens in the observes(eventsOfKind:) method, which tells whether the observer wants notification of specific kinds of changes, or not. For example, here is how an observer can focus on the changes that happen on the player database table:
+
classPlayerObserver:TransactionObserver{
+ funcobserves(eventsOfKindeventKind:DatabaseEventKind)->Bool{
+ // Only observe changes to the "player" table.
+ returneventKind.tableName=="player"
+ }
+
+ funcdatabaseDidChange(withevent:DatabaseEvent){
+ // This method is only called for changes that happen to
+ // the "player" table.
+ }
+}
+
+
+
Generally speaking, the observes(eventsOfKind:) method can distinguish insertions from deletions and updates, and is also able to inspect the columns that are about to be changed:
+
classPlayerScoreObserver:TransactionObserver{
+ funcobserves(eventsOfKindeventKind:DatabaseEventKind)->Bool{
+ // Only observe changes to the "score" column of the "player" table.
+ switcheventKind{
+ case.insert(lettableName):
+ returntableName=="player"
+ case.delete(lettableName):
+ returntableName=="player"
+ case.update(lettableName,letcolumnNames):
+ returntableName=="player"&&columnNames.contains("score")
+ }
+ }
+}
+
+
+
When the observes(eventsOfKind:) method returns false for all event kinds, the observer is still notified of commits and rollbacks:
+
classPureTransactionObserver:TransactionObserver{
+ funcobserves(eventsOfKindeventKind:DatabaseEventKind)->Bool{
+ // Ignore all individual changes
+ returnfalse
+ }
+
+ funcdatabaseDidChange(withevent:DatabaseEvent){/* Never called */}
+ funcdatabaseWillCommit()throws{/* Called before commit */}
+ funcdatabaseDidRollback(_db:Database){/* Called on rollback */}
+ funcdatabaseDidCommit(_db:Database){/* Called on commit */}
+}
+
+
+
For more information about event filtering, see DatabaseRegion.
+
Observation Extent
+
+
You can specify how long an observer is notified of database changes and transactions.
+
+
The remove(transactionObserver:) method explicitly stops notifications, at any time:
+
// From a database queue or pool:
+dbQueue.remove(transactionObserver:observer)
+
+// From a database connection:
+dbQueue.inDatabase{dbin
+ db.remove(transactionObserver:observer)
+}
+
+
+
Alternatively, use the extent parameter of the add(transactionObserver:extent:) method:
+
letobserver=MyObserver()
+
+// On a database queue or pool:
+dbQueue.add(transactionObserver:observer)// default extent
+dbQueue.add(transactionObserver:observer,extent:.observerLifetime)
+dbQueue.add(transactionObserver:observer,extent:.nextTransaction)
+dbQueue.add(transactionObserver:observer,extent:.databaseLifetime)
+
+// On a database connection:
+dbQueue.inDatabase{dbin
+ db.add(transactionObserver:...)
+}
+
+
+
+
The default extent is .observerLifetime: the database holds a weak reference to the observer, and the observation automatically ends when the observer is deallocated. Meanwhile, observer is notified of all changes and transactions.
+
.nextTransaction activates the observer until the current or next transaction completes. The database keeps a strong reference to the observer until its databaseDidCommit or databaseDidRollback method is eventually called. Hereafter the observer won’t get any further notification.
+
.databaseLifetime has the database retain and notify the observer until the database connection is closed.
+
+
+
Finally, an observer may ignore all database changes until the end of the current transaction:
+
classPlayerObserver:TransactionObserver{
+ varplayerTableWasModified=false
+
+ funcobserves(eventsOfKindeventKind:DatabaseEventKind)->Bool{
+ returneventKind.tableName=="player"
+ }
+
+ funcdatabaseDidChange(withevent:DatabaseEvent){
+ playerTableWasModified=true
+
+ // It is pointless to keep on tracking further changes:
+ stopObservingDatabaseChangesUntilNextTransaction()
+ }
+}
+
+
+
After stopObservingDatabaseChangesUntilNextTransaction(), the databaseDidChange(with:) method will not be notified of any change for the remaining duration of the current transaction. This helps GRDB optimize database observation.
+
DatabaseRegion
+
+
DatabaseRegion is a type that helps observing changes in the results of a database request.
+
+
A request knows which database modifications can impact its results. It can communicate this information to a transaction observer by the way of a database region.
Beware that a region notifies potential changes, not actual changes in the results of a request. A change is notified if and only if a statement has actually modified the tracked tables and columns by inserting, updating, or deleting a row.
+
+
For example, if you observe the region of Player.select(max(Column("score"))), then you’ll get be notified of all changes performed on the score column of the player table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table.
+
+
Similarly, observing the region of Country.filter(key: "FR") will notify all changes that happen to the whole country table. That is because SQLite only notifies the numerical rowid of changed rows, and we can’t check if it is the row FR that has been changed, or another. This limitation does not apply to tables whose primary key is the rowid: Player.filter(key: 42) will only notify of changes performed on the row with id 42.
+
Support for SQLite Pre-Update Hooks
+
+
A custom SQLite build can activate SQLite preupdate hooks. In this case, TransactionObserverType gets an extra callback which lets you observe individual column values in the rows modified by a transaction:
+
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 FetchableRecord protocol, such as a subclass of the Record class, a FetchedRecordsController is able to track changes in the results of the fetch request, notify of those changes, and return the results of the request in a form that is suitable for a table view or a collection view, with one cell per fetched record.
+
+
See the Demo Application for an sample app that uses FetchedRecordsController.
+
+
See also RxGRDB, an RxSwift extension, for a reactive way to track request changes.
The type of the fetched records. It must be a type that adopts the FetchableRecord protocol, such as a subclass of the Record class
+
A fetch request
+
+
classPlayer:Record{...}
+letdbQueue=DatabaseQueue(...)// or DatabasePool
+
+// Using a Request from the Query Interface:
+letcontroller=FetchedRecordsController(
+ dbQueue,
+ request:Player.order(Column("name")))
+
+// Using SQL, and eventual arguments:
+letcontroller=FetchedRecordsController<Player>(
+ dbQueue,
+ sql:"SELECT * FROM player ORDER BY name WHERE countryCode = ?",
+ arguments:["FR"])
+
+
+
The fetch request can involve several database tables. The fetched records controller will only track changes in the columns and tables used by the fetch request.
+
letcontroller=FetchedRecordsController<Author>(
+ dbQueue,
+ sql:"""
+ SELECT author.name, COUNT(book.id) AS bookCount
+ FROM author
+ LEFT JOIN book ON book.authorId = author.id
+ GROUP BY author.id
+ ORDER BY author.name
+ """)
+
+
+
After creating an instance, you invoke performFetch() to actually execute
+the fetch.
+
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:
+
// One transaction
+trydbQueue.write{dbin// or dbPool.write
+ tryplayer1.insert(db)
+ tryplayer2.insert(db)
+}
+
+// One transaction
+trydbQueue.inTransaction{dbin// or dbPool.writeInTransaction
+ tryplayer1.insert(db)
+ tryplayer2.insert(db)
+ return.commit
+}
+
+// Two transactions
+trydbQueue.inDatabase{dbin// or dbPool.writeWithoutTransaction
+ tryplayer1.insert(db)
+ tryplayer2.insert(db)
+}
+
+
+
When you apply several changes to the database, you should group them in a single explicit transaction. The controller will then notify of all changes together.
+
The Changes Notifications
+
+
An instance of FetchedRecordsController notifies that the controller’s fetched records have been changed by the mean of callbacks:
+
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()
+
:warning: Warning: notification of individual record changes (the onChange callback) has FetchedRecordsController use a diffing algorithm that has a high complexity, a high memory consumption, and is thus not suited for large result sets. One hundred rows is probably OK, but one thousand is probably not. If your application experiences problems with large lists, see Issue 263 for more information.
+
+
+
Callbacks have the fetched record controller itself as an argument: use it in order to avoid memory leaks:
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:
+ returntryPlayer.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(Player.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 TableRecord 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()
+ })
+
+
+
+
:warning: Warning: notification of individual record changes (the onChange callback) has FetchedRecordsController use a diffing algorithm that has a high complexity, a high memory consumption, and is thus not suited for large result sets. One hundred rows is probably OK, but one thousand is probably not. If your application experiences problems with large lists, see Issue 263 for more information.
+
+
+
See the Demo Application for an sample app that uses FetchedRecordsController to animate a table view.
+
+
+
:point_up: Note: our sample code above uses unowned references to the table view controller. This is a safe pattern as long as the table view controller owns the fetched records controller, and is deallocated from the main thread (this is usually the case). In other situations, prefer weak references.
+
+
FetchedRecordsController Concurrency
+
+
A fetched records controller can not be used from any thread.
+
+
When the database itself can be read and modified from any thread, fetched records controllers must be used from the main thread. Record changes are also notified on the main thread.
+
+
Change callbacks are invoked asynchronously. This means that changes made from the main thread are not immediately notified. When you need to take immediate action, force the controller to refresh immediately with its performFetch method. In this case, changes callbacks are not called:
+
// Change database on the main thread:
+trydbQueue.write{dbin
+ tryPlayer(...).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.
+
Avoiding SQL Injection
+
+
SQL injection is a technique that lets an attacker nuke your database.
Here is an example of code that is vulnerable to SQL injection:
+
// BAD BAD BAD
+letid=1
+letname=textField.text
+trydbQueue.write{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 raw SQL queries:
+
letname=textField.text
+trydbQueue.write{dbin
+ // Good
+ trydb.execute(
+ "UPDATE students SET name = ? WHERE id = ?",
+ arguments:[name,id])
+
+ // Just as good
+ trydb.execute(
+ "UPDATE students SET name = :name WHERE id = :id",
+ arguments:["name":name,"id":id])
+}
+
+
+
When you use records and the query interface, GRDB always prevents SQL injection for you:
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.
do{
+ trydb.execute(
+ "INSERT INTO pet (masterId, name) VALUES (?, ?)",
+ arguments:[1,"Bobby"])
+}catchleterrorasDatabaseError{
+ // The SQLite error code: 19 (SQLITE_CONSTRAINT)
+ error.resultCode
+
+ // The extended error code: 787 (SQLITE_CONSTRAINT_FOREIGNKEY)
+ error.extendedResultCode
+
+ // The eventual SQLite message: FOREIGN KEY constraint failed
+ error.message
+
+ // The eventual erroneous SQL query
+ // "INSERT INTO pet (masterId, name) VALUES (?, ?)"
+ error.sql
+
+ // Full error description:
+ // "SQLite error 19 with statement `INSERT INTO pet (masterId, name)
+ // VALUES (?, ?)` arguments [1, "Bobby"]: FOREIGN KEY constraint failed""
+ error.description
+}
+
+
+
SQLite uses codes to distinguish between various errors:
+
do{
+ try...
+}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 PersistableRecord protocol, in a single case: when the update method could not find any row to update:
+
do{
+ tryplayer.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["name"]
+
+
+
Solution: fix the contents of the database, use NOT NULL constraints, or load an optional:
+
letname:String?=row["name"]
+
+
Conversion from database value to Swift type fails:
+
// fatal error: could not convert "Mom’s birthday" to Date.
+letdate:Date=row["date"]
+
+// fatal error: could not convert "" to URL.
+leturl:URL=row["url"]
+
+
+
Solution: fix the contents of the database, or use DatabaseValue to handle all possible cases:
+
letdbValue:DatabaseValue=row["date"]
+ifdbValue.isNull{
+ // Handle NULL
+}elseifletdate=Date.fromDatabaseValue(dbValue){
+ // Handle valid date
+}else{
+ // Handle invalid date
+}
+
+
The database can’t guarantee that the code does what it says:
+
// fatal error: table player has no unique index on column email
+tryPlayer.deleteOne(db,key:["email":"arthur@example.com"])
+
+
+
Solution: add a unique index to the player.email column, or use the deleteAll method to make it clear that you may delete more than one row:
// fatal error: Database methods are not reentrant.
+dbQueue.write{dbin
+ dbQueue.write{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[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:
:warning: Warning: Database.logError must be set before any database connection is opened. This includes the connections that your application opens with GRDB, but also connections opened by other tools, such as third-party libraries. Setting it after a connection has been opened is an SQLite misuse, and has no effect.
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:
+
Player.select(nameColumn.uppercased)
+
+
String Comparison
+
+
SQLite compares strings in many occasions: when you sort rows according to a string column, or when you use a comparison operator such as = and <=.
+
+
The comparison result comes from a collating function, or collation. SQLite comes with three built-in collations that do not support Unicode: binary, nocase, and rtrim.
+
+
GRDB comes with five extra collations that leverage unicode-aware comparisons based on the standard Swift String comparison functions and operators:
+
+
+
unicodeCompare (uses the built-in <= and == Swift operators)
+
caseInsensitiveCompare
+
localizedCaseInsensitiveCompare
+
localizedCompare
+
localizedStandardCompare
+
+
+
A collation can be applied to a table column. All comparisons involving this column will then automatically trigger the comparison function:
+
trydb.create(table:"player"){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)
+}
+
+// Players are sorted in a localized case insensitive way:
+letplayers=tryPlayer.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
+letplayers=tryPlayer.fetchAll(db,
+ "SELECT * FROM player ORDER BY name COLLATE \(collation.name))")
+letplayers=tryPlayer.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.shared)
+
+
Data Protection
+
+
Data Protection lets you protect files so that they are encrypted and unavailable until the device is unlocked.
+
+
Data protection can be enabled globally for all files created by an application.
+
+
You can also explicitly protect a database, by configuring its enclosing directory. This will not only protect the database file, but also all temporary files created by SQLite (including the persistent .shm and .wal files created by database pools).
+
+
For example, to explicitly use complete protection:
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.
+
DatabaseSnapshot opens a single read-only database connection on an unchanging database content, and (currently) serializes all database accesses
+
+
+
All foster application safety: regardless of the concurrency mode you choose, GRDB provides you with the same guarantees, as long as you follow three rules.
+
+
+
:bowtie: Guarantee 1: writes are always serialized. At every moment, there is no more than a single thread that is writing into the database.
+
+
+
Database writes always happen in a unique serial dispatch queue, named the writer protected dispatch queue.
+
+
:bowtie: Guarantee 2: reads are always isolated. This means that they are guaranteed an immutable view of the last committed state of the database, and that you can perform subsequent fetches without fearing eventual concurrent writes to mess with your application logic:
+
trydbPool.read{dbin// or dbQueue.read
+ // Guaranteed to be equal
+ letcount1=tryPlayer.fetchCount(db)
+ letcount2=tryPlayer.fetchCount(db)
+}
+
+
+
+
In database queues, reads happen in the same protected dispatch queue as writes: isolation is just a consequence of the serialization of database accesses
: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 a bad idea. Do share a single connection instead.
+
+
See the Demo Application for an sample app that sets up a single database queue that is available throughout the application.
+
+
If there are several instances of database queues or pools that write in the same database, a multi-threaded application will eventually face database is locked errors. See Dealing with External Connections.
+
// SAFE CONCURRENCY
+funcfetchCurrentUser(_db:Database)throws->User?{
+ returntryUser.fetchOne(db)
+}
+// dbQueue is a singleton defined somewhere in your app
+letuser=trydbQueue.read{dbin// or dbPool.read
+ tryfetchCurrentUser(db)
+}
+
+// UNSAFE CONCURRENCY
+// This method fails when some other thread is currently writing into
+// the database.
+funccurrentUser()throws->User?{
+ letdbQueue=tryDatabaseQueue(...)
+ returntrydbQueue.read{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 (or use snapshots).
+
+
Database access methods isolate your groups of related statements against eventual database updates performed by other threads, and guarantee a consistent view of the database. This isolation is only guaranteed inside the closure argument of those methods. Two consecutive calls do not guarantee isolation:
+
// SAFE CONCURRENCY
+trydbPool.read{dbin// or dbQueue.read
+ // Guaranteed to be equal:
+ letcount1=tryPlace.fetchCount(db)
+ letcount2=tryPlace.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{dbintryPlace.fetchCount(db)}
+letcount2=trydbPool.read{dbintryPlace.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
+ tryPlace(...).insert(db)
+ letcount=tryPlace.fetchCount(db)
+}
+
+// UNSAFE CONCURRENCY
+// The count may be zero because some other thread may have performed
+// a deletion between the two blocks:
+trydbPool.write{dbintryPlace(...).insert(db)}
+letcount=trydbPool.read{dbintryPlace.fetchCount(db)}
+
+
+
On that last example, see Advanced DatabasePool if you look after extra performance.
+
:point_up: Rule 3: When you perform several modifications of the database that temporarily put the database in an inconsistent state, make sure those modifications are grouped within a transaction.
+
// SAFE CONCURRENCY
+trydbPool.write{dbin// or dbQueue.write
+ tryCredit(destinationAccout,amount).insert(db)
+ tryDebit(sourceAccount,amount).insert(db)
+}
+
+// SAFE CONCURRENCY
+trydbPool.writeInTransaction{dbin// or dbQueue.inTransaction
+ tryCredit(destinationAccout,amount).insert(db)
+ tryDebit(sourceAccount,amount).insert(db)
+ return.commit
+}
+
+// UNSAFE CONCURRENCY
+trydbPool.writeWithoutTransaction{dbin
+ tryCredit(destinationAccout,amount).insert(db)
+ // <- Concurrent dbPool.read sees a partial db update here
+ tryDebit(sourceAccount,amount).insert(db)
+}
+
+
+
Without transaction, DatabasePool.read { ... } may see the first statement, but not the second, and access a database where the balance of accounts is not zero. A highly bug-prone situation.
+
+
So do use transactions in order to guarantee database consistency accross your application threads: that’s what they are made for.
Database queues serialize all database accesses, reads, and writes. There is never more than one thread that uses the database. In the image below, we see how three threads can see the database as time passes:
+
+
+
+
Database pools also serialize all writes. But they allow concurrent reads and writes, and isolate reads so that they don’t see changes performed by other threads. This gives a very different picture:
+
+
+
+
See how, with database pools, two reads can see different database states at the same time.
+
+
For more information about database pools, grab information about SQLite WAL mode and snapshot isolation. See Database Observation when you look after automatic notifications of database changes.
+
Advanced DatabasePool
+
+
Database pools are very concurrent, since all reads can run in parallel, and can even run during write operations. But writes are still serialized: at any given point in time, there is no more than a single thread that is writing into the database.
+
+
When your application modifies the database, and then reads some value that depends on those modifications, you may want to avoid locking the writer queue longer than necessary:
+
trydbPool.write{dbin
+ // Increment the number of players
+ tryPlayer(...).insert(db)
+
+ // Read the number of players. The writer queue is still locked :-(
+ letcount=tryPlayer.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 players
+ tryPlayer(...).insert(db)
+}
+// <- other threads can write in the database here
+trydbPool.read{dbin
+ // Read some random value :-(
+ letcount=tryPlayer.fetchCount(db)
+}
+
+
+
The correct solution is the concurrentRead method, which must be called from within a write block, outside of any transaction.
+
+
concurrentRead returns a future value which you consume on any dispatch queue, with the wait() method:
+
// CORRECT
+letfutureCount:Future<Int>=trydbPool.writeWithoutTransaction{dbin
+ // increment the number of players
+ tryPlayer(...).insert(db)
+
+ // <- not in a transaction here
+ letfutureCount=dbPool.concurrentRead{db
+ returntryPlayer.fetchCount(db)
+ }
+ returnfutureCount
+}
+// <- The writer queue has been unlocked :-)
+
+// Wait for the player count
+letcount:Int=tryfutureCount.wait()
+
+
+
concurrentRead 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.
+
+
The closure can run concurrently with eventual updates performed after concurrentRead: those updates won’t be visible from within the closure. In the example below, the number of players is guaranteed to be non-zero, even though it is fetched concurrently with the player deletion:
+
trydbPool.writeWithoutTransaction{dbin
+ // Increment the number of players
+ tryPlayer(...).insert(db)
+
+ letfutureCount=dbPool.concurrentRead{db
+ // Guaranteed to be non-zero
+ returntryPlayer.fetchCount(db)
+ }
+
+ tryPlayer.deleteAll(db)
+}
+
+
+
Transaction Observers can also use concurrentRead in their databaseDidCommit method in order to process database changes without blocking other threads that want to write into the database.
+
Database Snapshots
+
+
A database snapshot sees an unchanging database content, as it existed at the moment it was created.
+
+
Unchanging means that a snapshot never sees any database modifications during all its lifetime. And yet it doesn’t prevent database updates. This magic is made possible by SQLite’s WAL mode (see Isolation In SQLite).
You can create as many snapshots as you need, regardless of the maximum number of readers in the pool. A snapshot database connection is closed when the snapshot gets deallocated.
+
+
A snapshot can be used from any thread. Its read methods is synchronous, and blocks the current thread until your database statements are executed:
+
// Read values:
+trysnapshot.read{dbin
+ letplayers=tryPlayer.fetchAll(db)
+ letplayerCount=tryPlayer.fetchCount(db)
+}
+
+// Extract a value from the database:
+letplayerCount=trysnapshot.read{dbin
+ tryPlayer.fetchCount(db)
+}
+
+
+
When you want to control the latest committed changes seen by a snapshot, create it from the pool’s writer protected dispatch queue, outside of any transaction:
+
letsnapshot1=trydbPool.writeWithoutTransaction{db->DatabaseSnapshotin
+ trydb.inTransaction{
+ // delete all players
+ tryPlayer.deleteAll()
+ return.commit
+ }
+
+ // <- not in a transaction here
+ returndbPool.makeSnapshot()
+}
+// <- Other threads may modify the database here
+letsnapshot2=trydbPool.makeSnapshot()
+
+trysnapshot1.read{dbin
+ // Guaranteed to be zero
+ tryPlayer.fetchCount(db)
+}
+
+trysnapshot2.read{dbin
+ // Could be anything
+ tryPlayer.fetchCount(db)
+}
+
+
+
+
:point_up: Note: snapshots currently serialize all database accesses. In the future, snapshots may allow concurrent reads.
+
+
DatabaseWriter and DatabaseReader Protocols
+
+
Both DatabaseQueue and DatabasePool adopt the DatabaseReader and DatabaseWriter protocols. DatabaseSnapshot adopts DatabaseReader only.
+
+
These protocols provide a unified API that let you write generic code that targets all concurrency modes. They fuel, for example:
Caution: DatabaseReader and DatabaseWriter only provide the smallest common guarantees. They don’t erase the differences between queues, pools, and snapshots. See for example Differences between Database Queues and Pools.
+
Unsafe Concurrency APIs
+
+
Database queues, pools, snapshots, as well as their common protocols DatabaseReader and DatabaseWriter provide unsafe APIs. Unsafe APIs lift concurrency guarantees, and allow advanced yet unsafe patterns.
+
+
+
unsafeRead
+
+
The unsafeRead method is synchronous, and blocks the current thread until your database statements are executed in a protected dispatch queue. GRDB does just the bare minimum to provide a database connection that can read.
+
+
When used on a database pool, reads are no longer isolated:
+
dbPool.unsafeRead{dbin
+ // Those two values may be different because some other thread
+ // may have inserted or deleted a player between the two requests:
+ letcount1=tryPlayer.fetchCount(db)
+ letcount2=tryPlayer.fetchCount(db)
+}
+
+
+
When used on a database queue, the closure argument is allowed to write in the database.
+
unsafeReentrantRead
+
+
The unsafeReentrantRead behaves just as unsafeRead (see above), and allows reentrant calls:
+
dbPool.read{db1in
+ // No "Database methods are not reentrant" fatal error:
+ dbPool.unsafeReentrantRead{db2in
+ dbPool.unsafeReentrantRead{db3in
+ ...
+ }
+ }
+}
+
+
+
Reentrant database accesses make it very easy to break the second safety rule, which says: group related statements within a single call to a DatabaseQueue or DatabasePool database access method.. Using a reentrant method is pretty much likely the sign of a wrong application architecture that needs refactoring.
+
+
There is a single valid use case for reentrant methods, which is when you are unable to control database access scheduling.
+
unsafeReentrantWrite
+
+
The unsafeReentrantWrite method is synchronous, and blocks the current thread until your database statements are executed in a protected dispatch queue. Writes are serialized: eventual concurrent database updates are postponed until the block has executed.
+
+
Reentrant calls are allowed:
+
dbQueue.write{db1in
+ // No "Database methods are not reentrant" fatal error:
+ dbQueue.unsafeReentrantWrite{db2in
+ dbQueue.unsafeReentrantWrite{db3in
+ ...
+ }
+ }
+}
+
+
+
Reentrant database accesses make it very easy to break the second safety rule, which says: group related statements within a single call to a DatabaseQueue or DatabasePool database access method.. Using a reentrant method is pretty much likely the sign of a wrong application architecture that needs refactoring.
+
+
There is a single valid use case for reentrant methods, which is when you are unable to control database access scheduling.
+
+
Dealing with External Connections
+
+
The first rule of GRDB is:
+
+
+
Rule 1: Have a unique instance of DatabaseQueue or DatabasePool connected to any database file.
+
+
+
This means that dealing with external connections is not a focus of GRDB. Guarantees of GRDB may or may not hold as soon as some external connection modifies a database.
+
+
If you absolutely need multiple connections, then:
You’ll find below general advice when you do look after performance:
+
+
+
Focus
+
Know your platform
+
Use transactions
+
Don’t do useless work
+
Learn about SQL strengths and weaknesses
+
Avoid strings & dictionaries
+
+
Performance tip: focus
+
+
You don’t know which part of your program needs improvement until you have run a benchmarking tool.
+
+
Don’t make any assumption, avoid optimizing code too early, and use Instruments.
+
Performance tip: know your platform
+
+
If your application processes a huge JSON file and inserts thousands of rows in the database right from the main thread, it will quite likely become unresponsive, and provide a sub-quality user experience.
+
+
If not done yet, read the Concurrency Programming Guide and learn how to perform heavy computations without blocking your application.
+
+
Most GRBD APIs are synchronous. Spawning them into parallel queues is as easy as:
+
DispatchQueue.global().async{
+ dbQueue.write{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:
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
+letplayers=tryPlayer.order(scoreColumn.desc).fetchAll(db)
+lethallOfFame=players.prefix(5)
+
+// Better way
+lethallOfFame=tryPlayer.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 author
+letauthors=tryAuthor.fetchAll(db)
+forauthorinauthors{
+ // SELECT COUNT(*) FROM book WHERE authorId = ...
+ author.bookCount=tryBook.filter(authorIdColumn==author.id).fetchCount(db)
+}
+
+
+
Instead, perform a single query:
+
letsql="""
+ SELECT author.*, COUNT(book.id) AS bookCount
+ FROM author
+ LEFT JOIN book ON book.authorId = author.id
+ GROUP BY author.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
+forplayerinplayers{
+ tryplayer.insert(db)
+}
+
+// Prepared statement
+letinsertStatement=db.prepareStatement("INSERT INTO player (name, email) VALUES (?, ?)")
+forplayerinplayers{
+ // Only use the unsafe arguments setter if you are sure that you provide
+ // all statement arguments. A mistake can store unexpected values in
+ // the database.
+ insertStatement.unsafeSetArguments([player.name,player.email])
+ tryinsertStatement.execute()
+}
+
This question assumes that your application has to create a new database from scratch. If your app has to open an existing database that is embedded inside your application as a resource, see How do I open a database stored as a resource of my application? instead.
+
+
The database has to be stored in a valid place where it can be created and modified. For example, in the Application Support directory:
If the application should modify the database, you need to copy it to a place where it can be modified. For example, in the Application Support directory. Only then, open a connection:
Database connections are managed by database queues and pools. A connection is closed when its database queue or pool is deallocated, and all usages of this connection are completed.
+
+
Database accesses that run in background threads postpone the closing of connections.
+
How do I print a request as SQL?
+
+
When you want to debug a request that does not deliver the expected results, you may want to print the SQL that is actually executed.
+
+
You can turn your request into a SQLRequest instance:
+
trydbQueue.read{dbin
+ letrequest=Wine
+ .filter(Column("origin")=="Burgundy")
+ .order(Column("price")
+
+ letsqlRequest=trySQLRequest(db,request:request)
+ print(sqlRequest.sql)
+ // Prints SELECT * FROM wine WHERE origin = ? ORDER BY price
+ print(sqlRequest.arguments)
+ // Prints ["Burgundy"]
+}
+
+
+
Another option is to setup a tracing function that will print out all SQL requests executed by your application. You provide the trace function when you connect to the database:
+
varconfig=Configuration()
+config.trace={print($0)}// Prints all SQL statements
+letdbQueue=tryDatabaseQueue(path:dbPath,configuration:config)
+
+trydbQueue.read{dbin
+ letwines=Wine
+ .filter(Column("origin")=="Burgundy")
+ .order(Column("price")
+ .fetchAll(db)
+ // Prints SELECT * FROM wine WHERE origin = 'Burgundy' ORDER BY price
+}
+
+
Generic parameter ‘T’ could not be inferred
+
+
You may get this error when using the read and write methods of database queues and pools:
+
// Generic parameter 'T' could not be inferred
+letx=trydbQueue.read{dbin
+ letresult=tryString.fetchOne(db,...)
+ returnresult
+}
+
This error can also be prevented altogether by using a more relaxed file protection.
+
What Are Experimental Features?
+
+
Since GRDB 1.0, all backwards compatibility guarantees of semantic versioning apply: no breaking change will happen until the next major version of the library.
+
+
There is an exception, though: experimental features, marked with the **:fire: EXPERIMENTAL** badge. Those are advanced features that are too young, or lack user feedback. They are not stabilized yet.
+
+
Those experimental features are not protected by semantic versioning, and may break between two minor releases of the library. To help them becoming stable, your feedback is greatly appreciated.
Creates a request with a full-text predicate added to the eventual","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB21QueryInterfaceRequestVA2A11TableRecordRzlE9including8optionalACyxGqd___t16OriginRowDecoderQyd__RszAA11AssociationRd__lF":{"name":"including(optional:)","abstract":"
Creates a request that includes an association. The columns of the","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB21QueryInterfaceRequestVA2A11TableRecordRzlE9including8requiredACyxGqd___t16OriginRowDecoderQyd__RszAA11AssociationRd__lF":{"name":"including(required:)","abstract":"
Creates a request that includes an association. The columns of the","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB21QueryInterfaceRequestVA2A11TableRecordRzlE7joining8optionalACyxGqd___t16OriginRowDecoderQyd__RszAA11AssociationRd__lF":{"name":"joining(optional:)","abstract":"
Creates a request that includes an association. The columns of the","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB21QueryInterfaceRequestVA2A11TableRecordRzlE7joining8requiredACyxGqd___t16OriginRowDecoderQyd__RszAA11AssociationRd__lF":{"name":"joining(required:)","abstract":"
Creates a request that includes an association. The columns of the","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB21QueryInterfaceRequestVA2A11TableRecordRzlE9annotated4withACyxGAA20AssociationAggregateVyxGd_tF":{"name":"annotated(with:)","abstract":"
Creates a request which appends aggregates to the current selection.
Creates a request which appends the provided aggregate predicate to","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB12FetchRequestP10RowDecoderQa":{"name":"RowDecoder","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB21QueryInterfaceRequestV6selectyACyxGSayAA13SQLSelectable_pGF":{"name":"select(_:)","abstract":"
Creates a request which selects selection, and fetches values of","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB21QueryInterfaceRequestV6select_2asACyqd__GAA13SQLSelectable_pd_qd__mtlF":{"name":"select(_:as:)","abstract":"
Creates a request which selects selection, and fetches values of","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB21QueryInterfaceRequestV6select3sql9arguments2asACyqd__GSS_AA18StatementArgumentsVSgqd__mtlF":{"name":"select(sql:arguments:as:)","abstract":"
Creates a request which selects sql, and fetches values of","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB21QueryInterfaceRequestV9annotated4withACyxGSayAA13SQLSelectable_pG_tF":{"name":"annotated(with:)","abstract":"
Creates a request with the provided predicate promise added to the","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB21QueryInterfaceRequestV5groupyACyxGSayAA14SQLExpressible_pGAA8DatabaseCKcF":{"name":"group(_:)","abstract":"
Creates a request grouped according to expressions promise.
Creates a request with the provided predicate added to the","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB21QueryInterfaceRequestV5orderyACyxGSayAA15SQLOrderingTerm_pGAA8DatabaseCKcF":{"name":"order(_:)","abstract":"
Creates a request with the provided orderings promise.
Creates a request that allows you to define expressions that target","parent_name":"QueryInterfaceRequest"},"Structs/QueryInterfaceRequest.html#/s:4GRDB21QueryInterfaceRequestV02asD02ofACyqd__Gqd__m_tlF":{"name":"asRequest(of:)","abstract":"
Returns an aggregate that is selected in a column named like the given","parent_name":"AssociationAggregate"},"Structs/DatabaseMigrator.html#/s:4GRDB16DatabaseMigratorV05eraseB14OnSchemaChangeSbvp":{"name":"eraseDatabaseOnSchemaChange","abstract":"
When the eraseDatabaseOnSchemaChange flag is true, the migrator will","parent_name":"DatabaseMigrator"},"Structs/DatabaseMigrator.html#/s:4GRDB16DatabaseMigratorVACycfc":{"name":"init()","abstract":"
Iterate migrations in the same order as they were registered. If a","parent_name":"DatabaseMigrator"},"Structs/DatabaseMigrator.html#/s:4GRDB16DatabaseMigratorV7migrate_4upToyAA0B6Writer_p_SStKF":{"name":"migrate(_:upTo:)","abstract":"
Iterate migrations in the same order as they were registered, up to the","parent_name":"DatabaseMigrator"},"Structs/DatabaseMigrator.html#/s:4GRDB16DatabaseMigratorV17appliedMigrations2inShySSGAA0B6Reader_p_tKF":{"name":"appliedMigrations(in:)","abstract":"
Creates a pattern that matches any token found in the input string;","parent_name":"FTS5Pattern"},"Structs/FTS5Pattern.html#/init(matchingAllTokensIn:)":{"name":"init(matchingAllTokensIn:)","abstract":"
Creates a pattern that matches all tokens found in the input string;","parent_name":"FTS5Pattern"},"Structs/FTS5Pattern.html#/init(matchingPhrase:)":{"name":"init(matchingPhrase:)","abstract":"
Creates a pattern that matches a contiguous string; returns nil if no","parent_name":"FTS5Pattern"},"Structs/FTS5Pattern.html#/init(matchingPrefixPhrase:)":{"name":"init(matchingPrefixPhrase:)","abstract":"
Creates a pattern that matches a contiguous string prefix; returns","parent_name":"FTS5Pattern"},"Structs/FTS5Pattern.html#/databaseValue":{"name":"databaseValue","abstract":"
Returns a value that can be stored in the database.
Creates a FTS4 module suitable for the Database","parent_name":"FTS4"},"Structs/FTS4.html#/s:4GRDB4FTS4V10moduleNameSSvp":{"name":"moduleName","abstract":"
Creates a pattern from a raw pattern string; throws DatabaseError on","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/init(matchingAnyTokenIn:)":{"name":"init(matchingAnyTokenIn:)","abstract":"
Creates a pattern that matches any token found in the input string;","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/init(matchingAllTokensIn:)":{"name":"init(matchingAllTokensIn:)","abstract":"
Creates a pattern that matches all tokens found in the input string;","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/init(matchingPhrase:)":{"name":"init(matchingPhrase:)","abstract":"
Creates a pattern that matches a contiguous string; returns nil if no","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/s:4GRDB11FTS3PatternV18matchingAnyTokenInACSgSS_tcfc":{"name":"init(matchingAnyTokenIn:)","abstract":"
Creates a pattern that matches any token found in the input string;","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/s:4GRDB11FTS3PatternV19matchingAllTokensInACSgSS_tcfc":{"name":"init(matchingAllTokensIn:)","abstract":"
Creates a pattern that matches all tokens found in the input string;","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/s:4GRDB11FTS3PatternV14matchingPhraseACSgSS_tcfc":{"name":"init(matchingPhrase:)","abstract":"
Creates a pattern that matches a contiguous string; returns nil if no","parent_name":"FTS3Pattern"},"Structs/FTS3Pattern.html#/s:4GRDB11FTS3PatternV13databaseValueAA08DatabaseE0Vvp":{"name":"databaseValue","abstract":"
Returns a value that can be stored in the database.
Returns an FTS3Pattern initialized from dbValue, if it contains","parent_name":"FTS3Pattern"},"Structs/FTS3.html#/s:4GRDB4FTS3VACycfc":{"name":"init()","abstract":"
Creates a FTS3 module suitable for the Database","parent_name":"FTS3"},"Structs/FTS3.html#/s:4GRDB4FTS3V10moduleNameSSvp":{"name":"moduleName","abstract":"
1 for inserts, updates, or deletes invoked by top-level triggers;","parent_name":"DatabasePreUpdateEvent"},"Structs/DatabasePreUpdateEvent.html#/initialRowID":{"name":"initialRowID","abstract":"
The initial rowID of the row being changed for .Update and .Delete changes,","parent_name":"DatabasePreUpdateEvent"},"Structs/DatabasePreUpdateEvent.html#/finalRowID":{"name":"finalRowID","abstract":"
The final rowID of the row being changed for .Update and .Insert changes,","parent_name":"DatabasePreUpdateEvent"},"Structs/DatabasePreUpdateEvent.html#/initialDatabaseValues":{"name":"initialDatabaseValues","abstract":"
Returns a DatabaseDateComponents if dbValue contains a","parent_name":"DatabaseDateComponents"},"Structs/StatementArguments.html#/s:4GRDB18StatementArgumentsV7isEmptySbvp":{"name":"isEmpty","abstract":"
Creates statement arguments from any array. The result is nil unless all","parent_name":"StatementArguments"},"Structs/StatementArguments.html#/s:4GRDB18StatementArgumentsVyACSDySSAA24DatabaseValueConvertible_pSgGcfc":{"name":"init(_:)","abstract":"
Creates statement arguments from a sequence of (key, value) dictionary,","parent_name":"StatementArguments"},"Structs/StatementArguments.html#/s:4GRDB18StatementArgumentsVyACxcSTRzSS_AA24DatabaseValueConvertible_pSgt7ElementRtzlufc":{"name":"init(_:)","abstract":"
Creates statement arguments from a sequence of (key, value) pairs, such","parent_name":"StatementArguments"},"Structs/StatementArguments.html#/s:4GRDB18StatementArgumentsVyACSgSDys11AnyHashableVypGcfc":{"name":"init(_:)","abstract":"
Creates statement arguments from [AnyHashable: Any].
Creates a new StatementArguments by extending the left-hand size","parent_name":"StatementArguments"},"Structs/StatementArguments.html#/s:4GRDB18StatementArgumentsV2apoiyA2C_ACtFZ":{"name":"&+(_:_:)","abstract":"
Creates a new StatementArguments by extending the left-hand size","parent_name":"StatementArguments"},"Structs/StatementArguments.html#/s:4GRDB18StatementArgumentsV2peoiyyACz_ACtFZ":{"name":"+=(_:_:)","abstract":"
Extends the left-hand size arguments with the right-hand side arguments.
Creates a SuffixRowAdapter that hides all columns before the","parent_name":"SuffixRowAdapter"},"Structs/ColumnMapping.html#/s:4GRDB13ColumnMappingVyACSDyS2SGcfc":{"name":"init(_:)","abstract":"
Creates a ColumnMapping with a dictionary from mapped column names to","parent_name":"ColumnMapping"},"Structs/EmptyRowAdapter.html#/s:4GRDB15EmptyRowAdapterVACycfc":{"name":"init()","abstract":"
Creates a request from an SQL string, optional arguments, and","parent_name":"SQLRequest"},"Structs/SQLRequest.html#/s:4GRDB10SQLRequestV_7request6cachedACyxGAA8DatabaseC_qd__SbtKc10RowDecoderQyd__RszAA12FetchRequestRd__lufc":{"name":"init(_:request:cached:)","abstract":"
Creates an SQL request from any other fetch request.
Creates a request whose prepare() method wraps and forwards","parent_name":"AnyFetchRequest"},"Structs/AdaptedFetchRequest.html#/s:4GRDB12FetchRequestP10RowDecoderQa":{"name":"RowDecoder","parent_name":"AdaptedFetchRequest"},"Structs/DatabaseValue/Storage.html#/s:4GRDB13DatabaseValueV7StorageO4nullyA2EmF":{"name":"null","abstract":"
The region that covers the full database: all columns and all rows","parent_name":"DatabaseRegion"},"Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionVACycfc":{"name":"init()","abstract":"
Returns whether the content in the region would be impacted if the","parent_name":"DatabaseRegion"},"Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF":{"name":"isModified(by:)","abstract":"
Returns whether the content in the region is impacted by this event.
The SQLite error code (see","parent_name":"DatabaseError"},"Structs/DatabaseError.html#/s:4GRDB13DatabaseErrorV18extendedResultCodeAA0eF0Vvp":{"name":"extendedResultCode","abstract":"
The SQLite extended error code (see","parent_name":"DatabaseError"},"Structs/DatabaseError.html#/s:4GRDB13DatabaseErrorV7messageSSSgvp":{"name":"message","abstract":"
A result code limited to the least significant 8 bits of the receiver.","parent_name":"ResultCode"},"Structs/ResultCode.html#/s:4GRDB10ResultCodeV2teoiySbAC_ACtFZ":{"name":"~=(_:_:)","abstract":"
Returns true if the code on the left matches the code on the right.
If false, it is a programmer error to leave a transaction opened at the","parent_name":"Configuration"},"Structs/Configuration.html#/s:4GRDB13ConfigurationV8busyModeAA8DatabaseC04BusyD0Ovp":{"name":"busyMode","abstract":"
The maximum number of concurrent readers (applies to database","parent_name":"Configuration"},"Structs/Configuration.html#/s:4GRDB13ConfigurationVACycfc":{"name":"init()","abstract":"
StatementArguments provide values to argument placeholders in raw"},"Structs/DatabaseDateComponents.html":{"name":"DatabaseDateComponents","abstract":"
DatabaseDateComponents reads and stores DateComponents in the database.
Use persistence containers in the encode(to:) method of your"},"Structs/PersistenceConflictPolicy.html":{"name":"PersistenceConflictPolicy","abstract":"
The MutablePersistableRecord protocol uses this type in order to handle SQLite"},"Protocols/PersistableRecord.html#/s:4GRDB17PersistableRecordP9didInsert4with3forys5Int64V_SSSgtF":{"name":"didInsert(with:for:)","abstract":"
Notifies the record that it was succesfully inserted.
Executes an INSERT or an UPDATE statement so that self is saved in","parent_name":"PersistableRecord"},"Protocols/PersistableRecord.html#/s:4GRDB17PersistableRecordPAAE13performInsertyyAA8DatabaseCKF":{"name":"performInsert(_:)","abstract":"
Don’t invoke this method directly: it is an internal method for types","parent_name":"PersistableRecord"},"Protocols/PersistableRecord.html#/s:4GRDB17PersistableRecordPAAE11performSaveyyAA8DatabaseCKF":{"name":"performSave(_:)","abstract":"
Don’t invoke this method directly: it is an internal method for types","parent_name":"PersistableRecord"},"Protocols/FetchableRecord.html#/s:4GRDB15FetchableRecordP3rowxAA3RowC_tcfc":{"name":"init(row:)","abstract":"
When the FetchableRecord type also adopts the standard Decodable","parent_name":"FetchableRecord"},"Protocols/FetchableRecord.html#/s:4GRDB15FetchableRecordP19databaseJSONDecoder3for10Foundation0E0CSS_tFZ":{"name":"databaseJSONDecoder(for:)","abstract":"
When the FetchableRecord type also adopts the standard Decodable","parent_name":"FetchableRecord"},"Protocols/FetchableRecord.html#/s:4GRDB15FetchableRecordP28databaseDateDecodingStrategyAA08DatabaseefG0OvpZ":{"name":"databaseDateDecodingStrategy","abstract":"
When the FetchableRecord type also adopts the standard Decodable","parent_name":"FetchableRecord"},"Protocols/FetchableRecord.html#/s:4GRDB15FetchableRecordPA2A05TableC0RzrlE11fetchCursoryAA0cF0CyxGAA8DatabaseCKFZ":{"name":"fetchCursor(_:)","abstract":"
A cursor over all records fetched from the database.
Returns a cursor over records identified by the provided unique keys","parent_name":"FetchableRecord"},"Protocols/FetchableRecord.html#/s:4GRDB15FetchableRecordPA2A05TableC0RzrlE8fetchAll_4keysSayxGAA8DatabaseC_SaySDySSAA0H16ValueConvertible_pSgGGtKFZ":{"name":"fetchAll(_:keys:)","abstract":"
Returns an array of records identified by the provided unique keys","parent_name":"FetchableRecord"},"Protocols/FetchableRecord.html#/s:4GRDB15FetchableRecordPA2A05TableC0RzrlE8fetchOne_3keyxSgAA8DatabaseC_SDySSAA0H16ValueConvertible_pSgGSgtKFZ":{"name":"fetchOne(_:key:)","abstract":"
Returns a single record identified by a unique key (the primary key or","parent_name":"FetchableRecord"},"Protocols/FetchableRecord.html#/s:4GRDB15FetchableRecordPAAE11fetchCursor_9arguments7adapterAA0cE0CyxGAA15SelectStatementC_AA0I9ArgumentsVSgAA10RowAdapter_pSgtKFZ":{"name":"fetchCursor(_:arguments:adapter:)","abstract":"
A cursor over records fetched from a prepared statement.
The type of the closure argument in the","parent_name":"VirtualTableModule"},"Protocols/VirtualTableModule.html#/s:4GRDB18VirtualTableModuleP10moduleNameSSvp":{"name":"moduleName","abstract":"
Returns a table definition that is passed as the closure argument in the","parent_name":"VirtualTableModule"},"Protocols/VirtualTableModule.html#/s:4GRDB18VirtualTableModuleP15moduleArguments3for2inSaySSG0C10DefinitionQz_AA8DatabaseCtKF":{"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/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordP25persistenceConflictPolicyAA011PersistencefG0VvpZ":{"name":"persistenceConflictPolicy","abstract":"
The policy that handles SQLite conflicts when records are inserted","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordP6encode2toyAA20PersistenceContainerVz_tF":{"name":"encode(to:)","abstract":"
Executes an INSERT or an UPDATE statement so that self is saved in","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordP6deleteySbAA8DatabaseCKF":{"name":"delete(_:)","abstract":"
Returns true if and only if the primary key matches a row in","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordP24databaseEncodingUserInfoSDys06CodinggH3KeyVypGvpZ":{"name":"databaseEncodingUserInfo","abstract":"
When the PersistableRecord type also adopts the standard Encodable","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordP19databaseJSONEncoder3for10Foundation0F0CSS_tFZ":{"name":"databaseJSONEncoder(for:)","abstract":"
When the PersistableRecord type also adopts the standard Encodable","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordP28databaseDateEncodingStrategyAA08DatabasefgH0OvpZ":{"name":"databaseDateEncodingStrategy","abstract":"
When the PersistableRecord type also adopts the standard Encodable","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordP28databaseUUIDEncodingStrategyAA08DatabasefG0OvpZ":{"name":"databaseUUIDEncodingStrategy","abstract":"
When the PersistableRecord type also adopts the standard Encodable","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordPAAE7request3forAA21QueryInterfaceRequestVy10RowDecoderQyd__Gqd___t06OriginjK0Qyd__RszAA11AssociationRd__lF":{"name":"request(for:)","abstract":"
Creates a request that fetches the associated record(s).
If the record has differences from the other record, executes an UPDATE","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordPAAE14databaseEqualsySbxF":{"name":"databaseEquals(_:)","abstract":"
Returns a boolean indicating whether this record and the other record","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordPAAE15databaseChanges4fromSDySSAA13DatabaseValueVGAaB_p_tF":{"name":"databaseChanges(from:)","abstract":"
A dictionary of values changed from the other record.
Don’t invoke this method directly: it is an internal method for types","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordPAAE13performUpdate_7columnsyAA8DatabaseC_ShySSGtKF":{"name":"performUpdate(_:columns:)","abstract":"
Don’t invoke this method directly: it is an internal method for types","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordPAAE11performSaveyyAA8DatabaseCKF":{"name":"performSave(_:)","abstract":"
Don’t invoke this method directly: it is an internal method for types","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordPAAE13performDeleteySbAA8DatabaseCKF":{"name":"performDelete(_:)","abstract":"
Don’t invoke this method directly: it is an internal method for types","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordPAAE13performExistsySbAA8DatabaseCKF":{"name":"performExists(_:)","abstract":"
Don’t invoke this method directly: it is an internal method for types","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordPAAE9deleteAllySiAA8DatabaseCKFZ":{"name":"deleteAll(_:)","abstract":"
Deletes all records; returns the number of deleted rows.
Delete records identified by their primary keys; returns the number of","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordPAAE9deleteOne_3keySbAA8DatabaseC_qd__SgtKAA0H16ValueConvertibleRd__lFZ":{"name":"deleteOne(_:key:)","abstract":"
Delete a record, identified by its primary key; returns whether a","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordPAAE9deleteAll_4keysSiAA8DatabaseC_SaySDySSAA0H16ValueConvertible_pSgGGtKFZ":{"name":"deleteAll(_:keys:)","abstract":"
Delete records identified by the provided unique keys (primary key or","parent_name":"MutablePersistableRecord"},"Protocols/MutablePersistableRecord.html#/s:4GRDB24MutablePersistableRecordPAAE9deleteOne_3keySbAA8DatabaseC_SDySSAA0H16ValueConvertible_pSgGtKFZ":{"name":"deleteOne(_:key:)","abstract":"
Delete a record, identified by a unique key (the primary key or any key","parent_name":"MutablePersistableRecord"},"Protocols/ColumnExpression.html#/s:4GRDB16ColumnExpressionP4nameSSvp":{"name":"name","abstract":"
Creates a Belongs To association between Self and the","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE7hasMany_3key5usingAA03HasE11AssociationVyxqd__Gqd__m_SSSgAA10ForeignKeyVSgtAaBRd__lFZ":{"name":"hasMany(_:key:using:)","abstract":"
Creates a Has many association between Self and the","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE6hasOne_3key5usingAA03HasE11AssociationVyxqd__Gqd__m_SSSgAA10ForeignKeyVSgtAaBRd__lFZ":{"name":"hasOne(_:key:using:)","abstract":"
Creates a Has one association between Self and the","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE8matchingyAA21QueryInterfaceRequestVyxGAA11FTS3PatternVSgFZ":{"name":"matching(_:)","abstract":"
Returns a QueryInterfaceRequest with a matching predicate.
Creates a request that includes an association. The columns of the","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE9including8requiredAA21QueryInterfaceRequestVyxGqd___t16OriginRowDecoderQyd__RszAA11AssociationRd__lFZ":{"name":"including(required:)","abstract":"
Creates a request that includes an association. The columns of the","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE7joining8optionalAA21QueryInterfaceRequestVyxGqd___t16OriginRowDecoderQyd__RszAA11AssociationRd__lFZ":{"name":"joining(optional:)","abstract":"
Creates a request that includes an association. The columns of the","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE7joining8requiredAA21QueryInterfaceRequestVyxGqd___t16OriginRowDecoderQyd__RszAA11AssociationRd__lFZ":{"name":"joining(required:)","abstract":"
Creates a request that includes an association. The columns of the","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE9annotated4withAA21QueryInterfaceRequestVyxGAA20AssociationAggregateVyxGd_tFZ":{"name":"annotated(with:)","abstract":"
Creates a request with aggregates appended to the selection.
Creates a request which selects selection, and fetches values of","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE6select_2asAA21QueryInterfaceRequestVyqd__GAA13SQLSelectable_pd_qd__mtlFZ":{"name":"select(_:as:)","abstract":"
Creates a request which selects selection, and fetches values of","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE6select3sql9arguments2asAA21QueryInterfaceRequestVyqd__GSS_AA18StatementArgumentsVSgqd__mtlFZ":{"name":"select(sql:arguments:as:)","abstract":"
Creates a request which selects sql, and fetches values of","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE6filteryAA21QueryInterfaceRequestVyxGAA14SQLExpressible_pFZ":{"name":"filter(_:)","abstract":"
Creates a request sorted according to the","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE5orderyAA21QueryInterfaceRequestVyxGSayAA15SQLOrderingTerm_pGFZ":{"name":"order(_:)","abstract":"
Creates a request sorted according to the","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE17orderByPrimaryKeyAA21QueryInterfaceRequestVyxGyFZ":{"name":"orderByPrimaryKey()","abstract":"
Creates a request which fetches limit rows, starting at","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE7aliasedyAA21QueryInterfaceRequestVyxGAA0B5AliasCFZ":{"name":"aliased(_:)","abstract":"
Creates a request that allows you to define expressions that target","parent_name":"TableRecord"},"Protocols/TableRecord.html#/s:4GRDB11TableRecordPAAE10fetchCountySiAA8DatabaseCKFZ":{"name":"fetchCount(_:)","abstract":"
The association key defines how rows fetched from this association","parent_name":"Association"},"Protocols/Association.html#/s:4GRDB11AssociationP6forKeyyxSSF":{"name":"forKey(_:)","abstract":"
Creates an association with the provided predicate promise added to","parent_name":"Association"},"Protocols/Association.html#/s:4GRDB11AssociationPAAE5orderyxSayAA15SQLOrderingTerm_pGAA8DatabaseCKcF":{"name":"order(_:)","abstract":"
Creates an association with the provided orderings promise.
Creates an association that allows you to define expressions that target","parent_name":"Association"},"Protocols/Association.html#/s:4GRDB11AssociationPAAE9including8optionalxqd___tAaBRd__16OriginRowDecoderQyd__0fG0RtzlF":{"name":"including(optional:)","abstract":"
Creates an association that includes another one. The columns of the","parent_name":"Association"},"Protocols/Association.html#/s:4GRDB11AssociationPAAE9including8requiredxqd___tAaBRd__16OriginRowDecoderQyd__0fG0RtzlF":{"name":"including(required:)","abstract":"
Creates an association that includes another one. The columns of the","parent_name":"Association"},"Protocols/Association.html#/s:4GRDB11AssociationPAAE7joining8optionalxqd___tAaBRd__16OriginRowDecoderQyd__0fG0RtzlF":{"name":"joining(optional:)","abstract":"
Creates an association that joins another one. The columns of the","parent_name":"Association"},"Protocols/Association.html#/s:4GRDB11AssociationPAAE7joining8requiredxqd___tAaBRd__16OriginRowDecoderQyd__0fG0RtzlF":{"name":"joining(required:)","abstract":"
Creates an association that joins another one. The columns of the","parent_name":"Association"},"Protocols/FTS5WrapperTokenizer.html#/wrappedTokenizer":{"name":"wrappedTokenizer","abstract":"
Given a token produced by the wrapped tokenizer, notifies customized","parent_name":"FTS5WrapperTokenizer"},"Protocols/FTS5WrapperTokenizer.html#/tokenize(context:tokenization:pText:nText:tokenCallback:)":{"name":"tokenize(context:tokenization:pText:nText:tokenCallback:)","abstract":"
Tokenizes the text described by pText and nText, and","parent_name":"FTS5Tokenizer"},"Protocols/FTS5CustomTokenizer.html#/name":{"name":"name","abstract":"
The name of the tokenizer; should uniquely identify your custom","parent_name":"FTS5CustomTokenizer"},"Protocols/FTS5CustomTokenizer.html#/init(db:arguments:)":{"name":"init(db:arguments:)","abstract":"
Filters database changes that should be notified the the","parent_name":"TransactionObserver"},"Protocols/TransactionObserver.html#/s:4GRDB19TransactionObserverP17databaseDidChange4withyAA13DatabaseEventV_tF":{"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:4GRDB19TransactionObserverP17databaseDidCommityyAA8DatabaseCF":{"name":"databaseDidCommit(_:)","abstract":"
Notifies before a database change (insert, update, or delete)","parent_name":"TransactionObserver"},"Protocols/TransactionObserver.html#/s:4GRDB19TransactionObserverPAAE037stopObservingDatabaseChangesUntilNextB0yyF":{"name":"stopObservingDatabaseChangesUntilNextTransaction()","abstract":"
After this method has been called, the databaseDidChange(with:)","parent_name":"TransactionObserver"},"Protocols/StatementColumnConvertible.html#/s:4GRDB26StatementColumnConvertibleP06sqliteB05indexxs13OpaquePointerV_s5Int32Vtcfc":{"name":"init(sqliteStatement:index:)","abstract":"
Initializes a value from a raw SQLite statement pointer.
Synchronously executes a block that takes a database connection, and","parent_name":"DatabaseWriter"},"Protocols/DatabaseWriter.html#/s:4GRDB14DatabaseWriterP23writeWithoutTransactionyqd__qd__AA0B0CKXEKlF":{"name":"writeWithoutTransaction(_:)","abstract":"
Synchronously executes a block that takes a database connection, and","parent_name":"DatabaseWriter"},"Protocols/DatabaseWriter.html#/s:4GRDB14DatabaseWriterP20unsafeReentrantWriteyqd__qd__AA0B0CKXEKlF":{"name":"unsafeReentrantWrite(_:)","abstract":"
Synchronously executes a block that takes a database connection, and","parent_name":"DatabaseWriter"},"Protocols/DatabaseWriter.html#/s:4GRDB14DatabaseWriterP20readFromCurrentStateyyyAA0B0CcKF":{"name":"readFromCurrentState(_:)","abstract":"
This method is deprecated. Use concurrentRead instead.
Concurrently executes a read-only block that takes a","parent_name":"DatabaseWriter"},"Protocols/DatabaseWriter.html#/s:4GRDB14DatabaseWriterPAAE3add19transactionObserver6extentyAA011TransactionF0_p_AA0B0C0H17ObservationExtentOtF":{"name":"add(transactionObserver:extent:)","abstract":"
Add a transaction observer, so that it gets notified of","parent_name":"DatabaseWriter"},"Protocols/DatabaseWriter.html#/s:4GRDB14DatabaseWriterPAAE6remove19transactionObserveryAA011TransactionF0_p_tF":{"name":"remove(transactionObserver:)","abstract":"
Rebuilds the database file, repacking it into a minimal amount of","parent_name":"DatabaseWriter"},"Protocols/FetchRequest.html#/s:4GRDB12FetchRequestP10RowDecoderQa":{"name":"RowDecoder","abstract":"
The type that tells how fetched database rows should be interpreted.
Returns a tuple that contains a prepared statement that is ready to be","parent_name":"FetchRequest"},"Protocols/FetchRequest.html#/s:4GRDB12FetchRequestP10fetchCountySiAA8DatabaseCKF":{"name":"fetchCount(_:)","abstract":"
Returns the number of rows fetched by the request.
Synchronously executes a read-only block that takes a database","parent_name":"DatabaseReader"},"Protocols/DatabaseReader.html#/s:4GRDB14DatabaseReaderP10unsafeReadyqd__qd__AA0B0CKXEKlF":{"name":"unsafeRead(_:)","abstract":"
Synchronously executes a read-only block that takes a database","parent_name":"DatabaseReader"},"Protocols/DatabaseReader.html#/s:4GRDB14DatabaseReaderP19unsafeReentrantReadyqd__qd__AA0B0CKXEKlF":{"name":"unsafeReentrantRead(_:)","abstract":"
Synchronously executes a block that takes a database connection, and","parent_name":"DatabaseReader"},"Protocols/DatabaseReader.html#/s:4GRDB14DatabaseReaderP3add8functionyAA0B8FunctionC_tF":{"name":"add(function:)","abstract":"
Advances to the next element and returns it, or nil if no next element","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE7isEmptySbyKF":{"name":"isEmpty()","abstract":"
Returns a Boolean value indicating whether the cursor contains","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE8contains5whereS2b7ElementQzKXE_tKF":{"name":"contains(where:)","abstract":"
Returns a Boolean value indicating whether the cursor contains an","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE10enumeratedAA010EnumeratedB0CyxGyF":{"name":"enumerated()","abstract":"
Returns a cursor of pairs (n, x), where n represents a consecutive","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE6filteryAA06FilterB0CyxGSb7ElementQzKcF":{"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:4GRDB6CursorPAAE10compactMapyAA0dB0CyAA06FilterB0CyAFyxqd__SgGGqd__GAI7ElementQzKclF":{"name":"compactMap(_:)","abstract":"
Returns a cursor over the concatenated non-nil results of mapping","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE7flatMapyAA0dB0CyAA06FilterB0CyAFyxqd__SgGGqd__GAI7ElementQzKclF":{"name":"flatMap(_:)","abstract":"
Returns a cursor that skips any initial elements that satisfy","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE9dropFirstyAA04DropdB0CyxGSiF":{"name":"dropFirst(_:)","abstract":"
Returns a cursor containing all but the given number of initial","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE9dropFirstAA04DropdB0CyxGyF":{"name":"dropFirst()","abstract":"
Returns a cursor containing all but the first element of the cursor.
Returns an array containing all but the given number of final","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE8dropLastSay7ElementQzGyKF":{"name":"dropLast()","abstract":"
Returns an array containing all but the last element of the cursor.
Returns a cursor over the concatenated results of mapping transform","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE7flatMapyAA07FlattenB0CyAA0dB0Cyxqd__GGqd__7ElementQzKcAaBRd__lF":{"name":"flatMap(_:)","abstract":"
Returns a cursor over the concatenated results of mapping transform","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE7forEachyyy7ElementQzKXEKF":{"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:4GRDB6CursorPAAE3max2by7ElementQzSgSbAG_AGtKXE_tKF":{"name":"max(by:)","abstract":"
Returns the maximum element in the cursor, using the given predicate as","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE3min2by7ElementQzSgSbAG_AGtKXE_tKF":{"name":"min(by:)","abstract":"
Returns the minimum element in the cursor, using the given predicate as","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE6prefixyAA06PrefixB0CyxGSiF":{"name":"prefix(_:)","abstract":"
Returns a cursor, up to the specified maximum length, containing the","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE6prefix5whileAA011PrefixWhileB0CyxGSb7ElementQzKc_tF":{"name":"prefix(while:)","abstract":"
Returns a cursor of the initial consecutive elements that satisfy","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE6reduceyqd__qd___qd__qd___7ElementQztKXEtKlF":{"name":"reduce(_:_:)","abstract":"
Returns the result of calling the given combining closure with each","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE6reduce4into_qd__qd___yqd__z_7ElementQztKXEtKlF":{"name":"reduce(into:_:)","abstract":"
Returns the result of calling the given combining closure with each","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAAE6suffixySay7ElementQzGSiKF":{"name":"suffix(_:)","abstract":"
Returns an array, up to the given maximum length, containing the","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAASQ7ElementRpzrlE8containsySbAEKF":{"name":"contains(_:)","abstract":"
Returns a Boolean value indicating whether the cursor contains the","parent_name":"Cursor"},"Protocols/Cursor.html#/s:4GRDB6CursorPAASL7ElementRpzrlE3maxAESgyKF":{"name":"max()","abstract":"
RowAdapter is a protocol that helps two incompatible row interfaces working"},"Protocols/StatementColumnConvertible.html":{"name":"StatementColumnConvertible","abstract":"
The StatementColumnConvertible protocol grants access to the low-level C"},"Protocols/TransactionObserver.html":{"name":"TransactionObserver","abstract":"
A transaction observer is notified of all changes and transactions committed"},"Protocols/FTS5CustomTokenizer.html":{"name":"FTS5CustomTokenizer","abstract":"
Returns an array of row adapters that split a row according to the input"},"Functions.html#/s:4GRDB3absyAA13SQLExpression_pAA22SQLSpecificExpressible_pF":{"name":"abs(_:)","abstract":"
Returns an expression that evaluates the ABS SQL function.
Creates a request with a full-text predicate added to the eventual","parent_name":"QueryInterfaceRequest"},"Extensions/Database.html#/dropFTS5SynchronizationTriggers(forTable:)":{"name":"dropFTS5SynchronizationTriggers(forTable:)","abstract":"
Deletes the synchronization triggers for a synchronized FTS5 table
Creates a pattern from a raw pattern string; throws DatabaseError on","parent_name":"Database"},"Extensions/Database.html#/makeTokenizer(_:)":{"name":"makeTokenizer(_:)","abstract":"
Returns the receiver, quoted for safe insertion as an identifier in an","parent_name":"String"},"Extensions/Float.html#/s:Sf4GRDBE15sqliteStatement5indexSfs13OpaquePointerV_s5Int32Vtcfc":{"name":"init(sqliteStatement:index:)","abstract":"
Returns a value initialized from a raw SQLite statement pointer.
Returns a value that can be stored in the database.","parent_name":"NSURL"},"Extensions/NSURL.html#/s:So5NSURLC4GRDBE17fromDatabaseValueyABXDSgAC0dE0VFZ":{"name":"fromDatabaseValue(_:)","abstract":"
Returns an NSURL initialized from dbValue, if possible.
Returns an NSData initialized from dbValue, if it contains","parent_name":"NSData"},"Extensions/Date.html#/s:10Foundation4DateV4GRDBE13databaseValueAD08DatabaseE0Vvp":{"name":"databaseValue","abstract":"
Returns a database value that contains the date encoded as","parent_name":"Date"},"Extensions/Date.html#/s:10Foundation4DateV4GRDBE17fromDatabaseValueyACSgAD0eF0VFZ":{"name":"fromDatabaseValue(_:)","abstract":"
Returns a date initialized from dbValue, if possible.
Returns a database value that contains the date encoded as","parent_name":"NSDate"},"Extensions/NSDate.html#/s:So6NSDateC4GRDBE17fromDatabaseValueyABXDSgAC0dE0VFZ":{"name":"fromDatabaseValue(_:)","abstract":"
Returns a date initialized from dbValue, if possible.
Returns a Data initialized from dbValue, if it contains","parent_name":"Data"},"Extensions/CGFloat.html#/s:12CoreGraphics7CGFloatV4GRDBE13databaseValueAD08DatabaseF0Vvp":{"name":"databaseValue","abstract":"
Returns a value that can be stored in the database.
Returns a cursor over the concatenated results of mapping transform","parent_name":"Sequence"},"Extensions/Sequence.html#/s:ST4GRDBAA14SQLExpressible7ElementRpzrlE8containsyAA13SQLExpression_pAA22SQLSpecificExpressible_pF":{"name":"contains(_:)","abstract":"
An SQL expression that checks the inclusion of an expression in","parent_name":"Sequence"},"Extensions/Sequence.html#/s:ST4GRDBAA14SQLExpressible7ElementRpzrlE8containsyAA13SQLExpression_pAA21SQLCollatedExpressionVF":{"name":"contains(_:)","abstract":"
An SQL expression that checks the inclusion of an expression in","parent_name":"Sequence"},"Extensions/Sequence.html#/s:ST4GRDBAA13SQLExpression_p7ElementRtzrlE6joined8operatorAaB_pAA24SQLLogicalBinaryOperatorO_tF":{"name":"joined(operator:)","abstract":"
Returns an expression by joining all elements with an SQL","parent_name":"Sequence"},"Extensions/Array.html#/s:Sa4GRDBEySayxGqd__Kc7ElementQyd__RszAA6CursorRd__lufc":{"name":"init(_:)","abstract":"
Creates an array containing the elements of a cursor.
Encodes a Double: the number of seconds between the date and","parent_name":"DatabaseDateEncodingStrategy"},"Enums/DatabaseDateEncodingStrategy.html#/s:4GRDB28DatabaseDateEncodingStrategyO21timeIntervalSince1970yA2CmF":{"name":"timeIntervalSince1970","abstract":"
Encodes a Double: the number of seconds between the date and","parent_name":"DatabaseDateEncodingStrategy"},"Enums/DatabaseDateEncodingStrategy.html#/s:4GRDB28DatabaseDateEncodingStrategyO16secondsSince1970yA2CmF":{"name":"secondsSince1970","abstract":"
Encodes an Int64: the number of seconds between the date and","parent_name":"DatabaseDateEncodingStrategy"},"Enums/DatabaseDateEncodingStrategy.html#/s:4GRDB28DatabaseDateEncodingStrategyO21millisecondsSince1970yA2CmF":{"name":"millisecondsSince1970","abstract":"
Encodes an Int64: the number of milliseconds between the date and","parent_name":"DatabaseDateEncodingStrategy"},"Enums/DatabaseDateEncodingStrategy.html#/s:4GRDB28DatabaseDateEncodingStrategyO7iso8601yA2CmF":{"name":"iso8601","abstract":"
Encodes dates according to the ISO 8601 and RFC 3339 standards
Thrown by MutablePersistableRecord.update() when no matching row could be","parent_name":"PersistenceError"},"Enums/FetchedRecordChange.html#/s:4GRDB19FetchedRecordChangeO9insertionyAC10Foundation9IndexPathV_tcACmF":{"name":"insertion(indexPath:)","abstract":"
A move event, from indexPath to newIndexPath. The changes are a","parent_name":"FetchedRecordChange"},"Enums/FetchedRecordChange.html#/s:4GRDB19FetchedRecordChangeO6updateyAC10Foundation9IndexPathV_SDySSAA13DatabaseValueVGtcACmF":{"name":"update(indexPath:changes:)","abstract":"
An update event, at given indexPath. The changes are a dictionary","parent_name":"FetchedRecordChange"},"Enums/FetchedRecordChange.html#/s:s23CustomStringConvertibleP11descriptionSSvp":{"name":"description","parent_name":"FetchedRecordChange"},"Enums/DatabaseDateDecodingStrategy.html#/s:4GRDB28DatabaseDateDecodingStrategyO010deferredToC0yA2CmF":{"name":"deferredToDate","abstract":"
The strategy that uses formatting from the Date structure.
Decodes numeric values as a number of seconds between the date and","parent_name":"DatabaseDateDecodingStrategy"},"Enums/DatabaseDateDecodingStrategy.html#/s:4GRDB28DatabaseDateDecodingStrategyO21timeIntervalSince1970yA2CmF":{"name":"timeIntervalSince1970","abstract":"
Decodes numeric values as a number of seconds between the date and","parent_name":"DatabaseDateDecodingStrategy"},"Enums/DatabaseDateDecodingStrategy.html#/s:4GRDB28DatabaseDateDecodingStrategyO21millisecondsSince1970yA2CmF":{"name":"millisecondsSince1970","abstract":"
Decodes numeric values as a number of milliseconds between the date and","parent_name":"DatabaseDateDecodingStrategy"},"Enums/DatabaseDateDecodingStrategy.html#/s:4GRDB28DatabaseDateDecodingStrategyO7iso8601yA2CmF":{"name":"iso8601","abstract":"
A kind of database event. See the TransactionObserver protocol for"},"Enums/SQLLogicalBinaryOperator.html":{"name":"SQLLogicalBinaryOperator","abstract":"
DatabaseDateDecodingStrategy specifies how FetchableRecord types that also"},"Enums/FetchedRecordChange.html":{"name":"FetchedRecordChange","abstract":"
A record change, given by a FetchedRecordsController to its change callback.
DatabaseDateEncodingStrategy specifies how PersistableRecord types that also"},"Enums/DatabaseUUIDEncodingStrategy.html":{"name":"DatabaseUUIDEncodingStrategy","abstract":"
DatabaseUUIDEncodingStrategy specifies how FetchableRecord types that also"},"Classes/Record.html#/s:4GRDB6RecordCACycfc":{"name":"init()","abstract":"
The policy that handles SQLite conflicts when records are inserted","parent_name":"Record"},"Classes/Record.html#/s:4GRDB6RecordC17databaseSelectionSayAA13SQLSelectable_pGvpZ":{"name":"databaseSelection","abstract":"
Returns a copy of self, initialized from all values encoded in the","parent_name":"Record"},"Classes/Record.html#/s:4GRDB6RecordC18hasDatabaseChangesSbvp":{"name":"hasDatabaseChanges","abstract":"
A boolean that indicates whether the record has changes that have not","parent_name":"Record"},"Classes/Record.html#/s:4GRDB6RecordC15databaseChangesSDySSAA13DatabaseValueVSgGvp":{"name":"databaseChanges","abstract":"
If the record has been changed, executes an UPDATE statement so that","parent_name":"Record"},"Classes/Record.html#/s:4GRDB6RecordC4saveyyAA8DatabaseCKF":{"name":"save(_:)","abstract":"
Executes an INSERT or an UPDATE statement so that self is saved in","parent_name":"Record"},"Classes/Record.html#/s:4GRDB6RecordC6deleteySbAA8DatabaseCKF":{"name":"delete(_:)","abstract":"
Creates a fetched records controller initialized from a SQL query and","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:4GRDB24FetchedRecordsControllerC_7request5queue12isSameRecordACyxGAA14DatabaseWriter_p_qd__So012OS_dispatch_F0CSbx_xtcSgtKc10RowDecoderQyd__RszAA12FetchRequestRd__lufc":{"name":"init(_:request:queue:isSameRecord:)","abstract":"
Creates a fetched records controller initialized from a fetch request","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:4GRDB24FetchedRecordsControllerC12performFetchyyKF":{"name":"performFetch()","abstract":"
Updates the fetch request, and eventually notifies the tracking","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:4GRDB24FetchedRecordsControllerC10setRequest3sql9arguments7adapterySS_AA18StatementArgumentsVSgAA10RowAdapter_pSgtKF":{"name":"setRequest(sql:arguments:adapter:)","abstract":"
Updates the fetch request, and eventually notifies the tracking","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:4GRDB24FetchedRecordsControllerC12trackChanges10willChange02onH003didH0yyACyxGcSg_yAH_xAA0b6RecordH0OtcSgAItF":{"name":"trackChanges(willChange:onChange:didChange:)","abstract":"
Call this method when changes performed while the application is","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:4GRDB24FetchedRecordsControllerC07fetchedC0SayxGvp":{"name":"fetchedRecords","abstract":"
Creates a fetched records controller initialized from a SQL query and","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:4GRDB24FetchedRecordsControllerCA2A11TableRecordRzrlE_7request5queueACyxGAA14DatabaseWriter_p_qd__So012OS_dispatch_H0CtKc10RowDecoderQyd__RszAA12FetchRequestRd__lufc":{"name":"init(_:request:queue:)","abstract":"
Creates a fetched records controller initialized from a fetch request","parent_name":"FetchedRecordsController"},"Classes/FetchedRecordsController.html#/s:4GRDB24FetchedRecordsControllerC6record2atx10Foundation9IndexPathV_tF":{"name":"record(at:)","abstract":"
Returns a qualified value that is able to resolve ambiguities in","parent_name":"TableAlias"},"Classes/TableAlias.html#/s:4GRDB10TableAliasCyAA13SQLExpression_pAaD_pcip":{"name":"subscript(_:)","abstract":"
Returns a qualified expression that is able to resolve ambiguities in","parent_name":"TableAlias"},"Classes/FTS5ColumnDefinition.html#/notIndexed()":{"name":"notIndexed()","abstract":"
Synchronizes the full-text table with the content of an external","parent_name":"FTS5TableDefinition"},"Classes/FTS4ColumnDefinition.html#/s:4GRDB20FTS4ColumnDefinitionC10notIndexedACXDyF":{"name":"notIndexed()","abstract":"
Synchronizes the full-text table with the content of an external","parent_name":"FTS4TableDefinition"},"Classes/FTS3TableDefinition.html#/s:4GRDB19FTS3TableDefinitionC9tokenizerAA0B19TokenizerDescriptorVSgvp":{"name":"tokenizer","abstract":"
Returns the index of the leftmost column named name, in a","parent_name":"SelectStatement"},"Classes/Statement.html#/s:4GRDB9StatementC06sqliteB0s13OpaquePointerVvp":{"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:4GRDB9StatementC18unsafeSetArgumentsyyAA0bE0VF":{"name":"unsafeSetArguments(_:)","abstract":"
Set arguments without any validation. Trades safety for performance.
Returns the row associated with the given scope, by performing a","parent_name":"ScopesTreeView"},"Classes/Row/ScopesView.html#/s:Sl5IndexQa":{"name":"Index","parent_name":"ScopesView"},"Classes/Row/ScopesView.html#/s:4GRDB3RowC10ScopesViewV5namesSD4KeysVySSAA08LayoutedB7Adapter_p_Gvp":{"name":"names","abstract":"
Returns the row associated with the given scope, or nil if the","parent_name":"ScopesView"},"Classes/Row.html#/s:4GRDB3RowC5countSivp":{"name":"count","abstract":"
Returns true if and only if one column contains a non-null value, or if","parent_name":"Row"},"Classes/Row.html#/s:4GRDB3RowC7hasNull7atIndexSbSi_tF":{"name":"hasNull(atIndex:)","abstract":"
Returns true if the row contains null at given index.
Returns Int64, Double, String, Data or nil, depending on the value","parent_name":"Row"},"Classes/Row.html#/s:4GRDB3RowCyxSgSicAA24DatabaseValueConvertibleRzluip":{"name":"subscript(_:)","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:4GRDB3RowCyxSgSScAA24DatabaseValueConvertibleRzluip":{"name":"subscript(_:)","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:4GRDB3RowCyxSgAA16ColumnExpression_pcAA24DatabaseValueConvertibleRzluip":{"name":"subscript(_:)","abstract":"
Returns the value at given column, converted to the requested type.
Returns the record encoded in the given scope, if and only if the scope","parent_name":"Row"},"Classes/Row.html#/s:4GRDB3RowC6scopesAC10ScopesViewVvp":{"name":"scopes","abstract":"
Returns a view on the scopes defined by row adapters.
Creates a row initialized with elements. Column order is preserved, and","parent_name":"Row"},"Classes/Row.html#/s:4GRDB3RowCySS_AA13DatabaseValueVtAA0B5IndexVcip":{"name":"subscript(_:)","abstract":"
Accesses the (ColumnName, DatabaseValue) pair at given index.
A view of the scopes defined by row adapters. It is a collection of","parent_name":"Row"},"Classes/Row/ScopesTreeView.html":{"name":"ScopesTreeView","abstract":"
A view on the scopes tree defined by row adapters.
Synchronously executes a read-only block that takes a database","parent_name":"DatabaseSnapshot"},"Classes/DatabaseSnapshot.html#/s:4GRDB16DatabaseSnapshotC3add8functionyAA0B8FunctionC_tF":{"name":"add(function:)","abstract":"
Listens to UIApplicationDidEnterBackgroundNotification and","parent_name":"DatabaseQueue"},"Classes/DatabaseQueue.html#/s:4GRDB13DatabaseQueueC4readyxxAA0B0CKXEKlF":{"name":"read(_:)","abstract":"
Synchronously executes a read-only block in a protected dispatch queue,","parent_name":"DatabaseQueue"},"Classes/DatabaseQueue.html#/s:4GRDB13DatabaseQueueC20readFromCurrentStateyyyAA0B0CcF":{"name":"readFromCurrentState(_:)","abstract":"
This method is deprecated. Use concurrentRead instead.
Synchronously executes a block in a protected dispatch queue, wrapped","parent_name":"DatabaseQueue"},"Classes/DatabaseQueue.html#/s:4GRDB13DatabaseQueueC13inTransactionyyAA0B0C0E4KindOSg_AF0E10CompletionOAFKXEtKF":{"name":"inTransaction(_:_:)","abstract":"
Synchronously executes a block in a protected dispatch queue, wrapped","parent_name":"DatabaseQueue"},"Classes/DatabaseQueue.html#/s:4GRDB13DatabaseQueueC02inB0yxxAA0B0CKXEKlF":{"name":"inDatabase(_:)","abstract":"
Synchronously executes a block in a protected dispatch queue, and","parent_name":"DatabaseQueue"},"Classes/DatabaseQueue.html#/s:4GRDB13DatabaseQueueC20unsafeReentrantWriteyxxAA0B0CKXEKlF":{"name":"unsafeReentrantWrite(_:)","abstract":"
Synchronously executes a block in a protected dispatch queue, and","parent_name":"DatabaseQueue"},"Classes/DatabaseQueue.html#/s:4GRDB13DatabaseQueueC3add8functionyAA0B8FunctionC_tF":{"name":"add(function:)","abstract":"
Listens to UIApplicationDidEnterBackgroundNotification and","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:4GRDB12DatabasePoolC4readyxxAA0B0CKXEKlF":{"name":"read(_:)","abstract":"
Synchronously executes a read-only block in a protected dispatch queue,","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:4GRDB12DatabasePoolC10unsafeReadyxxAA0B0CKXEKlF":{"name":"unsafeRead(_:)","abstract":"
Synchronously executes a read-only block in a protected dispatch queue,","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:4GRDB12DatabasePoolC19unsafeReentrantReadyxxAA0B0CKXEKlF":{"name":"unsafeReentrantRead(_:)","abstract":"
Synchronously executes a read-only block in a protected dispatch queue,","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:4GRDB12DatabasePoolC20readFromCurrentStateyyyAA0B0CcKF":{"name":"readFromCurrentState(_:)","abstract":"
This method is deprecated. Use concurrentRead instead.
Synchronously executes an update block in a protected dispatch queue,","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:4GRDB12DatabasePoolC23writeWithoutTransactionyxxAA0B0CKXEKlF":{"name":"writeWithoutTransaction(_:)","abstract":"
Synchronously executes a block that takes a database connection, and","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:4GRDB12DatabasePoolC18writeInTransactionyyAA0B0C0F4KindOSg_AF0F10CompletionOAFKXEtKF":{"name":"writeInTransaction(_:_:)","abstract":"
Synchronously executes a block in a protected dispatch queue, wrapped","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:4GRDB12DatabasePoolC20unsafeReentrantWriteyxxAA0B0CKXEKlF":{"name":"unsafeReentrantWrite(_:)","abstract":"
Synchronously executes an update block in a protected dispatch queue,","parent_name":"DatabasePool"},"Classes/DatabasePool.html#/s:4GRDB12DatabasePoolC3add8functionyAA0B8FunctionC_tF":{"name":"add(function:)","abstract":"
An SQL function that returns the Swift built-in capitalized","parent_name":"DatabaseFunction"},"Classes/DatabaseFunction.html#/s:4GRDB16DatabaseFunctionC9lowercaseACvpZ":{"name":"lowercase","abstract":"
An SQL function that returns the Swift built-in lowercased","parent_name":"DatabaseFunction"},"Classes/DatabaseFunction.html#/s:4GRDB16DatabaseFunctionC9uppercaseACvpZ":{"name":"uppercase","abstract":"
An SQL function that returns the Swift built-in uppercased","parent_name":"DatabaseFunction"},"Classes/DatabaseFunction.html#/s:4GRDB16DatabaseFunctionC19localizedCapitalizeACvpZ":{"name":"localizedCapitalize","abstract":"
An SQL function that returns the Swift built-in","parent_name":"DatabaseFunction"},"Classes/DatabaseFunction.html#/s:4GRDB16DatabaseFunctionC18localizedLowercaseACvpZ":{"name":"localizedLowercase","abstract":"
An SQL function that returns the Swift built-in","parent_name":"DatabaseFunction"},"Classes/DatabaseFunction.html#/s:4GRDB16DatabaseFunctionC18localizedUppercaseACvpZ":{"name":"localizedUppercase","abstract":"
An SQL function that returns the Swift built-in","parent_name":"DatabaseFunction"},"Classes/DatabaseFunction.html#/s:4GRDB16DatabaseFunctionC5applyyAA13SQLExpression_pAA14SQLExpressible_pd_tF":{"name":"apply(_:)","abstract":"
Returns an SQL expression that applies the function.
A collation, or SQL string comparison function, that compares strings","parent_name":"DatabaseCollation"},"Classes/DatabaseCollation.html#/s:4GRDB17DatabaseCollationC22caseInsensitiveCompareACvpZ":{"name":"caseInsensitiveCompare","abstract":"
A collation, or SQL string comparison function, that compares strings","parent_name":"DatabaseCollation"},"Classes/DatabaseCollation.html#/s:4GRDB17DatabaseCollationC31localizedCaseInsensitiveCompareACvpZ":{"name":"localizedCaseInsensitiveCompare","abstract":"
A collation, or SQL string comparison function, that compares strings","parent_name":"DatabaseCollation"},"Classes/DatabaseCollation.html#/s:4GRDB17DatabaseCollationC16localizedCompareACvpZ":{"name":"localizedCompare","abstract":"
A collation, or SQL string comparison function, that compares strings","parent_name":"DatabaseCollation"},"Classes/DatabaseCollation.html#/s:4GRDB17DatabaseCollationC24localizedStandardCompareACvpZ":{"name":"localizedStandardCompare","abstract":"
A collation, or SQL string comparison function, that compares strings","parent_name":"DatabaseCollation"},"Classes/Database/TransactionObservationExtent.html#/s:4GRDB8DatabaseC28TransactionObservationExtentO16observerLifetimeyA2EmF":{"name":"observerLifetime","abstract":"
The SQLITE_BUSY error is immediately returned to the connection that","parent_name":"BusyMode"},"Classes/Database/BusyMode.html#/s:4GRDB8DatabaseC8BusyModeO7timeoutyAESdcAEmF":{"name":"timeout(_:)","abstract":"
The SQLITE_BUSY error will be returned only if the database remains","parent_name":"BusyMode"},"Classes/Database/BusyMode.html#/s:4GRDB8DatabaseC8BusyModeO8callbackyAESbSiccAEmF":{"name":"callback(_:)","abstract":"
A custom callback that is called when a database is locked.","parent_name":"BusyMode"},"Classes/Database.html#/s:4GRDB8DatabaseC16sqliteConnections13OpaquePointerVvp":{"name":"sqliteConnection","abstract":"
The raw SQLite connection, suitable for the SQLite C API.
The number of rows modified, inserted or deleted by the most recent","parent_name":"Database"},"Classes/Database.html#/s:4GRDB8DatabaseC17totalChangesCountSivp":{"name":"totalChangesCount","abstract":"
The total number of rows modified, inserted or deleted by all successful","parent_name":"Database"},"Classes/Database.html#/s:4GRDB8DatabaseC19isInsideTransactionSbvp":{"name":"isInsideTransaction","abstract":"
True if the database connection is currently in a transaction.
The indexes on table named tableName; returns the empty array if the","parent_name":"Database"},"Classes/Database.html#/s:4GRDB8DatabaseC5table_12hasUniqueKeySbSS_xtKSTRzSS7ElementRtzlF":{"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:4GRDB8DatabaseC11foreignKeys2onSayAA14ForeignKeyInfoVGSS_tKF":{"name":"foreignKeys(on:)","abstract":"
The foreign keys defined on table named tableName.
When there are several connections to a database, a connection may try","parent_name":"Database"},"Classes/Database/CheckpointMode.html":{"name":"CheckpointMode","abstract":"
Add a transaction observer, so that it gets notified of","parent_name":"Database"},"Classes/Database.html#/s:4GRDB8DatabaseC6remove19transactionObserveryAA011TransactionE0_p_tF":{"name":"remove(transactionObserver:)","abstract":"
Registers a closure to be executed after the next or current","parent_name":"Database"},"Classes/Database/TransactionObservationExtent.html":{"name":"TransactionObservationExtent","abstract":"
Creates a cursor that wraps a base cursor but whose type depends only on","parent_name":"AnyCursor"},"Classes/AnyCursor.html#/s:4GRDB9AnyCursorC8iteratorACyxGqd___tc7ElementQyd__RszStRd__lufc":{"name":"init(iterator:)","abstract":"
Creates a cursor that wraps a base iterator but whose type depends only","parent_name":"AnyCursor"},"Classes/AnyCursor.html#/s:4GRDB9AnyCursorCyACyxGqd__c7ElementQyd__RszSTRd__lufc":{"name":"init(_:)","abstract":"
Creates a cursor that wraps a base sequence but whose type depends only","parent_name":"AnyCursor"},"Classes/AnyCursor.html#/s:4GRDB9AnyCursorCyACyxGxSgyKccfc":{"name":"init(_:)","abstract":"
Creates a cursor that wraps the given closure in its next() method
A DatabaseSnapshot sees an unchanging database content, as it existed at the"},"Classes.html#/s:4GRDB19DatabaseValueCursorC":{"name":"DatabaseValueCursor","abstract":"
A cursor of database values extracted from a single column."},"Classes.html#/s:4GRDB27NullableDatabaseValueCursorC":{"name":"NullableDatabaseValueCursor","abstract":"
A cursor of optional database values extracted from a single column."},"Classes/Future.html":{"name":"Future","abstract":"
A cursor of database values extracted from a single column."},"Classes.html#/s:4GRDB31FastNullableDatabaseValueCursorC":{"name":"FastNullableDatabaseValueCursor","abstract":"
A cursor of optional database values extracted from a single column."},"Classes/FTS3TableDefinition.html":{"name":"FTS3TableDefinition","abstract":"
The FTS3TableDefinition class lets you define columns of a FTS3 virtual table.