Skip to content

Type to search extensions

pgfmt

v0.4.0

PostgreSQL SQL formatting and diagnostics via pgfmt-lsp

Updated 3 months ago
99 downloads 1 star Repository ↗

pgfmt

A PostgreSQL SQL formatter. Reads SQL from stdin, outputs formatted SQL to stdout.

Uses libpg_query to parse SQL with the actual PostgreSQL parser, so it handles everything the real parser handles — including PL/pgSQL function bodies.

Try it in the browser: pgfmt playground.

Robustness

pgfmt is designed to never lose or corrupt SQL:

  • Statements and expressions the formatter doesn't explicitly support fall back to libpg_query's deparser, which emits valid (if plainly formatted) SQL rather than dropping anything.
  • PL/pgSQL statements the formatter doesn't recognize keep their original body text verbatim.
  • The test suite sweeps the entire PostgreSQL 17 regression corpus (~44,000 statements) and verifies that every formatted statement still parses, preserves its AST, and formats idempotently. The handful of known deviations (currently 48, all benign deparse artifacts of legacy syntaxes) are pinned in a baseline that CI enforces.

Install

Homebrew (installs both pgfmt and pgfmt-lsp):

brew install middle-management/tap/pgfmt

Go:

go install github.com/middle-management/pgfmt@latest

Usage

echo "SELECT id,name FROM users WHERE active=true" | pgfmt
pgfmt < query.sql

LSP Server

pgfmt includes an LSP server that provides formatting and diagnostics for SQL files.

Install

Already included with the Homebrew formula above, or install separately with Go:

go install github.com/middle-management/pgfmt/cmd/pgfmt-lsp@latest

Editor Setup

Neovim (via nvim-lspconfig):

vim.lsp.config['pgfmt'] = {
  cmd = { 'pgfmt-lsp' },
  filetypes = { 'sql' },
  root_markers = { '.git' },
}
vim.lsp.enable('pgfmt')

VS Code (via a generic LSP client like vscode-languageclient):

{
  "pgfmt.server.path": "pgfmt-lsp"
}

Zed — install the pgfmt Zed extension from the extension registry. It bundles pgfmt-lsp and downloads it automatically — no manual setup required.

Then enable formatting in .zed/settings.json or ~/.config/zed/settings.json:

{
  "languages": {
    "SQL": {
      "formatter": "language_server",
      "format_on_save": "on"
    }
  }
}

See the extension README for advanced configuration, including how to use a custom binary path.

Features

  • Formatting — format SQL files using textDocument/formatting
  • Diagnostics — parse errors reported on open and change

Build from source

git clone https://github.com/middle-management/pgfmt.git
cd pgfmt
go build -o pgfmt .
go build -o pgfmt-lsp ./cmd/pgfmt-lsp

Prebuilt binaries for Linux and macOS (amd64 and arm64) are attached to each release.

ZedExt An unofficial community project. Not affiliated with Zed Industries.

Data from Zed’s extension registry and GitHub · updated