Search code examples
swiftpostgresqlfluentvapor

Can I use straight SQL to get the number of rows in a table using Fluent (Vapor)?


I want to do this SELECT COUNT(column_name) FROM table_name; to get back an Int and return it as part of a response. I don't want to have to load every object into memory just to get the count; like this: User.query().all().count

Please tell me this is possible with Fluent! :)


Solution

  • It is possible with raw method. Here you have example for MySQL

    guard let mysql = drop.database?.driver as? MySQLDriver else {
        return
    }
    
    let count = try mysql.raw("SELECT COUNT(column_name) FROM table_name")
    

    Also, every driver has to implement raw method

    public protocol Driver {
        var idKey: String { get }
        func query<T: Entity>(_ query: Query<T>) throws -> Node
        func schema(_ schema: Schema) throws
        func raw(_ raw: String, _ values: [Node]) throws -> Node
    }