Table

open class Table : Buildable

The Table class is used to create a class in Swift that maps to an external SQL database table. To reference a table, you must implement this class and define the table name as well as the Column instances present. The Table class then provides methods to build SQL String descriptions for the various database engines.

Usage Example:

In this example, we define a ToDoTable class which maps to an existing table in a SQL database. An instance of the ToDoTable class is then initialized and used in a SQL SELECT query to retrieve the data from the table within the external database.

public class ToDoTable: Table {
   let tableName = "toDoTable"
   let toDo_id = Column("toDo_id", Int32.self, autoIncrement: true, primaryKey: true, notNull: true, unique: true)
   let toDo_title = Column("toDo_title", String.self, notNull: true)
   let toDo_completed = Column("toDo_completed", Bool.self, defaultValue: false)
}

public class Application {
   let selectQuery = Select(from: ToDoTable())
}

Parameters

  • The columns inside the table.

    Declaration

    Swift

    public private(set) var columns: [Column] { get }
  • The alias of the table.

    Declaration

    Swift

    public private(set) var alias: String? { get }
  • The name of the table to be used inside a query, i.e., either its alias (if exists) or its name.

    Declaration

    Swift

    public var nameInQuery: String { get }

Initializer

  • Initialize an instance of Table.

    Declaration

    Swift

    public required init(name: String? = nil)

    Parameters

    name

    The name of the table (Optional).

  • Initialize an instance of the table with a table name and an array of Columns.

    Declaration

    Swift

    public required init(tableName: String, columns: [Column])

    Parameters

    tableName

    The name of the table.

    columns

    The array of columns inside the table.

String Representation

  • Function to build a String representation for referencing a Table instance. A QueryBuilder is used to handle variances between the various database engines and produce a correct SQL description. This function is required to conform to the Buildable protocol.

    Usage Example:

    In this example, QueryBuilder and Table instances are initialized. (ToDoTable() is defined in the class example). The build function is then called to produce a String description and print the results. If the alias is set, this will return the format tableName AS alias

    let queryBuilder = QueryBuilder()
    let todotable = ToDoTable()
    let description = try todotable.build(queryBuilder: queryBuilder)
    print(description)
    // Prints toDoTable
    

    Throws

    QueryError.syntaxError if query build fails.

    Declaration

    Swift

    public func build(queryBuilder: QueryBuilder) throws -> String

    Parameters

    queryBuilder

    The QueryBuilder to use.

    Return Value

    A String representation of the table.

  • Function that returns the SQL CREATE TABLE statement for this table in string fromat.

    Usage Example:

    In this example we define a simple table named exampleTable and then print its description

    class ExampleTable: Table {
        let tableName = "ExampleTable"
        let name = Column("name", String.self)
    }
    let examples = ExampleTable()
    let description = try examples.description(connection: getConnection(from: postgresPool))
    print(description)
    // Prints CREATE TABLE ExampleTable (name text)
    

    Throws

    QueryError.syntaxError if statement build fails.

    Declaration

    Swift

    public func description(connection: Connection) throws -> String

    Return Value

    A String representation of the table create statement.

Create Alias

  • Function to return a copy of the current Table instance with the given name as its alias. This is equivalent to the SQL AS operator.

    Usage Example:

    In this example, a Table instance is created. An alias for this Table instance is then created and its alias printed.

    let todotable = ToDoTable()
    let aliasTable = todotable.as("new name")
    print(String(describing: aliasTable.alias))
    // Prints Optional("new name")
    

    Declaration

    Swift

    public func `as`(_ newName: String) -> Self

    Parameters

    newName

    A String containing the alias for the table.

    Return Value

    A new Table instance with the alias.

Query Database

  • Function to return a Raw instance, which will execute a TRUNCATE query on the current Table instance.

    Usage Example:

    In this example, a Table instance is created. The truncate function is called to create a Raw instance of a String to execute the TRUNCATE SQL Query for todotable.

    let todotable = ToDoTable()
    let truncateRaw = todotable.truncate()
    print(truncateRaw)
    // Prints Raw(query: "TRUNCATE TABLE", tables: [Application.ToDoTable])
    

    Declaration

    Swift

    public func truncate() -> Raw

    Return Value

    An instance of Raw.

  • Function to return a Raw instance, which will execute a DROP TABLE query on the current Table instance.

    Usage Example:

    In this example, a Table instance is created. The drop function is called to create a Raw instance of a String to execute the DROP TABLE SQL Query for todotable.

    let todotable = ToDoTable()
    let dropRaw = todotable.drop()
    print(dropRaw)
    //Prints Raw(query: "DROP TABLE", tables: [Application.ToDoTable])
    

    Declaration

    Swift

    public func drop() -> Raw

    Return Value

    An instance of Raw.

  • Function to create a table in an SQL database, with matching parameters to an instance of the Table class.

    Usage Example:

    In this example, a Table instance is created and a connection to an SQL database is established. The create function is called, executing an SQL query to create a matching table in the database. The QueryResult is then handled by “queryHandler”, a function, which accepts a QueryResult.

    public func queryHandler(queryResult: QueryResult) {
       print(queryResult)
    }
    let todotable = ToDoTable()
    let connection = PostgreSQLConnection(host: "localhost", port: 5432, options: [.databaseName("ToDoDatabase")])
    todotable.create(connection: connection, onCompletion: queryHandler)
    

    Declaration

    Swift

    public func create(connection: Connection, onCompletion: @escaping ((QueryResult) -> ()))

    Parameters

    connection

    The connection to the database.

    onCompletion

    The function to be called when the execution of the query has completed.

Assign Keys

  • Function to set multiple Column instances, as a composite primary key, in the Table instance. The function also validates the columns to ensure they belong to the table and do not conflict with the definition of a primary key.

    Usage Example:

    In this example, columns for first and last name are initialized and a Table instance called personTable is created. The personTable primary key is then set to be a composite of firstColumn and lastColumn.

    let firstColumn = Column("firstName", String.self, notNull: true)
    let lastColumn = Column("lastName", String.self, notNull: true)
    public class PersonTable: Table {
       let tableName = "personTable"
       let firstName = firstColumn
       let lastName = lastColumn
       let dateOfBirth = Column("toDo_completed", String.self)
    }
    var personTable = PersonTable()
    personTable = personTable.primaryKey([firstColumn, lastColumn])
    

    Declaration

    Swift

    public func primaryKey(_ columns: [Column]) -> Self

    Parameters

    columns

    An Array of columns that constitute the primary key.

    Return Value

    A new instance of Table.

  • Function to set a single Column instance as a primary key, in the Table instance. This function calls the composite primaryKey function with a single column to create a single primary key.

    Usage Example:

    In this example, the primary key is set to the id column for the table personTable.

    public class PersonTable: Table {
       let tableName = "personTable"
       let id = Column("id", Int32.self, notNull: true)
       let firstName = Column("firstName", String.self, notNull: true)
       let lastName = Column("lastName", String.self, notNull: true)
    }
    var personTable = PersonTable()
    personTable = personTable.primaryKey(personTable.id)
    

    Declaration

    Swift

    public func primaryKey(_ columns: Column...) -> Self

    Parameters

    columns

    A single column that constitutes the primary key.

    Return Value

    A new instance of Table.

  • Function to set a multiple Column instance, as a composite foreign key, in the Table instance referencing multiple columns in another Table. The function also validates the columns to ensure they belong to the table and do not conflict with the definition of an existing foreign key.

    Usage Example:

    In this example, Table instances called personTable and employeeTable are created. A composite primary key is created on “employeeTable”. A “personTable” foreign key is then set to be a composite of firstColumn and lastColumn, which reference firstName and surname in employeeTable.

    public class EmployeeTable: Table {
        let tableName = "employeeTable"
        let firstName = Column("firstName", String.self, notNull: true)
        let surname = Column("surname", String.self, notNull: true)
        let monthlyPay = Column("monthlyPay", Int32.self)
    }
    public class PersonTable: Table {
        let tableName = "personTable"
        let firstName = Column("firstName", String.self, notNull: true)
        let lastName = Column("lastName", String.self, notNull: true)
        let dateOfBirth = Column("toDo_completed", String.self)
    }
    var personTable = PersonTable()
    var employeeTable = EmployeeTable()
    employeeTable = employeeTable.primaryKey([employeeTable.firstname, employeeTable.surname])
    personTable = personTable.foreignKey([personTable.firstName, personTable.lastName], references: [employeeTable.firstName, employeeTable.surname])
    

    Declaration

    Swift

    public func foreignKey(_ columns: [Column], references: [Column]) -> Self

    Parameters

    columns

    An Array of columns that constitute the foreign key.

    references

    An Array of columns from the foreign table that are referenced by the foreign key.

    Return Value

    A new instance of Table.

  • Function to set a single Column instance, as a foreign key, in the Table instance. The function also validates the column to ensure it belongs to the table and does not conflict with the definition of an existing foreign key.

    Usage Example:

    In this example, Table instances called personTable and employeeTable are created. A “personTable” foreign key is then set to be id, which references identifier in employeeTable.

    public class EmployeeTable: Table {
        let identifier = Column("identifier", Int32.self, notNull: true)
        let monthlyPay = Column("monthlyPay", Int32.self)
        let employeeBand = Column("employeeBand", String.self)
    }
    public class PersonTable: Table {
        let tableName = "personTable"
        let id = Column("id", Int32.self, notNull: true)
        let firstName = Column("firstName", String.self, notNull: true)
        let lastName = Column("lastName", String.self, notNull: true)
    }
    var personTable = PersonTable()
    var employeeTable = EmployeeTable()
    personTable = personTable.foreignKey(personTable.id, references: employeeTable.identifier)
    

    Declaration

    Swift

    public func foreignKey(_ column: Column, references: Column) -> Self

    Parameters

    columns

    A column that is the foreign key.

    references

    A column in the foreign table the foreign key references.

    Return Value

    A new instance of Table.