Skip to content

General query language

David Ask edited this page Mar 8, 2016 · 1 revision

SELECT

// Select specified fields
Select(["id", "name"], from: "artists")

// Select all fields
Select(from: "artists")

// Limit to one result
Select(["id", "name"], from: "artists").first

// Join
Select(from: "artists").join("albums", using: .Inner, leftKey: "artists.id", rightKey: "albums.artist_id")

// Limit & Offset
Select(from: "artists").limit(10).offset(1)

// Ordering
Select(from: "artists").orderBy(.Descending("name"), .Ascending("id"))

You can chain most methods, ending up with a query that looks like this.

let result = try Select(from: "artists")
    .join("albums", using: .Inner, leftKey: "artists.id", rightKey: "albums.artist_id")
    .offset(1)
    .limit(1)
    .orderBy(.Descending("name"), .Ascending("id"))
    .execute(connection)

UPDATE

Update("artists", set: ["name": "Mike Snow"])

DELETE

Delete(from: "albums")

Filtering queries

SELECT, UPDATE, and DELETE queries can be filtered like so:

Select(from: "artists").filter(field("id") >= 1 && field("genre") == field("genre") || field("id") == 2)

INSERT

Insert(["name": "Lady Gaga"], into: "artists")

Running built queries

All built queries have an execute method, that takes a Connection class ass a parameter.

try Select(from: "albums").execute(connection)

You can also pass the query to Connection.execute.

try connection.execute(Select(from: "albums"))
Clone this wiki locally