npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

prettier-plugin-postgresql

v0.2.5

Published

Prettier plugin for PostgreSQL using the official libpg_query parser

Downloads

881

Readme

prettier-plugin-postgresql

Beta — covers the core PostgreSQL DML and DDL statement set. A small number of advanced or uncommon constructs fall back to a /* unknown */ comment placeholder while support is being added.

A Prettier plugin for PostgreSQL SQL. Parses SQL with libpg_query (the actual PostgreSQL parser) and formats it using Prettier's document IR for consistent, readable output.


Features

DML

  • SELECT — column lists, table aliases, all JOIN types (INNER, LEFT, RIGHT, FULL, CROSS, NATURAL), WHERE, GROUP BY / HAVING, ORDER BY, LIMIT / OFFSET, DISTINCT, DISTINCT ON
  • Set operations — UNION / UNION ALL / INTERSECT / EXCEPT
  • Subqueries — correlated subqueries, EXISTS, scalar sublinks, LATERAL
  • CTEs — WITH / WITH RECURSIVE, data-modifying CTEs (WITH ... DELETE/INSERT/UPDATE)
  • Window functions — OVER (PARTITION BY, ORDER BY, frame clauses: ROWS/RANGE/GROUPS BETWEEN)
  • Aggregate functions — FILTER (WHERE ...), ORDER BY inside aggregate (e.g. string_agg)
  • GROUP BY extensions — ROLLUP, CUBE, GROUPING SETS
  • Locking — FOR UPDATE / FOR SHARE / FOR NO KEY UPDATE / FOR KEY SHARE with OF, NOWAIT, SKIP LOCKED
  • INSERT — VALUES (single and multi-row), DEFAULT VALUES, ON CONFLICT DO NOTHING / DO UPDATE SET, RETURNING, OVERRIDING USER/SYSTEM VALUE, WITH clause
  • UPDATE — SET, FROM, WHERE, RETURNING, WITH clause
  • DELETE — WHERE, RETURNING, WITH clause
  • TRUNCATE — with RESTART IDENTITY and CASCADE
  • Transaction control — BEGIN / START TRANSACTION / COMMIT / ROLLBACK / SAVEPOINT / RELEASE SAVEPOINT / ROLLBACK TO SAVEPOINT / SET TRANSACTION (isolation level, READ ONLY/WRITE, DEFERRABLE) / PREPARE TRANSACTION / COMMIT PREPARED / ROLLBACK PREPARED
  • MERGE — WHEN MATCHED / WHEN NOT MATCHED / WHEN NOT MATCHED BY SOURCE; UPDATE SET, INSERT, DELETE, DO NOTHING actions; conditional AND clause; RETURNING
  • CALL — stored-procedure invocation

DDL

  • CREATE TABLE — column definitions with full constraint support: NOT NULL, DEFAULT, PRIMARY KEY, FOREIGN KEY (column-level and table-level, with ON UPDATE/DELETE actions), CHECK, UNIQUE, GENERATED ALWAYS AS (stored), GENERATED AS IDENTITY, named constraints, DEFERRABLE; type modifiers (VARCHAR(100), NUMERIC(10,2)), array types (TEXT[])
  • ALTER TABLE — ADD COLUMN, DROP COLUMN, ADD CONSTRAINT, RENAME COLUMN, ALTER COLUMN TYPE, SET/DROP DEFAULT, SET/DROP NOT NULL, RENAME TABLE
  • CREATE VIEW / CREATE MATERIALIZED VIEW
  • CREATE TABLE ASCREATE TABLE foo AS SELECT ...
  • CREATE INDEX / CREATE UNIQUE INDEX
  • CREATE FUNCTION — RETURNS, LANGUAGE, dollar-quoted $$...$$ body, parameter lists with modes (IN, OUT, INOUT)
  • CREATE TYPE — composite (AS (...)) and enum (AS ENUM (...))
  • ALTER TYPE — ADD VALUE for enums (with BEFORE/AFTER placement, IF NOT EXISTS)
  • CREATE / ALTER SEQUENCE — START WITH, INCREMENT BY, MINVALUE, MAXVALUE, CACHE, CYCLE, RESTART WITH
  • CREATE SCHEMA — with IF NOT EXISTS and AUTHORIZATION
  • CREATE EXTENSION — with IF NOT EXISTS
  • CREATE TRIGGER — BEFORE/AFTER/INSTEAD OF, INSERT/UPDATE/DELETE/TRUNCATE, FOR EACH ROW/STATEMENT
  • DROP — TABLE, VIEW, INDEX, FUNCTION
  • GRANT / REVOKE — on TABLE, SCHEMA, FUNCTION, and ALL ... IN SCHEMA; WITH GRANT OPTION; CASCADE
  • CREATE / ALTER ROLE — with LOGIN, PASSWORD, SUPERUSER, CREATEDB, CREATEROLE, INHERIT, REPLICATION, BYPASSRLS, CONNECTION LIMIT
  • COMMENT ON — TABLE, COLUMN, SCHEMA, DATABASE, INDEX, SEQUENCE, VIEW, FUNCTION, TYPE
  • CREATE TABLE LIKECREATE TABLE new (LIKE existing INCLUDING ALL)
  • Table partitioningPARTITION BY RANGE/LIST/HASH, CREATE TABLE ... PARTITION OF, partition bounds (FOR VALUES FROM/TO, IN, WITH, DEFAULT)
  • TABLESAMPLEFROM t TABLESAMPLE BERNOULLI(10) / SYSTEM(5) REPEATABLE (42)
  • VACUUM / ANALYZE / CLUSTER / REINDEX — maintenance statements with options
  • CHECKPOINTCHECKPOINT
  • LOADLOAD 'filename'
  • CREATE / DROP TABLESPACECREATE TABLESPACE name LOCATION path, DROP TABLESPACE [IF EXISTS] name
  • Foreign data wrappersCREATE SERVER, CREATE FOREIGN TABLE, CREATE USER MAPPING, IMPORT FOREIGN SCHEMA
  • Logical replicationCREATE / ALTER / DROP PUBLICATION and SUBSCRIPTION
  • CREATE AGGREGATECREATE AGGREGATE name (SFUNC = ..., STYPE = ...)
  • CREATE OPERATORCREATE OPERATOR op (LEFTARG = ..., PROCEDURE = ...)
  • CREATE COLLATIONCREATE COLLATION name (LOCALE = ...) and FROM existing
  • SECURITY LABELSECURITY LABEL FOR provider ON object IS label

Expressions

  • SQL standard functionsSUBSTRING(str FROM pattern), EXTRACT(field FROM expr), TRIM(LEADING/TRAILING/BOTH ... FROM str), POSITION(x IN y), expr AT TIME ZONE tz, OVERLAY(...)
  • Type castingexpr::type (PostgreSQL style), INTERVAL '1 day' literals with optional field modifiers (HOUR TO MINUTE, DAY TO SECOND, etc.)
  • Array subscriptsarr[1], arr[2:4], arr[:3]
  • Named argumentsfunc(param => value)
  • Conditional — CASE / WHEN / THEN / ELSE, COALESCE, NULLIF, GREATEST, LEAST
  • XML functionsXMLELEMENT (with XMLATTRIBUTES), XMLFOREST, XMLCONCAT, XMLPI, XMLAGG
  • XMLTABLE — tabular XML query in the FROM clause; PASSING, COLUMNS with PATH, DEFAULT, NOT NULL, FOR ORDINALITY
  • SQL/JSON functionsJSON_QUERY, JSON_EXISTS, JSON_VALUE (with RETURNING type) — PostgreSQL 16+
  • JSON_TABLE — tabular JSON query in the FROM clause; PATH, EXISTS PATH, FORMAT JSON PATH, NESTED PATH, FOR ORDINALITY, ON EMPTY/ON ERROR — PostgreSQL 16+
  • Predicates — IN / NOT IN, BETWEEN / NOT BETWEEN, LIKE / NOT LIKE, ILIKE / NOT ILIKE, SIMILAR TO, IS NULL / IS NOT NULL, IS DISTINCT FROM, ANY / ALL
  • SQL value functions — CURRENT_DATE, CURRENT_TIMESTAMP, CURRENT_USER, SESSION_USER, LOCALTIME, LOCALTIMESTAMP, and others
  • GROUPING()GROUPING(col) predicate used alongside GROUPING SETS

DML (continued)

  • SET / SHOW / RESETSET search_path = myschema, SHOW work_mem, RESET ALL
  • ALTER SYSTEMALTER SYSTEM SET param = value, ALTER SYSTEM RESET [ALL] — writes to postgresql.conf
  • DISCARDDISCARD ALL, DISCARD PLANS, DISCARD SEQUENCES, DISCARD TEMP
  • SELECT INTOSELECT ... INTO [TEMP] table
  • COPYCOPY table FROM/TO, COPY (query) TO; program and option list
  • EXPLAINEXPLAIN, EXPLAIN ANALYZE, EXPLAIN (ANALYZE, VERBOSE, FORMAT JSON) stmt
  • PREPARE / EXECUTE / DEALLOCATE — server-side prepared statements
  • LISTEN / UNLISTEN / NOTIFY — async pub/sub with optional payload
  • LOCK TABLELOCK TABLE t IN ACCESS EXCLUSIVE MODE [NOWAIT]
  • CursorsDECLARE CURSOR, FETCH, MOVE, CLOSE
  • Comment preservation — line comments (-- ...) and block comments (/* ... */) are preserved: leading comments before a statement stay before it; inline trailing comments stay on the statement's final line

DDL (continued)

  • ALTER FUNCTION — SET COST, SET ROWS, SET VOLATILE/STABLE/IMMUTABLE, RENAME TO, OWNER TO, SET SCHEMA
  • REFRESH MATERIALIZED VIEW — with CONCURRENTLY
  • CREATE RULE — BEFORE/AFTER/INSTEAD, INSERT/UPDATE/DELETE/SELECT, DO ALSO/INSTEAD
  • Row Security PoliciesCREATE / ALTER POLICY with USING and WITH CHECK
  • REASSIGN OWNEDREASSIGN OWNED BY old_role TO new_role
  • DROP OWNEDDROP OWNED BY roles [CASCADE]

Pending Implementation

| Feature | Notes | |---|---| | PL/pgSQL | Full procedural language (IF/ELSIF, LOOP, RETURN, EXCEPTION, DECLARE) — out of scope for a SQL formatter |


Requirements

| Requirement | Version | |---|---| | Node.js | 20 or later | | .NET Runtime | 8.0 or later | | Prettier | 3.x |


Installation

npm install --save-dev prettier prettier-plugin-postgresql

Then add the plugin to your Prettier configuration:

// prettier.config.js
export default {
  plugins: ['prettier-plugin-postgresql'],
  overrides: [
    {
      files: ['*.sql', '*.pgsql'],
      options: {
        parser: 'pgsql',
      },
    },
  ],
};

See Getting Started for VS Code setup and build-from-source instructions.


Quick Example

Input (unformatted):

SELECT id,title,price,author_id FROM books WHERE in_stock=TRUE AND price<50 ORDER BY price ASC;

Output (default options — lowercase keywords, standard density, trailing commas):

select
  id,
  title,
  price,
  author_id
from
  books
where
  in_stock = true
  and price < 50
order by
  price asc;

Configuration

Three formatting options are available. See Options for full details and examples.

| Option | Values | Default | Description | |---|---|---|---| | sqlKeywordCase | lower | upper | preserve | lower | Case for SQL keywords | | sqlDensity | compact | standard | spacious | standard | Whitespace density | | sqlCommaStyle | trailing | leading | trailing | Comma placement in lists |

// prettier.config.js
export default {
  plugins: ['prettier-plugin-postgresql'],
  overrides: [
    {
      files: '*.sql',
      options: {
        parser: 'pgsql',
        sqlKeywordCase: 'upper',
        sqlDensity: 'standard',
        sqlCommaStyle: 'trailing',
      },
    },
  ],
};

Documentation

  • Getting Started — installation, VS Code setup, building from source
  • Options — all formatting options with examples
  • Examples — before/after formatting examples for common patterns
  • Formatting Reference — comprehensive formatting rules by statement type