sqlalign 1.3.0__tar.gz → 1.3.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {sqlalign-1.3.0 → sqlalign-1.3.1}/CHANGELOG.md +58 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/PKG-INFO +5 -1
- {sqlalign-1.3.0 → sqlalign-1.3.1}/README.md +4 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/docs/guide/cli.md +5 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/docs/guide/dialects.md +7 -1
- {sqlalign-1.3.0 → sqlalign-1.3.1}/docs/guide/faq.md +3 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/docs/v1/cli.html +4 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/docs/v1/dialects.html +6 -1
- {sqlalign-1.3.0 → sqlalign-1.3.1}/docs/v1/faq.html +2 -0
- sqlalign-1.3.1/docs/v1/search-index.json +1 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/docs/v1/settings.html +1 -1
- {sqlalign-1.3.0 → sqlalign-1.3.1}/pyproject.toml +1 -1
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/cli.py +24 -4
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/formatter.py +103 -17
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/gui.py +2 -2
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/keywordcase.py +1 -1
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/layout/__init__.py +13 -2
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/lint.py +21 -9
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/plpgsql.py +34 -14
- sqlalign-1.3.1/src/sqlalign/splitter.py +267 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_construct_sweep.py +28 -10
- sqlalign-1.3.1/tests/test_encoding.py +104 -0
- sqlalign-1.3.1/tests/test_file_invariant.py +84 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_plpgsql.py +37 -0
- sqlalign-1.3.1/tests/test_set_source.py +38 -0
- sqlalign-1.3.1/tests/test_splitter.py +122 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_tsql.py +59 -2
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tools/docs_settings.py +11 -1
- {sqlalign-1.3.0 → sqlalign-1.3.1}/uv.lock +1 -1
- sqlalign-1.3.0/docs/v1/search-index.json +0 -1
- sqlalign-1.3.0/src/sqlalign/splitter.py +0 -255
- sqlalign-1.3.0/tests/test_splitter.py +0 -68
- {sqlalign-1.3.0 → sqlalign-1.3.1}/.github/workflows/ci.yml +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/.github/workflows/release.yml +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/.gitignore +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/.pre-commit-hooks.yaml +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/.sqlfluff +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/CONTRIBUTING.md +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/LICENSE +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/action.yml +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/docs/guide/README.md +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/docs/guide/architecture.md +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/docs/guide/configuration.md +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/docs/guide/getting-started.md +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/docs/guide/style.md +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/docs/index.html +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/docs/v1/architecture.html +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/docs/v1/configuration.html +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/docs/v1/getting-started.html +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/docs/v1/index.html +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/docs/v1/style.html +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/samples/queries.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/scripts/build_fixtures.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/__init__.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/align.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/bodylint.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/casing.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/commas.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/config.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/configfile.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/ir.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/layout/case.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/layout/comments.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/layout/conditions.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/layout/cte.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/layout/ddl.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/layout/dml.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/layout/expr.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/layout/fromjoin.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/layout/grouporder.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/layout/select.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/layout/setop.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/layout/subquery.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/layout/window.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/py.typed +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/sourcecase.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/spelling.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/sqlfluffconfig.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/style.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/src/sqlalign/templating.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/conftest.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/README.md +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__math__log_natural.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__math__median.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__math__percentile_cont.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__math__rand.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__regex__regexp_instr.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests___generalized___ignore_row_if_expression.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests___generalized___truth_expression.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests___generalized__equal_expression.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests___generalized__expression_between.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests___generalized__expression_is_true.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__aggregate_functions__expect_column_distinct_count_to_be_greater_than.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__aggregate_functions__expect_column_distinct_count_to_be_less_than.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__aggregate_functions__expect_column_distinct_count_to_equal.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__aggregate_functions__expect_column_distinct_count_to_equal_other_table.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__aggregate_functions__expect_column_distinct_values_to_be_in_set.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__aggregate_functions__expect_column_distinct_values_to_contain_set.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__aggregate_functions__expect_column_distinct_values_to_equal_set.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__aggregate_functions__expect_column_max_to_be_between.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__aggregate_functions__expect_column_mean_to_be_between.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__aggregate_functions__expect_column_median_to_be_between.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__aggregate_functions__expect_column_min_to_be_between.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__aggregate_functions__expect_column_most_common_value_to_be_in_set.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__aggregate_functions__expect_column_proportion_of_unique_values_to_be_between.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__aggregate_functions__expect_column_quantile_values_to_be_between.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__aggregate_functions__expect_column_stdev_to_be_between.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__aggregate_functions__expect_column_sum_to_be_between.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__aggregate_functions__expect_column_unique_value_count_to_be_between.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__column_values_basic__expect_column_values_to_be_between.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__column_values_basic__expect_column_values_to_be_decreasing.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__column_values_basic__expect_column_values_to_be_in_set.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__column_values_basic__expect_column_values_to_be_in_type_list.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__column_values_basic__expect_column_values_to_be_increasing.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__column_values_basic__expect_column_values_to_be_null.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__column_values_basic__expect_column_values_to_be_of_type.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__column_values_basic__expect_column_values_to_be_unique.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__column_values_basic__expect_column_values_to_have_consistent_casing.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__column_values_basic__expect_column_values_to_not_be_in_set.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__column_values_basic__expect_column_values_to_not_be_null.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__distributional__expect_column_values_to_be_within_n_moving_stdevs.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/dbt-expectations/macros__schema_tests__distributional__expect_column_values_to_be_within_n_stdevs.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/jaffle-shop/models__customers.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/jaffle-shop/models__orders.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/jaffle-shop/models__staging__stg_customers.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/jaffle-shop/models__staging__stg_orders.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/jaffle-shop/models__staging__stg_payments.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/sqlglot/tests__fixtures__identity.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/sqlglot/tests__fixtures__optimizer__optimizer.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/corpus/sqlglot/tests__fixtures__pretty.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/docs/dbt.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/docs/fromblock.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/docs/hero.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/docs/plpgsql.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/01.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/02.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/03.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/04.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/05.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/06.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/07.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/08.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/09.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/10.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/11.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/12.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/13.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/14.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/15.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/16.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/17.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/18.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/19.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/20.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/21.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/22.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/23.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/24.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/25.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/26.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/27.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/28.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/expected/29.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/01.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/02.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/03.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/04.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/05.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/06.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/07.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/08.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/09.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/10.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/11.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/12.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/13.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/14.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/15.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/16.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/17.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/18.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/19.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/20.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/21.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/22.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/23.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/24.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/25.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/26.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/27.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/28.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/fixtures/input/29.sql +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_align.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_align_off.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_align_targets.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_ast_equiv.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_atomic_writes.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_axis_matrix.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_benchmark_tool.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_blank_lines.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_body_census.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_body_comments.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_bodylint.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_boolean_position.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_casing.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_clause_order.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_clauses.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_cli.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_comma_joins_lateral_udf.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_comma_position.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_comment_and_procedure_bugs.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_comment_safety.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_comments.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_comments_in_predicates.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_configfile.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_corpus.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_coverage_round_2.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_ddl.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_decline_naming.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_dialect_config.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_dialect_guard.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_distinct.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_dml.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_docs_examples.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_docs_site.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_dollar_tags.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_expr.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_fetch_and_lateral_subquery.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_file_selection.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_fromjoin.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_golden.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_gui.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_init_config.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_keyword_case.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_knob_combinations.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_line_endings.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_line_ranges.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_lint_flag.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_literal_spelling.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_negated_is_null.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_nested_constructs.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_no_silent_declines.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_on_placement.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_packaging.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_pivot.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_positioning.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_presets.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_quoted_column_aliases.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_remaining_constructs.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_report.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_report_growth_and_policy.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_rewrite_guard.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_river.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_robustness.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_safety.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_select_placement.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_skip.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_source_casing.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_sqlfluff_coexistence.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_sqlfluff_gate.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_sqlglot_conformance.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_stdin_and_api.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_style_knobs.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_subquery.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_table_alias.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_table_names.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_templating.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_trailing_punctuation.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_unaliased_tables.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_upstream_and_tail.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_values_and_joins.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tests/test_width_off_and_body_blanks.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tools/benchmark.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tools/build_docs.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tools/docs.css +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tools/docs.js +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tools/fetch_corpus.py +0 -0
- {sqlalign-1.3.0 → sqlalign-1.3.1}/tools/shots.py +0 -0
|
@@ -1,5 +1,63 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.3.1
|
|
4
|
+
|
|
5
|
+
**If you format T-SQL, upgrade.** In every earlier release with T-SQL support,
|
|
6
|
+
a `GO` line inside a string literal or a block comment split the batch, and
|
|
7
|
+
sqlalign wrote blank lines into the literal. SQL Agent job steps and dynamic
|
|
8
|
+
SQL carry exactly this. The safety check cut both sides at the same false `GO`,
|
|
9
|
+
so it reported nothing. 1.3.0 stays on PyPI: yanking it would install 1.2.0,
|
|
10
|
+
which has the same bug.
|
|
11
|
+
|
|
12
|
+
The rest of this release fixes files that failed on first contact: SSMS files,
|
|
13
|
+
Windows encodings, Redshift escapes, and procedure bodies.
|
|
14
|
+
|
|
15
|
+
### A new check covers the whole file
|
|
16
|
+
|
|
17
|
+
Every check before 1.3.1 ran per statement, on the pieces the splitter cut, so
|
|
18
|
+
a wrong cut was invisible to all of them. sqlalign now compares every string
|
|
19
|
+
literal and every comment in the output against the input, across the whole
|
|
20
|
+
file, including those inside `$$` bodies and after `EXEC` or `CALL`. If any
|
|
21
|
+
differ, the file comes back unformatted with a warning.
|
|
22
|
+
|
|
23
|
+
### Fixed
|
|
24
|
+
|
|
25
|
+
- **`GO` inside a string (T-SQL).** sqlalign finds `GO` lines the way the
|
|
26
|
+
tokenizer does, skipping strings and comments.
|
|
27
|
+
- **`\'` in a Redshift string.** sqlalign read `'it\'s'` as ending at the
|
|
28
|
+
backslash, so every statement after it declined. In a Redshift procedure body
|
|
29
|
+
the same misreading wrote blank lines into the literal. Backslash escapes now
|
|
30
|
+
follow the dialect: Redshift has them, Postgres only in `E'...'`, T-SQL never.
|
|
31
|
+
- **SSMS headers (T-SQL).** `SET ANSI_NULLS ON` / `GO` / `SET QUOTED_IDENTIFIER
|
|
32
|
+
ON` / `GO` above a procedure declined as unsupported `SET`, because sqlalign
|
|
33
|
+
looked for procedures before splitting on `GO`. It now splits on `GO` first.
|
|
34
|
+
- **`TRY`/`CATCH` procedures (T-SQL).** A procedure written `AS BEGIN TRY ...
|
|
35
|
+
END TRY BEGIN CATCH ... END CATCH` was cut after `END TRY`. A `CREATE
|
|
36
|
+
PROCEDURE`, `FUNCTION` or `TRIGGER` now runs to the end of its batch, as SQL
|
|
37
|
+
Server reads it. A `-- sqlalign: skip` above a procedure now covers the
|
|
38
|
+
procedure, and `GRANT CREATE PROCEDURE` no longer counts as one.
|
|
39
|
+
- **UTF-8 on Windows.** Files, stdin, stdout and `--lint` use UTF-8 whatever
|
|
40
|
+
the code page. Valid UTF-8 had failed as "not valid UTF-8", and `--stdout`
|
|
41
|
+
wrote CRLF for LF input.
|
|
42
|
+
- **Byte-order mark.** The first statement of an SSMS-saved file failed to
|
|
43
|
+
parse because the BOM reached the parser. sqlalign sets the BOM aside and
|
|
44
|
+
writes it back.
|
|
45
|
+
- **`SET` with a comment beside it** declined in every dialect. It formats.
|
|
46
|
+
- **`SET NOCOUNT ON` in a T-SQL procedure body** printed the whole procedure in
|
|
47
|
+
its place, and the statement declined. It formats.
|
|
48
|
+
- **Procedure body line breaks.** A body statement the layout engine does not
|
|
49
|
+
handle (a CTAS, `CREATE TABLE`, `RAISE`) was joined onto one line, thousands
|
|
50
|
+
of characters long in real files. sqlalign now cases its keywords and keeps
|
|
51
|
+
its lines.
|
|
52
|
+
- **Array subscripts (Postgres, Redshift).** `a[b[1]]` swallowed the statement
|
|
53
|
+
after it.
|
|
54
|
+
|
|
55
|
+
### Known limits: T-SQL procedures
|
|
56
|
+
|
|
57
|
+
Procedure support is partial. A procedure with `IF` or `WHILE` in its body, a
|
|
58
|
+
`TRY`/`CATCH` block, or header options such as `WITH EXECUTE AS` passes through
|
|
59
|
+
unformatted with a warning. 1.4 works on these.
|
|
60
|
+
|
|
3
61
|
## 1.3.0
|
|
4
62
|
|
|
5
63
|
The release is in two halves. The first is what sqlalign now does that it did
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: sqlalign
|
|
3
|
-
Version: 1.3.
|
|
3
|
+
Version: 1.3.1
|
|
4
4
|
Summary: A SQL formatter that cannot change what your SQL means
|
|
5
5
|
Project-URL: Homepage, https://sqlalign.lumaru.app/
|
|
6
6
|
Project-URL: Documentation, https://sqlalign.lumaru.app/v1/
|
|
@@ -425,6 +425,10 @@ not cover.
|
|
|
425
425
|
variants, cursors/`FOR` loops in plpgsql bodies, comments buried inside an
|
|
426
426
|
expression) pass through byte-identical with a warning rather than being
|
|
427
427
|
reformatted. This is by design: correctness over coverage.
|
|
428
|
+
- **T-SQL procedures are partial.** A procedure with `IF` or `WHILE` in its
|
|
429
|
+
body, a `TRY`/`CATCH` block, or header options such as `WITH EXECUTE AS`
|
|
430
|
+
passes through unformatted with a warning. Procedures holding plain DML,
|
|
431
|
+
`SELECT`, `SET` and `DECLARE` format.
|
|
428
432
|
|
|
429
433
|
## Adding a new golden sample
|
|
430
434
|
|
|
@@ -393,6 +393,10 @@ not cover.
|
|
|
393
393
|
variants, cursors/`FOR` loops in plpgsql bodies, comments buried inside an
|
|
394
394
|
expression) pass through byte-identical with a warning rather than being
|
|
395
395
|
reformatted. This is by design: correctness over coverage.
|
|
396
|
+
- **T-SQL procedures are partial.** A procedure with `IF` or `WHILE` in its
|
|
397
|
+
body, a `TRY`/`CATCH` block, or header options such as `WITH EXECUTE AS`
|
|
398
|
+
passes through unformatted with a warning. Procedures holding plain DML,
|
|
399
|
+
`SELECT`, `SET` and `DECLARE` format.
|
|
396
400
|
|
|
397
401
|
## Adding a new golden sample
|
|
398
402
|
|
|
@@ -54,6 +54,11 @@ sqlalign: error: argument --stdout: not allowed with argument --check
|
|
|
54
54
|
A file with lone `\r` (classic-Mac) line endings is not a shape sqlalign models;
|
|
55
55
|
it is passed through untouched with a warning.
|
|
56
56
|
|
|
57
|
+
Files, stdin and stdout are UTF-8 whatever the system locale, and stdout writes
|
|
58
|
+
exactly the line endings chosen above (no `\r\n` added on Windows). A UTF-8
|
|
59
|
+
byte-order mark, as SSMS saves, is kept. A file that is not UTF-8 is reported
|
|
60
|
+
and left unchanged.
|
|
61
|
+
|
|
57
62
|
## File selection
|
|
58
63
|
|
|
59
64
|
| Flag | Default | What it does |
|
|
@@ -437,7 +437,13 @@ GO
|
|
|
437
437
|
|
|
438
438
|
The safety check is batch-aware too: it compares each batch's AST separately and
|
|
439
439
|
compares the separators themselves, so a dropped or added `GO` is still caught.
|
|
440
|
-
`GO 5` (with a repeat count) is recognised.
|
|
440
|
+
`GO 5` (with a repeat count) is recognised. A `GO` line inside a string literal
|
|
441
|
+
or a block comment (an SQL Agent job step, dynamic SQL) is part of that literal,
|
|
442
|
+
not a separator.
|
|
443
|
+
|
|
444
|
+
A `CREATE PROCEDURE`, `FUNCTION` or `TRIGGER` runs to the end of its batch, as
|
|
445
|
+
SQL Server reads it: everything up to the next `GO` is the routine, whatever
|
|
446
|
+
`;`, `END` or `END TRY` comes first.
|
|
441
447
|
|
|
442
448
|
### `REAL` and `NTEXT` decline on sight
|
|
443
449
|
|
|
@@ -261,6 +261,9 @@ reports clean rather than showing a spurious diff on every line.
|
|
|
261
261
|
Override the choice with `--line-ending {auto,lf,crlf}`. `auto` is the default and
|
|
262
262
|
preserves each file's own.
|
|
263
263
|
|
|
264
|
+
Encoding does not follow the Windows code page: files and stdout are UTF-8, and a
|
|
265
|
+
file saved by SSMS with a byte-order mark keeps it.
|
|
266
|
+
|
|
264
267
|
Lone `CR` endings (classic Mac) are not a line ending sqlalign models. Those files
|
|
265
268
|
pass through untouched with a warning rather than being silently rewritten:
|
|
266
269
|
|
|
@@ -270,6 +270,10 @@ argument error, not a silent precedence rule:</p>
|
|
|
270
270
|
</code></pre>
|
|
271
271
|
<p>A file with lone <code>\r</code> (classic-Mac) line endings is not a shape sqlalign models;
|
|
272
272
|
it is passed through untouched with a warning.</p>
|
|
273
|
+
<p>Files, stdin and stdout are UTF-8 whatever the system locale, and stdout writes
|
|
274
|
+
exactly the line endings chosen above (no <code>\r\n</code> added on Windows). A UTF-8
|
|
275
|
+
byte-order mark, as SSMS saves, is kept. A file that is not UTF-8 is reported
|
|
276
|
+
and left unchanged.</p>
|
|
273
277
|
<h2 id="file-selection">File selection<a class="anchor" href="#file-selection" aria-label="Link to this section">#</a></h2>
|
|
274
278
|
<table>
|
|
275
279
|
<thead>
|
|
@@ -585,7 +585,12 @@ GO
|
|
|
585
585
|
</code></pre>
|
|
586
586
|
<p>The safety check is batch-aware too: it compares each batch's AST separately and
|
|
587
587
|
compares the separators themselves, so a dropped or added <code>GO</code> is still caught.
|
|
588
|
-
<code>GO 5</code> (with a repeat count) is recognised
|
|
588
|
+
<code>GO 5</code> (with a repeat count) is recognised. A <code>GO</code> line inside a string literal
|
|
589
|
+
or a block comment (an SQL Agent job step, dynamic SQL) is part of that literal,
|
|
590
|
+
not a separator.</p>
|
|
591
|
+
<p>A <code>CREATE PROCEDURE</code>, <code>FUNCTION</code> or <code>TRIGGER</code> runs to the end of its batch, as
|
|
592
|
+
SQL Server reads it: everything up to the next <code>GO</code> is the routine, whatever
|
|
593
|
+
<code>;</code>, <code>END</code> or <code>END TRY</code> comes first.</p>
|
|
589
594
|
<h3 id="real-and-ntext-decline-on-sight"><code>REAL</code> and <code>NTEXT</code> decline on sight<a class="anchor" href="#real-and-ntext-decline-on-sight" aria-label="Link to this section">#</a></h3>
|
|
590
595
|
<p>These two are the reason T-SQL needs a guard the other dialects do not.</p>
|
|
591
596
|
<pre><code class="language-console">$ sqlalign --stdout --dialect tsql types.sql
|
|
@@ -453,6 +453,8 @@ crlf.sql: ASCII text, with CRLF line terminators
|
|
|
453
453
|
reports clean rather than showing a spurious diff on every line.</p>
|
|
454
454
|
<p>Override the choice with <code>--line-ending {auto,lf,crlf}</code>. <code>auto</code> is the default and
|
|
455
455
|
preserves each file's own.</p>
|
|
456
|
+
<p>Encoding does not follow the Windows code page: files and stdout are UTF-8, and a
|
|
457
|
+
file saved by SSMS with a byte-order mark keeps it.</p>
|
|
456
458
|
<p>Lone <code>CR</code> endings (classic Mac) are not a line ending sqlalign models. Those files
|
|
457
459
|
pass through untouched with a warning rather than being silently rewritten:</p>
|
|
458
460
|
<pre><code class="language-console">sqlalign: old.sql: lone CR line endings — passed through untouched
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
[{"slug":"index","title":"Overview","text":" sqlalign is a SQL formatter that produces columnar, aligned output \u2014 and re-parses every statement it writes to prove it did not change what the SQL means. In: select cust.customer_id, cust.email, sum(ord.total) as lifetime_value from customers cust inner join orders ord on ord.customer_id = cust.customer_id where ord.order_date >= '2026-07-01' group by cust.customer_id, cust.email; Out: SELECT cust.customer_id , cust.email , SUM(ord.total) AS lifetime_value FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.customer_id WHERE ord.order_date >= '2026-07-01' GROUP BY cust.customer_id , cust.email; The guarantee # Every statement is re-parsed after formatting and compared against the input as a syntax tree. If the output would differ semantically \u2014 or if the engine does not fully model the construct \u2014 that statement is passed through byte-identical with a warning instead. A passthrough is not a failure, and the run still exits 0 . Pages # Getting started Install it, run it on a file, wire it into a pre-commit hook. Configuration The config file, the CLI flags that override it, and the presets. Settings reference Every setting, with its default and the same SQL rendered under each value. The house style What the output looks like, and the rule behind each decision. CLI reference Every flag, its default, and what it does. Dialects Postgres, Redshift and T-SQL \u2014 what each supports and what each declines. Architecture The layout IR, the alignment resolver, and the safety model. FAQ Why it declines, why it will not fix your SQL, and how it compares. ","headings":[{"id":"the-guarantee","text":"The guarantee"},{"id":"pages","text":"Pages"}]},{"slug":"getting-started","title":"Getting started","text":" This page takes you from nothing installed to sqlalign running over a whole repository and gating your CI. sqlalign formats presentation only . Every statement it touches is re-parsed and AST-compared against your input; if the output would mean anything different \u2014 or if the engine does not fully model the construct \u2014 that statement is passed through byte-identical with a warning instead. It does not lint, and it will not rewrite your SQL for you. Install # sqlalign needs Python 3.10 or newer . Its one runtime dependency is sqlglot , accepted as >=30.14,<31 . The layout engine reads exact AST shapes, so the range is not a passive float: tests/test_sqlglot_conformance.py asserts each of those shapes by name, and CI runs the whole suite against the newest release the range allows as well as the locked one. On 3.10 it also installs tomli , which is tomllib from the standard library of every later version. pip install sqlalign That installs a sqlalign command on your PATH. Check it: sqlalign --help uv tool install sqlalign does the same while keeping it out of your project's environment. For development on sqlalign itself, work from a clone instead \u2014 this adds the dev tools ( pytest , ruff , sqlfluff ): git clone https://github.com/pua2/sqlalign && cd sqlalign uv sync Your first format # Save this as revenue.sql : select c.customer_id, c.email, sum(o.total) as lifetime_value, count(*) as order_count from customers c join orders o on o.customer_id = c.customer_id where o.status = 'complete' and o.order_date >= '2026-01-01' group by c.customer_id, c.email having sum(o.total) > 500 order by lifetime_value desc; Print the formatted result without touching the file: sqlalign --stdout revenue.sql SELECT c.customer_id , c.email , SUM(o.total) AS lifetime_value , COUNT(*) AS order_count FROM customers c JOIN orders o ON o.customer_id = c.customer_id WHERE o.status = 'complete' AND o.order_date >= '2026-01-01' GROUP BY c.customer_id , c.email HAVING SUM(o.total) > 500 ORDER BY lifetime_value DESC; The AS clauses, the operators in WHERE , and the table aliases in the FROM block are each padded into a column. That is the house style; it is a fixpoint resolver pass, not a search-and-replace over printed text, so it composes with line wrapping instead of fighting it. Now rewrite the file for real. In-place is the default \u2014 no flag: sqlalign revenue.sql It prints nothing on success. Run it again and nothing changes: formatting is idempotent, and the golden test suite asserts that. Look before you write # Three flags control where the output goes. They are mutually exclusive \u2014 pass at most one. Flag Writes the file? Prints Exit code (none) yes nothing 0 --stdout no the formatted SQL 0 --check no would reformat <path> per file 1 if any file would change --diff no a unified diff per file 1 if any file would change --check is for CI logs you want to stay readable; --diff is for when you want to see the change itself: sqlalign --diff revenue.sql --- revenue.sql +++ revenue.sql (formatted) @@ -1,6 +1,12 @@ -select c.customer_id, c.email, sum(o.total) as lifetime_value, count(*) as order_count -from customers c join orders o on o.customer_id = c.customer_id -where o.status = 'complete' and o.order_date >= '2026-01-01' -group by c.customer_id, c.email -having sum(o.total) > 500 -order by lifetime_value desc; +SELECT c.customer_id + , c.email + , SUM(o.total) AS lifetime_value + , COUNT(*) AS order_count +FROM customers c +JOIN orders o ON o.customer_id = c.customer_id +WHERE o.status = 'complete' + AND o.order_date >= '2026-01-01' +GROUP BY c.customer_id + , c.email +HAVING SUM(o.total) > 500 +ORDER BY lifetime_value DESC; Formatting a directory # Pass a directory and sqlalign walks it recursively for *.sql , in sorted order so a run is reproducible: sqlalign --check . would reformat models/gen_out.gen.sql would reformat models/marts/rollup.sql would reformat models/users.sql would reformat vendor/legacy.sql Excluding files # Generated SQL and vendored SQL usually should not be reformatted. --exclude takes a glob and is repeatable: sqlalign --check --exclude 'vendor/*' --exclude '*.gen.sql' . would reformat models/marts/rollup.sql would reformat models/users.sql Two things to know: Patterns are matched against each file's path relative to the directory you named , and also against its bare filename \u2014 so vendor/* and *.gen.sql both work above. A file you name explicitly on the command line is never excluded. Asking for it by name is a clearer signal than a pattern in a config file: sqlalign --check --exclude 'vendor/*' vendor/legacy.sql # would reformat vendor/legacy.sql Once the patterns are right, drop --check to actually write: sqlalign --exclude 'vendor/*' --exclude '*.gen.sql' . Rather than repeat those flags forever, commit them. sqlalign reads a .sqlalign.toml (or a [tool.sqlalign] table in pyproject.toml ) discovered by walking up from each file: # .sqlalign.toml exclude = [\"vendor/*\", \"*.gen.sql\"] Run sqlalign --show-config <path> at any point to print the settings that would actually apply, as TOML, with the config file they came from on the first line. Skipping one statement # Put -- sqlalign: skip on the line above a statement and that statement passes through byte-identical. Its neighbours still format: -- sqlalign: skip select a,b from t; select c, d from u; sqlalign --stdout skip.sql -- sqlalign: skip select a,b from t; SELECT c , d FROM u; When sqlalign declines # sqlalign would rather leave your SQL alone than render it wrong. A statement it cannot reproduce exactly is emitted unchanged, with a warning on stderr : sqlalign --stdout passthru.sql sqlalign: passthru.sql: unsupported construct (PIVOT: this dialect has no such syntax), passed through: select * from t pivot (sum(x) for y in ( select * from t pivot (sum(x) for y in (1, 2)) p; Unparseable input behaves the same way rather than blowing up the run: sqlalign: broken.sql: passthrough (parse error line 1): this is not sql at all ((( ; There is a second kind of message, and it means something different: sqlalign: q.sql: formatting would change semantics, passed through unformatted: ... That one is a bug report , not a decline. It means sqlalign rendered the statement, read its own output back, and found it no longer meant the same thing \u2014 so it threw the output away. The construct is not unsupported; the renderer is wrong. Two shipped that way and both were found by accident (every lowercase user-defined function, and every quoted column alias), so the test suite now sweeps for that wording specifically. If you see it, it is worth reporting. A passthrough is not a failure. Both of those runs exit 0 \u2014 the file is valid output, just unformatted. That is safe but invisible: a CI run stays green with any fraction of a repository unformatted, and nothing tells you which fraction. --report counts it: $ sqlalign --report --check models/ 1,204 statements 1,151 formatted (95.6%) 53 declined declined by cause 38 unsupported Pivot 12 unsupported Subquery 3 parse parse error --max-declines N turns that into a gate \u2014 exit 1 if more than N statements were passed through. Start it at whatever your repository reports today and ratchet it down; it stops new unformattable SQL arriving unnoticed. The causes are ranked, so the list doubles as a priority order for what to implement next \u2014 measured on your SQL rather than guessed at. A -- sqlalign: skip counts too, under its own skipped kind, so a deliberate opt-out is distinguishable from a gap in the tool. Linting inside $$ bodies # sqlfluff cannot lint a plpgsql body. To its parser the whole body is one string literal, so a function full of badly-written SQL passes clean \u2014 and in a repository that keeps logic in functions, that is a large blind spot. It is not a rule sqlfluff is missing; it is the shape of the parse. sqlalign already has to find those statements in order to format them, so --lint hands them to sqlfluff as well. Given this function: CREATE FUNCTION report() RETURNS int AS $$ BEGIN SELECT * FROM orders o, customers c WHERE o.cid = c.id; RETURN 1; END; $$ LANGUAGE plpgsql; sqlfluff on its own sees the header and nothing else: L: 1 | P: 17 | CP03 | Function names must be upper case. L: 1 | P: 34 | CP05 | Datatypes must be upper case. [capitalisation.types] All Finished! Through sqlalign, the body is linted too: $ sqlalign --check --lint report.sql L: 1 | P: 17 | CP03 | Function names must be upper case. All Finished! == [report.sql] inside $$ bodies (sqlfluff cannot reach these on its own) L: 8 | P: 1 | AM04 | Query produces an unknown number of result columns. [ambiguous.column_count] L: 8 | P: 8 | RF02 | Unqualified reference '*' found in select with more than one referenced table/view. [references.qualification] Line 8 is line 8 of the file. sqlalign lints a view of it \u2014 the same text with the plpgsql scaffolding replaced by spaces, so every line and column stays where it was. Blanking rather than deleting is the point: delete, and every column after it shifts, and a finding would point at the wrong place. Two things follow from how this works: The body is linted after formatting , like the rest of the file, so whitespace and keyword-case findings inside a body are already fixed by the time sqlfluff sees it. What surfaces is what formatting cannot fix \u2014 the semantic rules. Statements inside an IF \u2026 THEN branch are not covered. The layout models a single-statement branch, so there is no statement span to lint. Running sqlfluff alongside it # sqlalign and sqlfluff overlap, and left alone they fight \u2014 sqlfluff fix will undo the alignment on every run: -- sqlalign's output -- after stock `sqlfluff fix` SELECT cust.customer_id SELECT , cust.email cust.customer_id, FROM customers cust cust.email INNER JOIN orders ord ON \u2026 FROM customers AS cust WHERE ord.total > 0 INNER JOIN orders AS ord ON \u2026 AND cust.segment = 'ent'; WHERE ord.total > 0 AND cust.segment = 'ent'; The fix is the one Prettier and eslint-config-prettier settled on: the formatter owns layout, and the linter is told to stop having opinions about it. sqlalign --print-sqlfluff-config > .sqlfluff With that in place sqlfluff fix leaves sqlalign's output byte-identical. The generated config does two things. It excludes sqlfluff's whole layout rule group \u2014 by group rather than by name, so a sqlfluff upgrade that adds a layout rule cannot start failing your formatted SQL. And it translates the settings where both tools have an opinion ( keyword_case , table_alias_style , neq_style ) into the matching sqlfluff rule config, so the two agree instead of contradicting each other. Every semantic rule stays on. Those lint your SQL rather than sqlalign's whitespace, and sqlalign preserves the choices they are about \u2014 it would be the wrong trade to silence them for a formatting truce. It reads your effective settings, so run it where your config lives: sqlalign --print-sqlfluff-config models/orders.sql > .sqlfluff One command instead of two # --lint formats and then runs sqlfluff over the result: $ pip install 'sqlalign[lint]' $ sqlalign --lint models/orders.sql == [models/orders.sql] FAIL L: 4 | P: 1 | AM05 | Join clauses should be fully qualified. [ambiguous.join] All Finished! sqlfluff stays an optional dependency \u2014 sqlalign's own guarantee does not rest on a linter, so neither does its install. It lints what would be written, so --lint --check reports on the formatted result rather than on whatever is currently on disk. Exit codes are 0 clean, 1 findings (or --check changes), 2 an error. A committed .sqlfluff wins \u2014 your file is a decision someone made, and overriding it silently would be the wrong kind of helpful. The generated coexistence config is only the fallback when there is nothing to respect. If you write one by hand rather than generating it, expect AL01 noise: sqlfluff defaults to requiring AS on table aliases, and sqlalign's default omits it. A shared sqlfluff config # --lint uses the .sqlfluff it finds beside your file, walking upwards the way sqlfluff itself does. A config your team keeps outside the repository is not on that path, so name it: sqlalign --lint --sqlfluff-config ~/team/shared.sqlfluff models/ It wins over anything discovered. One editor action can then format and report your team's findings together \u2014 in a JetBrains External Tool, that is --lint --sqlfluff-config /path/to/shared.sqlfluff \"$FilePath$\" . It is refused without --lint , and refused if the path does not exist: taking a config nobody reads would leave you believing your rules had run. --lint reports; it never fixes. sqlfluff fix rewrites SQL \u2014 qualifying joins, changing cast styles \u2014 which is the thing sqlalign does not do, and a flag that reads like a reporter is a poor place to hide a rewriter. Run it yourself as a second step if you want it; the generated .sqlfluff excludes the whole layout group, so sqlfluff fix will not undo the alignment. The settings panel # The panel is experimental. It is useful and it is tested, but it is the one part of sqlalign not covered by any stability promise: its layout and behaviour may change without a major version. The CLI and the config file are the supported surface. Eighteen knobs is more than anyone wants to read about. sqlalign --gui opens a panel next to a live preview \u2014 every control re-runs the real engine on the text in the pane, so what you see is what the CLI would write: sqlalign --gui sqlalign --gui --dialect tsql Left: dialect, preset, and every setting. Right: an editable input pane over the formatted result, with a status line counting statements and naming anything that declined. A setting that currently does nothing is greyed out, with a line saying which control it is waiting on rather than leaving it looking broken. Save settings writes a .sqlalign.toml with the values written out live, because they are choices you just made \u2014 the opposite of what --init writes, and for the opposite reason. The file records which preset it matches, if any, and the dialect you previewed with as a comment, since dialect has no config key. Open loads a real .sql file in place of the bundled samples. Open SQL\u2026 ( \u2318O ) loads a file, and the window is named for it from then on. Save formatted\u2026 ( \u2318S ) defaults to that same file, so formatting one in place is the one-click path and matches what sqlalign <file> writes byte for byte; the dialog still asks before overwriting. Copy formatted is \u2318\u21e7C rather than \u2318C , which stays yours for ordinary copying. Save config\u2026 writes a .sqlalign.toml \u2014 the same text --show-config prints \u2014 so the panel is a way to find a style, not a second place to keep one. It is Tkinter, from the standard library, so it needs no extra install. On Debian and Ubuntu that means apt install python3-tk ; the flag says so if it is missing rather than failing with a traceback. Editors # sqlalign has no editor plugin and does not need one: it reads stdin, writes stdout, and starts in about a tenth of a second, which is what every editor's \"external formatter\" setting expects. Filter the buffer (vim, Neovim, Helix, and anything with a ! filter): :%!sqlalign - - resolves .sqlalign.toml from the working directory, so a committed config is picked up. /dev/stdin also works as a path, but config discovery walks up from the path you named and /dev/stdin is not in your repository \u2014 so that route needs an explicit --config and - does not. Format on save. Point any \"run a command on save\" extension at the file and let the editor reload it: sqlalign \"$FILE\" VS Code. sqlalign reads stdin, so it can be registered as a real formatter rather than as a command bolted onto save \u2014 which is what makes Format Document , format-on-save and format-selection all work through the same path. With the Custom Local Formatters extension: { \"customLocalFormatters.formatters\": [ { \"command\": \"sqlalign -\", \"languages\": [\"sql\"] } ], \"[sql]\": { \"editor.formatOnSave\": true } } Any \"run a command on save\" extension works too, pointed at $FILE as above \u2014 but it formats the file behind the editor's back and makes you reload, where the formatter route does not. JetBrains (DataGrip, PyCharm, IntelliJ). Use the bundled File Watchers plugin rather than looking for a marketplace listing \u2014 Settings \u2192 Tools \u2192 File Watchers \u2192 + \u2192 <custom> : If your projects target different engines, put dialect = \"redshift\" (or postgres , tsql ) in each one's .sqlalign.toml \u2014 the watcher then needs no --dialect and is right in every project. Field Value File type SQL Program sqlalign Arguments $FilePath$ Output paths to refresh $FilePath$ Advanced \u2192 Auto-save edited files off Turning auto-save off is what stops the watcher firing on every keystroke. Git pre-commit hook # The repository ships hooks for pre-commit , which is the no-maintenance route: # .pre-commit-config.yaml repos: - repo: https://github.com/pua2/sqlalign rev: v1.1.0 hooks: - id: sqlalign # rewrites and restages # - id: sqlalign-check # or: only report, change nothing sqlalign rewrites and fails so you restage \u2014 the pre-commit convention for a formatter. sqlalign-check only reports, which is what a repository you do not own wants. For CI there is a published action, which defaults to --check because an action that silently reformats a checkout is not what a gate is for: - uses: pua2/sqlalign@v1.1.0 # with: # args: --diff # show the change, not just the file names # paths: models/ Without the framework, a hand-rolled hook that formats staged SQL and re-stages what changed: #!/bin/sh # .githooks/pre-commit files=$(git diff --cached --name-only --diff-filter=ACM -- '*.sql') [ -z \"$files\" ] && exit 0 sqlalign $files || exit $? git add $files chmod +x .githooks/pre-commit git config core.hooksPath .githooks If you would rather reject an unformatted commit than fix it, swap the body for sqlalign --check $files and drop the git add . CI # One command, no wrapper needed. --check exits 1 when anything would change, which is exactly what a CI runner treats as a failure: sqlalign --check . Wrapped in a job step: - name: Check SQL formatting run: | pip install sqlalign sqlalign --check . Use --diff instead of --check if you want the log to show what is wrong rather than only which files are: sqlalign --diff . Starting a config # sqlalign --init writes a .sqlalign.toml next to you: sqlalign --init # house defaults sqlalign --init --preset compact # start from a published style guide Every setting is written commented out , showing the value currently in effect, so the file changes nothing until you uncomment something. That is deliberate: a starter that arrived pinning all eighteen settings would freeze you on whatever the defaults were the day you ran it and call that a decision. --preset is the exception and is written live, because choosing one is the decision you just made. The commented values below it then show what that preset does, which makes the file worth reading as well as editing. It refuses to overwrite an existing config. Calling it from Python # The CLI is the supported surface for a repository. For a notebook, a dbt hook or a code generator, there are two functions: import sqlalign sqlalign.format(\"select a,b from t;\") # 'SELECT a\\n , b\\nFROM t;' result = sqlalign.format_result(sql, dialect=\"redshift\") result.text # the formatted SQL result.statements # how many statements were seen result.declines # what was passed through, and why format returns the text. format_result also tells you what happened, which matters more than it sounds: a statement sqlalign cannot model comes back byte-identical rather than raising , so format alone cannot distinguish \"formatted\" from \"left alone\" \u2014 both are valid SQL. Anything that gates on the result should read declines . style takes a Style , so a preset carries across: from sqlalign.style import preset_style sqlalign.format(sql, style=preset_style(\"compact\")) An unsupported dialect raises ValueError rather than being formatted with keywords the target engine may not accept. These two names are the API. Everything else under sqlalign.* is internal and moves between releases. Because sqlalign does not lint, it slots in beside a linter rather than replacing one \u2014 running sqlfluff lint in a neighbouring step is the intended setup. Exit codes # Code Meaning 0 Success. Files were formatted, or --check / --diff found nothing to change. Statements that passed through untouched still exit 0 . 1 --check or --diff found at least one file that would change. --max-declines and --lint return 1 on their own findings too \u2014 1 always means a gate found something, never a malfunction. 2 A file could not be read, a config file is invalid, or an argument is invalid (an unsupported --dialect , an unknown --align-targets name, two output modes at once). Also an unexpected engine error on a single file. Exit 2 is per-file where it can be: an unreadable or misconfigured file is reported on stderr and skipped, and the rest of the run still processes . The final exit code is the worst one seen. sqlalign nope.sql # sqlalign: [Errno 2] No such file or directory: 'nope.sql' # exit 2 Where to go next # The full flag reference: cli.md \u2014 every flag, its default, and which ones conflict. Committing a team style: configuration.md \u2014 config file discovery, presets, and precedence. What the output looks like, construct by construct: style.md . The style itself, in the repo: samples/queries.sql is 29 hand-formatted goldens that the test suite asserts byte-for-byte. It is the executable spec. Positioning, presets and the honest comparison against other formatters: the README . Architecture, the alignment formula, the safety model: the Architecture page. ","headings":[{"id":"install","text":"Install"},{"id":"your-first-format","text":"Your first format"},{"id":"look-before-you-write","text":"Look before you write"},{"id":"formatting-a-directory","text":"Formatting a directory"},{"id":"excluding-files","text":"Excluding files"},{"id":"skipping-one-statement","text":"Skipping one statement"},{"id":"when-sqlalign-declines","text":"When sqlalign declines"},{"id":"linting-inside-bodies","text":"Linting inside $$ bodies"},{"id":"running-sqlfluff-alongside-it","text":"Running sqlfluff alongside it"},{"id":"one-command-instead-of-two","text":"One command instead of two"},{"id":"a-shared-sqlfluff-config","text":"A shared sqlfluff config"},{"id":"the-settings-panel","text":"The settings panel"},{"id":"editors","text":"Editors"},{"id":"git-pre-commit-hook","text":"Git pre-commit hook"},{"id":"ci","text":"CI"},{"id":"starting-a-config","text":"Starting a config"},{"id":"calling-it-from-python","text":"Calling it from Python"},{"id":"exit-codes","text":"Exit codes"},{"id":"where-to-go-next","text":"Where to go next"}]},{"slug":"configuration","title":"Configuration","text":" Commit your team's style once instead of passing flags on every run. Put a .sqlalign.toml at the root of your repo, or a [tool.sqlalign] table in your pyproject.toml , and every sqlalign invocation under that directory picks it up. # .sqlalign.toml preset = \"trailing\" width = 100 keyword_case = \"upper\" exclude = [\"vendor/*\", \"*.gen.sql\"] sqlalign --show-config models/orders.sql # what will actually be applied sqlalign --check . # CI gate, using the committed config This page covers where sqlalign looks for that file, how it merges with presets and flags, every key you can put in it, and what happens when you get it wrong. For the flags themselves see the CLI reference ; for what each setting does to your SQL see the style guide . Where sqlalign looks # sqlalign resolves a config per file , by walking up from the directory of the file it is about to format. At each directory it takes the first of: Order File Shape 1 .sqlalign.toml keys at the top level 2 pyproject.toml keys under a [tool.sqlalign] table The first directory that has either one wins, and it stops there \u2014 settings are not merged across levels. A pyproject.toml without a [tool.sqlalign] table is skipped entirely, so a repo that already has a pyproject.toml for other tools is unaffected until you add the table. Two consequences worth knowing: A subdirectory overrides its parent. Drop a .sqlalign.toml in legacy/ and everything under it formats by that file's rules, while the rest of the repo uses the root config. Because resolution is per file, one invocation can span both: sqlalign --stdout models/q.sql legacy/q.sql # two files, two configs The walk goes all the way to the filesystem root. If no config exists in your project, a stray .sqlalign.toml in a parent directory or in your home directory will be found. sqlalign --show-config tells you which file was used; --isolated guarantees none is. Both file forms accept the same keys, and the two forms mean the same thing: # .sqlalign.toml comma_position = \"trailing\" # pyproject.toml [tool.sqlalign] comma_position = \"trailing\" Precedence # Settings compose in this order, each layer winning over the one before it: built-in defaults < preset < config file < command-line flags A preset only supplies a base . Any key you set explicitly \u2014 in the config file or on the command line \u2014 layers on top of it, so preset plus an override means both, not one or the other: preset = \"compact\" # base: no alignment padding comma_position = \"trailing\" # ...and trailing commas on top Two details follow from \"a preset is only a base\": A --preset flag beats a preset = key , because it is the newer answer to the same question. Config file preset = \"trailing\" plus sqlalign --preset compact gives you compact . An explicit key beats a preset from either source. A config file with comma_position = \"leading\" , run with --preset dbt , gives you dbt's lowercase keywords and unpadded output but keeps your leading commas. The relevant lines of sqlalign --preset dbt --show-config q.sql : # /home/you/warehouse/.sqlalign.toml align = false comma_position = \"leading\" keyword_case = \"lower\" A flag you do not pass never overrides the config file. sqlalign distinguishes \"not passed\" from \"passed the value that happens to be the default\", so --comma-position leading forces leading commas even when the config says trailing, while omitting the flag leaves the config's choice alone. Key reference # These are the complete set of keys a config file accepts. Anything else is an error (see Unknown keys ). Key Type Default What it does preset \"house\" | \"compact\" | \"trailing\" | \"dbt\" none Named starting point. Every other key layers on top of it. width integer 100 Target line width for wrapping decisions. A target, not a hard cap \u2014 see below. align boolean true Master alignment switch. false emits one space between tokens and keeps the same line structure. align_targets list of strings all but table_names Which alignment columns are padded \u2014 the nine names in the CLI reference's target table . Anything omitted collapses to a single space. comma_position \"leading\" | \"trailing\" \"leading\" Where the separator comma sits in a stacked list. boolean_operator_position \"leading\" | \"trailing\" \"leading\" Where AND / OR sit when a predicate spans lines. on_placement \"inline\" | \"own_line\" \"inline\" Whether a JOIN's ON rides the table line or drops below it. select_placement \"inline\" | \"own_line\" \"inline\" Whether the first select item rides the SELECT line or the list starts below it. select_indent integer 2 Columns the select list indents when it starts below SELECT . Ignored when inline. clause_keyword_align \"left\" | \"river\" \"left\" Root clause keywords flush left, or right-aligned so their last character lands on the gutter. river_gutter integer 6 The column a river aligns them to. 6 is the width of SELECT . table_alias_style \"bare\" | \"as\" \"bare\" FROM orders o or FROM orders AS o . sqlglot destroys the distinction at parse time, so sqlalign must pick one. keyword_case \"upper\" | \"lower\" \"upper\" Case for keywords, function names and type names. Your identifiers and string literals are never touched. neq_style \"!=\" | \"<>\" \"!=\" Spelling for the not-equal operator. decimal_style \"NUMERIC\" | \"DECIMAL\" \"NUMERIC\" Spelling for the NUMERIC / DECIMAL type. body_blank_lines integer 1 Blank lines between the elements of a dollar-quoted body ( DECLARE , BEGIN , each statement, END ). Separate from blank_lines_between_statements , which never reaches inside a body. 0 packs the body tight. format_dollar_bodies boolean true Format inside dollar-quoted ( $$ ) procedure and function bodies. false passes the whole CREATE FUNCTION through byte-identical. protect_templating boolean true Mask Jinja/dbt template expressions ( {{ }} , {% %} , {# #} ) before formatting so a templated model can be formatted at all. blank_lines_between_statements integer, or unset unset Force N blank lines between every pair of statements. Unset means the house rule: one blank line between two multi-line statements, none otherwise. dialect \"postgres\" | \"redshift\" | \"tsql\" postgres The engine the SQL will run on. Resolved per file from the config nearest it, so one command can span a Postgres tree and a Redshift one. --dialect overrides it. exclude list of glob strings (a bare string is also accepted) none Skip matching files when a directory is expanded. Selects files, not style \u2014 see Excluding files . neq_style and decimal_style exist because the parser collapses each of those pairs to a single node, so a spelling has to be chosen when printing. They are the only two places sqlalign picks for you. Not config keys # --line-ending is the only setting with no config key. --dialect has one \u2014 see the dialect row above \u2014 and the flag overrides it for a one-off run. width is a target, not a limit # width drives wrapping decisions, but a construct anchored deep in an indent is allowed some room past it rather than being shredded. On the multi-join sample, --width 60 produces output byte-identical to the default --width 100 , whose longest line is 81 characters. Lower width when you want more aggressive wrapping; do not treat it as a hard maximum your lines cannot cross. on_placement = \"own_line\" retires the ON column # With own_line , the ON drops below the table reference ( FROM block shown): FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.customer_id LEFT JOIN order_line_items line_items ON line_items.order_id = ord.order_id LEFT JOIN shipping_addresses addr ON addr.order_id = ord.order_id AND addr.address_type = 'shipping' There is no longer an ON sitting after each alias, so the join_conditions target has nothing to act on. Set on_placement = \"own_line\" and join_conditions together and only the first has an effect. Presets # A preset is one word instead of a handful of keys. Pick the one closest to your team's existing style and override the rest. Preset Sets For house nothing \u2014 the built-in defaults Teams adopting sqlalign's columnar style as-is: aligned, leading separators, ON inline, uppercase keywords. compact align = false Teams that want sqlalign's line structure without the padding. 9 of 10 published SQL style guides produce unpadded output, so this is the widest-reach starting point. trailing comma_position = \"trailing\" , boolean_operator_position = \"trailing\" Teams that want the alignment but write trailing commas (8 of 10 guides) and trailing booleans (7 of 10). dbt keyword_case = \"lower\" , comma_position = \"trailing\" , align = false dbt and analytics-engineering repos. Everything a preset does not set stays at the built-in default \u2014 dbt leaves boolean_operator_position at leading , for instance. Run sqlalign --isolated --preset NAME --show-config file.sql to see the full picture for any of them. The house , compact and trailing blocks below are all the same input query, formatted under each preset; dbt uses a CTE query so its one deviation is visible. house # -- #13: multi-character aliases (mixed lengths) SELECT cust.customer_id , cust.email , ord.order_id , ord.total , line_items.product_id , line_items.quantity , addr.city FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.customer_id LEFT JOIN order_line_items line_items ON line_items.order_id = ord.order_id LEFT JOIN shipping_addresses addr ON addr.order_id = ord.order_id AND addr.address_type = 'shipping' WHERE ord.order_date >= '2026-07-01' AND cust.segment = 'enterprise'; compact # Same line structure, every run of padding collapsed to one space. -- #13: multi-character aliases (mixed lengths) SELECT cust.customer_id , cust.email , ord.order_id , ord.total , line_items.product_id , line_items.quantity , addr.city FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.customer_id LEFT JOIN order_line_items line_items ON line_items.order_id = ord.order_id LEFT JOIN shipping_addresses addr ON addr.order_id = ord.order_id AND addr.address_type = 'shipping' WHERE ord.order_date >= '2026-07-01' AND cust.segment = 'enterprise'; trailing # Alignment intact; both separators move to the end of the line. -- #13: multi-character aliases (mixed lengths) SELECT cust.customer_id, cust.email, ord.order_id, ord.total, line_items.product_id, line_items.quantity, addr.city FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.customer_id LEFT JOIN order_line_items line_items ON line_items.order_id = ord.order_id LEFT JOIN shipping_addresses addr ON addr.order_id = ord.order_id AND addr.address_type = 'shipping' WHERE ord.order_date >= '2026-07-01' AND cust.segment = 'enterprise'; dbt , and its one deviation # -- #6: CTEs with monthly_revenue as ( select customer_id, date_trunc('month', order_date) as month, sum(total) as revenue from orders group by 1, 2 ), top_customers as ( select customer_id from monthly_revenue group by customer_id having sum(revenue) > 10000 ) select m.customer_id, m.month, m.revenue from monthly_revenue m join top_customers t on t.customer_id = m.customer_id order by m.customer_id, m.month; The deviation: dbt's own style guide indents a nested block 4 spaces. sqlalign indents a CTE body 2 , as you can see above. sqlalign's indent literals are three different concepts internally rather than one knob, so there is no setting that changes this. If your dbt project enforces 4-space CTE bodies in review, this preset will fight you on exactly that one point and nothing else. Unknown keys are an error # A key sqlalign does not recognise stops the run. The file is left untouched and the exit code is 2 : $ sqlalign q.sql sqlalign: /home/you/warehouse/.sqlalign.toml: unknown setting(s) ['comma_postion']; valid: ['align', 'align_targets', 'blank_lines_between_statements', 'body_blank_lines', 'boolean_operator_position', 'clause_keyword_align', 'comma_position', 'decimal_style', 'dialect', 'exclude', 'format_dollar_bodies', 'keyword_case', 'neq_style', 'on_placement', 'preset', 'protect_templating', 'river_gutter', 'select_indent', 'select_placement', 'table_alias_style', 'width'] This is deliberate, and it is the opposite of what most tools do. A typo in a committed config that is silently ignored means a whole team believes it has a setting it does not have, and finds out from a surprising diff months later. A failure at the moment you commit the typo costs you thirty seconds; a silent no-op costs you the trust you had in the file. The same strictness applies to values, not just key names. Every one of these exits 2 without touching a file: Config Error comma_position = \"sideways\" comma_position must be 'leading' or 'trailing', got 'sideways' width = \"wide\" width must be an integer, got 'wide' align_targets = [\"aliases\", \"typo\"] unknown align_targets ['typo']; valid: ['aliases', 'case_results', 'column_aliases', 'column_constraints', 'column_types', 'join_conditions', 'operators', 'table_aliases', 'table_names'] preset = \"nice\" unknown preset 'nice'; valid: ['compact', 'dbt', 'gitlab', 'house', 'river', 'trailing'] malformed TOML invalid TOML: ... --no-strict-config # Pass --no-strict-config to downgrade the unknown-key failure to a warning. The unrecognised key is dropped and formatting proceeds: $ sqlalign --no-strict-config --stdout q.sql sqlalign: /home/you/warehouse/.sqlalign.toml: unknown setting(s) ['comma_postion']; valid: [...] SELECT a , b FROM t WHERE a = 1 AND b = 2; Use it when one config file is shared with a newer sqlalign that knows keys your version does not \u2014 a mixed-version team, or a rollout in progress. Do not use it as a default in CI: that gives you the silent no-op the strict behaviour exists to prevent. Note that it only relaxes unknown keys ; a bad value is still a hard error either way. Inspecting what will be applied # --show-config prints the effective settings and the file they came from, then exits without formatting anything: $ sqlalign --show-config models/orders.sql # /home/you/warehouse/.sqlalign.toml width = 100 align = true align_targets = [\"aliases\", \"join_conditions\", \"operators\"] comma_position = \"trailing\" boolean_operator_position = \"trailing\" on_placement = \"inline\" select_placement = \"inline\" select_indent = 2 clause_keyword_align = \"left\" river_gutter = 6 format_dollar_bodies = true neq_style = \"!=\" decimal_style = \"NUMERIC\" table_alias_style = \"bare\" keyword_case = \"upper\" protect_templating = true # blank_lines_between_statements is unset: one blank line between two # multi-line statements, none otherwise. Set an integer to force a count. The body is valid TOML you can paste straight into a .sqlalign.toml \u2014 that round trip is a tested guarantee, which is why an unset blank_lines_between_statements is emitted commented out rather than as something with no TOML spelling. Three things to know about it: It reports on the first path you give it, since config resolution is per file. To compare two directories, run it twice. The path does not have to be a file that exists, or a file at all. A directory works, and so does a filename you are about to create \u2014 sqlalign only needs a location to start the walk from. With --isolated it prints # built-in defaults (no config file found) even when a config file exists nearby. That header means \"none was consulted\", not \"none is there\". Overriding discovery # Flag Effect --config PATH Use this file instead of discovering one. Any filename works \u2014 it does not have to be called .sqlalign.toml . A pyproject.toml passed this way is still read from its [tool.sqlalign] table. --isolated Ignore every config file and start from the built-in defaults. Presets and flags still apply, so --isolated --preset dbt is meaningful. --config pointing at a file that does not exist is an error, not a fallback to discovery: $ sqlalign --config /tmp/nope.toml --check q.sql sqlalign: /tmp/nope.toml: [Errno 2] No such file or directory: '/tmp/nope.toml' Reach for --isolated when you want to prove what sqlalign does with no local influence \u2014 reproducing a bug report, or checking whether a config is the reason for a diff you did not expect. Excluding files # exclude skips files when you hand sqlalign a directory . It selects files rather than style, so it never reaches the formatter. exclude = [\"vendor/*\", \"*.gen.sql\"] Given that config and a tree holding models/orders.sql , models/build.gen.sql , vendor/v.sql and vendor/deep/d.sql , only the first is considered: $ sqlalign --check . would reformat models/orders.sql The rules: Patterns are fnmatch globs , matched against each file's path relative to the directory you named, and also against its bare filename. *.gen.sql therefore matches at any depth, and * spans / , so vendor/* also excludes vendor/deep/d.sql . Relative to the directory you named, not the repo root. With the config above, sqlalign --check . from the repo root skips vendor/ . But sqlalign --check vendor expands vendor as the root, so the file's relative path is v.sql , vendor/* does not match, and it gets formatted. Name the root you wrote the patterns against. A file named explicitly on the command line is never excluded. Asking for it by name is a clearer signal of intent than a pattern in a config, so sqlalign vendor/v.sql formats it regardless. --exclude GLOB adds to the config's patterns rather than replacing them, and is repeatable. --isolated drops the config's patterns too , since it consults no config at all. Expect it to pick up files your normal runs skip. A bare string is accepted where you would write a one-element list, so exclude = \"*.gen.sql\" works. A realistic committed config # This is the shape most repos end up with: a preset, two or three deliberate overrides, and the excludes. # .sqlalign.toml \u2014 committed at the repo root # # Style is `trailing`: sqlalign's columnar alignment, but with the commas and # AND/OR at end of line, which is what our existing SQL already does. preset = \"trailing\" # Alignment we actually want. `case_results`, `column_types` and # `column_constraints` are left out, so those collapse to single spaces. align_targets = [\"aliases\", \"operators\", \"join_conditions\"] width = 100 # Generated and third-party SQL is not ours to restyle. exclude = [\"vendor/*\", \"*.gen.sql\"] Verify it before you commit: $ sqlalign --show-config models/orders.sql # /home/you/warehouse/.sqlalign.toml width = 100 align = true align_targets = [\"aliases\", \"join_conditions\", \"operators\"] comma_position = \"trailing\" boolean_operator_position = \"trailing\" on_placement = \"inline\" select_placement = \"inline\" select_indent = 2 clause_keyword_align = \"left\" river_gutter = 6 format_dollar_bodies = true neq_style = \"!=\" decimal_style = \"NUMERIC\" table_alias_style = \"bare\" keyword_case = \"upper\" protect_templating = true # blank_lines_between_statements is unset: one blank line between two # multi-line statements, none otherwise. Set an integer to force a count. And what it produces: -- #13: multi-character aliases (mixed lengths) SELECT cust.customer_id, cust.email, ord.order_id, ord.total, line_items.product_id, line_items.quantity, addr.city FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.customer_id LEFT JOIN order_line_items line_items ON line_items.order_id = ord.order_id LEFT JOIN shipping_addresses addr ON addr.order_id = ord.order_id AND addr.address_type = 'shipping' WHERE ord.order_date >= '2026-07-01' AND cust.segment = 'enterprise'; Then gate it in CI with sqlalign --check . , which writes nothing and exits 1 if any file would change. Staging adoption across a legacy repo # Two keys exist for repos you cannot reformat all at once: format_dollar_bodies = false leaves $$ procedure and function bodies alone, so you can adopt sqlalign for queries before you take on stored procedures. A nested .sqlalign.toml scopes a different style to a subtree. Put preset = \"compact\" in legacy/ and the rest of the repo keeps the house style, with no flag juggling at the call site. Error reference # Every config failure exits 2 and prints to stderr. A broken config never gets guessed past: the file it applies to is left untouched, but because resolution is per file, other files in the same run still process . Formatting two files where only one has a broken config gives you the good file's output, the error on stderr, and exit 2 . Message Cause Fix unknown setting(s) [...]; valid: [...] A key sqlalign does not recognise Fix the spelling, or --no-strict-config for a mixed-version rollout <key> must be ... A valid key with an invalid value Use one of the listed values width must be an integer, got ... width given a string or float Write it unquoted: width = 100 align_targets must be a list, got ... align_targets given a non-list Write it as a TOML array unknown align_targets [...] A misspelled target name Use one of the six listed unknown preset '...' A misspelled preset house , compact , trailing , dbt blank_lines_between_statements must be a non-negative integer or unset, got ... A negative or non-integer count Use 0 or more, or delete the key invalid TOML: ... The file does not parse Fix the syntax <path>: [Errno 2] No such file or directory --config points at nothing Correct the path exclude must be a list of glob patterns exclude given a non-string, non-list Write a string or an array of strings exclude is the one exception to per-file recovery. It is read while expanding the directories you named, before any file is formatted, so a bad exclude aborts the whole run with an argparse-style sqlalign: error: ... and a usage banner rather than a per-file message. ","headings":[{"id":"where-sqlalign-looks","text":"Where sqlalign looks"},{"id":"precedence","text":"Precedence"},{"id":"key-reference","text":"Key reference"},{"id":"not-config-keys","text":"Not config keys"},{"id":"width-is-a-target-not-a-limit","text":"width is a target, not a limit"},{"id":"on-placement-quot-own-line-quot-retires-the-on-column","text":"on_placement = "own_line" retires the ON column"},{"id":"presets","text":"Presets"},{"id":"house","text":"house"},{"id":"compact","text":"compact"},{"id":"trailing","text":"trailing"},{"id":"dbt-and-its-one-deviation","text":"dbt, and its one deviation"},{"id":"unknown-keys-are-an-error","text":"Unknown keys are an error"},{"id":"no-strict-config","text":"--no-strict-config"},{"id":"inspecting-what-will-be-applied","text":"Inspecting what will be applied"},{"id":"overriding-discovery","text":"Overriding discovery"},{"id":"excluding-files","text":"Excluding files"},{"id":"a-realistic-committed-config","text":"A realistic committed config"},{"id":"staging-adoption-across-a-legacy-repo","text":"Staging adoption across a legacy repo"},{"id":"error-reference","text":"Error reference"}]},{"slug":"settings","title":"Settings reference","text":" Every setting sqlalign has, with its type, its default, and the same SQL rendered under each value . The examples on this page are produced by running the formatter when the page is built \u2014 none of them is written by hand, so none of them can drift away from what the tool actually does. Settings go in a .sqlalign.toml file under [tool.sqlalign] , and most have a CLI flag that overrides the file for one run. See Configuration for how the two combine, and CLI reference for the flags. All settings # keyword_case Whether SQL keywords are upper- or lowercase. align The master switch for columnar alignment. align_targets Which columns are aligned, when align is on. comma_position Whether a list's commas lead or trail their line. boolean_operator_position Whether AND / OR lead or trail their line. on_placement Whether a join's ON rides the join line or takes its own. select_placement Whether the first select item rides the SELECT line. select_indent How far the select list is indented under SELECT . clause_keyword_align Whether root clause keywords are left-aligned or form a river. river_gutter How wide the river's gutter is. table_alias_style Whether a table alias is written bare or with AS . neq_style How the not-equal operator is spelled. decimal_style How the fixed-point type is spelled. width The column the formatter tries to stay inside. blank_lines_between_statements How many blank lines separate two statements. body_blank_lines How many blank lines separate statements inside a $$ body. format_dollar_bodies Whether $$ \u2026 $$ procedure bodies are formatted at all. protect_templating Whether Jinja / dbt templating is masked before parsing. keyword_case # Whether SQL keywords are upper- or lowercase. Type str Default 'upper' Applies to keywords and function names, never to identifiers or string literals \u2014 a quoted identifier keeps the spelling you gave it, because in most dialects that spelling is load-bearing. Given this input: select customer_id, email, signup_date from customers where active; 'upper' \u00b7 default SELECT customer_id , email , signup_date FROM customers WHERE active; 'lower' select customer_id , email , signup_date from customers where active; align # The master switch for columnar alignment. Type bool Default True With it off, every alignment column collapses to a single space and you get the same line structure without the padding \u2014 which is what nine of ten published style guides ask for. Nothing else about the layout changes, so turning it off is not a different style so much as the same style unpadded. Given this input: select cust.id, cust.email, ord.total from customers cust inner join orders ord on ord.customer_id = cust.id where ord.total > 0 and cust.segment = 'enterprise'; True \u00b7 default SELECT cust.id , cust.email , ord.total FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.id WHERE ord.total > 0 AND cust.segment = 'enterprise'; False SELECT cust.id , cust.email , ord.total FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.id WHERE ord.total > 0 AND cust.segment = 'enterprise'; align_targets # Which columns are aligned, when align is on. Type set of str Default the default set A set of names. aliases is shorthand for column_aliases plus table_aliases . Anything not listed simply takes one space, so you can keep the join-condition column and drop the rest. Available: aliases , case_results , column_aliases , column_constraints , column_types , join_conditions , operators , table_aliases , table_names Given this input: select cust.id, cust.email, ord.total from customers cust inner join orders ord on ord.customer_id = cust.id where ord.total > 0 and cust.segment = 'enterprise'; the default set \u00b7 default SELECT cust.id , cust.email , ord.total FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.id WHERE ord.total > 0 AND cust.segment = 'enterprise'; {operators} SELECT cust.id , cust.email , ord.total FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.id WHERE ord.total > 0 AND cust.segment = 'enterprise'; frozenset() SELECT cust.id , cust.email , ord.total FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.id WHERE ord.total > 0 AND cust.segment = 'enterprise'; comma_position # Whether a list's commas lead or trail their line. Type str Default 'leading' Leading commas put the separator where the eye already is when scanning a column of items, and make adding or removing the last item a one-line diff. Given this input: select customer_id, email, signup_date from customers where active; 'leading' \u00b7 default SELECT customer_id , email , signup_date FROM customers WHERE active; 'trailing' SELECT customer_id, email, signup_date FROM customers WHERE active; boolean_operator_position # Whether AND / OR lead or trail their line. Type str Default 'leading' The same choice as comma_position , for predicates. Leading operators right-align under the clause keyword, so WHERE , AND and OR all end in the same column. Given this input: select cust.id, cust.email, ord.total from customers cust inner join orders ord on ord.customer_id = cust.id where ord.total > 0 and cust.segment = 'enterprise'; 'leading' \u00b7 default SELECT cust.id , cust.email , ord.total FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.id WHERE ord.total > 0 AND cust.segment = 'enterprise'; 'trailing' SELECT cust.id , cust.email , ord.total FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.id WHERE ord.total > 0 AND cust.segment = 'enterprise'; on_placement # Whether a join's ON rides the join line or takes its own. Type str Default 'inline' Inline keeps a join to one row and lets the ON column align across the whole FROM block. On its own line it drops below, indented, which reads better when conditions are long. Given this input: select cust.id, cust.email, ord.total from customers cust inner join orders ord on ord.customer_id = cust.id where ord.total > 0 and cust.segment = 'enterprise'; 'inline' \u00b7 default SELECT cust.id , cust.email , ord.total FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.id WHERE ord.total > 0 AND cust.segment = 'enterprise'; 'own_line' SELECT cust.id , cust.email , ord.total FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.id WHERE ord.total > 0 AND cust.segment = 'enterprise'; select_placement # Whether the first select item rides the SELECT line. Type str Default 'inline' Inline starts the list on the SELECT row itself. own_line puts every item below, indented by select_indent \u2014 the dbt and GitLab convention. Given this input: select customer_id, email, signup_date from customers where active; 'inline' \u00b7 default SELECT customer_id , email , signup_date FROM customers WHERE active; 'own_line' SELECT customer_id , email , signup_date FROM customers WHERE active; select_indent # How far the select list is indented under SELECT . Type int Default 2 Only applies when select_placement is own_line ; it is greyed out in the GUI otherwise, and ignored here. Rendered below with select_placement = own_line , since the setting does nothing without it. Given this input: select customer_id, email, signup_date from customers where active; 2 \u00b7 default SELECT customer_id , email , signup_date FROM customers WHERE active; 4 SELECT customer_id , email , signup_date FROM customers WHERE active; clause_keyword_align # Whether root clause keywords are left-aligned or form a river. Type str Default 'left' A river right-aligns every root keyword so its last character lands on a shared gutter, which puts every clause body in one column. It is the arrangement Holywell's style guide describes. Given this input: select cust.id, cust.email, ord.total from customers cust inner join orders ord on ord.customer_id = cust.id where ord.total > 0 and cust.segment = 'enterprise'; 'left' \u00b7 default SELECT cust.id , cust.email , ord.total FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.id WHERE ord.total > 0 AND cust.segment = 'enterprise'; 'river' SELECT cust.id , cust.email , ord.total FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.id WHERE ord.total > 0 AND cust.segment = 'enterprise'; river_gutter # How wide the river's gutter is. Type int Default 6 The column every root keyword ends on. Fixed rather than derived from the widest keyword present, so a clause added later cannot shift the whole statement sideways. Rendered below with clause_keyword_align = river , since the setting does nothing without it. Given this input: select cust.id, cust.email, ord.total from customers cust inner join orders ord on ord.customer_id = cust.id where ord.total > 0 and cust.segment = 'enterprise'; 6 \u00b7 default SELECT cust.id , cust.email , ord.total FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.id WHERE ord.total > 0 AND cust.segment = 'enterprise'; 10 SELECT cust.id , cust.email , ord.total FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.id WHERE ord.total > 0 AND cust.segment = 'enterprise'; table_alias_style # Whether a table alias is written bare or with AS . Type str Default 'bare' FROM orders ord and FROM orders AS ord parse identically, so which one comes out is sqlalign's decision rather than yours \u2014 which is exactly why it is a setting. Given this input: select cust.id as customer, sum(ord.total) as lifetime_value from customers cust join orders ord on ord.customer_id = cust.id group by cust.id; 'bare' \u00b7 default SELECT cust.id AS customer , SUM(ord.total) AS lifetime_value FROM customers cust JOIN orders ord ON ord.customer_id = cust.id GROUP BY cust.id; 'as' SELECT cust.id AS customer , SUM(ord.total) AS lifetime_value FROM customers AS cust JOIN orders AS ord ON ord.customer_id = cust.id GROUP BY cust.id; neq_style # How the not-equal operator is spelled. Type str Default '!=' <> and != parse to the same node, so the distinction is lost before layout ever runs and one of them has to be chosen. Set it to whatever your linter expects. Given this input: select a from t where status != 'draft' and total <> 0; '!=' \u00b7 default SELECT a FROM t WHERE status != 'draft' AND total != 0; '<>' SELECT a FROM t WHERE status <> 'draft' AND total <> 0; decimal_style # How the fixed-point type is spelled. Type str Default 'NUMERIC' DECIMAL and NUMERIC are synonyms that parse to one node \u2014 the same forced choice as neq_style . Given this input: create table t (amount decimal(10, 2), rate numeric(5, 4)); 'NUMERIC' \u00b7 default CREATE TABLE t ( amount NUMERIC(10, 2) , rate NUMERIC(5, 4) ); 'DECIMAL' CREATE TABLE t ( amount DECIMAL(10, 2) , rate DECIMAL(5, 4) ); width # The column the formatter tries to stay inside. Type Width Default 100 A trigger for the breaks that are modelled, not a hard ceiling: an expression with no modelled break stays on one line however long it is. 0 turns the limit off entirely. 0 turns the limit off, which is the same as a width nothing reaches \u2014 so it is described here rather than shown. Given this input: select customer_id, coalesce(sum(case when status = 'paid' then amount end), 0.00) as paid_total from ledger group by customer_id; 100 \u00b7 default SELECT customer_id , COALESCE(SUM(CASE WHEN status = 'paid' THEN amount END), 0.00) AS paid_total FROM ledger GROUP BY customer_id; 60 SELECT customer_id , COALESCE(SUM(CASE WHEN status = 'paid' THEN amount END), 0.00) AS paid_total FROM ledger GROUP BY customer_id; blank_lines_between_statements # How many blank lines separate two statements. Type int or unset Default None Unset, the house rule applies: exactly one blank line between two statements when both are multi-line, and otherwise whatever adjacency the input had. A number overrides that for every pair. Given this input: select a from t; update u set b = 2 where c = 3; None \u00b7 default SELECT a FROM t; UPDATE u SET b = 2 WHERE c = 3; 0 SELECT a FROM t; UPDATE u SET b = 2 WHERE c = 3; 2 SELECT a FROM t; UPDATE u SET b = 2 WHERE c = 3; body_blank_lines # How many blank lines separate statements inside a $$ body. Type int Default 1 A procedure body has its own vertical rhythm, separate from the one between top-level statements. Given this input: create function bump() returns int as $$ begin update t set n = n + 1; return 1; end; $$ language plpgsql; 1 \u00b7 default CREATE FUNCTION bump() RETURNS INT LANGUAGE plpgsql AS $$ BEGIN UPDATE t SET n = n + 1; RETURN 1; END; $$; 0 CREATE FUNCTION bump() RETURNS INT LANGUAGE plpgsql AS $$ BEGIN UPDATE t SET n = n + 1; RETURN 1; END; $$; format_dollar_bodies # Whether $$ \u2026 $$ procedure bodies are formatted at all. Type bool Default True With it off the whole CREATE FUNCTION is left byte-identical. Useful for staging a migration: format the repository, leave the procedures for a later pass. Given this input: create function bump() returns int as $$ begin update t set n = n + 1; return 1; end; $$ language plpgsql; True \u00b7 default CREATE FUNCTION bump() RETURNS INT LANGUAGE plpgsql AS $$ BEGIN UPDATE t SET n = n + 1; RETURN 1; END; $$; False create function bump() returns int as $$ begin update t set n = n + 1; return 1; end; $$ language plpgsql; protect_templating # Whether Jinja / dbt templating is masked before parsing. Type bool Default True {{ ref('x') }} is not SQL and sqlglot cannot parse it. With this on, each template expression is replaced by a placeholder for the duration of the parse and restored afterwards, so a dbt model formats instead of declining. Given this input: select * from {{ ref('stg_orders') }} where status = 'paid'; True \u00b7 default SELECT * FROM {{ ref('stg_orders') }} WHERE status = 'paid'; False Declined \u2014 passed through unchanged. parse error select * from {{ ref('stg_orders') }} where status = 'paid'; Presets # A preset is a named bundle of the settings above. --preset NAME applies one, and any explicit setting still wins over it. Given this input: select customer_id, email, signup_date from customers where active; compact SELECT customer_id , email , signup_date FROM customers WHERE active; dbt select customer_id, email, signup_date from customers where active; gitlab SELECT customer_id, email, signup_date FROM customers WHERE active; house SELECT customer_id , email , signup_date FROM customers WHERE active; river SELECT customer_id , email , signup_date FROM customers WHERE active; trailing SELECT customer_id, email, signup_date FROM customers WHERE active; ","headings":[{"id":"all-settings","text":"All settings"},{"id":"keyword_case","text":"keyword_case"},{"id":"align","text":"align"},{"id":"align_targets","text":"align_targets"},{"id":"comma_position","text":"comma_position"},{"id":"boolean_operator_position","text":"boolean_operator_position"},{"id":"on_placement","text":"on_placement"},{"id":"select_placement","text":"select_placement"},{"id":"select_indent","text":"select_indent"},{"id":"clause_keyword_align","text":"clause_keyword_align"},{"id":"river_gutter","text":"river_gutter"},{"id":"table_alias_style","text":"table_alias_style"},{"id":"neq_style","text":"neq_style"},{"id":"decimal_style","text":"decimal_style"},{"id":"width","text":"width"},{"id":"blank_lines_between_statements","text":"blank_lines_between_statements"},{"id":"body_blank_lines","text":"body_blank_lines"},{"id":"format_dollar_bodies","text":"format_dollar_bodies"},{"id":"protect_templating","text":"protect_templating"},{"id":"presets","text":"Presets"}]},{"slug":"style","title":"The house style","text":" Read this page to see exactly what sqlalign does to your SQL, construct by construct, and to find the handful of decisions you can change. Every SQL block below is real output from sqlalign --stdout , paired with the messy input that produced it. A few later blocks reuse an input shown earlier. Nothing here is hand-written \"expected\" SQL. If you only want the summary: sqlalign stacks lists one item per line with the separator leading, and pads repeated elements into vertical columns. It does not change what your SQL means, and it does not lint. Two rules generate most of the layout # One element per line, separator first. In any stacked list \u2014 select items, GROUP BY columns, SET assignments, CREATE TABLE columns \u2014 each item gets its own line, opened by the comma rather than closed by it. In a clause, the first item rides the clause keyword's line. Repeated elements pad into a column. Table aliases, AS aliases, ON keywords, comparison operators, THEN values, column types: each kind gets one column per scope, wide enough for the longest entry. Two details make the columns look the way they do: Everything except operators is left-aligned and starts one space past the longest content to its left. Operators right-align. Their end is what lines up, so = , >= , IN , IS and BETWEEN all finish in the same column and their right-hand operands start together. A scope is the region a column spans: one select list, one whole FROM block, one WHERE clause, one CASE . Brackets end a scope, so a subquery or CTE aligns internally and never with its parent. The select list # select id, first_name, last_name, email, created_at from users where status = 'active' and created_at >= '2026-01-01' order by created_at desc limit 100; SELECT id , first_name , last_name , email , created_at FROM users WHERE status = 'active' AND created_at >= '2026-01-01' ORDER BY created_at DESC LIMIT 100; The first item stays on the SELECT line. Every later item starts in that same column, with its comma two columns to the left. * is never expanded into columns. When items carry aliases, the AS keywords form a column across the select list. Select-list aliases always render with AS , so SELECT a x comes back as SELECT a AS x \u2014 but sqlalign never invents an alias where you had none, and never changes the name you chose: select customer_id, date_trunc('month', order_date) as order_month, count(*) as order_count, sum(total) as revenue, avg(total) as avg_order_value from orders where status = 'complete' group by customer_id, date_trunc('month', order_date) having count(*) > 3 and sum(total) > 1000 order by revenue desc; SELECT customer_id , DATE_TRUNC('month', order_date) AS order_month , COUNT(*) AS order_count , SUM(total) AS revenue , AVG(total) AS avg_order_value FROM orders WHERE status = 'complete' GROUP BY customer_id , DATE_TRUNC('month', order_date) HAVING COUNT(*) > 3 AND SUM(total) > 1000 ORDER BY revenue DESC; GROUP BY, ORDER BY, LIMIT # GROUP BY and ORDER BY use the same stacking rule as the select list, with two exceptions. A single item stays inline \u2014 ORDER BY revenue DESC above. So do positional references , however many: GROUP BY 1, 2 stays on one line (see the CTE example further down). Two or more named columns stack. LIMIT gets its own line. Set operations # A set operator sits alone on its line with a blank line on each side, and each branch is formatted independently: select id, email, 'customer' as source from customers where created_at >= '2026-01-01' union all select id, email, 'lead' as source from leads where converted = false union all select id, email, 'partner' as source from partner_contacts; SELECT id , email , 'customer' AS source FROM customers WHERE created_at >= '2026-01-01' UNION ALL SELECT id , email , 'lead' AS source FROM leads WHERE converted = FALSE UNION ALL SELECT id , email , 'partner' AS source FROM partner_contacts; The FROM block # Table aliases align into one column that spans the whole FROM block \u2014 the base table and every join together, not each join on its own. Table aliases render implicitly, so FROM orders AS o comes back as FROM orders o . select cust.customer_id, cust.email, ord.order_id, ord.total, line_items.product_id, line_items.quantity, addr.city from customers cust inner join orders ord on ord.customer_id = cust.customer_id left join order_line_items line_items on line_items.order_id = ord.order_id left join shipping_addresses addr on addr.order_id = ord.order_id and addr.address_type = 'shipping' where ord.order_date >= '2026-07-01' and cust.segment = 'enterprise'; SELECT cust.customer_id , cust.email , ord.order_id , ord.total , line_items.product_id , line_items.quantity , addr.city FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.customer_id LEFT JOIN order_line_items line_items ON line_items.order_id = ord.order_id LEFT JOIN shipping_addresses addr ON addr.order_id = ord.order_id AND addr.address_type = 'shipping' WHERE ord.order_date >= '2026-07-01' AND cust.segment = 'enterprise'; shipping_addresses is the longest table name, so the alias column opens one space past it and cust , ord , line_items and addr all start there. The ON/AND condition column # This is the part of the style you are least likely to have seen before. Look at the same block again: FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.customer_id LEFT JOIN order_line_items line_items ON line_items.order_id = ord.order_id LEFT JOIN shipping_addresses addr ON addr.order_id = ord.order_id AND addr.address_type = 'shipping' Three columns run the full height of the block: the aliases, the ON keyword, and the = operators. The join conditions therefore read as a two-column table of left operand and right operand \u2014 across every join at once, not per join. (Table names are not a column; they start wherever their join keyword ends.) An extra condition drops to its own line and its AND right-aligns to end where ON ends, so ON and AND read as one stack of connectives. Aligning aliases is not unusual \u2014 sqlfluff aligns alias expressions too. Carrying one ON / AND column across an entire FROM block is the unusual part: the other formatters surveyed in the README break the line instead of padding it. If you want it gone, --align-targets drops join_conditions and keeps the rest. WHERE and HAVING # The first condition rides the keyword's line. Later conditions get their own lines, and their AND / OR right-aligns to end where the keyword ends \u2014 column 5 for WHERE , column 6 for HAVING . That is why AND is indented two under WHERE and three under HAVING . Within the clause, comparison operators right-align: SELECT id, name, category, price FROM products WHERE (category IN ('electronics', 'appliances', 'accessories') OR name LIKE '%refurb%') AND price BETWEEN 25 AND 500 AND discontinued = false AND supplier_id IS NOT NULL; SELECT id , name , category , price FROM products WHERE (category IN ('electronics', 'appliances', 'accessories') OR name LIKE '%refurb%') AND price BETWEEN 25 AND 500 AND discontinued = FALSE AND supplier_id IS NOT NULL; Two things are worth reading closely there. Operators end together, they do not start together. BETWEEN , = and IS are 7, 1 and 2 characters wide, and all three finish in the same column, so the values to their right line up. A parenthesized group is its own sub-scope. IN and LIKE align with each other inside the parens; BETWEEN , = and IS align with each other outside it. The two groups do not share a column. Inside the group, OR aligns with the group's first condition rather than with the outer AND . CASE # sqlalign has two CASE forms and picks between them automatically. Short form puts each WHEN cond THEN val on one line, with the WHEN s aligned one space past CASE and the THEN s padded into a column. END sits under CASE . Long form puts THEN on its own line, indented two past its WHEN . You get it when a WHEN condition is a compound boolean ( AND / OR ), or when a WHEN \u2026 THEN \u2026 row would not fit the width limit. Both forms in one query \u2014 the second CASE goes long because its second WHEN is compound, even though every row would have fit: select order_id, total, case when total >= 1000 then 'large' when total >= 100 then 'medium' when total > 0 then 'small' else 'invalid' end as order_size, case when status = 'complete' then 1 when status = 'pending' and not is_archived then 2 else 99 end as status_rank from orders; SELECT order_id , total , CASE WHEN total >= 1000 THEN 'large' WHEN total >= 100 THEN 'medium' WHEN total > 0 THEN 'small' ELSE 'invalid' END AS order_size , CASE WHEN status = 'complete' THEN 1 WHEN status = 'pending' AND NOT is_archived THEN 2 ELSE 99 END AS status_rank FROM orders; CASE is never left alone on a line: the first WHEN always stays with it. Here is the width trigger on its own \u2014 no compound condition, just a result string too long for the line: select order_id, case when total >= 1000 then 'a really quite long result string that pushes this row over the configured width limit' when total > 0 then 'small' else 'none' end as bucket from orders; SELECT order_id , CASE WHEN total >= 1000 THEN 'a really quite long result string that pushes this row over the configured width limit' WHEN total > 0 THEN 'small' ELSE 'none' END AS bucket FROM orders; Window functions # OVER takes a space before its paren \u2014 it is a keyword, not a function name. A window that fits stays on one line. One that does not breaks at window sub-clause boundaries, with continuation lines aligned under PARTITION . The AS alias still joins the select list's alias column, measured against the last line: select customer_id, order_id, order_date, total, row_number() over (partition by customer_id order by order_date desc) as rn, sum(total) over (partition by customer_id order by order_date rows between unbounded preceding and current row) as running_total, lag(order_date) over (partition by customer_id order by order_date) as prev_order_date from orders; SELECT customer_id , order_id , order_date , total , ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS rn , SUM(total) OVER (PARTITION BY customer_id ORDER BY order_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total , LAG(order_date) OVER (PARTITION BY customer_id ORDER BY order_date) AS prev_order_date FROM orders; The frame clause is the first thing to move down when a window is too wide. CTEs # Each CTE opens with name AS ( , indents its body two, and closes with ) at the statement's anchor column. A blank line separates CTEs from each other and from the final SELECT , and the separator comma opens the next CTE's line: with monthly_revenue as (select customer_id, date_trunc('month', order_date) as month, sum(total) as revenue from orders group by 1, 2), top_customers as (select customer_id from monthly_revenue group by customer_id having sum(revenue) > 10000) select m.customer_id, m.month, m.revenue from monthly_revenue m join top_customers t on t.customer_id = m.customer_id order by m.customer_id, m.month; WITH monthly_revenue AS ( SELECT customer_id , DATE_TRUNC('month', order_date) AS month , SUM(total) AS revenue FROM orders GROUP BY 1, 2 ) , top_customers AS ( SELECT customer_id FROM monthly_revenue GROUP BY customer_id HAVING SUM(revenue) > 10000 ) SELECT m.customer_id , m.month , m.revenue FROM monthly_revenue m JOIN top_customers t ON t.customer_id = m.customer_id ORDER BY m.customer_id , m.month; The AS column inside monthly_revenue is computed from that CTE's items alone. top_customers and the final SELECT each resolve their own columns; the brackets keep them apart. WITH RECURSIVE gets the same layout, with the set operator inside the CTE body following the usual blank-line rule: with recursive tree as (select id, parent_id, 1 as depth from nodes where parent_id is null union all select n.id, n.parent_id, t.depth + 1 from nodes n join tree t on t.id = n.parent_id) select id, depth from tree order by depth; WITH RECURSIVE tree AS ( SELECT id , parent_id , 1 AS depth FROM nodes WHERE parent_id IS NULL UNION ALL SELECT n.id , n.parent_id , t.depth + 1 FROM nodes n JOIN tree t ON t.id = n.parent_id ) SELECT id , depth FROM tree ORDER BY depth; Subqueries # A derived table opens inline after ( , aligns its body to its own SELECT , and drops the closing ) to a line of its own, with the alias and ON following it there. Scalar, IN (\u2026) and EXISTS (\u2026) subqueries close inline instead: select u.id, u.email, recent.last_order_date, (select count(*) from support_tickets st where st.user_id = u.id) as ticket_count from users u join (select customer_id, max(order_date) as last_order_date from orders group by customer_id) recent on recent.customer_id = u.id where u.id in (select user_id from subscriptions where plan = 'premium'); SELECT u.id , u.email , recent.last_order_date , (SELECT COUNT(*) FROM support_tickets st WHERE st.user_id = u.id) AS ticket_count FROM users u JOIN (SELECT customer_id , MAX(order_date) AS last_order_date FROM orders GROUP BY customer_id ) recent ON recent.customer_id = u.id WHERE u.id IN (SELECT user_id FROM subscriptions WHERE plan = 'premium'); A derived table is deliberately excluded from the FROM block's alias and ON columns \u2014 its alias sits on the closing-paren line, anchored to the subquery. INSERT, UPDATE, DELETE # INSERT INTO table takes its own line. The column list uses the same leading separator as a select list, opened by ( and two spaces, and closed by ) touching the last column. The SELECT then starts at column 1. (A top-level INSERT \u2026 VALUES is not modelled yet and passes through byte-identical; VALUES inside a MERGE is formatted, as below.) UPDATE \u2026 SET stacks assignments with the = aligned. DELETE FROM is followed by a normal WHERE clause. insert into daily_revenue (report_date, channel, revenue, order_count) select order_date, channel, sum(total), count(*) from orders where order_date = current_date - 1 group by order_date, channel; update products set price = price * 1.05, updated_at = current_timestamp where category = 'electronics' and discontinued = false; delete from daily_revenue where report_date < '2026-01-01' and channel = 'legacy'; INSERT INTO daily_revenue ( report_date , channel , revenue , order_count) SELECT order_date , channel , SUM(total) , COUNT(*) FROM orders WHERE order_date = CURRENT_DATE - 1 GROUP BY order_date , channel; UPDATE products SET price = price * 1.05 , updated_at = CURRENT_TIMESTAMP WHERE category = 'electronics' AND discontinued = FALSE; DELETE FROM daily_revenue WHERE report_date < '2026-01-01' AND channel = 'legacy'; The blank lines between those three statements are not from the input, which had none. sqlalign puts exactly one blank line between two statements when both are multi-line , and leaves adjacency alone otherwise. --blank-lines-between-statements N forces a fixed count instead. MERGE # Every MERGE clause starts its own line at column 1. The ON block uses WHERE -clause geometry \u2014 ON and AND right-aligned to end at column 5, with the operators padded \u2014 and SET behaves exactly like an UPDATE : merge into daily_revenue tgt using staging_daily_revenue src on tgt.report_date = src.report_date and tgt.channel = src.channel when matched then update set revenue = src.revenue, order_count = src.order_count, updated_at = current_timestamp when not matched then insert (report_date, channel, revenue, order_count) values (src.report_date, src.channel, src.revenue, src.order_count); MERGE INTO daily_revenue tgt USING staging_daily_revenue src ON tgt.report_date = src.report_date AND tgt.channel = src.channel WHEN MATCHED THEN UPDATE SET revenue = src.revenue , order_count = src.order_count , updated_at = CURRENT_TIMESTAMP WHEN NOT MATCHED THEN INSERT ( report_date , channel , revenue , order_count) VALUES ( src.report_date , src.channel , src.revenue , src.order_count ); CREATE TABLE # One column per line. The first is indented 4, the leading commas sit at column 3, and three columns align: name, type, then constraints. A table-level constraint is the last list item. create table daily_revenue (report_date date not null, channel varchar(50) not null, revenue numeric(12,2) default 0, order_count int default 0, created_at timestamp default current_timestamp, primary key (report_date, channel)); CREATE TABLE daily_revenue ( report_date DATE NOT NULL , channel VARCHAR(50) NOT NULL , revenue NUMERIC(12, 2) DEFAULT 0 , order_count INT DEFAULT 0 , created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (report_date, channel) ); Note NUMERIC(12,2) became NUMERIC(12, 2) : inline lists always take a space after the comma. On Redshift, constraints align per kind rather than sharing one column, and table attributes follow the closing paren, one clause per line. ENCODE values are identifiers, so they come through exactly as you wrote them \u2014 az64 stays lowercase, AZ64 stays uppercase: create table fact_orders (order_id bigint not null, customer_id bigint not null encode az64, order_date date not null encode az64, total numeric(12, 2) encode az64, channel varchar(32) encode lzo) diststyle key distkey (customer_id) compound sortkey (order_date, customer_id); CREATE TABLE fact_orders ( order_id BIGINT NOT NULL , customer_id BIGINT NOT NULL ENCODE az64 , order_date DATE NOT NULL ENCODE az64 , total NUMERIC(12, 2) ENCODE az64 , channel VARCHAR(32) ENCODE lzo ) DISTSTYLE KEY DISTKEY (customer_id) COMPOUND SORTKEY (order_date, customer_id); The NOT NULL column is measured over only the three lines that carry it; the ENCODE column over only the four that carry it. That is why total and channel have no NOT NULL gap to pay for. plpgsql $$ bodies # sqlalign parses the body between $$ \u2026 $$ and formats it with the same engine it uses at the top level, rather than treating it as an opaque string. Header clauses each get their own line, body statements sit at column 1 with blank lines between them, and $$; closes at column 1. create or replace function get_customer_ltv(p_customer_id int) returns numeric language plpgsql as $$ declare v_ltv numeric; begin select sum(total) into v_ltv from orders where customer_id = p_customer_id and status = 'complete'; if v_ltv is null then v_ltv := 0; end if; return v_ltv; end; $$; CREATE OR REPLACE FUNCTION get_customer_ltv(p_customer_id INT) RETURNS NUMERIC LANGUAGE plpgsql AS $$ DECLARE v_ltv NUMERIC; BEGIN SELECT SUM(total) INTO v_ltv FROM orders WHERE customer_id = p_customer_id AND status = 'complete'; IF v_ltv IS NULL THEN v_ltv := 0; END IF; RETURN v_ltv; END; $$; The WHERE clause inside the body is aligned by the same rules as one at the top level. A larger body shows the full treatment \u2014 DELETE , an INSERT with its column list, GET DIAGNOSTICS , and an IF / THEN / ELSE block: create procedure refresh_daily_revenue(target_date date) language plpgsql as $$ declare row_count int; begin delete from daily_revenue where report_date = target_date; insert into daily_revenue (report_date, channel, revenue, order_count) select order_date, channel, sum(total), count(*) from orders where order_date = target_date group by order_date, channel; get diagnostics row_count = row_count; if row_count = 0 then raise warning 'no orders found for %', target_date; else raise notice 'loaded % rows', row_count; end if; end; $$; CREATE PROCEDURE refresh_daily_revenue(target_date DATE) LANGUAGE plpgsql AS $$ DECLARE row_count INT; BEGIN DELETE FROM daily_revenue WHERE report_date = target_date; INSERT INTO daily_revenue ( report_date , channel , revenue , order_count) SELECT order_date , channel , SUM(total) , COUNT(*) FROM orders WHERE order_date = target_date GROUP BY order_date , channel; GET DIAGNOSTICS row_count = ROW_COUNT; IF row_count = 0 THEN RAISE WARNING 'no orders found for %', target_date; ELSE RAISE NOTICE 'loaded % rows', row_count; END IF; END; $$; One header normalization to know about: LANGUAGE 'plpgsql' loses its quotes and comes back as LANGUAGE plpgsql . The quoted form is legacy syntax; the Postgres and Redshift docs both use the unquoted one. --no-format-bodies turns body formatting off. Note what that does: the whole CREATE FUNCTION / CREATE PROCEDURE statement is left byte-identical, header included, while other statements in the same file still format. Stability # The style does not change in a patch release. If you pin sqlalign~=1.1 , every file it formats today it formats identically tomorrow, and a patch upgrade cannot land a reformatting commit in your repository. That is not a promise so much as a property. samples/queries.sql and tests/fixtures/expected/ are hand-formatted and compared byte for byte , and they run as their own CI job. A change to the layout \u2014 even one nobody intended \u2014 turns that job red before it can reach a release. The goldens are the specification; the code is what has to agree with them. When the style does change, it changes in a minor release, the changelog says which construct moved and why, and the goldens change in their own commit with the reason. A style change that arrives without those three things is a bug. There is deliberately no style_version key to pin. A version selector is worth having the day there are two styles to select between and not before: today it would be a setting with one value, a second code path with nothing in it, and a promise to maintain old layouts forever that this project has not made. The release policy above is the guarantee; the config file does not need to restate it. What the style deliberately does not do # It cannot change what your SQL means. Every formatted statement is re-parsed and compared against the input as a syntax tree, and that tree is what \"means\" is measured by. Anything that would differ is discarded and the original bytes are kept. Identifiers, string literals, cast form ( :: versus CAST ), GROUP BY reference form, comments and the alias names you chose all survive exactly as written. (The AS keyword itself is layout, not content, so it is normalized: present in select lists, absent for table aliases.) Two spellings collapse before that comparison exists, and are therefore sqlalign's to pick rather than yours: != against <> , and decimal against numeric . Both are settings \u2014 neq_style and decimal_style \u2014 rather than accidents, precisely because the guarantee cannot reach them. It does not lint. sqlalign will not unify your cast styles, insert missing aliases, turn JOIN into INNER JOIN , or make GROUP BY references consistent. That is sqlfluff's job, and the two are designed to run together. It declines what it cannot reproduce exactly. A construct the engine does not model passes through byte-identical, with a warning on stderr and exit code 0. A CTE column list is one such construct today: with c(a, b) as (select 1, 2) select a from c; with c(a, b) as (select 1, 2) select a from c; sqlalign: query.sql: unsupported construct (CTE column list), passed through: with c(a, b) as (select 1, 2) select a f Nothing was reformatted and nothing was mangled. The rest of the file still formats normally. What you can configure # Eleven settings change the style itself. Each is a CLI flag and a .sqlalign.toml key (or a [tool.sqlalign] key in pyproject.toml ), and each can also arrive via a preset. sqlalign --show-config file.sql prints what is actually in effect. Flag Config key Default Changes --no-align align true all column padding, on or off --align-targets a,b,\u2026 align_targets all but table_names which columns are padded --comma-position comma_position leading where the separator comma sits --boolean-operator-position boolean_operator_position leading where AND / OR sit --on-placement on_placement inline whether a join's ON rides the table line --keyword-case keyword_case upper case of keywords, functions and types --select-placement select_placement inline whether the first select item rides the SELECT line --select-indent N select_indent 2 how far the list indents when it starts below SELECT --clause-keyword-align clause_keyword_align left r","headings":[{"id":"two-rules-generate-most-of-the-layout","text":"Two rules generate most of the layout"},{"id":"the-select-list","text":"The select list"},{"id":"group-by-order-by-limit","text":"GROUP BY, ORDER BY, LIMIT"},{"id":"set-operations","text":"Set operations"},{"id":"the-from-block","text":"The FROM block"},{"id":"the-on-and-condition-column","text":"The ON/AND condition column"},{"id":"where-and-having","text":"WHERE and HAVING"},{"id":"case","text":"CASE"},{"id":"window-functions","text":"Window functions"},{"id":"ctes","text":"CTEs"},{"id":"subqueries","text":"Subqueries"},{"id":"insert-update-delete","text":"INSERT, UPDATE, DELETE"},{"id":"merge","text":"MERGE"},{"id":"create-table","text":"CREATE TABLE"},{"id":"plpgsql-bodies","text":"plpgsql $$ bodies"},{"id":"stability","text":"Stability"},{"id":"what-the-style-deliberately-does-not-do","text":"What the style deliberately does not do"},{"id":"what-you-can-configure","text":"What you can configure"},{"id":"align-turn-the-padding-off","text":"align \u2014 turn the padding off"},{"id":"align-targets-keep-some-columns-drop-others","text":"align_targets \u2014 keep some columns, drop others"},{"id":"comma-position-trailing-commas","text":"comma_position \u2014 trailing commas"},{"id":"boolean-operator-position-trailing-and-or","text":"boolean_operator_position \u2014 trailing AND/OR"},{"id":"on-placement-drop-on-below-the-table","text":"on_placement \u2014 drop ON below the table"},{"id":"keyword-case-lowercase-keywords","text":"keyword_case \u2014 lowercase keywords"},{"id":"presets","text":"Presets"},{"id":"two-settings-sqlalign-has-to-choose-for-you","text":"Two settings sqlalign has to choose for you"}]},{"slug":"cli","title":"CLI reference","text":" All flags # Generated from the parser, so it cannot fall behind it. The sections below explain the ones that need more than a line. Flag Description -h , --help show this help message and exit --version print the version and exit --check do not write; exit 1 if any file would change --stdout write the result to stdout instead of the file --diff write nothing; print a unified diff of what would change (exit 1 if anything would) --dialect postgres , redshift , tsql the SQL dialect to parse and print. Overrides a dialect in the config file (default: postgres) --lines format only statements overlapping these 1-based, inclusive line numbers; the rest of the file is left byte-identical. Repeatable. Applies to one file (or stdin), since line numbers mean nothing across several --line-ending auto , lf , crlf line endings to write: auto preserves the file's own (default) --config use this config file instead of discovering one --exclude skip files matching this glob when expanding a directory (repeatable; also settable as exclude in a config file) --isolated ignore any config file and use the built-in defaults --show-config print the effective settings as TOML and exit --init write a commented .sqlalign.toml in the current directory and exit; every setting is commented out, so the file changes nothing until you edit it --gui (experimental) open the settings panel with a live preview, and exit --report print a coverage summary: how many statements were formatted, and what the rest declined on. Adds output without changing the mode, so on its own it still rewrites; pair it with --check to survey without writing --max-declines exit 1 if more than N statements are passed through unformatted (implies --report) --lint after formatting, run sqlfluff over the result (needs the optional sqlalign[lint] extra) --sqlfluff-config lint with this sqlfluff config instead of the one discovered next to each file. For a shared config that lives outside the repository, which discovery cannot reach. Requires --lint --print-sqlfluff-config print a .sqlfluff that lets sqlfluff run alongside sqlalign without fighting it, and exit --no-strict-config warn on unknown config keys instead of failing --preset compact , dbt , gitlab , house , river , trailing named starting point; config keys and flags layer on top --width column the formatter tries to stay inside; 0 turns it off --blank-lines-between-statements force N blank lines between every pair of statements (default: one only between two multi-line statements) --no-align emit one space between tokens instead of aligning them into columns (same line structure, no padding) --no-protect-templating do not mask Jinja/dbt template expressions before formatting --no-format-bodies leave dollar-quoted ($$) procedure and function bodies untouched --align-targets comma-separated alignment targets to keep. Default is every target except table_names, which is opt-in because it pads the FROM/JOIN keyword out to a shared table column. Valid: aliases, case_results, column_aliases, column_constraints, column_types, join_conditions, operators, table_aliases, table_names --comma-position leading , trailing where the separator comma sits in a stacked list (default: leading) --boolean-operator-position leading , trailing where AND/OR sit when a predicate spans lines (default: leading) --on-placement inline , own_line whether a JOIN ON rides the table line or drops below it --select-placement inline , own_line whether the first select item rides the SELECT line --select-indent columns the select list indents under --select-placement own_line (default: 2) --body-blank-lines blank lines between the elements of a $$ body (default: 1) --clause-keyword-align left , river root clause keywords flush left, or right-aligned to a river --river-gutter column a river right-aligns clause keywords to (default: 6) --keyword-case upper , lower case for keywords, function names and types (default: upper) --neq-style != , <> spelling for the not-equal operator (default: !=) --table-alias-style bare , as print a table alias as t a (bare) or t AS a --decimal-style NUMERIC , DECIMAL spelling for the NUMERIC/DECIMAL type (default: NUMERIC) sqlalign [OPTIONS] FILE_OR_DIRECTORY... Every flag below is the complete set \u2014 this page is written against sqlalign --help and nothing is omitted. New to the tool? Start with Getting started ; this page is for looking things up. For committing these settings to a config file rather than typing them, see Configuration . Defaults marked (house) are what you get with no config file and no flags. Positional arguments # Argument Default What it does files \u2026 required One or more files or directories. A directory is searched recursively for *.sql , in sorted order so a run is reproducible. At least one path is required, including with --show-config . -h , --help \u2014 Print the usage summary and exit. A single - reads stdin and writes the result to stdout, which is what an editor's format-on-save runs through a generic external-formatter setting: cat query.sql | sqlalign - sqlalign - --dialect tsql < query.sql --check and --diff still report rather than write when the input is - , so sqlalign --check - is a gate on piped SQL. - cannot be combined with file arguments: stdin is read once, so that has no sensible reading. Output mode # By default sqlalign rewrites each file in place and prints nothing. These flags change that. Flag Default What it does --check off Write nothing. Print would reformat <path> for each file that is not already formatted. Exit 1 if any is. --stdout off Write the formatted result to stdout instead of rewriting the file. Exit 0 . --diff off Write nothing. Print a unified diff of what would change. Exit 1 if anything would. --lines START:END off Format only statements overlapping these 1-based, inclusive lines; the rest of the file comes back byte-identical. Repeatable. A bare --lines 12 is that one line. Applies to a single file or - . --line-ending {auto,lf,crlf} auto Line endings to write. auto preserves each file's own \u2014 a CRLF file stays CRLF, and an already-formatted CRLF file does not report a spurious diff. --check , --stdout and --diff are mutually exclusive. Passing two is an argument error, not a silent precedence rule: sqlalign: error: argument --stdout: not allowed with argument --check A file with lone \\r (classic-Mac) line endings is not a shape sqlalign models; it is passed through untouched with a warning. Files, stdin and stdout are UTF-8 whatever the system locale, and stdout writes exactly the line endings chosen above (no \\r\\n added on Windows). A UTF-8 byte-order mark, as SSMS saves, is kept. A file that is not UTF-8 is reported and left unchanged. File selection # Flag Default What it does --exclude GLOB none Skip files matching this glob when expanding a directory . Repeatable. Matched against the path relative to the directory you named (posix separators, fnmatch semantics) and against the bare filename. Also settable as exclude in a config file. A file you name explicitly on the command line is never excluded \u2014 naming it is a clearer signal of intent than a pattern in a config file. Exclusions are resolved per directory argument, before per-file style resolution, from --exclude plus the exclude key of the config discovered at that directory. Configuration # sqlalign reads a .sqlalign.toml , or a [tool.sqlalign] table in a pyproject.toml , discovered by walking up from each file being formatted. Precedence is built-in defaults \u2192 preset \u2192 config file \u2192 command-line flags . Flag Default What it does --config PATH discovered Use this config file instead of discovering one. --isolated off Ignore any config file and use the built-in defaults. --show-config off Print the effective settings as TOML and exit 0 . Formats nothing. The first line is the config file they came from, or # built-in defaults (no config file found) . --no-strict-config off Warn on unknown config keys instead of failing. By default an unknown key is a hard error (exit 2 ) \u2014 a typo in a committed config would otherwise mean a team believes it has a setting it does not have. --dialect {postgres,redshift,tsql} postgres Dialect to parse and emit. CLI only \u2014 there is no dialect config key. --show-config resolves the config against the first path you give it, so in a repo with per-directory configs, ask about the directory you care about. Its output is valid TOML you can paste straight into a config file: sqlalign --show-config . # built-in defaults (no config file found) width = 100 align = true align_targets = [\"aliases\", \"case_results\", \"column_aliases\", \"column_constraints\", \"column_types\", \"join_conditions\", \"operators\", \"table_aliases\"] comma_position = \"leading\" boolean_operator_position = \"leading\" on_placement = \"inline\" select_placement = \"inline\" select_indent = 2 clause_keyword_align = \"left\" river_gutter = 6 format_dollar_bodies = true neq_style = \"!=\" decimal_style = \"NUMERIC\" table_alias_style = \"bare\" keyword_case = \"upper\" protect_templating = true # blank_lines_between_statements is unset: one blank line between two # multi-line statements, none otherwise. Set an integer to force a count. Valid config keys # Every key below is accepted in .sqlalign.toml or [tool.sqlalign] . Anything else is an error unless you pass --no-strict-config . align \u00b7 align_targets \u00b7 blank_lines_between_statements \u00b7 boolean_operator_position \u00b7 clause_keyword_align \u00b7 comma_position \u00b7 decimal_style \u00b7 dialect \u00b7 exclude \u00b7 format_dollar_bodies \u00b7 keyword_case \u00b7 neq_style \u00b7 on_placement \u00b7 preset \u00b7 protect_templating \u00b7 river_gutter \u00b7 select_indent \u00b7 select_placement \u00b7 table_alias_style \u00b7 width Formatting a selection # $ sqlalign --lines 40:58 models/orders.sql # just those lines $ sqlalign --lines 12 --lines 40:58 orders.sql # two selections $ sqlalign --diff --lines 40:58 orders.sql # review before writing The unit is the statement, not the line. Half a statement does not parse, so a range starting or ending inside one formats that statement entire \u2014 which is also what a dragged editor selection means. A range that covers only blank lines selects nothing and the file is left alone. Everything outside the range is byte-identical, including the blank lines around it. Asking for line 12 is not asking for the spacing at line 40 to be normalised. The use this exists for is adopting sqlalign on a repository nobody wants to reformat in one commit: format the lines your change touches, leave the rest, and the review stays about your change. For an editor filter that hands over just the selected text \u2014 a visual selection piped through :! in vim \u2014 use stdin instead: sqlalign - formats what it is given and needs no line numbers. --line-ending is the only setting with no config key. Three of the four --no-* flags map onto the positive keys: --no-align is align = false , --no-protect-templating is protect_templating = false , and --no-format-bodies is format_dollar_bodies = false . The fourth, --no-strict-config , is not a style setting at all \u2014 it changes how the config file itself is read. Style # Flag Default What it does --preset {compact,dbt,gitlab,house,river,trailing} none (the house defaults) Named starting point. Sets a base that config keys and flags then layer on top of, so --preset compact --comma-position trailing means both. Not passing it leaves any preset key in your config file in force. --width WIDTH 100 Target line width for wrapping decisions. Not a hard cap: a construct anchored deep in an indent gets a floor of anchor + 60 , plus 5 characters of grace, so alignment is never sacrificed to shave two columns. --blank-lines-between-statements N unset Force N blank lines between every pair of statements. Unset is the house rule: exactly one blank line between two multi-line statements and none otherwise, so a run of one-line GRANT s stays a block. 0 removes them all. --no-align off (aligned) Emit one space between tokens instead of padding them into columns. Same line structure, no padding \u2014 this is what 9 of 10 published SQL style guides call for. --align-targets a,b,\u2026 all but table_names Comma-separated alignment columns to keep. Anything left out collapses to a single space. See the table below. --comma-position {leading,trailing} leading (house) Where the separator comma sits in a stacked list \u2014 select items, GROUP BY / ORDER BY terms, INSERT columns, UPDATE SET assignments, CREATE TABLE columns, window terms. --boolean-operator-position {leading,trailing} leading (house) Where AND / OR sit when a predicate spans lines. The condition column is identical either way \u2014 only the operator moves. --on-placement {inline,own_line} inline (house) Whether a JOIN 's ON rides the table line or drops below it. own_line retires the FROM-block-wide ON column \u2014 there is no longer an ON after each alias to align \u2014 so join_conditions has nothing to act on. --keyword-case {upper,lower} upper (house) Case for keywords, function names and type names. Your identifiers and string literals are never touched. --neq-style {!=,<>} != Spelling for the not-equal operator. --decimal-style {NUMERIC,DECIMAL} NUMERIC Spelling for the NUMERIC / DECIMAL type. --no-protect-templating off (protected) Do not mask Jinja/dbt template expressions ( {{ \u2026 }} , {% \u2026 %} , {# \u2026 #} ) before formatting. With protection on, each expression becomes a same-width placeholder, so alignment is computed against the real text width. --no-format-bodies off (formatted) Leave dollar-quoted ( $$ ) procedure and function bodies untouched. On by default; off passes the whole CREATE FUNCTION / PROCEDURE through byte-identical. --neq-style and --decimal-style exist because sqlglot's parser collapses each of those pairs into a single AST node, so a spelling has to be chosen when printing. They are the only two places sqlalign picks for you. Presets # Preset Sets house nothing \u2014 the built-in columnar default: aligned, leading separators, ON inline, uppercase keywords compact align = false trailing comma_position = \"trailing\" , boolean_operator_position = \"trailing\" dbt keyword_case = \"lower\" , comma_position = \"trailing\" , align = false dbt ships with its one remaining deviation stated: dbt indents nested blocks 4, sqlalign indents a CTE body 2. Alignment targets # Target Aligns aliases AS x in a select list, and table aliases in FROM / JOIN operators = , != , < , LIKE , IS \u2026 in WHERE / ON / HAVING / CASE join_conditions the ON / AND column across a whole FROM block case_results THEN in a short-form CASE column_types column types in CREATE TABLE column_constraints NOT NULL / DEFAULT , and Redshift ENCODE column_aliases the alias column alone, inside a select list table_aliases the alias column alone, across a FROM / JOIN block table_names table names padded to a shared column \u2014 opt-in, not in the default set An unknown name is an error, not a silent no-op: sqlalign: unknown align_targets ['alias']; valid: ['aliases', 'case_results', 'column_aliases', 'column_constraints', 'column_types', 'join_conditions', 'operators', 'table_aliases', 'table_names'] --no-align is the shorthand for switching every target off. Exit codes # Code Meaning 0 Success, including --check / --diff finding nothing to change, and including statements that passed through untouched with a warning. 1 Something a gate should fail on: --check or --diff found a file that would change, --max-declines was exceeded, or --lint reported findings. 2 Unreadable file, invalid config file, invalid argument, or an unexpected engine error on one file. 141 The reader closed the pipe ( sqlalign - | head ). The shell's spelling of death-by-SIGPIPE; not an error. Per-file failures do not abort the run: the file is reported on stderr and skipped, the rest still process, and the worst code seen is returned. sqlalign --check nope.sql still.sql # sqlalign: [Errno 2] No such file or directory: 'nope.sql' # would reformat still.sql # exit 2 Worked invocations # Each block below is real output. The input for the style examples is tests/fixtures/input/13.sql ; the default rendering of it is in the README . Adopt the line structure without the padding # sqlalign --stdout --no-align 13.sql -- #13: multi-character aliases (mixed lengths) SELECT cust.customer_id , cust.email , ord.order_id , ord.total , line_items.product_id , line_items.quantity , addr.city FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.customer_id LEFT JOIN order_line_items line_items ON line_items.order_id = ord.order_id LEFT JOIN shipping_addresses addr ON addr.order_id = ord.order_id AND addr.address_type = 'shipping' WHERE ord.order_date >= '2026-07-01' AND cust.segment = 'enterprise'; Keep the alignment, move the separators to end of line # sqlalign --stdout --preset trailing 13.sql -- #13: multi-character aliases (mixed lengths) SELECT cust.customer_id, cust.email, ord.order_id, ord.total, line_items.product_id, line_items.quantity, addr.city FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.customer_id LEFT JOIN order_line_items line_items ON line_items.order_id = ord.order_id LEFT JOIN shipping_addresses addr ON addr.order_id = ord.order_id AND addr.address_type = 'shipping' WHERE ord.order_date >= '2026-07-01' AND cust.segment = 'enterprise'; Drop ON to its own line # Note what this costs: the ON conditions are now justified within each join instead of into one column spanning the whole FROM block. sqlalign --stdout --on-placement own_line 13.sql -- #13: multi-character aliases (mixed lengths) SELECT cust.customer_id , cust.email , ord.order_id , ord.total , line_items.product_id , line_items.quantity , addr.city FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.customer_id LEFT JOIN order_line_items line_items ON line_items.order_id = ord.order_id LEFT JOIN shipping_addresses addr ON addr.order_id = ord.order_id AND addr.address_type = 'shipping' WHERE ord.order_date >= '2026-07-01' AND cust.segment = 'enterprise'; Lowercase everything # sqlalign --stdout --keyword-case lower 13.sql -- #13: multi-character aliases (mixed lengths) select cust.customer_id , cust.email , ord.order_id , ord.total , line_items.product_id , line_items.quantity , addr.city from customers cust inner join orders ord on ord.customer_id = cust.customer_id left join order_line_items line_items on line_items.order_id = ord.order_id left join shipping_addresses addr on addr.order_id = ord.order_id and addr.address_type = 'shipping' where ord.order_date >= '2026-07-01' and cust.segment = 'enterprise'; Identifiers and string literals are untouched \u2014 the pass is AST-driven. Format a dbt model # --preset dbt is keyword_case = \"lower\" + trailing commas + no padding. Jinja survives because it is masked with same-width placeholders before parsing. sqlalign --stdout --preset dbt orders.sql select o.id, o.total, c.email from {{ ref('orders') }} o join {{ ref('customers') }} c on c.id = o.customer_id where o.status = 'complete'; Give a long window function room # --width moves the wrapping threshold. Same query, two widths: sqlalign --stdout wide.sql # default width 100 SELECT customer_id , SUM(total) OVER (PARTITION BY customer_id ORDER BY order_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total FROM orders; sqlalign --stdout --width 200 wide.sql SELECT customer_id , SUM(total) OVER (PARTITION BY customer_id ORDER BY order_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total FROM orders; Lowering --width below the default often changes nothing, because the anchor + 60 floor keeps a deeply-indented construct readable regardless. Space out a migration script # sqlalign --stdout --blank-lines-between-statements 1 multi.sql TRUNCATE TABLE staging_orders; TRUNCATE TABLE staging_customers; SELECT a , b FROM t WHERE a = 1 AND b = 2; SELECT c FROM u; With the flag unset, the two TRUNCATE s stay packed together and only the multi-line statements get air: TRUNCATE TABLE staging_orders; TRUNCATE TABLE staging_customers; SELECT a , b FROM t WHERE a = 1 AND b = 2; SELECT c FROM u; Gate a repository in CI # sqlalign --check --exclude 'vendor/*' --exclude '*.gen.sql' . would reformat models/marts/rollup.sql would reformat models/users.sql Exit 1 . Swap --check for --diff when you want the log to show the change rather than only the filename. ","headings":[{"id":"all-flags","text":"All flags"},{"id":"positional-arguments","text":"Positional arguments"},{"id":"output-mode","text":"Output mode"},{"id":"file-selection","text":"File selection"},{"id":"configuration","text":"Configuration"},{"id":"valid-config-keys","text":"Valid config keys"},{"id":"formatting-a-selection","text":"Formatting a selection"},{"id":"style","text":"Style"},{"id":"presets","text":"Presets"},{"id":"alignment-targets","text":"Alignment targets"},{"id":"exit-codes","text":"Exit codes"},{"id":"worked-invocations","text":"Worked invocations"},{"id":"adopt-the-line-structure-without-the-padding","text":"Adopt the line structure without the padding"},{"id":"keep-the-alignment-move-the-separators-to-end-of-line","text":"Keep the alignment, move the separators to end of line"},{"id":"drop-on-to-its-own-line","text":"Drop ON to its own line"},{"id":"lowercase-everything","text":"Lowercase everything"},{"id":"format-a-dbt-model","text":"Format a dbt model"},{"id":"give-a-long-window-function-room","text":"Give a long window function room"},{"id":"space-out-a-migration-script","text":"Space out a migration script"},{"id":"gate-a-repository-in-ci","text":"Gate a repository in CI"}]},{"slug":"dialects","title":"Dialects","text":" sqlalign parses and prints three dialects. Pick one with --dialect : sqlalign query.sql # postgres (the default) sqlalign --dialect redshift ddl.sql sqlalign --dialect tsql report.sql Dialect Flag Covers Postgres --dialect postgres (default) Postgres SQL, including $$ -quoted plpgsql function and procedure bodies Redshift --dialect redshift Redshift SQL: ENCODE , DISTSTYLE / DISTKEY / SORTKEY , LISTAGG \u2026 WITHIN GROUP , plpgsql stored procedures SQL Server --dialect tsql T-SQL: TOP , [bracketed] identifiers, @variables , AS BEGIN \u2026 END procedures, GO batches Three things to know before you read the per-dialect sections: The dialect can be declared in the config, or given as a flag. --dialect wins for a one-off run; dialect in .sqlalign.toml is what a repository commits. If a repository holds SQL for more than one engine, put a config beside each tree rather than running once per directory \u2014 see below. There is no dialect auto-detection. sqlalign will not sniff your file, and naming the wrong dialect is not covered by the safety guarantee \u2014 that guarantee is scoped to the dialect you asked for, and the layout handlers emit that dialect's keywords. Name the engine the file will run on. Declare it once, in the config. Guessing and declaring are different acts: # redshift-warehouse/.sqlalign.toml dialect = \"redshift\" The dialect is then resolved per file, from the config nearest it \u2014 so one command, one editor action or one pre-commit hook can span a Postgres repository and a Redshift one and be right in both, without anyone choosing correctly each time. --dialect still overrides it for a one-off run, and an unknown value is refused rather than attempted, exactly as the flag is. That is not sniffing. It is the author naming the engine in a file their team reviews, which is more explicit than a flag typed into an editor's tool settings and never looked at again. A dialect outside the three is refused, not attempted. The CLI rejects the argument outright: $ sqlalign --dialect mysql q.sql sqlalign: error: argument --dialect: invalid choice: 'mysql' (choose from postgres, redshift, tsql) and the Python API raises rather than producing output: ValueError: unsupported dialect 'snowflake'; sqlalign supports postgres, redshift, tsql The reason that refusal is loud, rather than a best-effort attempt, is the subject of the last section on this page. Postgres # The default, and the dialect the style was designed against. Twenty-four of the twenty-nine golden fixtures are Postgres: selects, joins, WHERE with AND / OR / IN / BETWEEN / LIKE , aggregates, CTEs, subqueries, CASE , window functions, set operations, INSERT / UPDATE / DELETE / MERGE , nested expressions and comments, CREATE TABLE , CTAS, views and materialized views, CREATE FUNCTION and CREATE PROCEDURE , TRUNCATE , CREATE INDEX , GRANT and REVOKE . $ sqlalign --stdout query.sql SELECT cust.customer_id , cust.email , ord.order_id , ord.total , line_items.product_id , line_items.quantity , addr.city FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.customer_id LEFT JOIN order_line_items line_items ON line_items.order_id = ord.order_id LEFT JOIN shipping_addresses addr ON addr.order_id = ord.order_id AND addr.address_type = 'shipping' WHERE ord.order_date >= '2026-07-01' AND cust.segment = 'enterprise'; Both cast forms survive as written, at every nesting depth \u2014 sqlalign will not unify them for you: $ sqlalign --stdout casts.sql SELECT x::NUMERIC AS v , CAST(y AS DATE) AS d FROM t; Redshift behaves identically here. T-SQL does not, because it has no :: operator at all \u2014 see below. Dollar-quoted bodies # A $$ \u2026 $$ plpgsql body is parsed and formatted with the same engine as top-level SQL, not treated as an opaque string: $ sqlalign --stdout function.sql CREATE OR REPLACE FUNCTION get_customer_ltv(p_customer_id INT) RETURNS NUMERIC LANGUAGE plpgsql AS $$ DECLARE v_ltv NUMERIC; BEGIN SELECT SUM(total) INTO v_ltv FROM orders WHERE customer_id = p_customer_id AND status = 'complete'; IF v_ltv IS NULL THEN v_ltv := 0; END IF; RETURN v_ltv; END; $$; --no-format-bodies leaves every $$ body byte-identical if you would rather it did not. Unmodelled plpgsql constructs \u2014 cursors, FOR loops, EXCEPTION blocks \u2014 pass through per statement inside the body, so the rest of the procedure still formats. LANGUAGE sql bodies format too. They are a bare statement list rather than a DECLARE/BEGIN/END block, so they get their own branch \u2014 but each statement goes through the same renderer a plpgsql body's statements do, so the two cannot drift apart. A body in a language that is not SQL at all ( plpythonu , plperl ) is declined at the header. What Postgres declines # Anything without a layout handler passes through byte-identical with a warning. PIVOT is a current example: $ sqlalign --stdout declines.sql sqlalign: declines.sql: unsupported construct (PIVOT: this dialect has no such syntax), passed through: select * from t pivot (sum(x) for y in ( select * from t pivot (sum(x) for y in (1, 2)) p; INSERT INTO staging VALUES (1, 2); INSERT INTO staging ( a) SELECT a FROM source; PIVOT / UNPIVOT declines under Postgres only , and not because it is hard: Postgres has no such syntax. sqlglot's Postgres generator drops the clause silently \u2014 SELECT * FROM t PIVOT(...) comes back as SELECT * FROM t , the whole thing gone \u2014 so declining is the only safe answer, and the re-parse guard is what noticed. Under --dialect redshift and --dialect tsql , which do have it, PIVOT formats: SELECT * FROM (SELECT a , b , c FROM src ) s PIVOT(AVG(c) FOR b IN (1, 2)) AS p; The check renders the node and looks at what comes out, rather than consulting a list of dialects \u2014 so if sqlglot ever grows Postgres support, this stops declining on its own. Run sqlalign --report --check over your own SQL rather than trusting this list \u2014 it counts what actually declined, ranked, so you can see whether any of it matters to you. --check is what keeps it a survey: --report adds output without changing the mode, so on its own it would rewrite the files it counted. The legacy comma join \u2014 FROM a, b \u2014 formats, and is worth a note because it was once declined. It parses as a join with no condition, exactly like CROSS JOIN does, and rebuilding it through the join keyword would emit FROM a JOIN b , which Postgres rejects: a bare JOIN requires a condition. The re-parse check cannot catch that either, because sqlglot reads its own lenient output back without complaint. The option that was missed is the obvious one \u2014 emit the comma, which is both valid and what the author wrote: SELECT 1 FROM a x , b y WHERE x.id = y.id; Redshift # Use --dialect redshift for Redshift DDL in particular \u2014 the column encodings and table attributes get their own aligned columns and clause lines: $ sqlalign --stdout --dialect redshift fact_orders.sql CREATE TABLE fact_orders ( order_id BIGINT NOT NULL , customer_id BIGINT NOT NULL ENCODE az64 , order_date DATE NOT NULL ENCODE az64 , total NUMERIC(12, 2) ENCODE az64 , channel VARCHAR(32) ENCODE lzo ) DISTSTYLE KEY DISTKEY (customer_id) COMPOUND SORTKEY (order_date, customer_id); Two details worth noting in that output. The ENCODE keyword is uppercased but its value is passed through as written \u2014 az64 stays az64 , and AZ64 would stay AZ64 . And the constraint alignment is per kind: the NOT NULL column pads over only the lines that carry NOT NULL , and the ENCODE column pads over only the lines that carry ENCODE , so a row with no nullability constraint does not drag the encoding column right. One type spelling changes under Redshift that does not under Postgres: int renders as INTEGER , because sqlglot's Redshift generator prints the long form. The two are the same type. DECIMAL renders as NUMERIC here as it does under Postgres, and --decimal-style DECIMAL brings it back. LISTAGG(\u2026) WITHIN GROUP (ORDER BY \u2026) formats, with a space before the keyword's paren, the same family as OVER ( : $ sqlalign --stdout --dialect redshift listagg.sql SELECT customer_id , LISTAGG(channel, ',') WITHIN GROUP (ORDER BY channel) AS channels FROM orders GROUP BY customer_id; Redshift stored procedures use the same $$ body machinery as Postgres: $ sqlalign --stdout --dialect redshift proc.sql CREATE OR REPLACE PROCEDURE refresh_totals() LANGUAGE plpgsql AS $$ DECLARE v_rows INT; BEGIN DELETE FROM daily_totals WHERE report_date = CURRENT_DATE; INSERT INTO daily_totals SELECT order_date , SUM(total) FROM orders WHERE order_date = CURRENT_DATE GROUP BY order_date; END; $$; TEXT declines, and why # Redshift TEXT is an alias for VARCHAR(256) . sqlglot renders it as VARCHAR(MAX) , which is VARCHAR(65535) \u2014 a different column width. That is a change to your schema, not to its presentation, so the safety net rejects it and the statement is passed through untouched: $ sqlalign --stdout --dialect redshift table.sql sqlalign: table.sql: sqlglot cannot round-trip this statement, passed through unformatted: create table t (a text not null, b int); create table t (a text not null, b int); This one is caught rather than declined on sight because TEXT and VARCHAR(MAX) parse to different AST nodes \u2014 the rewrite is visible to the comparison, so the general guarantee handles it. (Contrast the T-SQL type collapses below, which are not visible and need a separate guard.) CAST(x AS TEXT) declines the same way. If you want those statements formatted, write the width you mean: VARCHAR(256) . Other Redshift declines # Construct What happens UNLOAD ('\u2026') TO 's3://\u2026' unsupported construct, passed through Python/Perl UDFs ( LANGUAGE plpythonu ) unsupported construct, passed through \u2014 the body is not SQL TEXT in a type position formatting would change semantics, passed through unformatted SQL Server (T-SQL) # --dialect tsql covers ordinary queries and DDL, plus three T-SQL specifics: TOP with bracketed identifiers, AS BEGIN \u2026 END procedures, and GO batches. It is the newest and narrowest of the three \u2014 the declines below are longer than the other dialects' for that reason. TOP and bracketed identifiers # TOP n rides the SELECT line; continuation commas keep their usual column, and [bracketed] identifiers are preserved verbatim like every other identifier: $ sqlalign --stdout --dialect tsql orders.sql SELECT TOP 10 [Order Id] , cust.[Full Name] , ord.total FROM [Sales Orders] ord INNER JOIN customers cust ON cust.id = ord.customer_id WHERE ord.status = 'complete' AND ord.total > 100 ORDER BY ord.total DESC; The statement splitter understands brackets, so a semicolon inside one ( [my;col] ) does not cut the statement in half, and ]] escapes a literal bracket. TOP is worth calling out because it is where the T-SQL support began. sqlglot parses TOP n into the same Limit node Postgres uses, so a dialect-agnostic layout handler emitted LIMIT n \u2014 valid SQL to sqlglot, rejected by SQL Server. See Adding a dialect below. CREATE TABLE # $ sqlalign --stdout --dialect tsql daily_revenue.sql CREATE TABLE daily_revenue ( report_id INTEGER NOT NULL , report_date DATE NOT NULL , channel NVARCHAR(50) NOT NULL , revenue NUMERIC(12, 2) , PRIMARY KEY (report_id) ); Two spelling changes in that output are worth knowing about, because both are sqlglot parse-time collapses that sqlalign cannot undo: You wrote You get Why it is safe int INTEGER INT and INTEGER are the same type decimal(12,2) NUMERIC(12, 2) SQL Server treats decimal and numeric as synonyms Under --dialect tsql , --decimal-style DECIMAL does not bring DECIMAL back \u2014 the T-SQL generator has already printed NUMERIC before the knob is consulted. --neq-style does work under T-SQL. If preserving the DECIMAL spelling matters to you, put those statements behind -- sqlalign: skip . BEGIN / END procedures # A procedure body is ordinary T-SQL \u2014 there is no dollar quoting \u2014 so it goes through the main engine. Statements sit at column 1 inside the block, separated by blank lines: $ sqlalign --stdout --dialect tsql refresh_daily.sql CREATE PROCEDURE refresh_daily @target DATE AS BEGIN DELETE FROM daily_revenue WHERE report_date = @target; INSERT INTO daily_revenue ( report_date , channel , revenue) SELECT order_date , channel , SUM(total) FROM orders WHERE order_date = @target GROUP BY order_date , channel; END; The splitter keeps the whole routine as one statement rather than cutting at the semicolons inside it. It does that with a small stack that records what opened each block, so a CASE \u2026 END inside the body does not look like the end of the procedure, and BEGIN TRANSACTION \u2014 which never gets a matching END \u2014 does not open one. sqlalign closes the block with END; whichever way the source spells it \u2014 with or without a terminating semicolon: $ sqlalign --stdout --dialect tsql proc.sql CREATE PROCEDURE refresh_daily @target DATE AS BEGIN DELETE FROM daily_revenue WHERE report_date = @target; END; A source that wrote END; used to decline here, which this guide described as a sharp edge. It was a bug, not an edge: the layout owns that semicolon, and the statement emitter appended the source's own on top of it, producing END;; \u2014 which re-parses differently, so the safety net stopped it. Fixed. GO batches # GO is a client directive, not SQL. sqlglot cannot parse it, and worse, it swallows the following statement into the GO as a string literal. sqlalign splits the file at GO lines before anything is parsed, formats each batch independently, and passes the GO line through verbatim: $ sqlalign --stdout --dialect tsql batches.sql TRUNCATE TABLE staging; GO INSERT INTO staging ( a , b) SELECT a , b FROM source WHERE a IS NOT NULL; GO The safety check is batch-aware too: it compares each batch's AST separately and compares the separators themselves, so a dropped or added GO is still caught. GO 5 (with a repeat count) is recognised. A GO line inside a string literal or a block comment (an SQL Agent job step, dynamic SQL) is part of that literal, not a separator. A CREATE PROCEDURE , FUNCTION or TRIGGER runs to the end of its batch, as SQL Server reads it: everything up to the next GO is the routine, whatever ; , END or END TRY comes first. REAL and NTEXT decline on sight # These two are the reason T-SQL needs a guard the other dialects do not. $ sqlalign --stdout --dialect tsql types.sql sqlalign: types.sql: unsupported construct (tsql: type whose spelling sqlglot cannot preserve), passed through: create table t (a real not null, b int); sqlalign: types.sql: unsupported construct (tsql: type whose spelling sqlglot cannot preserve), passed through: select cast(x as ntext) from t; create table t (a real not null, b int); select cast(x as ntext) from t; sqlglot collapses REAL / FLOAT to one node, and NTEXT / TEXT to one node, at parse time . In T-SQL those pairs are not synonyms: Pair Difference REAL vs FLOAT REAL is FLOAT(24) , FLOAT is FLOAT(53) \u2014 rewriting one widens precision NTEXT vs TEXT NTEXT is Unicode, TEXT is not The AST safety net is useless here, and not because it is weak: the distinction is destroyed before the AST exists , so both sides of the comparison collapse the same way and ast_equal returns True on a rewrite that changed your schema. The only defence left is the raw source, so a statement whose text contains REAL or NTEXT under --dialect tsql is declined by a regex over the input before any layout runs. INT / INTEGER , DECIMAL / NUMERIC and TIMESTAMP / ROWVERSION also collapse, but those are synonyms, so canonicalising them is harmless and they still format. Other T-SQL declines # Construct Example IF / WHILE inside a procedure body sqlglot does not parse it \u2014 part of the body comes back as raw text, and an IF \u2026 ELSE is indistinguishable from an IF without one, so laying out the tree would drop the ELSE TRY / CATCH blocks create procedure q as begin begin try \u2026 end try begin catch \u2026 end catch end REAL , NTEXT in a type position see above All of these pass through byte-identical with a warning and exit code 0 . Procedure bodies containing only DML and SELECT format; a body containing control flow declines as a whole. Adding a dialect is more than registering a parser # SUPPORTED_DIALECTS is a whitelist of three, and it is not the list of dialects sqlglot can parse \u2014 sqlglot parses many more. It is the list whose emitted keywords have been audited against a real engine. The distinction is not theoretical. It shipped once. The chain: sqlglot parses T-SQL SELECT TOP 10 id FROM users into the same Limit node it uses for Postgres LIMIT 10 . The layout handler emitted its hard-coded LIMIT keyword. Handlers are dialect-agnostic, which is true for Postgres and Redshift \u2014 they share the syntax \u2014 and false for SQL Server. sqlglot then parsed that LIMIT back as T-SQL , because its grammar accepts it, so ast_equal compared the two trees equal and reported nothing. Valid SQL in, SQL Server rejects the output, no warning. Two of the twenty-six keywords the handlers emit diverge for T-SQL ( LIMIT and OFFSET ); finding that out required going through them. The lesson generalises, and it is the one real limit on sqlalign's guarantee: the AST safety net cannot detect dialect-invalid output. The round trip never leaves sqlglot's permissive grammar, so a keyword that is valid to sqlglot and invalid to your engine is invisible to the comparison. \"sqlalign cannot change what your SQL means\" holds within a verified dialect. That is why format_sql raises for an unlisted dialect instead of doing its best. A passthrough would be the wrong response \u2014 an unsupported dialect is a caller error, not an unmodelled statement, so it fails where you can see it rather than silently mid-file. If you want a fourth dialect, the work is: audit every keyword the layout handlers emit against that engine's grammar, hunt for parse-time collapses whose two spellings are not synonyms (the REAL / NTEXT class), and add byte-exact golden fixtures pinning the result. Registering the parser is the easy part. See also # Configuration \u2014 the config keys, and why dialect is not one Command-line reference \u2014 every flag and the exit codes Architecture \u2014 the safety model and the decline contract in full FAQ \u2014 why a statement did not get formatted, and what to do about it ","headings":[{"id":"postgres","text":"Postgres"},{"id":"dollar-quoted-bodies","text":"Dollar-quoted bodies"},{"id":"what-postgres-declines","text":"What Postgres declines"},{"id":"redshift","text":"Redshift"},{"id":"text-declines-and-why","text":"TEXT declines, and why"},{"id":"other-redshift-declines","text":"Other Redshift declines"},{"id":"sql-server-t-sql","text":"SQL Server (T-SQL)"},{"id":"top-and-bracketed-identifiers","text":"TOP and bracketed identifiers"},{"id":"create-table","text":"CREATE TABLE"},{"id":"begin-end-procedures","text":"BEGIN/END procedures"},{"id":"go-batches","text":"GO batches"},{"id":"real-and-ntext-decline-on-sight","text":"REAL and NTEXT decline on sight"},{"id":"other-t-sql-declines","text":"Other T-SQL declines"},{"id":"adding-a-dialect-is-more-than-registering-a-parser","text":"Adding a dialect is more than registering a parser"},{"id":"see-also","text":"See also"}]},{"slug":"architecture","title":"Architecture","text":" Read this page to understand why sqlalign's output looks the way it does, where to add support for a construct it declines, and \u2014 precisely \u2014 how far its semantic guarantee reaches and where it stops. Two ideas explain almost everything else on this page: Layout and alignment are separate passes. Handlers decide what goes on which line without knowing any final column; a second, deterministic pass resolves the columns and pads. That is why alignment composes with line wrapping instead of fighting it. Declining is a first-class result. Anything the engine cannot reproduce exactly \u2014 an unmodelled construct, a render that would change meaning, an outright bug \u2014 degrades to a byte-identical passthrough with a warning. The file is never mangled. The pipeline # A file goes through this. The masking and the splitting happen once; everything between them happens once per statement: source text \u2502 \u251c\u2500 mask Jinja/dbt expressions templating.py (same-width placeholders) \u251c\u2500 split into statements splitter.py (lossless; parts rejoin byte-for-byte) \u2502 \u2514\u2500 for each statement: \u251c\u2500 parse sqlglot.parse (postgres | redshift | tsql) \u251c\u2500 recover comments layout/comments.py \u251c\u2500 lay out to a Line/Seg IR layout/*.py (line breaks + indents fixed here) \u251c\u2500 move separator commas commas.py (IR transform) \u251c\u2500 drop disabled align targets align.py \u251c\u2500 resolve columns and render align.py (fixpoint, then pad) \u251c\u2500 apply keyword case keywordcase.py (AST-driven, only when `lower`) \u2514\u2500 re-parse and AST-compare formatter.ast_equal \u2502 \u251c\u2500 equal \u2192 keep the formatted text \u2514\u2500 differs \u2192 keep the ORIGINAL bytes + warn \u2502 \u251c\u2500 rejoin statements formatter._join_statements \u251c\u2500 restore the template expressions templating.py \u2514\u2500 restore line endings, write cli.py The safety check compares the masked input against the masked output, not the raw text \u2014 raw templated SQL does not parse, so there would be nothing to compare. Because the mask is a bijection over the same character positions, equality of the masked forms is equality of the originals. The modules: Module Responsibility cli.py argparse, file/directory expansion and excludes, line endings, writing, exit codes configfile.py .sqlalign.toml / [tool.sqlalign] discovery, precedence, strict unknown-key checking style.py the Style dataclass (every knob), presets, ALIGN_TARGETS , SUPPORTED_DIALECTS config.py Width \u2014 the width / grace / floor triple and the effective break limit splitter.py cuts a file into statements; string-, comment-, dollar-quote- and GO -aware formatter.py orchestration, the AST safety check, the decline handling, inter-statement blank lines templating.py masks {{ }} / {% %} / {# #} with same-width placeholders plpgsql.py dollar-quoted body scanning, body statement splitting, plpgsql skeleton layout layout/ one module per node family (select, fromjoin, conditions, case, window, cte, subquery, setop, dml, ddl, expr, grouporder) plus the comment engine ir.py Seg , Line , and the set of right-aligned kinds commas.py comma position, applied to the IR align.py align-target filtering, the fixpoint column resolver, and render casing.py render_expr and the ambient render style ( neq_style , decimal_style ) keywordcase.py the lower keyword pass, driven by the parse tree rather than a word list Layout and alignment are two passes # The IR is deliberately small. A Line has an indent and a list of Seg s; a Seg is text plus an optional (scope, kind) tag: @dataclass class Seg: text: str scope: str | None = None kind: str | None = None # item|op|alias|on|as|type|constraint|then A layout handler emits lines and tags. It never counts spaces and never asks where a column will land. align.py owns all column math. That split is what makes the columnar style tractable. Consider what a handler would otherwise have to know: FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.customer_id LEFT JOIN order_line_items line_items ON line_items.order_id = ord.order_id LEFT JOIN shipping_addresses addr ON addr.order_id = ord.order_id AND addr.address_type = 'shipping' The alias column is set by the longest table reference ( LEFT JOIN shipping_addresses , row 4). The ON column is set by the longest alias ( line_items , row 3) \u2014 a different row. The operator column is set by row 3 again, but only after every ON has been pushed right. Three columns, three different driving rows, and each depends on the resolution of the one before it. No handler emitting row 1 could know any of that. Alignment composes with wrapping because it runs second # Line breaking happens in the layout pass, against the width limit, before any padding exists. Alignment then pads whatever lines came out. So a wrapped item still participates in its column: SELECT customer_id , order_id , order_date , total , ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS rn , SUM(total) OVER (PARTITION BY customer_id ORDER BY order_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total , LAG(order_date) OVER (PARTITION BY customer_id ORDER BY order_date) AS prev_order_date FROM orders; The second window function wrapped inside its OVER (...) . Its AS still lands in the same column as the two unwrapped siblings, because the AS column is resolved over the rendered lines , and the last line of a wrapped item is just another line. The ordering is one-way on purpose: breaking runs before alignment, and alignment is never sacrificed to fit the width limit. Padding that pushes a line past the limit is accepted rather than fed back into the breaker. Feeding it back is what makes an aligning formatter oscillate \u2014 pad, overflow, break, un-pad, fit, pad again. The width limit itself is a soft target, computed per construct: def limit(self, anchor: int) -> int: return max(self.width, anchor + self.floor) + self.grace with width=100 , grace=5 , floor=60 by default. A construct anchored deep in a subquery still gets 60 columns of working room, and nothing breaks over five columns of overshoot. The second pass is genuinely separable # Because padding is the only thing the alignment pass adds, switching it off leaves the line structure untouched. Same input, --no-align : SELECT cust.customer_id , cust.email , ord.order_id , ord.total , line_items.product_id , line_items.quantity , addr.city FROM customers cust INNER JOIN orders ord ON ord.customer_id = cust.customer_id LEFT JOIN order_line_items line_items ON line_items.order_id = ord.order_id LEFT JOIN shipping_addresses addr ON addr.order_id = ord.order_id AND addr.address_type = 'shipping' WHERE ord.order_date >= '2026-07-01' AND cust.segment = 'enterprise'; Every line break is where it was. render(lines, align=False) skips column resolution entirely and joins segments with one space; the continuation AND falls back to its layout indent because there is no longer an ON column to justify against. --align-targets is the same mechanism at finer grain: a disabled target has its scope and kind cleared, so the resolver simply never sees it and that one column collapses to single spaces. There is no separate unaligned code path that could drift from the aligned one. The same reasoning drives --comma-position . Moving a separator comma is an IR transform \u2014 each comma is its own tagged segment \u2014 not a rewrite over printed text. A text pass cannot reliably tell a separator comma from the comma in NUMERIC(10, 2) , and it cannot know which physical line ends a multi-line item. Doing it on the IR also means alignment resolves against the final segment text rather than against text that is about to move. The fixpoint resolver # Column resolution is not a single left-to-right sweep. It cannot be: a tagged segment's position depends on the resolved targets of the tagged segments to its left on the same line, and those targets may be driven by a different row. _resolve_targets iterates instead. Each sweep replays the emit pass using the previous sweep's targets \u2014 when the running column reaches a tagged segment it is placed at max(natural_position, target_so_far) and the cursor advances past the placed position, not the natural one. Targets only ever increase, and they are bounded by total line length, so the iteration terminates; it stops as soon as a full sweep changes nothing. Two properties are worth knowing if you are reading align.py : The first sweep is the naive resolver. It starts from all-zero targets, so every max(natural, 0) is just natural . Any scope with at most one tagged column per line fixes in one sweep, at exactly the columns a single-pass resolver would produce. Later sweeps can only raise a column. They cannot lower one or move it sideways, so the iteration can correct an under-computed column but cannot invent a different layout. Right-aligned kinds ( op , on ) are resolved by their end column; everything else by its start. That is what puts = and >= in one column with their operands ragged on the left: WHERE ord.order_date >= '2026-07-01' AND cust.segment = 'enterprise'; The safety model # After a statement is rendered, sqlalign parses the output again and compares its AST to the input's. If they differ, the original bytes are kept and a warning goes to stderr. This is per statement: one statement declining does not stop the rest of the file from formatting. The comparison is not raw == on trees. _normalize first walks both sides and neutralises differences that cannot carry meaning: Normalisation Why comments = None on every node comments are not in the tree to begin with; they are compared separately, see comments_equal LANGUAGE plpgsql vs LANGUAGE 'plpgsql' optional legacy quoting; parses to Var vs Literal casefold WindowSpec.kind / start_side / end_side , TruncateTable.identity / option plain strings holding source-cased keywords casefold DistStyleProperty 's Var a closed keyword set ( KEY / EVEN / ALL / AUTO ), not user data casefold Command text outside quotes half-parsed raw source; quoted identifiers and string literals keep their case The exclusions are as deliberate as the inclusions. A bare exp.Var is not casefolded globally, because SET search_path = \"MySchema\" parses to Var(this=\"MySchema\") with the quotes already stripped \u2014 folding all Var.this would make a real, meaning-changing case edit invisible. Two constructs get a structural comparison instead of a whole-text one: Dollar-quoted bodies. sqlglot sees $$ \u2026 $$ as one opaque string, so a raw AST comparison would reject any body reformatting. Header and tail are compared as an AST (an empty-body CREATE that parses); the body is split into clauses; each embedded SQL statement is compared as an AST; skeleton statements ( DECLARE , BEGIN , IF \u2026 THEN ) are compared whitespace- and case-insensitively. T-SQL GO batches. GO is a client directive, not SQL, and sqlglot swallows the statement after it into a string literal \u2014 so a whole-file parse compares nonsense. The file is split at GO lines, each batch compared separately, and the separators themselves compared so a dropped or added GO is still caught. What the guarantee does not cover # Three limits. All three are real, and none of them can be closed by a better AST comparison. 1. It is a within-dialect guarantee. SUPPORTED_DIALECTS is a whitelist of postgres , redshift and tsql , and it is not a list of dialects sqlglot can parse \u2014 sqlglot parses many more. It is the list whose emitted keywords have been audited. The failure mode this guards against actually shipped once: sqlglot parses T-SQL SELECT TOP 10 into the same Limit node Postgres uses; a dialect-agnostic handler emitted its hard-coded LIMIT ; sqlglot then parsed that LIMIT back as T-SQL too, so ast_equal compared equal and the statement went out as SELECT id \u2026 LIMIT 10 , which SQL Server rejects outright. Valid SQL in, broken SQL out, no warning. The AST net cannot see this, because the round trip never leaves sqlglot's more permissive grammar. format_sql therefore raises a ValueError for any dialect outside the whitelist rather than producing output, and extending the list means auditing every keyword the handlers emit \u2014 two of them diverge for T-SQL \u2014 not just registering a parser. 2. ast_equal cannot see comments, so a second check does. sqlglot hangs a comment off the token it precedes rather than putting it in the tree, which means ast_equal(\"SELECT a -- keep me\", \"SELECT a\") is True: a statement and the same statement with its comment deleted compare equal. Until 1.1 the byte-exact goldens were the only guard on that, and they only cover SQL somebody thought to write down. Two of the worst bugs in the project's history lived in the gap and were semantic, not cosmetic: SELECT a -- c, lost a separator, and SELECT a -- note; left the statement unterminated so it swallowed the next one. Both were found by the preset matrix, which is luck rather than a guarantee. comments_equal now compares the comments each statement carries, by text and in order, and a statement whose comments would differ is passed through like any other. Position is deliberately not compared: the layout MOVES a comment to the end of the row above, so where it sits is expected to change and what it says is not. A $$ body is one string literal to the tokenizer, so comments inside one remain outside this check; those statements are compared structurally instead. None of which replaces layout/comments.py recovering each comment's original style and text from the raw source and re-attaching it by authorial position, or its raising Unsupported for any position it does not model. \"Reproduce faithfully or decline\" is still the contract; the check is what makes it enforceable rather than aspirational. 3. Some distinctions are destroyed before the comparison exists. When sqlglot's parser collapses two spellings into one node, both sides of the comparison collapse identically and the difference is invisible. Where the two spellings are true synonyms this is harmless, and sqlalign simply picks one: != / <> and NUMERIC / DECIMAL are the only two places it chooses for you, and both are configurable. Where they are not synonyms, the AST is useless and the only defence is the raw source: T-SQL REAL (FLOAT(24)) and FLOAT (FLOAT(53)) collapse to one node, as do NTEXT (Unicode) and TEXT , so a statement containing REAL or NTEXT under --dialect tsql is declined on sight by a regex over the input text. Where the collapse is visible, the net does its job. Redshift TEXT renders as VARCHAR(MAX) through sqlglot, which widens the column from 256 to 65535 \u2014 but those parse to different nodes, so: $ sqlalign --stdout --dialect redshift table.sql sqlalign: table.sql: sqlglot cannot round-trip this statement, passed through unformatted: create table t (a text not null, b int); create table t (a text not null, b int); The decline contract # Everything above funnels into one behaviour: when in doubt, emit the input bytes and say so. formatter._format_all wraps layout, render and the safety check per statement, and every failure class degrades to the same passthrough with a differently worded warning, so an expected decline is distinguishable from a bug in stderr: Condition Warning sqlglot cannot parse the statement passthrough (parse error line N): \u2026 a layout handler raised Unsupported unsupported construct, passed through: \u2026 the render would respell the statement, and casing it from source is not possible either formatting would respell this statement, passed through unformatted: \u2026 \u2014 the first half is usually recoverable (see below); this is what is left the output would not AST-compare equal formatting would change semantics, passed through unformatted: \u2026 \u2014 a bug report , not a decline: the renderer emitted something that means a different thing \u2026and sqlglot cannot round-trip the input either sqlglot cannot round-trip this statement, passed through unformatted: \u2026 \u2014 the fault is upstream, so no formatter built on sqlglot could satisfy the check any other exception internal formatter error, passed through (please report): \u2026 A respelling is usually recovered rather than declined. sqlglot's parser collapses some pairs of spellings onto one node \u2014 ALTER COLUMN x TYPE t and SET DATA TYPE t are the same tree \u2014 so rendering from the node prints whichever the generator prefers. When the token census catches that, the statement is cased from its own source instead ( sourcecase.py ): the source text with keyword spans recased and every other byte untouched. Nothing is rebuilt, so nothing can be respelt, and the same three checks are re-run against the result. Keywords are told from identifiers by the parse tree, not by the keyword table. What the author wrote as a name or value is a node; the grammar around it lives in the generator and is on no node. A statement sqlglot could only parse as exp.Command has no such tree and still passes through. The construct in an unsupported construct (\u2026) warning is the node type the layout engine declined to model. One node type needs translating: exp.Command is sqlglot's catch-all for syntax its parser does not model at all, so it is the same word for every unrelated statement that lands there. It is reported under the keyword sqlglot kept on the node instead \u2014 unsupported construct (SET) rather than unsupported construct (Command) . sqlglot logs its own fallback for those statements ( 'SET ROLE reporting' contains unsupported syntax. Falling back to parsing as a 'Command'. ). The CLI raises that logger to ERROR , because sqlalign reports the same statement by name and with the text it passed through \u2014 the warning is a second, less informative copy on the same stream. The library does not touch the logger: sqlalign.format runs inside someone else's program, where silencing a dependency is not a formatter's business. One decline is file-wide rather than per statement: a template expression too short to hold a same-width placeholder ( {{x}} ) fails before splitting, so the whole file passes through with templating not maskable, passed through: \u2026 . It has to be \u2014 masking runs over the file, not over one statement. Otherwise declining is per statement, not per file: $ sqlalign --stdout mixed.sql sqlalign: mixed.sql: unsupported construct (CTE column list), passed through: -- a decline next to a formatted stateme -- a decline next to a formatted statement with c(a, b) as (select 1, 2) select a from c; SELECT x , y FROM z WHERE a = 1 AND bb = 2; Exit code 0 . A construct sqlalign does not model is not an error \u2014 the file is still correct SQL, byte-for-byte where it was not understood and formatted everywhere else. Why this is the product, not a limitation # A formatter that reformats what it half-understands is worse than one that declines, because you cannot tell the two apart by reading the diff. Every declined statement is visibly unchanged and audibly reported, so the coverage gap is legible; a wrong render is not. The contract is enforced structurally rather than by discipline. layout_statement raises Unsupported for any node type it does not dispatch, so a new construct declines by default until someone writes its handler. Within a handler, guard_args declines a node carrying any argument the handler does not read: for name, value in node.args.items(): if value not in (None, [], False) and name not in allowed: raise Unsupported(f\"{label or type(node).__name__} arg: {name}\") Without that, an INSERT \u2026 ON CONFLICT or an unread CREATE TABLE option would be silently dropped from the output \u2014 a change the AST comparison would catch, but only after the handler had already produced wrong text. Declining at the arg level makes it a passthrough instead of a near miss. The same rule governs the edges of the pipeline. The splitter is lossless \u2014 its parts concatenate back to the input byte for byte \u2014 specifically so a declined statement can be emitted from its part verbatim. Template masking uses same-width placeholders and declines an expression too short to hold one ( {{x}} ), rather than approximating a width and shifting every column in the file. A file with lone CR line endings, which sqlalign does not model, passes through untouched with a warning instead of being silently rewritten. Two escape hatches exist for SQL that parses fine but that you want left alone: -- sqlalign: skip on the line above a statement passes exactly that statement through, with no parse, no layout and deliberately no warning; --no-format-bodies does the same for every dollar-quoted procedure body. $ sqlalign --stdout skip.sql -- sqlalign: skip select a,b from t where x=1; SELECT a , b FROM t WHERE x = 1; Testing # The design spec describes the style; the fixtures are what the suite actually enforces. Treat them as the executable specification \u2014 grow them, never weaken them. 29 byte-exact golden pairs live in tests/fixtures/input/NN.sql and tests/fixtures/expected/NN.sql , generated from the 29 hand-formatted samples in samples/queries.sql (24 postgres, one redshift, four T-SQL). Every pair is asserted three ways: Assertion What it catches format(input) == expected , byte for byte any layout regression at all format(expected) == expected a rule that keeps nudging a line every pass \u2014 invisible to a one-pass test input and output parse to equal ASTs the runtime safety net's own check, run over the corpus A sqlfluff gate lints every standard-SQL Postgres expected fixture against the repo's .sqlfluff , with three rules excluded and each exclusion documented in that file (the house style preserves GROUP BY reference form, does not force aliases, and keeps :: vs CAST(...) as written). The Redshift, T-SQL and plpgsql fixtures sit outside the gate \u2014 dialect and linter-model limits, each noted in tests/test_sqlfluff_gate.py . Goldens pin the default style. They cannot pin the knobs: enumerating knob combinations byte-for-byte would need one fixture per combination, which is how \"just add more options\" rots a formatter. tests/test_knob_combinations.py asserts invariants across combinations instead, drawn from a fixed seed so a failure reproduces. For every sample and every sampled combination: semantics never change ( ast_equal(input, output) ), the output is idempotent, the output re-parses, no line has trailing whitespace, the token stream is identical to the house rendering \u2014 layout knobs move tokens, they never add, drop, or reorder them. Two of those tests guard the test, which is worth copying: one asserts the sampled combinations actually produce different output (a property suite that exercises one behaviour ten times proves nothing), and one asserts invariant 5 fails when tokens are dropped or reordered (an invariant that cannot fail is indistinguishable from one that passes). A third pins that the defaults still reproduce every golden, so adding a knob cannot quietly change what sqlalign does when nobody configures it. Below that sit unit tests for the alignment formula, the fixpoint composition cases, the splitter, the dollar-quote scanner, comments, config precedence, file selection, line endings, and each individual knob. Run the lot with: PYTHONPATH=src pytest -q Adding a construct # Write the golden first. Add the hand-formatted statement to samples/queries.sql under a new -- #N: description header, regenerate with python scripts/build_fixtures.py samples/queries.sql tests/fixtures/expected (it writes zero-padded NN.sql ), and add the messy tests/fixtures/input/NN.sql . Run PYTHONPATH=src pytest -q . A new golden that fails is either a real gap in a layout handler or an unmodelled construct \u2014 in the second case confirm you get the warning and a passthrough , not a wrong render. Emit tags, never spaces. A handler adds Seg(text, scope, kind) ; if you find yourself computing a column width in layout/ , the logic belongs in align.py . Read every layout literal from Style . Handlers do not hard-code widths, indents, or spellings. Widen guard_args only for arguments you actually render. If the new output should lint clean, check the sqlfluff gate still passes, or document a new exclusion in .sqlfluff wit","headings":[{"id":"the-pipeline","text":"The pipeline"},{"id":"layout-and-alignment-are-two-passes","text":"Layout and alignment are two passes"},{"id":"alignment-composes-with-wrapping-because-it-runs-second","text":"Alignment composes with wrapping because it runs second"},{"id":"the-second-pass-is-genuinely-separable","text":"The second pass is genuinely separable"},{"id":"the-fixpoint-resolver","text":"The fixpoint resolver"},{"id":"the-safety-model","text":"The safety model"},{"id":"what-the-guarantee-does-not-cover","text":"What the guarantee does not cover"},{"id":"the-decline-contract","text":"The decline contract"},{"id":"why-this-is-the-product-not-a-limitation","text":"Why this is the product, not a limitation"},{"id":"testing","text":"Testing"},{"id":"adding-a-construct","text":"Adding a construct"},{"id":"see-also","text":"See also"}]},{"slug":"faq","title":"FAQ","text":" Why did my statement not get formatted? # Because sqlalign declined it, and it told you so on stderr. A statement it cannot reproduce exactly is emitted byte-identical rather than approximated: $ sqlalign --stdout mixed.sql sqlalign: mixed.sql: unsupported construct (CTE column list), passed through: with c(a, b) as (select 1, 2) select a f with c(a, b) as (select 1, 2) select a from c; SELECT x , y FROM z WHERE a = 1 AND bb = 2; Note what did not happen: the file did not fail, the other statement still formatted, and the exit code is 0 . Declining is per statement. There are five warning wordings, deliberately different so you can tell an expected decline from a bug: Warning What it means What to do passthrough (parse error line N): \u2026 sqlglot could not parse it. Usually a genuine syntax error, sometimes vendor syntax the parser does not know Fix the SQL, or leave it \u2014 it is safe either way unsupported construct, passed through: \u2026 It parsed, but no layout handler models it Nothing to do. File an issue if it is common in your codebase formatting would change semantics, passed through unformatted: \u2026 The output would not AST-compare equal to the input. The safety net caught it Nothing to do. This is the guarantee working templating not maskable, passed through: \u2026 A Jinja expression is too short to mask (see below) Pad the expression, or accept the passthrough internal formatter error, passed through (please report): \u2026 A bug in sqlalign. Your file is still intact Please report it A syntax error partway through a file does not stop the rest of it: $ sqlalign --stdout syntaxerr.sql sqlalign: syntaxerr.sql: passthrough (parse error line 2): selct oops from t; SELECT a , b FROM t WHERE a = 1; selct oops from t; SELECT c , d FROM u; One caveat on that: an unclosed string literal or $$ quote swallows the rest of the file into a single unparseable statement, so everything after it passes through until the quote is fixed. The declines you are most likely to meet in ordinary Postgres SQL: Construct Note Cursors, FOR loops, EXCEPTION blocks in a $$ body declines per statement inside the body, so the rest of the procedure still formats T-SQL IF / WHILE inside a procedure body sqlglot leaves part of the body unparsed, so there is no tree to lay out \u2014 see Dialects A comment buried inside an expression, or in a positional GROUP BY 1, 2 the whole statement passes through rather than the comment being moved or restyled. Every clause that gets one row per term \u2014 the select list, FROM , WHERE / HAVING / QUALIFY , GROUP BY , ORDER BY \u2014 is modelled Single-line DDL with a spelling sqlglot does not keep \u2014 ALTER COLUMN x TYPE t , DROP FUNCTION f() , COPY \u2026 WITH CSV HEADER reported as would respell this statement ; see below Per-dialect decline lists are on the Dialects page. Why \"would respell this statement\"? # Because formatting it would hand back SQL you did not write. sqlglot's parser collapses some spellings before sqlalign ever sees them. ALTER COLUMN x TYPE text and ALTER COLUMN x SET DATA TYPE text are one node, so the information about which you wrote is gone, and printing either one back compares equal to the tree check. The same happens to DROP FUNCTION f() , whose empty argument list names the overload, and to COPY \u2026 WITH CSV HEADER FORCE QUOTE a, b , where one option comes back as three. sqlalign cannot preserve what it was never given, so it declines: your statement is passed through byte-identical, exactly as any other decline. Before 1.2 these were rewritten silently, which was the worse of the two. The check counts the tokens either side of formatting and fires when one is gained or lost. Order is not compared \u2014 the tree check already covers anything that moved \u2014 and the spellings sqlalign's own settings choose between ( != / <> , DECIMAL / NUMERIC , an optional AS , type synonyms like INT / INTEGER ) are normalised away, so an ordinary reformat never trips it. Why won't it fix my SQL? # Because it is not a linter, and it is built so that it structurally cannot be one. sqlalign will not: unify your cast styles ( :: vs CAST(...) ) add missing AS keywords turn JOIN into INNER JOIN normalise GROUP BY 1, 2 to named columns, or the reverse reorder your ON operands rename or requote your identifiers Every one of those changes the AST, and a changed AST means the statement is passed through untouched. The two knobs where sqlalign does pick a spelling for you \u2014 --neq-style and --decimal-style \u2014 exist only because sqlglot's parser collapses each of those pairs to a single node, so a form has to be chosen when printing. Both are configurable. Linting is sqlfluff's job. The two are designed to run together. How do I run it alongside sqlfluff? # Run sqlfluff fix first, then sqlalign. sqlfluff rewrites your SQL \u2014 that is the point of a linter: -- q.sql, before SELECT c.id, o.total FROM customers c JOIN orders o ON c.id = o.customer_id WHERE o.status = 'complete'; $ sqlfluff fix --dialect postgres --rules ambiguous.join,aliasing.table q.sql == [q.sql] FIXED 3 fixable linting violations found -- q.sql, after SELECT c.id, o.total FROM customers AS c INNER JOIN orders AS o ON c.id = o.customer_id WHERE o.status = 'complete'; sqlalign then lays out whatever sqlfluff decided, and the final layout is sqlalign's. Doing it the other way round means sqlfluff's fixes land last and your alignment columns are gone. Then teach sqlfluff to stop fighting over layout. Out of the box it will flag every line of sqlalign's output: $ sqlfluff lint --dialect postgres formatted.sql L: 2 | P: 1 | LT09 | Select targets should be on a new line unless there is | only one select target. [layout.select_targets] L: 3 | P: 6 | LT04 | Found leading comma ','. Expected only trailing near | line breaks. [layout.commas] L: 9 | P: 15 | LT01 | Expected only single space before naked identifier. | Found ' '. [layout.spacing] This is the sqlalign-related part of a .sqlfluff . It hands layout to sqlalign and stands down the three rules the house style deliberately conflicts with: [sqlfluff] dialect = postgres exclude_rules = # Layout is sqlalign's job. sqlfluff cannot express this style, # so these rules have nothing useful to say about its output. layout.indent, layout.keyword_newline, layout.operators, layout.select_targets, layout.spacing, convention.not_equal, convention.terminator, # House-style conflicts: sqlalign preserves your valid choices rather # than normalising them, so these three would always fire. ambiguous.column_references, aliasing.expression, convention.casting_style max_line_length = -1 # Leading commas are the house default. Drop this block if you run # --comma-position trailing. [sqlfluff:layout:type:comma] spacing_before = touch line_position = leading # sqlalign writes implicit table aliases (no AS). [sqlfluff:rules:aliasing.table] aliasing = implicit Linting the 22 Postgres golden fixtures under exactly that config produces zero LT* layout violations . What remains are ordinary lint opinions with nothing to do with formatting \u2014 AM05 (fully qualify joins), RF02 / RF04 (references and keyword-shaped identifiers), ST05 / ST06 / ST09 (subquery placement, column order, ON operand order), PG01 (excessive locks). Those are for you and your team to settle; sqlalign neither causes nor fixes them, because it preserves whatever you wrote. The repo's own .sqlfluff goes further and excludes that second set too, which is why the project's lint gate passes on every one of those 22 fixtures: $ sqlfluff lint tests/fixtures/expected/13.sql All Finished! Read it as a worked example, not as a config to copy wholesale \u2014 most of what is in there is one team's taste in linting. Wire both into CI in whichever order you like \u2014 they do not interact at that point: sqlfluff lint . sqlalign --check . How do I make sqlalign leave one statement alone? # Put -- sqlalign: skip on the line above it. That statement is passed through with no parse, no layout and deliberately no warning: $ sqlalign --stdout skip.sql -- sqlalign: skip select a, b from generated_by_a_tool where a=1; SELECT c , d FROM t WHERE c = 2; A trailing same-line comment after the terminating ; works too, which is easier to read for a one-liner: $ sqlalign --stdout skip_trailing.sql select a, b from generated where a=1; -- sqlalign: skip SELECT c , d FROM t WHERE c = 2; For larger scopes: Scope How One statement -- sqlalign: skip above it, or after its ; Every $$ procedure body in the run --no-format-bodies Whole files --exclude 'vendor/*' , or an exclude list in .sqlalign.toml Does it work on Windows / with CRLF files? # Yes. A CRLF file is normalised to LF for the engine and written back with its own line endings, so the diff is your formatting change and not a whole-file \\r churn: $ file crlf.sql crlf.sql: ASCII text, with CRLF line terminators $ sqlalign crlf.sql $ file crlf.sql crlf.sql: ASCII text, with CRLF line terminators --check compares after restoring the endings, so an already-formatted CRLF file reports clean rather than showing a spurious diff on every line. Override the choice with --line-ending {auto,lf,crlf} . auto is the default and preserves each file's own. Encoding does not follow the Windows code page: files and stdout are UTF-8, and a file saved by SSMS with a byte-order mark keeps it. Lone CR endings (classic Mac) are not a line ending sqlalign models. Those files pass through untouched with a warning rather than being silently rewritten: sqlalign: old.sql: lone CR line endings \u2014 passed through untouched Does it handle dbt and Jinja? # Inline template expressions, yes. Block tags that wrap SQL structure, no. Templated SQL is not valid SQL, so most formatters decline it outright. sqlalign masks each template expression with a same-width placeholder, formats the result as ordinary SQL, then puts the original text back. Same width is the whole trick: alignment columns are computed against the real rendered width, so nothing shifts when the originals are restored. $ sqlalign --preset dbt --stdout model.sql select o.id, o.total, c.email from {{ ref('orders') }} o join {{ ref('customers') }} c on c.id = o.customer_id where o.status = 'complete'; {{ \u2026 }} , {% \u2026 %} and {# \u2026 #} are all recognised. --no-protect-templating turns the masking off. Three limits, all of which degrade to a passthrough rather than a wrong render: A template expression shorter than 12 characters cannot be masked. The placeholder needs room for a unique stem, and approximating a width would shift every column in the file. So {{ ref('orders') }} (19 characters) is fine, and {{ this }} (10) and {% endif %} (11) are not: $ sqlalign --stdout incremental.sql sqlalign: incremental.sql: templating not maskable, passed through: template expression too short to mask: '{{ this }}' Padding the expression to 12 characters ( {{ this }} ) gets past that specific check, at the cost of writing SQL that looks odd. Block tags that wrap SQL clauses make the statement unparseable. Take the standard incremental pattern: select a, b from t {% if is_incremental() %} where a > (select max(a) from {{ this }}) {% endif %} ; Padding every tag out to 12 characters gets past the masking check, and the statement still does not format \u2014 a masked placeholder standing where a WHERE clause should be is not valid SQL: $ sqlalign --stdout incremental.sql sqlalign: incremental.sql: passthrough (parse error line 1): select a, b from t _sqla_tpl_0_xxxxxxx The masking trick substitutes for expressions , not for control flow. Jinja that decides which clauses exist is beyond it. A leading {{ config(...) }} block merges with the query that follows it. There is no semicolon between them, so the two become one statement, and the masked form does not parse: $ sqlalign --stdout model.sql sqlalign: model.sql: passthrough (parse error line 1): _sqla_tpl_0_xxxxxxxxxxxxxxxxxxxxxx In practice: sqlalign formats dbt models whose Jinja is ref / source / var substitution inside an otherwise ordinary query. Models built out of Jinja control flow are passed through untouched. Nothing is corrupted either way. There is a dbt preset (lowercase keywords, trailing commas, no alignment padding) if you want output that reads like the rest of a dbt project. Is it safe to run on my whole repo? # The design answer is yes, and the reason is the safety net rather than a promise: every statement is re-parsed after rendering and its AST compared against the input's. If they differ, the original bytes are kept and you get a warning. A statement is either laid out or passed through byte-identical \u2014 there is no third outcome. Run it in this order anyway, because trust should be earned per repo: sqlalign --check . # which files would change, exit 1 if any would sqlalign --diff . | less # exactly what would change sqlalign . # commit this on its own branch --check and --diff write nothing. Both exit 1 if anything would change, which is what makes --check a CI gate. $ sqlalign --check q.sql would reformat q.sql $ echo $? 1 Commit the reformat as its own commit, with no logic changes in it, so reviewers can skip it and git log --follow stays usable. git blame has --ignore-rev / .git-blame-ignore-revs for exactly this. Three honest caveats on the guarantee: It is a within-dialect guarantee. The AST net cannot detect output that is valid to sqlglot but invalid to your engine, because the round trip never leaves sqlglot's grammar. That is why only three audited dialects are offered \u2014 see Dialects . Comments are compared separately, because they are not in the AST. sqlglot hangs a comment off the token it precedes rather than putting it in the tree, so the AST comparison passes whether or not a comment survived. That was once a real gap \u2014 a lost comment was invisible to the one check meant to catch a change in meaning, and two of the worst bugs this project had were exactly that: SELECT a -- c, lost a separator, and SELECT a -- note; left the statement unterminated so it swallowed the next one. Since 1.1 each statement is also compared on the comments it carries, and one that would differ is passed through like any other. Inside a $$ body the tokenizer sees one string literal, so those statements are compared structurally instead \u2014 and the body renderer holds the same line by construction: a same-line trailing comment is reproduced verbatim, and a comment position it does not model declines as comment inside a procedural clause rather than guessing. Some distinctions are destroyed before the comparison exists. Where sqlglot collapses two spellings into one node, both sides collapse identically. Where the two are true synonyms this is harmless; where they are not, a separate raw-source guard is needed \u2014 see T-SQL REAL / NTEXT in Dialects . Formatting is idempotent: running sqlalign on its own output is a no-op, and the test suite asserts that byte-for-byte for all 29 golden fixtures. How fast is it? # Fast enough for a pre-commit hook on a whole repository. Reproduce these with uv run python tools/benchmark.py , which builds a tree from the vendored corpus and times the CLI end to end \u2014 interpreter start, imports and all, because that is what you actually wait for. On an Apple M3 Pro, Python 3.12, 500 files totalling 1.4 MB: Wall time Rate sqlalign --check . 2.8 s 180 files/s Rewriting in place 2.8 s 177 files/s Startup alone 0.10 s \u2014 Which projects to about 5.5 s for a thousand files and 54 s for ten thousand . There is no --jobs flag, deliberately. These numbers are why: a thousand-file project checks in the time a test suite spends collecting, and the case that actually runs often \u2014 a pre-commit hook over the handful of files you changed \u2014 is dominated by startup rather than by formatting. Parallelism would buy a few seconds on the largest repositories and cost ordered output, aggregated --report counts, and a second way for the tool to fail. If your repository is large enough that this is wrong, that is worth an issue. About 0.10 s of every run is Python startup plus importing sqlglot, so a one-file-per-invocation hook pays that each time. If you are wiring up a pre-commit hook, pass all the changed files in one invocation rather than looping \u2014 which is what the hooks in this repository do. sqlalign never connects to a database. It parses, lays out, and re-parses \u2014 that is all it does, and it works on files that reference tables you do not have. What is this warning that doesn't say sqlalign: ? # 'GRANT SELECT ON ALL TABLES IN SCHEMA analytics TO readonly_user' contains unsupported syntax. Falling back to parsing as a 'Command'. That line comes from sqlglot's logger, not from sqlalign, and it is not a decline. sqlglot keeps such a statement as raw text it did not fully parse; sqlalign still formats it, and --check reports the file clean. Every message sqlalign itself emits is prefixed sqlalign: <file>: . Why did the exit code come back non-zero? # Code Meaning 0 Success. Also the code when statements were declined \u2014 a passthrough is not an error 1 --check or --diff found a file that would change 2 An unreadable file, or a broken config file. Other files in the same run still process Declines do not affect the exit code. A file consisting entirely of statements sqlalign cannot format is reported clean by --check , because it is: nothing would change. See also # Getting started \u2014 install and first run Command-line reference \u2014 every flag, with worked invocations Configuration \u2014 committing your team's style Dialects \u2014 what each dialect supports and declines Architecture \u2014 the safety model and decline contract in full ","headings":[{"id":"why-did-my-statement-not-get-formatted","text":"Why did my statement not get formatted?"},{"id":"why-quot-would-respell-this-statement-quot","text":"Why "would respell this statement"?"},{"id":"why-won-t-it-fix-my-sql","text":"Why won't it fix my SQL?"},{"id":"how-do-i-run-it-alongside-sqlfluff","text":"How do I run it alongside sqlfluff?"},{"id":"how-do-i-make-sqlalign-leave-one-statement-alone","text":"How do I make sqlalign leave one statement alone?"},{"id":"does-it-work-on-windows-with-crlf-files","text":"Does it work on Windows / with CRLF files?"},{"id":"does-it-handle-dbt-and-jinja","text":"Does it handle dbt and Jinja?"},{"id":"is-it-safe-to-run-on-my-whole-repo","text":"Is it safe to run on my whole repo?"},{"id":"how-fast-is-it","text":"How fast is it?"},{"id":"what-is-this-warning-that-doesn-t-say-sqlalign","text":"What is this warning that doesn't say sqlalign:?"},{"id":"why-did-the-exit-code-come-back-non-zero","text":"Why did the exit code come back non-zero?"},{"id":"see-also","text":"See also"}]}]
|