简体   繁体   中英

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:

数据库表

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?

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"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM