swift - 在 Vapor 中使用原始 sql 返回条目总数

我正在尝试路由传入的 GET返回以下字符串:

“我们的模型总数是12”

其中 12 是保存到数据库中的特定模型的实际条目数。

现在执行此操作的一种方法是使用以下内容:

func index(_ req: Request) throws -> Future<String> {
  return Model.query(on: req).all().map { models in
    return "The total number of our models is \(models.count)"
  }
}

这是记录最多但同时效率最低的方法。我找不到任何映射到 "SELECT COUNT(*) FROM Model;" 的查询

所以我求助于针对数据库编写自己的原始 SQL。我已经走到这一步了,但我不知道如何映射 [PostgreSQLColumn : PostgreSQLData]Future<String>

  func index(_ req: Request) throws -> Future<String> {
    return req.withPooledConnection(to: .psql) { (conn) in
      conn.raw("SELECT COUNT(*) FROM MODEL").all()
          ///....something something 
    }
  }

最佳答案

您可以使用 all(decoding:)first(decoding: ) 解码返回的原始行

struct CountResult: Content {
    let count: Int64
}

func index(_ req: Request) throws -> Future<String> {
    req.withPooledConnection(to: .psql) { conn in
        conn.raw("SELECT COUNT(*) as count FROM MODEL").first(decoding: CountResult.self).map {
            $0?.count ?? 0
        }.map {
            "The total number of our models is \($0)"
        }
    }
}

我还建议看一下 SwifQL和 Bridges以类型安全的方式处理原始 SQL 的库。

使用纯 SwifQL

struct CountResult: Content {
    let count: Int64
}

func index(_ req: Request) throws -> Future<String> {
    req.withPooledConnection(to: .psql) { conn in
        let query = SwifQL
            .select(Fn.count(MyTable.table.*))
            .from(MyTable.table)
        return conn.raw(query)
            .first(decoding: CountResult.self)
            .map { $0?.count ?? 0 }
            .map {
                "The total number of our models is \($0)"
            }
    }
}

使用 SwifQL + Bridges

func index(_ req: Request) throws -> Future<String> {
    MyTable.query(on: .psql, on: req).count().map {
        "The total number of our models is \($0)"
    }
}

https://stackoverflow.com/questions/61846890/

相关文章:

php - 如何解决 "The process has been signaled with sig

python - 将 Selenium 与 PyCharm CE 一起使用时的弃用问题

swiftui - 我怎样才能在 SwiftUI 中实现类似于 radiogroup 的一种可能选择

react-native - React 导航 5(导航到另一个堆栈屏幕)

c - 使用 for 循环初始化一个数组,并将最终数组元素的值作为条件(在 C 中)

forms - 如何判断表单字段在 vue.js 中是否无效

python - 生成最多 2 个重复的 3 个数字的列表

scala - 通过方法类型参数分配给类型成员的值打破了类型等价

amazon-web-services - 有没有办法使用 aws cloudformation 更

typescript - 如何使用可选的唯一字符串定义数组 typescript 接口(interf