TransactionCompletion
A transaction commit, or rollback.
@frozen enum TransactionCompletion
Related SQLite documentation: https://www.sqlite.org/lang_transaction.html.
A transaction commit, or rollback.
@frozen enum TransactionCompletion
Related SQLite documentation: https://www.sqlite.org/lang_transaction.html.
import GRDB
A toolkit for SQLite databases, with a focus on application development
final class Database
An SQLite connection.
case commit
case rollback
func beginTransaction(_ kind: TransactionKind? = nil) throws
Begins a database transaction.
func commit() throws
Commits a database transaction.
func inSavepoint(_ operations: () throws -> TransactionCompletion) throws
Wraps database operations inside a savepoint.
func inTransaction(_ kind: TransactionKind? = nil, _ operations: () throws -> TransactionCompletion) throws
Wraps database operations inside a database transaction.
var isInsideTransaction: Bool { get }
A Boolean value indicating whether the database connection is currently inside a transaction.
func readOnly<T>(_ value: () throws -> T) throws -> T
Executes read-only database operations, and returns their result after they have finished executing.
func rollback() throws
Rollbacks a database transaction.
var transactionDate: Date { get throws }
The date of the current transaction.
enum TransactionKind
A transaction kind.
nonisolated(unsafe) static var logError: LogErrorFunction? { get set }
The error logging function.
static let resumeNotification: Notification.Name
When this notification is posted, databases which were opened with the observesSuspensionNotifications
configuration flag are resumed.
static var sqliteLibVersionNumber: CInt { get }
An integer equal to SQLITE_VERSION_NUMBER
.
static let suspendNotification: Notification.Name
When this notification is posted, databases which were opened with the observesSuspensionNotifications
configuration flag are suspended.
static func isGRDBInternalTable(_ tableName: String) -> Bool
Returns whether a table is an internal GRDB table.
static func isSQLiteInternalTable(_ tableName: String) -> Bool
Returns whether a table is an internal SQLite table.
static func json(_ value: some SQLExpressible) -> SQLExpression
Validates and minifies a JSON string, with the JSON
SQL function.
static func jsonArray(_ values: some Collection<some SQLExpressible>) -> SQLExpression
Creates a JSON array with the JSON_ARRAY
SQL function.
static func jsonArray(_ values: some Collection<any SQLExpressible>) -> SQLExpression
Creates a JSON array with the JSON_ARRAY
SQL function.
static func jsonArrayLength(_ value: some SQLExpressible) -> SQLExpression
The number of elements in a JSON array, as returned by the JSON_ARRAY_LENGTH
SQL function.
static func jsonArrayLength(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression
The number of elements in a JSON array, as returned by the JSON_ARRAY_LENGTH
SQL function.
static func jsonExtract(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression
The JSON_EXTRACT
SQL function.
static func jsonExtract(_ value: some SQLExpressible, atPaths paths: some Collection<some SQLExpressible>) -> SQLExpression
The JSON_EXTRACT
SQL function.
static func jsonGroupArray(_ value: some SQLExpressible, filter: (any SQLSpecificExpressible)? = nil) -> SQLExpression
The JSON_GROUP_ARRAY
SQL function.
static func jsonGroupObject(key: some SQLExpressible, value: some SQLExpressible, filter: (any SQLSpecificExpressible)? = nil) -> SQLExpression
The JSON_GROUP_OBJECT
SQL function.
static func jsonInsert(_ value: some SQLExpressible, _ assignments: some Collection<(key: String, value: any SQLExpressible)>) -> SQLExpression
The JSON_INSERT
SQL function.
static func jsonIsValid(_ value: some SQLExpressible) -> SQLExpression
The JSON_VALID
SQL function.
static func jsonObject(_ elements: some Collection<(key: String, value: any SQLExpressible)>) -> SQLExpression
Creates a JSON object with the JSON_OBJECT
SQL function. Pass key/value pairs with a Swift collection such as a Dictionary
.
static func jsonPatch(_ value: some SQLExpressible, with patch: some SQLExpressible) -> SQLExpression
The JSON_PATCH
SQL function.
static func jsonQuote(_ value: some SQLExpressible) -> SQLExpression
Returns a valid JSON string with the JSON_QUOTE
SQL function.
static func jsonRemove(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression
The JSON_REMOVE
SQL function.
static func jsonRemove(_ value: some SQLExpressible, atPaths paths: some Collection<some SQLExpressible>) -> SQLExpression
The JSON_REMOVE
SQL function.
static func jsonReplace(_ value: some SQLExpressible, _ assignments: some Collection<(key: String, value: any SQLExpressible)>) -> SQLExpression
The JSON_REPLACE
SQL function.
static func jsonSet(_ value: some SQLExpressible, _ assignments: some Collection<(key: String, value: any SQLExpressible)>) -> SQLExpression
The JSON_SET
SQL function.
static func jsonType(_ value: some SQLExpressible) -> SQLExpression
The JSON_TYPE
SQL function.
static func jsonType(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression
The JSON_TYPE
SQL function.
var changesCount: Int { get }
The number of rows modified, inserted or deleted by the most recent successful INSERT, UPDATE or DELETE statement.
let configuration: Configuration
The database configuration.
var debugDescription: String { get }
let description: String
A description of this database connection.
var lastErrorCode: ResultCode { get }
The last error code.
var lastErrorMessage: String? { get }
The last error message.
var lastInsertedRowID: Int64 { get }
The rowID of the most recently inserted row.
var maximumStatementArgumentCount: Int { get }
The maximum number of arguments accepted by an SQLite statement.
var sqliteConnection: SQLiteConnection? { get }
The raw SQLite connection, suitable for the SQLite C API.
var totalChangesCount: Int { get }
The total number of rows modified, inserted or deleted by all successful INSERT, UPDATE or DELETE statements since the database connection was opened.
func add(collation: DatabaseCollation)
Adds or redefines a collation.
func add(function: DatabaseFunction)
Adds or redefines a custom SQL function.
func add(tokenizer: (some FTS5CustomTokenizer).Type)
Add a custom FTS5 tokenizer.
func add(transactionObserver: some TransactionObserver, extent: TransactionObservationExtent = .observerLifetime)
Adds a transaction observer on the database connection, so that it gets notified of database changes and transactions.
func afterNextTransaction(onCommit: @escaping (Database) -> Void, onRollback: @escaping (Database) -> Void = { _ in })
Registers closures to be executed after the next or current transaction completes.
func allStatements(literal sqlLiteral: SQL) throws -> SQLStatementCursor
Returns a cursor of prepared statements.
func allStatements(sql: String, arguments: StatementArguments? = nil) throws -> SQLStatementCursor
Returns a cursor of prepared statements.
func alter(table name: String, body: (TableAlteration) -> Void) throws
Modifies a database table.
func backup(to destDb: Database, pagesPerStep: CInt = -1, progress: ((DatabaseBackupProgress) throws -> Void)? = nil) throws
Copies the database contents into another database.
func cachedStatement(literal sqlLiteral: SQL) throws -> Statement
Returns a prepared statement that can be reused.
func cachedStatement(sql: String) throws -> Statement
Returns a prepared statement that can be reused.
func checkForeignKeys() throws
Throws an error if there exists a foreign key violation in the database.
func checkForeignKeys(in tableName: String, in schemaName: String? = nil) throws
Throws an error if there exists a foreign key violation in the table.
@discardableResult func checkpoint(_ kind: Database.CheckpointMode = .passive, on dbName: String? = "main") throws -> (walFrameCount: Int, checkpointedFrameCount: Int)
Runs a WAL checkpoint.
func clearSchemaCache()
Clears the database schema cache.
func columns(in tableName: String, in schemaName: String? = nil) throws -> [ColumnInfo]
Returns the columns in a table or a view.
func create(index name: String, on table: String, columns: [String], options: IndexOptions = [], condition: (any SQLExpressible)? = nil) throws
Creates an index on the specified table and columns.
func create(index name: String, on table: String, columns: [String], unique: Bool = false, ifNotExists: Bool = false, condition: (any SQLExpressible)? = nil) throws
Creates an index on the specified table and columns.
func create(index name: String, on table: String, expressions: [any SQLExpressible], options: IndexOptions = [], condition: (any SQLExpressible)? = nil) throws
Creates an index on the specified table and expressions.
func create(indexOn table: String, columns: [String], options: IndexOptions = [], condition: (any SQLExpressible)? = nil) throws
Creates an index with a default name on the specified table and columns.
func create(table name: String, options: TableOptions = [], body: (TableDefinition) throws -> Void) throws
Creates a database table.
func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, withoutRowID: Bool = false, body: (TableDefinition) throws -> Void) throws
Creates a database table.
func create(view name: String, options: ViewOptions = [], columns: [String]? = nil, as request: SQLSubqueryable) throws
Creates a database view.
func create(view name: String, options: ViewOptions = [], columns: [String]? = nil, asLiteral sqlLiteral: SQL) throws
Creates a database view.
func create(virtualTable name: String, ifNotExists: Bool = false, using module: String) throws
Creates a virtual database table.
func create<Module>(virtualTable tableName: String, ifNotExists: Bool = false, using module: Module, _ body: ((Module.TableDefinition) throws -> Void)? = nil) throws where Module : VirtualTableModule
Creates a virtual database table.
func create(virtualTable name: String, options: VirtualTableOptions = [], using module: String) throws
Creates a virtual database table.
func create<Module>(virtualTable tableName: String, options: VirtualTableOptions = [], using module: Module, _ body: ((Module.TableDefinition) throws -> Void)? = nil) throws where Module : VirtualTableModule
Creates a virtual database table.
func drop(index name: String) throws
Deletes a database index.
func drop(indexOn table: String, columns: [String]) throws
Deletes the database index on the specified table and columns if exactly one such index exists.
func drop(table name: String) throws
Deletes a database table.
func drop(view name: String) throws
Deletes a database view.
func dropFTS4SynchronizationTriggers(forTable tableName: String) throws
Deletes the synchronization triggers for a synchronized FTS4 table.
func dropFTS5SynchronizationTriggers(forTable tableName: String) throws
Deletes the synchronization triggers for a synchronized FTS5 table.
func dumpContent(format: some DumpFormat = .debug(), to stream: (any TextOutputStream)? = nil) throws
Prints the contents of the database.
func dumpRequest(_ request: some FetchRequest, format: some DumpFormat = .debug(), to stream: (any TextOutputStream)? = nil) throws
Prints the results of a request.
func dumpSQL(_ sql: SQL, format: some DumpFormat = .debug(), to stream: (any TextOutputStream)? = nil) throws
Prints the results of all statements in the provided SQL.
func dumpSchema(to stream: (any TextOutputStream)? = nil) throws
Prints the schema of the database.
func dumpTables(_ tables: [String], format: some DumpFormat = .debug(), tableHeader: DumpTableHeaderOptions = .automatic, stableOrder: Bool = false, to stream: (any TextOutputStream)? = nil) throws
Prints the contents of the provided tables and views.
func execute(literal sqlLiteral: SQL) throws
Executes one or several SQL statements.
func execute(sql: String, arguments: StatementArguments = StatementArguments()) throws
Executes one or several SQL statements.
func foreignKeyViolations() throws -> RecordCursor<ForeignKeyViolation>
Returns a cursor over foreign key violations in the database.
func foreignKeyViolations(in tableName: String, in schemaName: String? = nil) throws -> RecordCursor<ForeignKeyViolation>
Returns a cursor over foreign key violations in the table.
func foreignKeys(on tableName: String, in schemaName: String? = nil) throws -> [ForeignKeyInfo]
Returns the foreign keys defined on table named tableName
.
func indexes(on tableName: String, in schemaName: String? = nil) throws -> [IndexInfo]
The indexes on table named tableName
.
func makeFTS5Pattern(rawPattern: String, forTable table: String) throws -> FTS5Pattern
Creates an FTS5 pattern from a raw pattern string.
func makeStatement(literal sqlLiteral: SQL) throws -> Statement
Returns a new prepared statement that can be reused.
func makeStatement(sql: String) throws -> Statement
Returns a new prepared statement that can be reused.
func makeTokenizer(_ descriptor: FTS5TokenizerDescriptor) throws -> any FTS5Tokenizer
Creates an FTS5 tokenizer, given its descriptor.
func notifyChanges(in region: some DatabaseRegionConvertible) throws
Notifies that some changes were performed in the provided database region.
func primaryKey(_ tableName: String, in schemaName: String? = nil) throws -> PrimaryKeyInfo
The primary key for table named tableName
.
func registerAccess(to region: @autoclosure () -> some DatabaseRegionConvertible) throws
Reports the database region to ValueObservation
.
func reindex(collation: DatabaseCollation) throws
Deletes and recreates from scratch all indices that use this collation.
func reindex(collation: Database.CollationName) throws
Deletes and recreates from scratch all indices that use this collation.
func releaseMemory()
Frees as much memory as possible.
func remove(collation: DatabaseCollation)
Removes a collation.
func remove(function: DatabaseFunction)
Removes a custom SQL function.
func remove(transactionObserver: some TransactionObserver)
Removes a transaction observer from the database connection.
func rename(table name: String, to newName: String) throws
Renames a database table.
func schemaVersion() throws -> Int32
Returns the current schema version (PRAGMA schema_version
).
func table(_ tableName: String, hasUniqueKey columns: some Collection<String>) throws -> Bool
Returns whether a sequence of columns uniquely identifies a row.
func tableExists(_ name: String, in schemaName: String? = nil) throws -> Bool
Returns whether a table exists
func trace(options: TracingOptions = .statement, _ trace: ((TraceEvent) -> Void)? = nil)
Registers a tracing function.
func triggerExists(_ name: String, in schemaName: String? = nil) throws -> Bool
Returns whether a trigger exists, in the main or temp schema, or in an attached database.
func viewExists(_ name: String, in schemaName: String? = nil) throws -> Bool
Returns whether a view exists, in the main or temp schema, or in an attached database.
enum BusyMode
When there are several connections to a database, a connection may try to access the database while it is locked by another connection.
enum CheckpointMode
The available checkpoint modes.
struct CollationName
The name of a string comparison function used by SQLite.
struct ColumnType
An SQL column type.
enum ConflictResolution
An SQLite conflict resolution.
enum ForeignKeyAction
A foreign key action.
struct StorageClass
An SQLite storage class.
enum TraceEvent
A trace event.
struct TracingOptions
An option for the SQLite tracing feature.
enum TransactionObservationExtent
The extent of the observation performed by a TransactionObserver
.
typealias BusyCallback = (_ numberOfTries: Int) -> Bool
See BusyMode
and https://www.sqlite.org/c3ref/busy_handler.html
typealias LogErrorFunction = (_ resultCode: ResultCode, _ message: String) -> Void
An error log function that takes an error code and message.
protocol BitwiseCopyable
protocol Equatable
A type that can be compared for value equality.
protocol Hashable : Equatable
A type that can be hashed into a Hasher
to produce an integer hash value.
protocol Sendable
static func != (lhs: Self, rhs: Self) -> Bool
Returns a Boolean value indicating whether two values are not equal.