Skip to content

Commit

Permalink
Format SQL queries when printing them to the logs
Browse files Browse the repository at this point in the history
Before, the query would be formatted equivalent to the input string:

```
[2020-04-18T23:47:32Z DEBUG sqlx_core::postgres::executor] SELECT id, queue, ..., elapsed: 2.320µs

        SELECT id, queue, payload, status, priority, created_at, updated_at
    FROM jobs
    WHERE status = $1
    ORDER BY priority ASC, created_at ASC

```

After, the query is formatted cleanly and consistently:

```
[2020-04-19T00:30:18Z DEBUG sqlx_core::postgres::executor] SELECT id, queue, ..., elapsed: 2.280µs

    SELECT
      id,
      queue,
      payload,
      status,
      priority,
      created_at,
      updated_at
    FROM
      jobs
    WHERE
      status = $1
    ORDER BY
      priority ASC,
      created_at ASC

```

This uses the `sqlformat` crate, which was ported from the
Javascript `sql-formatter-plus` library specifically for this purpose.
  • Loading branch information
shssoichiro authored and mehcode committed Apr 19, 2020
1 parent 1cdfb85 commit f73149a
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 4 deletions.
18 changes: 18 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions sqlx-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ uuid = { version = "0.8.1", default-features = false, optional = true, features
serde = { version = "1.0", features = [ "derive" ], optional = true }
time = { version = "0.2.7", optional = true }
serde_json = { version = "1.0", features = [ "raw_value" ], optional = true }
sqlformat = "0.1.0"

# <https://github.com/jgallagher/rusqlite/tree/master/libsqlite3-sys>
[dependencies.libsqlite3-sys]
Expand Down
16 changes: 12 additions & 4 deletions sqlx-core/src/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,25 @@ macro_rules! log_execution {
let elapsed = timer.elapsed();
if elapsed >= std::time::Duration::from_secs(1) {
log::warn!(
"{} ..., elapsed: {:.3?}\n\n {}\n",
"{} ..., elapsed: {:.3?}\n\n{}\n",
crate::logging::parse_query_summary(query_string),
elapsed,
query_string
sqlformat::format(
query_string,
&sqlformat::QueryParams::None,
sqlformat::FormatOptions::default()
)
);
} else {
log::debug!(
"{} ..., elapsed: {:.3?}\n\n {}\n",
"{} ..., elapsed: {:.3?}\n\n{}\n",
crate::logging::parse_query_summary(query_string),
elapsed,
query_string
sqlformat::format(
query_string,
&sqlformat::QueryParams::None,
sqlformat::FormatOptions::default()
)
);
}
result
Expand Down

0 comments on commit f73149a

Please sign in to comment.