Search code examples
mysqlsqlswiftfluentvapor

Swift Vapor3 Raw SQL query with new connection


I'm attempting to use Vapor3 to perform raw SQL queries. The supplied documentation for this kind of thing is pretty vague on the website unfortunately.

Essentially I want to do something like:

router.get("example") { req -> Future<View> in
    let leaf = try request.make(LeafRenderer.self)

    // I can't get this next bit to work. Does anyone have any ideas how to do this? I seem to get all sorts of Xcode errors with .mysql, closures etc.
    let users = try request.withNewConnection(to: .mysql) { connection -> EventLoopFuture<[User]> 
       return try connection.raw("select * from users").all(decoding: User.self)
    }

    var context = [String: String]()
    context["user"] = users

    return leaf.render("example", context)
}

Any help on want I'm doing wrong here would be greatly appreciated.

Thanks in advance, Matt


Solution

  • You code was failing because you aren't implementing the closure properly. Your route returns in the let users... closure so the second return is never reached.

    This works:

    router.get("example")
    {
        insecure.get("example") {
            request -> Future<View> in
            return request.withNewConnection(to: .mysql) {
                connection in
                return connection.raw("select * from User").all(decoding: User.self).flatMap(to:View.self) {
                    users in
                    return try request.make(LeafRenderer.self).render("example",["users":users])
                }
            }
        }
    }
    

    The changes are:

    1. There's no need to define leaf until you need it.
    2. The definition of users is now inside the closure.