Skip to content

Database

Josh Wright edited this page Jan 14, 2021 · 4 revisions

Database

A generic type to represent any database you might be interacting with. Currently, the only two implementations are PostgresDatabase and MySQLDatabase. The QueryBuilder and Rune ORM are built on top of this abstraction.

public protocol Database

Requirements

migrations

Any migrations associated with this database, whether applied yet or not.

var migrations: [Migration]

grammar

Functions around compiling SQL statments for this database's SQL dialect when using the QueryBuilder or Rune.

var grammar: Grammar

query()

Start a QueryBuilder query on this database. See Query or QueryBuilder guides.

func query() -> Query

Usage:

database.query()
    .from(table: "users")
    .where("id" == 1)
    .first()
    .whenSuccess { row in
        guard let row = row else {
            return print("No row found :(")
        }

        print("Got a row with fields: \(row.allColumns)")
    }

Returns

The start of a QueryBuilder Query.

runRawQuery(_:​values:​)

Run a parameterized query on the database. Parameterization helps protect against SQL injection.

func runRawQuery(_ sql: String, values: [DatabaseValue]) -> EventLoopFuture<[DatabaseRow]>

Usage:

// No bindings
db.runRawQuery("SELECT * FROM users where id = 1")
    .whenSuccess { rows
        guard let first = rows.first else {
            return print("No rows found :(")
        }

        print("Got a user row with columns \(rows.allColumns)!")
    }

// Bindings, to protect against SQL injection.
db.runRawQuery("SELECT * FROM users where id = ?", values = [.int(1)])
    .whenSuccess { rows
        ...
    }

Parameters

  • sql: The SQL string with '?'s denoting variables that should be parameterized.
  • values: An array, [DatabaseValue], that will replace the '?'s in sql. Ensure there are the same amnount of values as there are '?'s in sql.

Returns

An EventLoopFuture of the rows returned by the query.

shutdown()

Called when the database connection will shut down.

func shutdown() throws

Throws

Any error that occurred when shutting down.

Alchemy
Types
Protocols
Global Typealiases
Global Variables
Global Functions
Fusion
Types
Protocols
Papyrus
Types
Protocols
Clone this wiki locally