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())
}
-
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 }
-
Initialize an instance of Table.
Declaration
Swift
public required init(name: String? = nil)Parameters
nameThe 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
tableNameThe name of the table.
columnsThe array of columns inside the table.
-
Function to build a String representation for referencing a
Tableinstance. AQueryBuilderis used to handle variances between the various database engines and produce a correct SQL description. This function is required to conform to theBuildableprotocol.Usage Example:
In this example,
QueryBuilderandTableinstances 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 formattableName AS aliaslet queryBuilder = QueryBuilder() let todotable = ToDoTable() let description = try todotable.build(queryBuilder: queryBuilder) print(description) // Prints toDoTableThrows
QueryError.syntaxError if query build fails.Declaration
Swift
public func build(queryBuilder: QueryBuilder) throws -> StringParameters
queryBuilderThe 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 -> StringReturn Value
A String representation of the table create statement.
-
Function to return a copy of the current
Tableinstance with the given name as its alias. This is equivalent to the SQL AS operator.Usage Example:
In this example, a
Tableinstance is created. An alias for thisTableinstance 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) -> SelfParameters
newNameA String containing the alias for the table.
Return Value
A new Table instance with the alias.
-
Function to return a
Rawinstance, which will execute a TRUNCATE query on the currentTableinstance.Usage Example:
In this example, a
Tableinstance is created. The truncate function is called to create aRawinstance 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() -> RawReturn Value
An instance of
Raw. -
Function to return a
Rawinstance, which will execute a DROP TABLE query on the currentTableinstance.Usage Example:
In this example, a
Tableinstance is created. The drop function is called to create aRawinstance 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() -> RawReturn Value
An instance of
Raw. -
Function to create a table in an SQL database, with matching parameters to an instance of the
Tableclass.Usage Example:
In this example, a
Tableinstance 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. TheQueryResultis then handled by “queryHandler”, a function, which accepts aQueryResult.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
connectionThe connection to the database.
onCompletionThe function to be called when the execution of the query has completed.
-
Function to set multiple
Columninstances, as a composite primary key, in theTableinstance. 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
Tableinstance 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]) -> SelfParameters
columnsAn Array of columns that constitute the primary key.
Return Value
A new instance of
Table. -
Function to set a single
Columninstance as a primary key, in theTableinstance. 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
idcolumn for the tablepersonTable.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...) -> SelfParameters
columnsA single column that constitutes the primary key.
Return Value
A new instance of
Table. -
Function to set a multiple
Columninstance, as a composite foreign key, in theTableinstance 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,
Tableinstances 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])Parameters
columnsAn Array of columns that constitute the foreign key.
referencesAn 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
Columninstance, as a foreign key, in theTableinstance. 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,
Tableinstances 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)Parameters
columnsA column that is the foreign key.
referencesA column in the foreign table the foreign key references.
Return Value
A new instance of
Table.
View on GitHub
Table Class Reference