We have been using this SQL formatter at work that we built in house. With the help of an LLM we managed to extract it from our code base and make it a proper tool for general use.
pgfmt, a formatter for PostgreSQL SQL files and for the SQL inside Haskell hasql-th quasiquotes.
We’ve taken lots of care in making sure the formatter does not alter the meaning of the SQL it outputs. Before rewriting a statement, pgfmt parses the result with libpg_query (PostgreSQL’s own parser) and compares parse trees. If they differ, the statement is left exactly as it was and pgfmt exits non-zero. We’ve run it over thousands of production migrations and hasql-th blocks.
The style it follows is quite arbitrarily our own preference. We never did agree in the end on what we liked, but after a while we just accepted the benefit of having a single style and the arguments were over.
For .hs files it formats the SQL inside singletonStatement, vectorStatement and the other hasql-th quoters, and leaves the Haskell alone, so it works alongside fourmolu or ormolu:
userEmails :: Statement Int64 (Vector (Text, Maybe Text))
userEmails =
[vectorStatement|
select u.name :: text, e.address :: text? from users u left join emails e on e.user_id = u.id where u.org_id = $1 :: int8 order by u.name
|]
becomes
userEmails :: Statement Int64 (Vector (Text, Maybe Text))
userEmails =
[vectorStatement|
select
u.name::text
, e.address::text?
from users u
left join emails e
on e.user_id = u.id
where u.org_id = $1::int8
order by u.name
|]
It skips comments and string literals the way GHC’s lexer does, so a quasiquote inside a string or a comment is never touched. Each quasiquote is only rewritten if it parses back to the same AST.
Other features:
--check for CI and pre-commit--keyword-case lower|upper``--quoter NAME for your own quoter aliases
Try it:
nix run --accept-flake-config github:kronor-io/pgfmt -- --check src/**/*.hs
Feedback and issues are welcome: GitHub - kronor-io/pgfmt: Format PostgreSQL files, checked against PostgreSQL's own parser. Part of sqitchcraft: https://kronor-io.github.io/sqitchcraft/ · GitHub