Database
Introduction
Alchemy makes interacting with SQL databases a breeze. You can use raw SQL, the fully featured query builder or the built in ORM, Rune.
Connecting to a Database
Out of the box, Alchemy supports connecting to Postgres & MySQL databases. Database is a Service
and so is configurable with the config
function.
Querying data
You can query with raw SQL strings using Database.rawQuery
. It supports bindings to protect against SQL injection.
Note regardless of SQL dialect, please use ?
as placeholders for bindings. Concrete Database
s representing dialects that use other placeholders, such as PostgresDatabase
, will replace ?
s with the proper placeholder.
Handling Query Responses
Every query returns a future with an array of SQLRow
s that you can use to parse out data. You can access all their columns with allColumns
or try to get the value of a column with .get(String) throws -> SQLValue
.
Note that SQLValue
contains functions for casting the value to a specific Swift data type, such as .string()
above.
These functions will throw if the value isn’t convertible to that type.
Transactions
Sometimes, you’ll want to run multiple database queries as a single atomic operation. For this, you can use the transaction()
function; a wrapper around SQL transactions. You’ll have exclusive access to a database connection for the lifetime of your transaction.