【问题标题】:Raw Query In Vapor 4Vapor 4 中的原始查询
【发布时间】:2020-09-20 11:27:00
【问题描述】:

在 Vapor 3 中,我能够获得到数据库的 newConnection 并使用以下方法调用原始 sql 查询:

return request.withNewConnection(to: .mysql) { (con) -> EventLoopFuture<T> in  
    return con.raw(sql)...
}

现在我正在将我的代码迁移到 Vapor 4,函数 raw 或 withNewConnection 不见了,我可以使用什么来进行原始查询。

重现步骤

return request.withNewConnection(to: .mysql) { (con) -> EventLoopFuture<T> in  
...
}

错误: 无法根据成员“mysql”推断上下文基础 “Request”类型的值没有成员“withNewConnection”

预期行为

在 request.db 中有一个函数可以让我获得新连接或运行原始查询。

环境

  • Vapor 框架版本:4.7.1
  • Vapor 工具箱版本:vapor-beta
  • 操作系统版本:macOS Catalina

【问题讨论】:

标签: vapor


【解决方案1】:

错误:无法根据成员“mysql”推断上下文基础“请求”类型的值没有成员“withNewConnection”

不幸的是,使用 Fluent 4 数据库标识符 .mysql 不再是通用的。所以你必须一直像这样request.db as! SQLDatabase 来获取像raw(...) 这样的方法来执行你的原始查询。现在,连接在引擎盖下的深处。

我建议用 Vapor 4 看看 SwifQL + Bridges

import Vapor
import MySQLBridge

struct MyResult: Codable {
    let column1: String
    let column2: Int
}
func someHandler(_ req: Request) throws -> EventLoopFuture<[MyResult]> {
    req.mysql.connection(to: .myDatabase) { conn in
        SwifQL
            .select(\SomeTable.$column1, \SomeTable.$column2)
            .from(SomeTable.table)
            .execute(on: conn)
            .all(decoding: MyResult.self)
    }
}

SwifQL 是一种 DSL,它使您能够安全地构建任何原始查询,而 Bridges 是 mysql-niopostgres-nio 等数据库驱动程序的助手,因此它只为它们提供了方便的方法。

【讨论】:

    【解决方案2】:

    试试这个:

    import SQLKit
    struct Row:Content
    {
        // fields go here
    }
    struct Context:Decodable
    {
        let rows:[Row]
    }
    func rawDemo(_ request:Request) throws -> EventLoopFuture<View>
    {
        return (request.db as! SQLDatabase).raw("SELECT * FROM MyTable").all(decoding:Row.self).flatMap
        {
            results in
            let context = Context(rows:results)
            return request.view.render("rawDemo", context)
        }
    }
    

    您必须导入SQLKit 模块并将request.db 转换为SQLDatabase,如图所示,才能执行原始查询。一旦你这样做了,它就变得很像 Vapor 3 方法。但是,借助 Vapor 4 中提供的新功能,我现在已经设法摆脱了所有原始查询并替换为流畅的 Fluent 查询!

    【讨论】:

    • 谢谢这个工作正常!而且我也喜欢新的 Vapor 4 fluent,我只需要它来处理涉及铸造的真正具体的查询。
    • 它像手套一样合身。
    猜你喜欢
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 2013-09-27
    • 1970-01-01
    • 2013-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多