LinusG.
LinusG.

Reputation: 28902

Vapor connect to SQLite Database

I'm trying to setup a Vapor 3 project with SQLite.
In the configure.swift file, I have the following setup related to sqlite:

try services.register(FluentSQLiteProvider())

...

// Get the root directory of the project
// I have verified that the file is present at this path
let path = DirectoryConfig.detect().workDir + "db_name.db"
let sqlite: SQLiteDatabase
do {
    sqlite = try SQLiteDatabase(storage: .file(path: path))
    print("connected") // called
} catch {
    print(error) // not called
    return
}

var databases = DatabasesConfig()
databases.add(database: sqlite, as: .sqlite)
services.register(databases)

In the database, I have a table called posts, that I want to query and return all entries from:

database table

This is the Post implementation inside /Sources/App/Models/:

final class Post: Content {
    var id: Int?
    var title: String
    var body: String

    init(id: Int? = nil, title: String, body: String) {
        self.id = id
        self.title = title
        self.body = body
    }
}
extension Post: SQLiteModel, Migration, Parameter { }

I have also added the migration in configure.swift:

var migrations = MigrationConfig()
migrations.add(model: Post.self, database: .sqlite)
services.register(migrations)

In routes.swift, I define the posts route as follows:

router.get("posts") { req in
    return Post.query(on: req).all()
}

Now, when calling localhost:8080/posts, I get:

[]

Have I not properly connected the database?
Have I missed something?

Upvotes: 2

Views: 769

Answers (1)

Mukesh
Mukesh

Reputation: 2902

It seems like the table name generated by fluent is different than your db table name as Fluent generate the table with name same as the Model class name. In your case Post.

Add static property entity in your model class Post to define a custom table name.

like this:

public static var entity: String {
    return "posts"
}

Upvotes: 5

Related Questions