Format SQL within SQLx macros
I'm a huge fan of SQLx, and it has always bothered me that SQL within its macros isn't formatted automatically:
sqlx::query!(
r#"
select *
from users
where verified = true
"#
)
So I created sqlx-fmt, a CLI and GitHub Action that formats SQL within SQLx macros in Rust code. It uses sqruff as a formatter under the hood. Tree-sitter is used to parse the Rust code and extract the (raw) string literals within SQLx macros. I had used regexes initially, but that required a lot of edge case handling, which tree-sitter solves elegantly.
Installation
Clone the repo and install SQLx-fmt using cargo:
# install SQLx-fmt
git clone https://github.com/jflessau/SQLx-fmt.git
cd sqlx-fmt
cargo install --path .
If you haven't already, install sqruff, which can also be installed via cargo:
cargo install sqruff
Usage
This CLI has two commands: format and check.
# format code
sqlx-fmt format --path path_to_files
# check if code is formatted
sqlx-fmt check --path path_to_files
Configuration
Optionally, specify a sqruff config file with --config .sqruff. The config file allows you to specify things like SQL dialect, rules to apply, and indentation style. Here's an example .sqruff config file:
[sqruff]
dialect = postgres
rules = ambiguous,capitalisation,convention,layout,references
[sqruff:indentation]
indent_unit = space
tab_space_size = 4
indented_joins = True
GitHub Action
You can also use it as a GitHub Action to automatically run format checks in CI:
steps:
- name: checkout code
uses: actions/checkout@v4
- name: run format checker
uses: jflessau/SQLx-fmt@main
with:
context: "./code_to_format"
config-file: "./code_to_format/.sqruff"
fail-on-unformatted: "true"