stephencelis / SQLite.swift

A type-safe, Swift-language layer over SQLite3.
MIT License
9.57k stars 1.54k forks source link

How do I convert data returned from sql query #1195

Closed duncangroenewald closed 1 year ago

duncangroenewald commented 1 year ago

I can't find any documentation that explains how to convert the returned column data to Swift types.

The example provided is singularly unhelpful

for row in try db.prepare("SELECT id, email FROM users") {
    print("id: \(row[0]), email: \(row[1])")
    // id: Optional(2), email: Optional("betty@icloud.com")
    // id: Optional(3), email: Optional("cathy@icloud.com")
}

If I try and cast the row[0] as? Int or anything else for that matter is always fails.

How does one extract the original type value ?

nathanfallet commented 1 year ago

You should use expressions instead:

let users  = Table("users")
let id = Expression<Int>("id")
let email = Expression<String>("email")

for row in try db.prepare(users.select(id, email)) {
    let idAsInt = try row.get(id)
    let emailAsString = try row.get(email)
    // You can do whatever you want with `idAsInt` and `emailAsString` which are safe Int/String
}

This is explained in the documentation here.