繁体   English   中英

使用Vapor框架设置数据库连接

[英]Setting up database connection using Vapor framework

我正在尝试使用Swift构建API,并且选择使用Vapor。

我已经创建了一个SQLite数据库,并能够使用DB客户端连接到它。

现在,我希望我的Swift Vapor项目也可以使用FluentSQLite软件包连接到它。

我已经在项目的根文件夹中创建了数据库:

/Users/rutgerhuijsmans/Documents/runk-3.0

我的数据库叫做runk-3.0-database

该文件夹如下所示:

在此处输入图片说明

我尝试使用以下配置连接到我的数据库:

import FluentSQLite
import Vapor

/// Called before your application initializes.
public func configure(_ config: inout Config, _ env: inout Environment, _ services: inout Services) throws {
    /// Register providers first
    try services.register(FluentSQLiteProvider())

    /// Register routes to the router
    let router = EngineRouter.default()
    try routes(router)
    services.register(router, as: Router.self)

    /// Register middleware
    var middlewares = MiddlewareConfig() // Create _empty_ middleware config
    /// middlewares.use(FileMiddleware.self) // Serves files from `Public/` directory
    middlewares.use(ErrorMiddleware.self) // Catches errors and converts to HTTP response
    services.register(middlewares)

    let sqlite: SQLiteDatabase?
    do {
        sqlite = try SQLiteDatabase(storage: .file(path: "runk-3.0-database"))
        print("data base connected") // This gets printed

        /// Register the configured SQLite database to the database config.
        var databases = DatabasesConfig()
        databases.add(database: sqlite!, as: .sqlite)
        services.register(databases)

        /// Configure migrations
        var migrations = MigrationConfig()
        migrations.add(model: User.self, database: .sqlite)
        services.register(migrations)
    } catch {
        print("couldn't connect") // This doesn't get printed
    }
}

我究竟做错了什么?

正如IMike17解释的那样,您的代码只是将新的DB文件创建到Build / Products / Debug或release文件夹中。 您必须动态设置完整路径,如下所示:

do {
let directory = DirectoryConfig.detect()
let filePath = directory.workDir + "runk-3.0-database"
sqlite = try SQLiteDatabase(storage: .file(path: filePath)) 
......

如果仅指定名称,则使用.file(path:“ runk-3.0-database”)方法,将在“派生数据”文件夹中创建具有指定名称的数据库文件。 如果该文件存在于“派生数据”文件夹中,则SQLiteDatabase会使用它。 因此,在清理构建文件夹时将擦除数据库。

控制台会打印出“派生数据”的路径,您可以在其中找到数据库:

Running default command: /Users/username/Library/Developer/Xcode/DerivedData/SQLiteDB-xxxxxxxxxxxxxxxxxxxxxxx/Build/Products/Debug/

如果您在项目中使用数据库的完整路径,那么将使用该文件。 如下更改您的init方法,应该适合于本地环境:

sqlite = try SQLiteDatabase(storage: .file(path: "/Users/rutgerhuijsmans/Documents/runk-3.0/runk-3.0-database"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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