TableDefinition

public final class TableDefinition

The TableDefinition class lets you define table columns and constraints.

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

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

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

  • Defines the auto-incremented primary key.

    try db.create(table: "player") { t in
        t.autoIncrementedPrimaryKey("id")
    }
    

    The auto-incremented primary key is an integer primary key that automatically generates unused values when you do not explicitly provide one, and prevents the reuse of ids over the lifetime of the database.

    It is the preferred way to define a numeric primary key.

    The fact that an auto-incremented primary key prevents the reuse of ids is an excellent guard against data races that could happen when your application processes ids in an asynchronous way. The auto-incremented primary key provides the guarantee that a given id can’t reference a row that is different from the one it used to be at the beginning of the asynchronous process, even if this row gets deleted and a new one is inserted in between.

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

    Declaration

    Swift

    @discardableResult
    public func autoIncrementedPrimaryKey(
        _ name: String,
        onConflict conflictResolution: Database.ConflictResolution? = nil)
    -> ColumnDefinition

    Parameters

    conflictResolution

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

    Return Value

    Self so that you can further refine the column definition.

  • Appends a table column.

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

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

    Declaration

    Swift

    @discardableResult
    public func column(_ name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition

    Parameters

    name

    the column name.

    type

    the eventual column type.

    Return Value

    An ColumnDefinition that allows you to refine the column definition.

  • Appends a table column defined with raw SQL.

    try db.create(table: "player") { t in
        t.column(sql: "name TEXT")
    }
    

    Declaration

    Swift

    public func column(sql: String)
  • Appends a table column defined with an SQL literal.

    Literals allow you to safely embed raw values in your SQL, without any risk of syntax errors or SQL injection:

    // CREATE TABLE player (
    //   name TEXT DEFAULT 'Anonymous'
    // )
    let defaultName = "Anonymous"
    try db.create(table: "player") { t in
        t.column(literal: "name TEXT DEFAULT \(defaultName)")
    }
    

    Declaration

    Swift

    public func column(literal: SQL)
  • Defines the table primary key.

    try db.create(table: "citizenship") { t in
        t.column("citizenID", .integer)
        t.column("countryCode", .text)
        t.primaryKey(["citizenID", "countryCode"])
    }
    

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

    Declaration

    Swift

    public func primaryKey(_ columns: [String], onConflict conflictResolution: Database.ConflictResolution? = nil)

    Parameters

    columns

    The primary key columns.

    conflictResolution

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

  • Adds a unique key.

    try db.create(table: "place") { t in
        t.column("latitude", .double)
        t.column("longitude", .double)
        t.uniqueKey(["latitude", "longitude"])
    }
    

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

    Declaration

    Swift

    public func uniqueKey(_ columns: [String], onConflict conflictResolution: Database.ConflictResolution? = nil)

    Parameters

    columns

    The unique key columns.

    conflictResolution

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

  • Adds a foreign key.

    try db.create(table: "passport") { t in
        t.column("issueDate", .date)
        t.column("citizenID", .integer)
        t.column("countryCode", .text)
        t.foreignKey(["citizenID", "countryCode"], references: "citizenship", onDelete: .cascade)
    }
    

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

    Declaration

    Swift

    public func foreignKey(
        _ columns: [String],
        references table: String,
        columns destinationColumns: [String]? = nil,
        onDelete deleteAction: Database.ForeignKeyAction? = nil,
        onUpdate updateAction: Database.ForeignKeyAction? = nil,
        deferred: Bool = false)

    Parameters

    columns

    The foreign key columns.

    table

    The referenced table.

    destinationColumns

    The columns in the referenced table. If not specified, the columns of the primary key of the referenced table are used.

    deleteAction

    Optional action when the referenced row is deleted.

    updateAction

    Optional action when the referenced row is updated.

    deferred

    If true, defines a deferred foreign key constraint. See https://www.sqlite.org/foreignkeys.html#fk_deferred.

  • Adds a CHECK constraint.

    try db.create(table: "player") { t in
        t.column("personalPhone", .text)
        t.column("workPhone", .text)
        let personalPhone = Column("personalPhone")
        let workPhone = Column("workPhone")
        t.check(personalPhone != nil || workPhone != nil)
    }
    

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

    Declaration

    Swift

    public func check(_ condition: SQLExpressible)

    Parameters

    condition

    The checked condition

  • Adds a CHECK constraint.

    try db.create(table: "player") { t in
        t.column("personalPhone", .text)
        t.column("workPhone", .text)
        t.check(sql: "personalPhone IS NOT NULL OR workPhone IS NOT NULL")
    }
    

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

    Declaration

    Swift

    public func check(sql: String)

    Parameters

    sql

    An SQL snippet

  • Appends a table constraint defined with raw SQL.

    // CREATE TABLE player (
    //   ...
    //   CHECK (score >= 0)
    // )
    try db.create(table: "player") { t in
        ...
        t.constraint(sql: "CHECK (score >= 0)")
    }
    

    Declaration

    Swift

    public func constraint(sql: String)
  • Appends a table constraint defined with an SQL literal.

    Literals allow you to safely embed raw values in your SQL, without any risk of syntax errors or SQL injection:

    // CREATE TABLE player (
    //   ...
    //   CHECK (score >= 0)
    // )
    let minScore = 0
    try db.create(table: "player") { t in
        ...
        t.constraint(literal: "CHECK (score >= \(minScore))")
    }
    

    Declaration

    Swift

    public func constraint(literal: SQL)