Core

  • An SQLite database.

    A database supports SQL statement execution, transactions and savepoints, custom collation sequences, and custom SQL functions.

    let db = try Database()
    try db.execute(sql: "create table t1(a);")
    try db.execute(sql: "insert into t1 default values;")
    let rowCount: Int = db.prepare(sql: "select count(*) from t1;").front()
    print("t1 has \(rowCount) rows")
    
    See more

    Declaration

    Swift

    public final class Database
  • A compiled SQL statement with support for SQL parameter binding and result row processing.

    Creation

    A statement is not created directly but is obtained from a Database.

    let statement = try db.prepare(sql: "select count(*) from t1;")
    

    Parameter Binding

    A statement supports binding values to SQL parameters by index or by name.

    Note

    Parameter indexes are 1-based. The leftmost parameter in a statement has index 1.
    let statement = try db.prepare(sql: "insert into t1(a, b, c, d, e, f) values (?, ?, ?, :d, :e, :f);")
    try statement.bind(value: 30, toParameter: 3)
    try statement.bind(value: 40, toParameter: ":d")
    try statement.bind(parameterValues: 10, 20)
    try statement.bind(parameters: [":f": 60, ":e": 50])
    

    Result Rows

    When executed a statement provides zero or more result rows.

    try statement.results { row in
        // Do something with `row`
    }
    
    for row in statement {
        // Do something with `row`
    }
    

    It is generally preferred to use the block-based method because any errors may be explicitly handled instead of silently discarded.

    See more

    Declaration

    Swift

    public final class Statement
    extension Statement: Sequence
    extension Statement: IteratorProtocol
  • Row

    A result row containing one or more columns with type-safe value access.

    Creation

    A row is not created directly but is obtained from a Statement.

    try statement.execute() { row in
        // Do something with `row`
    }
    

    Column Value Access

    The database-native column value is expressed by DatabaseValue, however custom type conversion is possible when a type implements either the ColumnConvertible or DatabaseSerializable protocol.

    The value of columns is accessed by the value(at:) or value(named:) methods.

    let value = try row.value(at: 0)
    let uuid: UUID = try row.value(named: "session_uuid")
    

    It is also possible to iterate over column values:

    for row in statement {
        for value in row {
            // Do something with `value`
        }
    
    }
    

    This allows for simple result row processing at the expense of error handling.

    See more

    Declaration

    Swift

    public struct Row
    extension Row: CustomStringConvertible
    extension Row: Collection