1

I am attempting to implement the code as displayed in the example. For example, when I place this in the app delegate:

import SQLite

let db = Database("path/to/db.sqlite3")

let users = db["users"]
let id = Expression<Int64>("id")
let name = Expression<String?>("name")
let email = Expression<String>("email")`

It seems to work okay. But then when I go to use the create table code:

db.create(table: users) { t in
    t.column(id, primaryKey: true)
    t.column(name)
    t.column(email, unique: true)
}

It doesn't seem to like it. My understanding is the table creation code needs to go in a method. But which method does it belong in? Or in a new method altogether?

Sorry if the question seems simplistic. I'm new to Swift as well as to SQLite. :-)

Eric LaRue
  • 25
  • 3

1 Answers1

1

The top block is OK because you are merely assigning lazy-loading global variables.

The bottom block is actually executing code and must take place inside a function. Here's an example structure:

import SQLite

struct User {

    static let connection = Database()
    static let table = connection["users"]

    static let id = Expression<Int64>("id")
    static let name = Expression<String?>("name")
    static let email = Expression<String>("email")`

    static func createTable() {
        db.create(table: table) { t in
            t.column(id, primaryKey: true)
            t.column(name)
            t.column(email, unique: true)
        }
    }

}

Elsewhere (in another function), you can call User.createTable() to create the table.

stephencelis
  • 4,954
  • 2
  • 29
  • 22