Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I log SQL statements in Vapor 3/Fluent?

It looks like in Vapor 2 you could do something like:

let query = <some fluent query object>
logger?.debug(query)

and it would print out the full SQL statement, but I'm not seeing any documentation of how to do that now in Vapor 3.

How can I see what SQL is being generated by my QueryBuilder?

like image 999
Elliot Schrock Avatar asked Mar 06 '23 04:03

Elliot Schrock


1 Answers

Thanks to Nick in the comments, who pointed me to the right set of docs. This can be accomplished by using the enableLogging method. So now my configure.swift includes this code:

let dbConfig: PostgreSQLDatabaseConfig
if let url = Environment.get("DATABASE_URL"), let psqlConfig = PostgreSQLDatabaseConfig(url: url, transport: .unverifiedTLS) {
    dbConfig = psqlConfig
} else {
    dbConfig = ...something for the local db...
}

let postgresql = PostgreSQLDatabase(config: dbConfig)

/// Register the configured SQLite database to the database config.
var databases = DatabasesConfig()
databases.enableLogging(on: .psql)
databases.add(database: postgresql, as: .psql)
services.register(databases)

The important line being the third from the bottom. For a while I was trying to enable debugging on PostgreSQLDatabaseConfig, so to anyone in the future, take note that you're enabling it on the DatabasesConfig object instead.

like image 130
Elliot Schrock Avatar answered Mar 11 '23 08:03

Elliot Schrock